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
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
neyric/aws-swf | lib/workflow-execution.js | function (config, cb) {
var o = {}, k;
o.domain = this.baseConfig.domain;
//o.execution = this.workflowId;
for (k in config) {
if (config.hasOwnProperty(k)) {
o[k] = config[k];
}
}
this.swfClient.getWorkflowExecutionHistory(o, cb);
} | javascript | function (config, cb) {
var o = {}, k;
o.domain = this.baseConfig.domain;
//o.execution = this.workflowId;
for (k in config) {
if (config.hasOwnProperty(k)) {
o[k] = config[k];
}
}
this.swfClient.getWorkflowExecutionHistory(o, cb);
} | [
"function",
"(",
"config",
",",
"cb",
")",
"{",
"var",
"o",
"=",
"{",
"}",
",",
"k",
";",
"o",
".",
"domain",
"=",
"this",
".",
"baseConfig",
".",
"domain",
";",
"for",
"(",
"k",
"in",
"config",
")",
"{",
"if",
"(",
"config",
".",
"hasOwnProperty",
"(",
"k",
")",
")",
"{",
"o",
"[",
"k",
"]",
"=",
"config",
"[",
"k",
"]",
";",
"}",
"}",
"this",
".",
"swfClient",
".",
"getWorkflowExecutionHistory",
"(",
"o",
",",
"cb",
")",
";",
"}"
] | Get the history for the workflow execution
@param {Object} config
@param {Function} cb | [
"Get",
"the",
"history",
"for",
"the",
"workflow",
"execution"
] | 31b96c9eef313199465b40204a92909996a85c3d | https://github.com/neyric/aws-swf/blob/31b96c9eef313199465b40204a92909996a85c3d/lib/workflow-execution.js#L86-L99 | train |
|
origin1tech/sequelize-cmd | lib/migrator.js | Migrator | function Migrator(sequelize, options) {
this.sequelize = sequelize;
this.options = Utils._.extend({
path: __dirname + '/../migrations',
from: null,
to: null,
logging: console.log,
filesFilter: /\.js$/
}, options || {});
if (this.options.logging === true) {
console.log('DEPRECATION WARNING: The logging-option should be either a function or false. Default: console.log');
this.options.logging = console.log;
}
if (this.options.logging == console.log) {
// using just console.log will break in node < 0.6
this.options.logging = function(s) { console.log(s); }
}
} | javascript | function Migrator(sequelize, options) {
this.sequelize = sequelize;
this.options = Utils._.extend({
path: __dirname + '/../migrations',
from: null,
to: null,
logging: console.log,
filesFilter: /\.js$/
}, options || {});
if (this.options.logging === true) {
console.log('DEPRECATION WARNING: The logging-option should be either a function or false. Default: console.log');
this.options.logging = console.log;
}
if (this.options.logging == console.log) {
// using just console.log will break in node < 0.6
this.options.logging = function(s) { console.log(s); }
}
} | [
"function",
"Migrator",
"(",
"sequelize",
",",
"options",
")",
"{",
"this",
".",
"sequelize",
"=",
"sequelize",
";",
"this",
".",
"options",
"=",
"Utils",
".",
"_",
".",
"extend",
"(",
"{",
"path",
":",
"__dirname",
"+",
"'/../migrations'",
",",
"from",
":",
"null",
",",
"to",
":",
"null",
",",
"logging",
":",
"console",
".",
"log",
",",
"filesFilter",
":",
"/",
"\\.js$",
"/",
"}",
",",
"options",
"||",
"{",
"}",
")",
";",
"if",
"(",
"this",
".",
"options",
".",
"logging",
"===",
"true",
")",
"{",
"console",
".",
"log",
"(",
"'DEPRECATION WARNING: The logging-option should be either a function or false. Default: console.log'",
")",
";",
"this",
".",
"options",
".",
"logging",
"=",
"console",
".",
"log",
";",
"}",
"if",
"(",
"this",
".",
"options",
".",
"logging",
"==",
"console",
".",
"log",
")",
"{",
"this",
".",
"options",
".",
"logging",
"=",
"function",
"(",
"s",
")",
"{",
"console",
".",
"log",
"(",
"s",
")",
";",
"}",
"}",
"}"
] | Sequelize Migrator class.
@class Migrator
@param {object} sequelize - the sequelize instance.
@param {object} [options] - the migration options.
@constructor | [
"Sequelize",
"Migrator",
"class",
"."
] | f9e1108997b484cd2d57504a7db9cee3220d46ef | https://github.com/origin1tech/sequelize-cmd/blob/f9e1108997b484cd2d57504a7db9cee3220d46ef/lib/migrator.js#L22-L43 | train |
jbielick/kona | lib/kona/watch.js | watch | function watch(path, cb) {
debug('watching %s for changes', path);
var options = {ignoreInitial: true, persistent: true},
watcher = chokidar.watch(path, options);
watcher.on('change', function(path, stat) {
/* istanbul ignore next */
debug(format("%s changed", path));
/* istanbul ignore next */
cb.call(this, path, stat);
}.bind(this));
return watcher;
} | javascript | function watch(path, cb) {
debug('watching %s for changes', path);
var options = {ignoreInitial: true, persistent: true},
watcher = chokidar.watch(path, options);
watcher.on('change', function(path, stat) {
/* istanbul ignore next */
debug(format("%s changed", path));
/* istanbul ignore next */
cb.call(this, path, stat);
}.bind(this));
return watcher;
} | [
"function",
"watch",
"(",
"path",
",",
"cb",
")",
"{",
"debug",
"(",
"'watching %s for changes'",
",",
"path",
")",
";",
"var",
"options",
"=",
"{",
"ignoreInitial",
":",
"true",
",",
"persistent",
":",
"true",
"}",
",",
"watcher",
"=",
"chokidar",
".",
"watch",
"(",
"path",
",",
"options",
")",
";",
"watcher",
".",
"on",
"(",
"'change'",
",",
"function",
"(",
"path",
",",
"stat",
")",
"{",
"debug",
"(",
"format",
"(",
"\"%s changed\"",
",",
"path",
")",
")",
";",
"cb",
".",
"call",
"(",
"this",
",",
"path",
",",
"stat",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"return",
"watcher",
";",
"}"
] | setup a chokidar persistent watcher on a dir or file and call
the callback on `change` event
@param {String} path directory (recursive) or file path to watch
@param {Function} cb callback to call on `change` event
@return {choikdar.watcher} the watcher instance created | [
"setup",
"a",
"chokidar",
"persistent",
"watcher",
"on",
"a",
"dir",
"or",
"file",
"and",
"call",
"the",
"callback",
"on",
"change",
"event"
] | 3a723c0b91157dec6b1b229e395de297fd725796 | https://github.com/jbielick/kona/blob/3a723c0b91157dec6b1b229e395de297fd725796/lib/kona/watch.js#L30-L47 | train |
jbielick/kona | lib/kona/watch.js | watchModules | function watchModules(paths) {
paths || (paths = []);
if (!Array.isArray(paths)) { paths = [paths]; }
// for all directories / files in `config.watch` array
paths.forEach(function(watchPath) {
// watch modules for changes
this.watch(watchPath, function(eventPath, stat) {
// delete from the warm cache, the next require will be fresh
var cached = require.cache[path.resolve(eventPath)];
var children;
if (!cached) return;
cached.children.forEach(function(module) {
delete require.cache[module.id]
});
delete require.cache[cached.parent.id];
delete require.cache[path.resolve(eventPath)]
});
}.bind(this));
} | javascript | function watchModules(paths) {
paths || (paths = []);
if (!Array.isArray(paths)) { paths = [paths]; }
// for all directories / files in `config.watch` array
paths.forEach(function(watchPath) {
// watch modules for changes
this.watch(watchPath, function(eventPath, stat) {
// delete from the warm cache, the next require will be fresh
var cached = require.cache[path.resolve(eventPath)];
var children;
if (!cached) return;
cached.children.forEach(function(module) {
delete require.cache[module.id]
});
delete require.cache[cached.parent.id];
delete require.cache[path.resolve(eventPath)]
});
}.bind(this));
} | [
"function",
"watchModules",
"(",
"paths",
")",
"{",
"paths",
"||",
"(",
"paths",
"=",
"[",
"]",
")",
";",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"paths",
")",
")",
"{",
"paths",
"=",
"[",
"paths",
"]",
";",
"}",
"paths",
".",
"forEach",
"(",
"function",
"(",
"watchPath",
")",
"{",
"this",
".",
"watch",
"(",
"watchPath",
",",
"function",
"(",
"eventPath",
",",
"stat",
")",
"{",
"var",
"cached",
"=",
"require",
".",
"cache",
"[",
"path",
".",
"resolve",
"(",
"eventPath",
")",
"]",
";",
"var",
"children",
";",
"if",
"(",
"!",
"cached",
")",
"return",
";",
"cached",
".",
"children",
".",
"forEach",
"(",
"function",
"(",
"module",
")",
"{",
"delete",
"require",
".",
"cache",
"[",
"module",
".",
"id",
"]",
"}",
")",
";",
"delete",
"require",
".",
"cache",
"[",
"cached",
".",
"parent",
".",
"id",
"]",
";",
"delete",
"require",
".",
"cache",
"[",
"path",
".",
"resolve",
"(",
"eventPath",
")",
"]",
"}",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] | watches routes, controllers, models for changes and clears require cache
for those objects to be reloaded or clears routes and reloads them | [
"watches",
"routes",
"controllers",
"models",
"for",
"changes",
"and",
"clears",
"require",
"cache",
"for",
"those",
"objects",
"to",
"be",
"reloaded",
"or",
"clears",
"routes",
"and",
"reloads",
"them"
] | 3a723c0b91157dec6b1b229e395de297fd725796 | https://github.com/jbielick/kona/blob/3a723c0b91157dec6b1b229e395de297fd725796/lib/kona/watch.js#L54-L81 | train |
jbielick/kona | lib/kona.js | Kona | function Kona(options) {
// call the koa constructor here
Koa.call(this);
options = options || {};
// setup kona root and application paths / helpers
this.setupPaths(options);
// setup env vars, logger, needed modules
this.setupEnvironment(options);
this.loadMixins(this.root.join('package.json'));
} | javascript | function Kona(options) {
// call the koa constructor here
Koa.call(this);
options = options || {};
// setup kona root and application paths / helpers
this.setupPaths(options);
// setup env vars, logger, needed modules
this.setupEnvironment(options);
this.loadMixins(this.root.join('package.json'));
} | [
"function",
"Kona",
"(",
"options",
")",
"{",
"Koa",
".",
"call",
"(",
"this",
")",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"this",
".",
"setupPaths",
"(",
"options",
")",
";",
"this",
".",
"setupEnvironment",
"(",
"options",
")",
";",
"this",
".",
"loadMixins",
"(",
"this",
".",
"root",
".",
"join",
"(",
"'package.json'",
")",
")",
";",
"}"
] | the application module that will house the koa app and provide
an api layer to registering middleware, establishing db connections,
loading application routes, controllers, models and helpers
@param {Object} options options options from commander | [
"the",
"application",
"module",
"that",
"will",
"house",
"the",
"koa",
"app",
"and",
"provide",
"an",
"api",
"layer",
"to",
"registering",
"middleware",
"establishing",
"db",
"connections",
"loading",
"application",
"routes",
"controllers",
"models",
"and",
"helpers"
] | 3a723c0b91157dec6b1b229e395de297fd725796 | https://github.com/jbielick/kona/blob/3a723c0b91157dec6b1b229e395de297fd725796/lib/kona.js#L25-L39 | train |
jbielick/kona | lib/kona.js | function (options) {
this.expose('kona', this);
// livepath for the application root
this.root = new LivePath(options.root || process.cwd());
// livepath for the kona module root
this._root = new LivePath(path.resolve(__dirname, '..'));
debug('Application CWD: ' + this.root.toString());
// kona's module semver version
this.version = require(this._root.join('package.json')).version;
} | javascript | function (options) {
this.expose('kona', this);
// livepath for the application root
this.root = new LivePath(options.root || process.cwd());
// livepath for the kona module root
this._root = new LivePath(path.resolve(__dirname, '..'));
debug('Application CWD: ' + this.root.toString());
// kona's module semver version
this.version = require(this._root.join('package.json')).version;
} | [
"function",
"(",
"options",
")",
"{",
"this",
".",
"expose",
"(",
"'kona'",
",",
"this",
")",
";",
"this",
".",
"root",
"=",
"new",
"LivePath",
"(",
"options",
".",
"root",
"||",
"process",
".",
"cwd",
"(",
")",
")",
";",
"this",
".",
"_root",
"=",
"new",
"LivePath",
"(",
"path",
".",
"resolve",
"(",
"__dirname",
",",
"'..'",
")",
")",
";",
"debug",
"(",
"'Application CWD: '",
"+",
"this",
".",
"root",
".",
"toString",
"(",
")",
")",
";",
"this",
".",
"version",
"=",
"require",
"(",
"this",
".",
"_root",
".",
"join",
"(",
"'package.json'",
")",
")",
".",
"version",
";",
"}"
] | sets up root paths, application version
@param {Object} options options or arguments passed in via constructor | [
"sets",
"up",
"root",
"paths",
"application",
"version"
] | 3a723c0b91157dec6b1b229e395de297fd725796 | https://github.com/jbielick/kona/blob/3a723c0b91157dec6b1b229e395de297fd725796/lib/kona.js#L158-L172 | train |
|
jbielick/kona | lib/kona.js | function(options) {
dotenv.config({path: this.root.join('.env'), silent: true});
this.env = options.environment || process.env.NODE_ENV || 'development';
// detect if we're in an kona application cwd
this.inApp = fs.existsSync(this.root.join('config', 'application.js'));
// create a winston logger instance
this.mountLogger(this.env);
// expose support objects on kona global
this.support = support;
// expose lodash
this._ = support.Utilities;
// lodash + inflections
this.inflector = support.inflector;
this.middlewarePaths = [
'metrics',
'logger',
'static',
'error',
'cache',
'session',
'body-parser',
'method-override',
'etag',
'views',
'router',
'dispatcher',
'invocation',
'autoresponder'
].map(function(name) {
return path.resolve(__dirname, join('middleware', name));
});
} | javascript | function(options) {
dotenv.config({path: this.root.join('.env'), silent: true});
this.env = options.environment || process.env.NODE_ENV || 'development';
// detect if we're in an kona application cwd
this.inApp = fs.existsSync(this.root.join('config', 'application.js'));
// create a winston logger instance
this.mountLogger(this.env);
// expose support objects on kona global
this.support = support;
// expose lodash
this._ = support.Utilities;
// lodash + inflections
this.inflector = support.inflector;
this.middlewarePaths = [
'metrics',
'logger',
'static',
'error',
'cache',
'session',
'body-parser',
'method-override',
'etag',
'views',
'router',
'dispatcher',
'invocation',
'autoresponder'
].map(function(name) {
return path.resolve(__dirname, join('middleware', name));
});
} | [
"function",
"(",
"options",
")",
"{",
"dotenv",
".",
"config",
"(",
"{",
"path",
":",
"this",
".",
"root",
".",
"join",
"(",
"'.env'",
")",
",",
"silent",
":",
"true",
"}",
")",
";",
"this",
".",
"env",
"=",
"options",
".",
"environment",
"||",
"process",
".",
"env",
".",
"NODE_ENV",
"||",
"'development'",
";",
"this",
".",
"inApp",
"=",
"fs",
".",
"existsSync",
"(",
"this",
".",
"root",
".",
"join",
"(",
"'config'",
",",
"'application.js'",
")",
")",
";",
"this",
".",
"mountLogger",
"(",
"this",
".",
"env",
")",
";",
"this",
".",
"support",
"=",
"support",
";",
"this",
".",
"_",
"=",
"support",
".",
"Utilities",
";",
"this",
".",
"inflector",
"=",
"support",
".",
"inflector",
";",
"this",
".",
"middlewarePaths",
"=",
"[",
"'metrics'",
",",
"'logger'",
",",
"'static'",
",",
"'error'",
",",
"'cache'",
",",
"'session'",
",",
"'body-parser'",
",",
"'method-override'",
",",
"'etag'",
",",
"'views'",
",",
"'router'",
",",
"'dispatcher'",
",",
"'invocation'",
",",
"'autoresponder'",
"]",
".",
"map",
"(",
"function",
"(",
"name",
")",
"{",
"return",
"path",
".",
"resolve",
"(",
"__dirname",
",",
"join",
"(",
"'middleware'",
",",
"name",
")",
")",
";",
"}",
")",
";",
"}"
] | parse .env, global env vars, inApp check and setup middleware paths
for readiness
@param {Object} options kona construction options | [
"parse",
".",
"env",
"global",
"env",
"vars",
"inApp",
"check",
"and",
"setup",
"middleware",
"paths",
"for",
"readiness"
] | 3a723c0b91157dec6b1b229e395de297fd725796 | https://github.com/jbielick/kona/blob/3a723c0b91157dec6b1b229e395de297fd725796/lib/kona.js#L180-L217 | train |
|
jbielick/kona | lib/kona.js | function () {
this.middlewarePaths.forEach(function (mwPath) {
require(mwPath)(this);
debug(format('mounted middleware/%s', path.basename(mwPath)));
}, this);
} | javascript | function () {
this.middlewarePaths.forEach(function (mwPath) {
require(mwPath)(this);
debug(format('mounted middleware/%s', path.basename(mwPath)));
}, this);
} | [
"function",
"(",
")",
"{",
"this",
".",
"middlewarePaths",
".",
"forEach",
"(",
"function",
"(",
"mwPath",
")",
"{",
"require",
"(",
"mwPath",
")",
"(",
"this",
")",
";",
"debug",
"(",
"format",
"(",
"'mounted middleware/%s'",
",",
"path",
".",
"basename",
"(",
"mwPath",
")",
")",
")",
";",
"}",
",",
"this",
")",
";",
"}"
] | requires barebones Kona middleware and pushes them to the koa
middleware stack one by one | [
"requires",
"barebones",
"Kona",
"middleware",
"and",
"pushes",
"them",
"to",
"the",
"koa",
"middleware",
"stack",
"one",
"by",
"one"
] | 3a723c0b91157dec6b1b229e395de297fd725796 | https://github.com/jbielick/kona/blob/3a723c0b91157dec6b1b229e395de297fd725796/lib/kona.js#L223-L233 | train |
|
jbielick/kona | lib/kona.js | function (name, object) {
if (global[name] && this.env !== 'test') {
debug(format('global "%s" already exists', name));
}
return (global[name] = object);
} | javascript | function (name, object) {
if (global[name] && this.env !== 'test') {
debug(format('global "%s" already exists', name));
}
return (global[name] = object);
} | [
"function",
"(",
"name",
",",
"object",
")",
"{",
"if",
"(",
"global",
"[",
"name",
"]",
"&&",
"this",
".",
"env",
"!==",
"'test'",
")",
"{",
"debug",
"(",
"format",
"(",
"'global \"%s\" already exists'",
",",
"name",
")",
")",
";",
"}",
"return",
"(",
"global",
"[",
"name",
"]",
"=",
"object",
")",
";",
"}"
] | exposes objects globally
@param {String} name name of the global
@param {Mixed} object the value to assign to the global | [
"exposes",
"objects",
"globally"
] | 3a723c0b91157dec6b1b229e395de297fd725796 | https://github.com/jbielick/kona/blob/3a723c0b91157dec6b1b229e395de297fd725796/lib/kona.js#L241-L246 | train |
|
jbielick/kona | lib/kona.js | function () {
var writeStream = fs.createWriteStream('/dev/null'),
readStream = fs.createReadStream('/dev/null');
return repl.start({
prompt: format('kona~%s > ', this.version),
useColors: true,
input: this.env === 'test' ? readStream : process.stdin,
output: this.env === 'test' ? writeStream : process.stdout
});
} | javascript | function () {
var writeStream = fs.createWriteStream('/dev/null'),
readStream = fs.createReadStream('/dev/null');
return repl.start({
prompt: format('kona~%s > ', this.version),
useColors: true,
input: this.env === 'test' ? readStream : process.stdin,
output: this.env === 'test' ? writeStream : process.stdout
});
} | [
"function",
"(",
")",
"{",
"var",
"writeStream",
"=",
"fs",
".",
"createWriteStream",
"(",
"'/dev/null'",
")",
",",
"readStream",
"=",
"fs",
".",
"createReadStream",
"(",
"'/dev/null'",
")",
";",
"return",
"repl",
".",
"start",
"(",
"{",
"prompt",
":",
"format",
"(",
"'kona~%s > '",
",",
"this",
".",
"version",
")",
",",
"useColors",
":",
"true",
",",
"input",
":",
"this",
".",
"env",
"===",
"'test'",
"?",
"readStream",
":",
"process",
".",
"stdin",
",",
"output",
":",
"this",
".",
"env",
"===",
"'test'",
"?",
"writeStream",
":",
"process",
".",
"stdout",
"}",
")",
";",
"}"
] | starts the kona repl | [
"starts",
"the",
"kona",
"repl"
] | 3a723c0b91157dec6b1b229e395de297fd725796 | https://github.com/jbielick/kona/blob/3a723c0b91157dec6b1b229e395de297fd725796/lib/kona.js#L252-L264 | train |
|
jbielick/kona | lib/kona.js | function () {
var args = Array.prototype.slice.call(arguments),
port = args.shift(),
bean;
if (!this._ready) {
throw new Error('Cannot call #listen before Kona has been intialized');
}
bean = require('./utilities/bean');
if (this.env === 'test') {
delete this.port;
} else {
this.port = port || process.env.KONA_PORT || this.config.port;
}
args.unshift(this.port);
this.server.listen.apply(this.server, args);
debug('listening');
/* istanbul ignore if */
if (this.env !== 'test') {
console.log(bean([
'listening on ' + chalk.dim(this.port),
'Env: ' + chalk.dim(this.env)
]));
}
return this.server;
} | javascript | function () {
var args = Array.prototype.slice.call(arguments),
port = args.shift(),
bean;
if (!this._ready) {
throw new Error('Cannot call #listen before Kona has been intialized');
}
bean = require('./utilities/bean');
if (this.env === 'test') {
delete this.port;
} else {
this.port = port || process.env.KONA_PORT || this.config.port;
}
args.unshift(this.port);
this.server.listen.apply(this.server, args);
debug('listening');
/* istanbul ignore if */
if (this.env !== 'test') {
console.log(bean([
'listening on ' + chalk.dim(this.port),
'Env: ' + chalk.dim(this.env)
]));
}
return this.server;
} | [
"function",
"(",
")",
"{",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
",",
"port",
"=",
"args",
".",
"shift",
"(",
")",
",",
"bean",
";",
"if",
"(",
"!",
"this",
".",
"_ready",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Cannot call #listen before Kona has been intialized'",
")",
";",
"}",
"bean",
"=",
"require",
"(",
"'./utilities/bean'",
")",
";",
"if",
"(",
"this",
".",
"env",
"===",
"'test'",
")",
"{",
"delete",
"this",
".",
"port",
";",
"}",
"else",
"{",
"this",
".",
"port",
"=",
"port",
"||",
"process",
".",
"env",
".",
"KONA_PORT",
"||",
"this",
".",
"config",
".",
"port",
";",
"}",
"args",
".",
"unshift",
"(",
"this",
".",
"port",
")",
";",
"this",
".",
"server",
".",
"listen",
".",
"apply",
"(",
"this",
".",
"server",
",",
"args",
")",
";",
"debug",
"(",
"'listening'",
")",
";",
"if",
"(",
"this",
".",
"env",
"!==",
"'test'",
")",
"{",
"console",
".",
"log",
"(",
"bean",
"(",
"[",
"'listening on '",
"+",
"chalk",
".",
"dim",
"(",
"this",
".",
"port",
")",
",",
"'Env: '",
"+",
"chalk",
".",
"dim",
"(",
"this",
".",
"env",
")",
"]",
")",
")",
";",
"}",
"return",
"this",
".",
"server",
";",
"}"
] | start the http server and listen
@return {HttpServer} koa server instance | [
"start",
"the",
"http",
"server",
"and",
"listen"
] | 3a723c0b91157dec6b1b229e395de297fd725796 | https://github.com/jbielick/kona/blob/3a723c0b91157dec6b1b229e395de297fd725796/lib/kona.js#L271-L304 | train |
|
bojand/grpc-create-error | index.js | applyCreate | function applyCreate (err, message, code, metadata) {
if (err instanceof Error === false) {
throw new Error('Source error must be an instance of Error')
}
if (message instanceof Error) {
err.message = message.message.toString()
if (typeof message.code === 'number') {
err.code = message.code
}
if (typeof message.metadata === 'object') {
err.metadata = createMetadata(message.metadata)
}
}
const isMsgMD = message instanceof Error
if (message && typeof message === 'object' && !isMsgMD) {
metadata = message
message = ''
code = null
}
if (typeof message === 'number') {
metadata = code
code = message
message = ''
}
if (code && typeof code === 'object') {
metadata = code
code = null
}
if (!metadata) {
metadata = null
}
if (typeof message === 'string') {
err.message = message
}
if (typeof code === 'number') {
err.code = code
}
if (metadata && typeof metadata === 'object') {
if (err.metadata) {
const existingMeta = err.metadata && typeof err.metadata.getMap === 'function'
? err.metadata.getMap()
: null
const md = typeof metadata.getMap === 'function'
? metadata.getMap()
: metadata
if (existingMeta || md) {
err.metadata = createMetadata(Object.assign({}, existingMeta || {}, md || {}))
}
} else {
err.metadata = createMetadata(metadata)
}
}
return err
} | javascript | function applyCreate (err, message, code, metadata) {
if (err instanceof Error === false) {
throw new Error('Source error must be an instance of Error')
}
if (message instanceof Error) {
err.message = message.message.toString()
if (typeof message.code === 'number') {
err.code = message.code
}
if (typeof message.metadata === 'object') {
err.metadata = createMetadata(message.metadata)
}
}
const isMsgMD = message instanceof Error
if (message && typeof message === 'object' && !isMsgMD) {
metadata = message
message = ''
code = null
}
if (typeof message === 'number') {
metadata = code
code = message
message = ''
}
if (code && typeof code === 'object') {
metadata = code
code = null
}
if (!metadata) {
metadata = null
}
if (typeof message === 'string') {
err.message = message
}
if (typeof code === 'number') {
err.code = code
}
if (metadata && typeof metadata === 'object') {
if (err.metadata) {
const existingMeta = err.metadata && typeof err.metadata.getMap === 'function'
? err.metadata.getMap()
: null
const md = typeof metadata.getMap === 'function'
? metadata.getMap()
: metadata
if (existingMeta || md) {
err.metadata = createMetadata(Object.assign({}, existingMeta || {}, md || {}))
}
} else {
err.metadata = createMetadata(metadata)
}
}
return err
} | [
"function",
"applyCreate",
"(",
"err",
",",
"message",
",",
"code",
",",
"metadata",
")",
"{",
"if",
"(",
"err",
"instanceof",
"Error",
"===",
"false",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Source error must be an instance of Error'",
")",
"}",
"if",
"(",
"message",
"instanceof",
"Error",
")",
"{",
"err",
".",
"message",
"=",
"message",
".",
"message",
".",
"toString",
"(",
")",
"if",
"(",
"typeof",
"message",
".",
"code",
"===",
"'number'",
")",
"{",
"err",
".",
"code",
"=",
"message",
".",
"code",
"}",
"if",
"(",
"typeof",
"message",
".",
"metadata",
"===",
"'object'",
")",
"{",
"err",
".",
"metadata",
"=",
"createMetadata",
"(",
"message",
".",
"metadata",
")",
"}",
"}",
"const",
"isMsgMD",
"=",
"message",
"instanceof",
"Error",
"if",
"(",
"message",
"&&",
"typeof",
"message",
"===",
"'object'",
"&&",
"!",
"isMsgMD",
")",
"{",
"metadata",
"=",
"message",
"message",
"=",
"''",
"code",
"=",
"null",
"}",
"if",
"(",
"typeof",
"message",
"===",
"'number'",
")",
"{",
"metadata",
"=",
"code",
"code",
"=",
"message",
"message",
"=",
"''",
"}",
"if",
"(",
"code",
"&&",
"typeof",
"code",
"===",
"'object'",
")",
"{",
"metadata",
"=",
"code",
"code",
"=",
"null",
"}",
"if",
"(",
"!",
"metadata",
")",
"{",
"metadata",
"=",
"null",
"}",
"if",
"(",
"typeof",
"message",
"===",
"'string'",
")",
"{",
"err",
".",
"message",
"=",
"message",
"}",
"if",
"(",
"typeof",
"code",
"===",
"'number'",
")",
"{",
"err",
".",
"code",
"=",
"code",
"}",
"if",
"(",
"metadata",
"&&",
"typeof",
"metadata",
"===",
"'object'",
")",
"{",
"if",
"(",
"err",
".",
"metadata",
")",
"{",
"const",
"existingMeta",
"=",
"err",
".",
"metadata",
"&&",
"typeof",
"err",
".",
"metadata",
".",
"getMap",
"===",
"'function'",
"?",
"err",
".",
"metadata",
".",
"getMap",
"(",
")",
":",
"null",
"const",
"md",
"=",
"typeof",
"metadata",
".",
"getMap",
"===",
"'function'",
"?",
"metadata",
".",
"getMap",
"(",
")",
":",
"metadata",
"if",
"(",
"existingMeta",
"||",
"md",
")",
"{",
"err",
".",
"metadata",
"=",
"createMetadata",
"(",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"existingMeta",
"||",
"{",
"}",
",",
"md",
"||",
"{",
"}",
")",
")",
"}",
"}",
"else",
"{",
"err",
".",
"metadata",
"=",
"createMetadata",
"(",
"metadata",
")",
"}",
"}",
"return",
"err",
"}"
] | Actual function that does all the work.
Same as createGRPCError but applies cretion to the existing error.
@param {Error} err The error to apply creation to
@param {String|Number|Error|Object} message See <code>createGRPCError</code> description
@param {Number|Object} code See <code>createGRPCError</code> description
@param {Object} metadata See <code>createGRPCError</code> description
@return {Error} See <code>createGRPCError</code> description | [
"Actual",
"function",
"that",
"does",
"all",
"the",
"work",
".",
"Same",
"as",
"createGRPCError",
"but",
"applies",
"cretion",
"to",
"the",
"existing",
"error",
"."
] | 01909b70c947ce2c28077ec2438e32561167e968 | https://github.com/bojand/grpc-create-error/blob/01909b70c947ce2c28077ec2438e32561167e968/index.js#L67-L131 | train |
neyric/aws-swf | lib/workflow.js | function (config, cb) {
var w = new WorkflowExecution(this.swfClient, this.config);
w.start(config, cb);
return w;
} | javascript | function (config, cb) {
var w = new WorkflowExecution(this.swfClient, this.config);
w.start(config, cb);
return w;
} | [
"function",
"(",
"config",
",",
"cb",
")",
"{",
"var",
"w",
"=",
"new",
"WorkflowExecution",
"(",
"this",
".",
"swfClient",
",",
"this",
".",
"config",
")",
";",
"w",
".",
"start",
"(",
"config",
",",
"cb",
")",
";",
"return",
"w",
";",
"}"
] | Creates a new Workflow instance and start it
@param {Object} config
@param {Function} [cb] - called once the workflow execution started
@returns {WorkflowExecution} workflowExecution - The new instance of the workflow execution | [
"Creates",
"a",
"new",
"Workflow",
"instance",
"and",
"start",
"it"
] | 31b96c9eef313199465b40204a92909996a85c3d | https://github.com/neyric/aws-swf/blob/31b96c9eef313199465b40204a92909996a85c3d/lib/workflow.js#L24-L28 | train |
|
neyric/aws-swf | lib/workflow.js | function (cb) {
this.swfClient.registerWorkflowType({
"domain": this.config.domain,
"name": this.config.workflowType.name,
"version": this.config.workflowType.version
}, cb);
} | javascript | function (cb) {
this.swfClient.registerWorkflowType({
"domain": this.config.domain,
"name": this.config.workflowType.name,
"version": this.config.workflowType.version
}, cb);
} | [
"function",
"(",
"cb",
")",
"{",
"this",
".",
"swfClient",
".",
"registerWorkflowType",
"(",
"{",
"\"domain\"",
":",
"this",
".",
"config",
".",
"domain",
",",
"\"name\"",
":",
"this",
".",
"config",
".",
"workflowType",
".",
"name",
",",
"\"version\"",
":",
"this",
".",
"config",
".",
"workflowType",
".",
"version",
"}",
",",
"cb",
")",
";",
"}"
] | register the workflow
@param {Function} [cb] | [
"register",
"the",
"workflow"
] | 31b96c9eef313199465b40204a92909996a85c3d | https://github.com/neyric/aws-swf/blob/31b96c9eef313199465b40204a92909996a85c3d/lib/workflow.js#L49-L55 | train |
|
origin1tech/sequelize-cmd | lib/compare.js | upToString | function upToString() {
var upStr = '',
ctr = 0,
items = getActions(build.up),
tab,
suffix;
// build the output string for up.
_.forEach(items, function (v,k) {
_.forEach(v, function(item, key){
suffix = (ctr < v.length -1) || (k+1 < items.length) ? '\n' : '';
tab = ctr > 0 ? getTabs(0, true) : '';
upStr += (tab + item + suffix);
ctr += 1;
});
});
return upStr;
} | javascript | function upToString() {
var upStr = '',
ctr = 0,
items = getActions(build.up),
tab,
suffix;
// build the output string for up.
_.forEach(items, function (v,k) {
_.forEach(v, function(item, key){
suffix = (ctr < v.length -1) || (k+1 < items.length) ? '\n' : '';
tab = ctr > 0 ? getTabs(0, true) : '';
upStr += (tab + item + suffix);
ctr += 1;
});
});
return upStr;
} | [
"function",
"upToString",
"(",
")",
"{",
"var",
"upStr",
"=",
"''",
",",
"ctr",
"=",
"0",
",",
"items",
"=",
"getActions",
"(",
"build",
".",
"up",
")",
",",
"tab",
",",
"suffix",
";",
"_",
".",
"forEach",
"(",
"items",
",",
"function",
"(",
"v",
",",
"k",
")",
"{",
"_",
".",
"forEach",
"(",
"v",
",",
"function",
"(",
"item",
",",
"key",
")",
"{",
"suffix",
"=",
"(",
"ctr",
"<",
"v",
".",
"length",
"-",
"1",
")",
"||",
"(",
"k",
"+",
"1",
"<",
"items",
".",
"length",
")",
"?",
"'\\n'",
":",
"\\n",
";",
"''",
"tab",
"=",
"ctr",
">",
"0",
"?",
"getTabs",
"(",
"0",
",",
"true",
")",
":",
"''",
";",
"upStr",
"+=",
"(",
"tab",
"+",
"item",
"+",
"suffix",
")",
";",
"}",
")",
";",
"}",
")",
";",
"ctr",
"+=",
"1",
";",
"}"
] | Concats all up migration events to string.
@private
@memberof Compare
@returns {string} | [
"Concats",
"all",
"up",
"migration",
"events",
"to",
"string",
"."
] | f9e1108997b484cd2d57504a7db9cee3220d46ef | https://github.com/origin1tech/sequelize-cmd/blob/f9e1108997b484cd2d57504a7db9cee3220d46ef/lib/compare.js#L125-L141 | train |
origin1tech/sequelize-cmd | lib/compare.js | downToString | function downToString() {
var dwnStr = '',
ctr = 0,
items = getActions(build.down),
tab,
suffix;
// build the output string for down.
_.forEach(items, function (v,k) {
_.forEach(v, function(item, key){
suffix = (ctr < v.length -1) || (k+1 < items.length) ? '\n' : '';
tab = ctr > 0 ? getTabs(0, true) : '';
dwnStr += (tab + item + suffix);
ctr += 1;
});
});
return dwnStr;
} | javascript | function downToString() {
var dwnStr = '',
ctr = 0,
items = getActions(build.down),
tab,
suffix;
// build the output string for down.
_.forEach(items, function (v,k) {
_.forEach(v, function(item, key){
suffix = (ctr < v.length -1) || (k+1 < items.length) ? '\n' : '';
tab = ctr > 0 ? getTabs(0, true) : '';
dwnStr += (tab + item + suffix);
ctr += 1;
});
});
return dwnStr;
} | [
"function",
"downToString",
"(",
")",
"{",
"var",
"dwnStr",
"=",
"''",
",",
"ctr",
"=",
"0",
",",
"items",
"=",
"getActions",
"(",
"build",
".",
"down",
")",
",",
"tab",
",",
"suffix",
";",
"_",
".",
"forEach",
"(",
"items",
",",
"function",
"(",
"v",
",",
"k",
")",
"{",
"_",
".",
"forEach",
"(",
"v",
",",
"function",
"(",
"item",
",",
"key",
")",
"{",
"suffix",
"=",
"(",
"ctr",
"<",
"v",
".",
"length",
"-",
"1",
")",
"||",
"(",
"k",
"+",
"1",
"<",
"items",
".",
"length",
")",
"?",
"'\\n'",
":",
"\\n",
";",
"''",
"tab",
"=",
"ctr",
">",
"0",
"?",
"getTabs",
"(",
"0",
",",
"true",
")",
":",
"''",
";",
"dwnStr",
"+=",
"(",
"tab",
"+",
"item",
"+",
"suffix",
")",
";",
"}",
")",
";",
"}",
")",
";",
"ctr",
"+=",
"1",
";",
"}"
] | Concats all down migration events to string.
@private
@memberof Compare
@returns {string} | [
"Concats",
"all",
"down",
"migration",
"events",
"to",
"string",
"."
] | f9e1108997b484cd2d57504a7db9cee3220d46ef | https://github.com/origin1tech/sequelize-cmd/blob/f9e1108997b484cd2d57504a7db9cee3220d46ef/lib/compare.js#L149-L165 | train |
origin1tech/sequelize-cmd | lib/compare.js | recurseChildOptions | function recurseChildOptions(obj, level){
var child = '',
len = Object.keys(obj).length,
ctr = 0,
prefix;
level = level || 1;
for(var prop in obj) {
if(obj.hasOwnProperty(prop)){
var tab = getTabs(level +1, true),
val;
prefix = ctr > 0 ? ',\n' : '';
if(_.isPlainObject(obj[prop])){
if(!_.isEmpty(obj[prop])){
var subChild = recurseChildOptions(obj[prop], level + 1);
if(subChild && subChild.length)
child += (tab + prop + ': { \n' + subChild + '\n' + tab + '}');
}
} else {
if(_.isArray(obj[prop])){
val = arrayToString(obj[prop]);
if(val){
tab = ctr === 0 ? getTabs(level) : getTabs(level +1, true);
child += (prefix + tab + prop + ': ' + arrayToString(obj[prop]));
}
} else {
var isFunc;
val = obj[prop];
isFunc = _.isFunction(val);
if(_.isString(val)){
val = "'" + val.toString() + "'";
} else {
val = val.toString();
if(isFunc)
val = funcToString(val, level);
}
child += (prefix + tab + prop + ': ' + val);
}
}
ctr +=1;
}
}
return child;
} | javascript | function recurseChildOptions(obj, level){
var child = '',
len = Object.keys(obj).length,
ctr = 0,
prefix;
level = level || 1;
for(var prop in obj) {
if(obj.hasOwnProperty(prop)){
var tab = getTabs(level +1, true),
val;
prefix = ctr > 0 ? ',\n' : '';
if(_.isPlainObject(obj[prop])){
if(!_.isEmpty(obj[prop])){
var subChild = recurseChildOptions(obj[prop], level + 1);
if(subChild && subChild.length)
child += (tab + prop + ': { \n' + subChild + '\n' + tab + '}');
}
} else {
if(_.isArray(obj[prop])){
val = arrayToString(obj[prop]);
if(val){
tab = ctr === 0 ? getTabs(level) : getTabs(level +1, true);
child += (prefix + tab + prop + ': ' + arrayToString(obj[prop]));
}
} else {
var isFunc;
val = obj[prop];
isFunc = _.isFunction(val);
if(_.isString(val)){
val = "'" + val.toString() + "'";
} else {
val = val.toString();
if(isFunc)
val = funcToString(val, level);
}
child += (prefix + tab + prop + ': ' + val);
}
}
ctr +=1;
}
}
return child;
} | [
"function",
"recurseChildOptions",
"(",
"obj",
",",
"level",
")",
"{",
"var",
"child",
"=",
"''",
",",
"len",
"=",
"Object",
".",
"keys",
"(",
"obj",
")",
".",
"length",
",",
"ctr",
"=",
"0",
",",
"prefix",
";",
"level",
"=",
"level",
"||",
"1",
";",
"for",
"(",
"var",
"prop",
"in",
"obj",
")",
"{",
"if",
"(",
"obj",
".",
"hasOwnProperty",
"(",
"prop",
")",
")",
"{",
"var",
"tab",
"=",
"getTabs",
"(",
"level",
"+",
"1",
",",
"true",
")",
",",
"val",
";",
"prefix",
"=",
"ctr",
">",
"0",
"?",
"',\\n'",
":",
"\\n",
";",
"''",
"if",
"(",
"_",
".",
"isPlainObject",
"(",
"obj",
"[",
"prop",
"]",
")",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isEmpty",
"(",
"obj",
"[",
"prop",
"]",
")",
")",
"{",
"var",
"subChild",
"=",
"recurseChildOptions",
"(",
"obj",
"[",
"prop",
"]",
",",
"level",
"+",
"1",
")",
";",
"if",
"(",
"subChild",
"&&",
"subChild",
".",
"length",
")",
"child",
"+=",
"(",
"tab",
"+",
"prop",
"+",
"': { \\n'",
"+",
"\\n",
"+",
"subChild",
"+",
"'\\n'",
"+",
"\\n",
")",
";",
"}",
"}",
"else",
"tab",
"}",
"}",
"'}'",
"}"
] | Recurse child options concat to string.
@private
@memberof Compare
@param {object} obj - the child object.
@returns {string} | [
"Recurse",
"child",
"options",
"concat",
"to",
"string",
"."
] | f9e1108997b484cd2d57504a7db9cee3220d46ef | https://github.com/origin1tech/sequelize-cmd/blob/f9e1108997b484cd2d57504a7db9cee3220d46ef/lib/compare.js#L174-L216 | train |
origin1tech/sequelize-cmd | lib/compare.js | parseOptions | function parseOptions(obj) {
var ctr = 0,
tab = getTabs(1, true);
for(var prop in obj) {
if(obj.hasOwnProperty(prop)){
if(_.isPlainObject(obj[prop])){
if(!_.isEmpty(obj[prop])){
var child = recurseChildOptions(obj[prop]);
if(child && child.length)
build.options.push(tab + prop + ': { \n' + child + ' \n' + tab + '}');
}
} else {
if(_.isArray(obj[prop])){
build.options.push(tab + prop + ': ' + arrayToString(obj[prop]));
} else {
var val = obj[prop];
if(_.isString(val))
val = qwrap(val);
else
val = val.toString();
build.options.push(tab + prop + ': ' + val);
}
}
}
ctr +=1;
}
} | javascript | function parseOptions(obj) {
var ctr = 0,
tab = getTabs(1, true);
for(var prop in obj) {
if(obj.hasOwnProperty(prop)){
if(_.isPlainObject(obj[prop])){
if(!_.isEmpty(obj[prop])){
var child = recurseChildOptions(obj[prop]);
if(child && child.length)
build.options.push(tab + prop + ': { \n' + child + ' \n' + tab + '}');
}
} else {
if(_.isArray(obj[prop])){
build.options.push(tab + prop + ': ' + arrayToString(obj[prop]));
} else {
var val = obj[prop];
if(_.isString(val))
val = qwrap(val);
else
val = val.toString();
build.options.push(tab + prop + ': ' + val);
}
}
}
ctr +=1;
}
} | [
"function",
"parseOptions",
"(",
"obj",
")",
"{",
"var",
"ctr",
"=",
"0",
",",
"tab",
"=",
"getTabs",
"(",
"1",
",",
"true",
")",
";",
"for",
"(",
"var",
"prop",
"in",
"obj",
")",
"{",
"if",
"(",
"obj",
".",
"hasOwnProperty",
"(",
"prop",
")",
")",
"{",
"if",
"(",
"_",
".",
"isPlainObject",
"(",
"obj",
"[",
"prop",
"]",
")",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isEmpty",
"(",
"obj",
"[",
"prop",
"]",
")",
")",
"{",
"var",
"child",
"=",
"recurseChildOptions",
"(",
"obj",
"[",
"prop",
"]",
")",
";",
"if",
"(",
"child",
"&&",
"child",
".",
"length",
")",
"build",
".",
"options",
".",
"push",
"(",
"tab",
"+",
"prop",
"+",
"': { \\n'",
"+",
"\\n",
"+",
"child",
"+",
"' \\n'",
"+",
"\\n",
")",
";",
"}",
"}",
"else",
"tab",
"}",
"'}'",
"}",
"}"
] | Parse options for create model migrations.
@private
@memberof Compare
@param {object} obj - the object of options. | [
"Parse",
"options",
"for",
"create",
"model",
"migrations",
"."
] | f9e1108997b484cd2d57504a7db9cee3220d46ef | https://github.com/origin1tech/sequelize-cmd/blob/f9e1108997b484cd2d57504a7db9cee3220d46ef/lib/compare.js#L224-L251 | train |
origin1tech/sequelize-cmd | lib/compare.js | attributesToString | function attributesToString(obj, prevObj, level) {
var attrs = '',
prefix,
tab;
level = level || 1;
tab = getTabs(level, true);
_.forEach(obj, function (v, k) {
if(excludeAttrs.indexOf(k) === -1){
var prev = prevObj && prevObj[k] !== undefined ? prevObj[k] : undefined;
prefix = attrs.length ? ',\n' : '';
if(_.isPlainObject(v)){
var subAttr = attributesToString(v, prev, level +1);
if(subAttr && subAttr.length)
attrs += (prefix + tab + k + ': {\n' + subAttr + '\n' + tab + '}');
} else {
if(prev !== v){
var val = k === 'type' ? 'types.' + v : v;
if(_.isArray(val))
val = arrayToString(val);
if(_.isFunction(val)){
val = funcToString(val.toString(), 2);
}
attrs += (prefix + tab + k + ': ' + val);
}
}
}
});
return attrs;
} | javascript | function attributesToString(obj, prevObj, level) {
var attrs = '',
prefix,
tab;
level = level || 1;
tab = getTabs(level, true);
_.forEach(obj, function (v, k) {
if(excludeAttrs.indexOf(k) === -1){
var prev = prevObj && prevObj[k] !== undefined ? prevObj[k] : undefined;
prefix = attrs.length ? ',\n' : '';
if(_.isPlainObject(v)){
var subAttr = attributesToString(v, prev, level +1);
if(subAttr && subAttr.length)
attrs += (prefix + tab + k + ': {\n' + subAttr + '\n' + tab + '}');
} else {
if(prev !== v){
var val = k === 'type' ? 'types.' + v : v;
if(_.isArray(val))
val = arrayToString(val);
if(_.isFunction(val)){
val = funcToString(val.toString(), 2);
}
attrs += (prefix + tab + k + ': ' + val);
}
}
}
});
return attrs;
} | [
"function",
"attributesToString",
"(",
"obj",
",",
"prevObj",
",",
"level",
")",
"{",
"var",
"attrs",
"=",
"''",
",",
"prefix",
",",
"tab",
";",
"level",
"=",
"level",
"||",
"1",
";",
"tab",
"=",
"getTabs",
"(",
"level",
",",
"true",
")",
";",
"_",
".",
"forEach",
"(",
"obj",
",",
"function",
"(",
"v",
",",
"k",
")",
"{",
"if",
"(",
"excludeAttrs",
".",
"indexOf",
"(",
"k",
")",
"===",
"-",
"1",
")",
"{",
"var",
"prev",
"=",
"prevObj",
"&&",
"prevObj",
"[",
"k",
"]",
"!==",
"undefined",
"?",
"prevObj",
"[",
"k",
"]",
":",
"undefined",
";",
"prefix",
"=",
"attrs",
".",
"length",
"?",
"',\\n'",
":",
"\\n",
";",
"''",
"}",
"}",
")",
";",
"if",
"(",
"_",
".",
"isPlainObject",
"(",
"v",
")",
")",
"{",
"var",
"subAttr",
"=",
"attributesToString",
"(",
"v",
",",
"prev",
",",
"level",
"+",
"1",
")",
";",
"if",
"(",
"subAttr",
"&&",
"subAttr",
".",
"length",
")",
"attrs",
"+=",
"(",
"prefix",
"+",
"tab",
"+",
"k",
"+",
"': {\\n'",
"+",
"\\n",
"+",
"subAttr",
"+",
"'\\n'",
"+",
"\\n",
")",
";",
"}",
"else",
"tab",
"}"
] | Converts a property's atttributes to string.
@private
@memberof Compare
@param {object} obj - the object of attributes.
@param {object} prevObj - the previous object of attributes from last snapshot.
@returns {string} | [
"Converts",
"a",
"property",
"s",
"atttributes",
"to",
"string",
"."
] | f9e1108997b484cd2d57504a7db9cee3220d46ef | https://github.com/origin1tech/sequelize-cmd/blob/f9e1108997b484cd2d57504a7db9cee3220d46ef/lib/compare.js#L261-L290 | train |
origin1tech/sequelize-cmd | lib/utils/helpers.js | strToCase | function strToCase(str, casing) {
casing = casing === 'capitalize' ? 'first' : casing;
if (!casing) return str;
casing = casing || 'first';
if (casing === 'lower')
return str.toLowerCase();
if (casing === 'upper')
return str.toUpperCase();
if (casing == 'title')
return str.replace(/\w\S*/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
if (casing == 'first')
return str.charAt(0).toUpperCase() + str.slice(1);
if (casing == 'camel') {
return str.toLowerCase().replace(/-(.)/g, function (match, group1) {
return group1.toUpperCase();
});
}
if (casing == 'pascal')
return str.replace(/\w+/g, function (w) {
return w[0].toUpperCase() + w.slice(1).toLowerCase();
});
return str;
} | javascript | function strToCase(str, casing) {
casing = casing === 'capitalize' ? 'first' : casing;
if (!casing) return str;
casing = casing || 'first';
if (casing === 'lower')
return str.toLowerCase();
if (casing === 'upper')
return str.toUpperCase();
if (casing == 'title')
return str.replace(/\w\S*/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
if (casing == 'first')
return str.charAt(0).toUpperCase() + str.slice(1);
if (casing == 'camel') {
return str.toLowerCase().replace(/-(.)/g, function (match, group1) {
return group1.toUpperCase();
});
}
if (casing == 'pascal')
return str.replace(/\w+/g, function (w) {
return w[0].toUpperCase() + w.slice(1).toLowerCase();
});
return str;
} | [
"function",
"strToCase",
"(",
"str",
",",
"casing",
")",
"{",
"casing",
"=",
"casing",
"===",
"'capitalize'",
"?",
"'first'",
":",
"casing",
";",
"if",
"(",
"!",
"casing",
")",
"return",
"str",
";",
"casing",
"=",
"casing",
"||",
"'first'",
";",
"if",
"(",
"casing",
"===",
"'lower'",
")",
"return",
"str",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"casing",
"===",
"'upper'",
")",
"return",
"str",
".",
"toUpperCase",
"(",
")",
";",
"if",
"(",
"casing",
"==",
"'title'",
")",
"return",
"str",
".",
"replace",
"(",
"/",
"\\w\\S*",
"/",
"g",
",",
"function",
"(",
"txt",
")",
"{",
"return",
"txt",
".",
"charAt",
"(",
"0",
")",
".",
"toUpperCase",
"(",
")",
"+",
"txt",
".",
"substr",
"(",
"1",
")",
".",
"toLowerCase",
"(",
")",
";",
"}",
")",
";",
"if",
"(",
"casing",
"==",
"'first'",
")",
"return",
"str",
".",
"charAt",
"(",
"0",
")",
".",
"toUpperCase",
"(",
")",
"+",
"str",
".",
"slice",
"(",
"1",
")",
";",
"if",
"(",
"casing",
"==",
"'camel'",
")",
"{",
"return",
"str",
".",
"toLowerCase",
"(",
")",
".",
"replace",
"(",
"/",
"-(.)",
"/",
"g",
",",
"function",
"(",
"match",
",",
"group1",
")",
"{",
"return",
"group1",
".",
"toUpperCase",
"(",
")",
";",
"}",
")",
";",
"}",
"if",
"(",
"casing",
"==",
"'pascal'",
")",
"return",
"str",
".",
"replace",
"(",
"/",
"\\w+",
"/",
"g",
",",
"function",
"(",
"w",
")",
"{",
"return",
"w",
"[",
"0",
"]",
".",
"toUpperCase",
"(",
")",
"+",
"w",
".",
"slice",
"(",
"1",
")",
".",
"toLowerCase",
"(",
")",
";",
"}",
")",
";",
"return",
"str",
";",
"}"
] | Converts the case of a string.
@memberof Helpers
@param {string} str - the string to convert.
@param {string} casing - case to convert to ex: 'first', 'upper', 'title', 'camel', 'pascal' | [
"Converts",
"the",
"case",
"of",
"a",
"string",
"."
] | f9e1108997b484cd2d57504a7db9cee3220d46ef | https://github.com/origin1tech/sequelize-cmd/blob/f9e1108997b484cd2d57504a7db9cee3220d46ef/lib/utils/helpers.js#L35-L61 | train |
origin1tech/sequelize-cmd | lib/utils/helpers.js | camelToUnderscore | function camelToUnderscore(str) {
return s.split(/(?=[A-Z])/).map(function (p) {
return p.charAt(0).toUpperCase() + p.slice(1);
}).join('_');
} | javascript | function camelToUnderscore(str) {
return s.split(/(?=[A-Z])/).map(function (p) {
return p.charAt(0).toUpperCase() + p.slice(1);
}).join('_');
} | [
"function",
"camelToUnderscore",
"(",
"str",
")",
"{",
"return",
"s",
".",
"split",
"(",
"/",
"(?=[A-Z])",
"/",
")",
".",
"map",
"(",
"function",
"(",
"p",
")",
"{",
"return",
"p",
".",
"charAt",
"(",
"0",
")",
".",
"toUpperCase",
"(",
")",
"+",
"p",
".",
"slice",
"(",
"1",
")",
";",
"}",
")",
".",
"join",
"(",
"'_'",
")",
";",
"}"
] | Converts camel case string to underscore.
@param {string} str - the string to convert.
@returns {string} | [
"Converts",
"camel",
"case",
"string",
"to",
"underscore",
"."
] | f9e1108997b484cd2d57504a7db9cee3220d46ef | https://github.com/origin1tech/sequelize-cmd/blob/f9e1108997b484cd2d57504a7db9cee3220d46ef/lib/utils/helpers.js#L68-L72 | train |
origin1tech/sequelize-cmd | lib/utils/helpers.js | normalizeAttributes | function normalizeAttributes(attrs, strip) {
// map for converting SQL types to Sequelize DataTypes.
var map = {
TINYINT: 'BOOLEAN',
DATETIME: 'DATE',
TIMESTAMP: 'DATE',
'VARCHAR BINARY': 'STRING.BINARY',
'TINYBLOB': 'BLOB',
VARCHAR: 'STRING[LEN]',
'INTEGER UNSIGNED ZEORFILL': 'INTEGER[LEN].UNSIGNED.ZEROFILL',
'INTEGER UNSIGNED': 'INTEGER[LEN].UNSIGNED',
'INTEGER ZEROFILL': 'INTEGER[LEN].ZEROFILL',
INTEGER: 'INTEGER[LEN]',
'FLOAT UNSIGNED ZEORFILL': 'FLOAT[LEN].UNSIGNED.ZEROFILL',
'FLOAT ZEROFILL': 'FLOAT[LEN].ZEROFILL',
'FLOAT UNSIGNED': 'FLOAT[LEN].UNSIGNED',
FLOAT: 'FLOAT[LEN]',
'BIGINT UNSIGNED ZEORFILL': 'BIGINT[LEN].UNSIGNED.ZEROFILL',
'BIGINT ZEROFILL': 'BIGINT[LEN].ZEROFILL',
'BIGINT UNSIGNED': 'BIGINT[LEN].UNSIGNED',
BIGINT: 'BIGINT[LEN]',
DECIMAL: 'DECIMAL[LEN]',
ENUM: 'ENUM'
},
mapKeys = Object.keys(map);
strip = strip || [];
strip.push('Model');
// convert and format to Sequelize Model Type.
function getType(type, len, name) {
if(!type) return undefined;
type = type.split('(')[0];
if(map[type]){
var tmp = map[type];
if(len && !_.contains([255, 11], len)) len = '(' + len + ')';
else len = '';
type = tmp.replace('[LEN]', len);
}
return type;
}
// iterate properties.
for(var prop in attrs) {
if(attrs.hasOwnProperty(prop)){
var attr = attrs[prop],
type = attr.type,
prec = type._precision && type._scale ? type._precision + ',' + type._scale : false,
len = prec ? prec : type._length || false;
// strip properties.
strip.forEach(function (s) {
if(attr[s]) delete attr[s];
});
if(attr.validate && attr.validate._checkEnum)
type = 'ENUM';
if(!type._binary && type._length)
type = 'VARCHAR';
if(type._binary)
type = 'VARCHAR BINARY';
if(_.contains(['INTEGER', 'FLOAT', 'BIGINT'], type._typeName)){
var tmp = '';
tmp = type._unsigned ? tmp += ' UNSIGNED' : tmp;
tmp = type._zerofill ? tmp += ' ZEROFILL' : tmp;
type = type._typeName + tmp;
}
if(_.isObject(type))
type = type._typeName;
attrs[prop].type = getType(type, len, attr.fieldName);
}
}
return attrs;
} | javascript | function normalizeAttributes(attrs, strip) {
// map for converting SQL types to Sequelize DataTypes.
var map = {
TINYINT: 'BOOLEAN',
DATETIME: 'DATE',
TIMESTAMP: 'DATE',
'VARCHAR BINARY': 'STRING.BINARY',
'TINYBLOB': 'BLOB',
VARCHAR: 'STRING[LEN]',
'INTEGER UNSIGNED ZEORFILL': 'INTEGER[LEN].UNSIGNED.ZEROFILL',
'INTEGER UNSIGNED': 'INTEGER[LEN].UNSIGNED',
'INTEGER ZEROFILL': 'INTEGER[LEN].ZEROFILL',
INTEGER: 'INTEGER[LEN]',
'FLOAT UNSIGNED ZEORFILL': 'FLOAT[LEN].UNSIGNED.ZEROFILL',
'FLOAT ZEROFILL': 'FLOAT[LEN].ZEROFILL',
'FLOAT UNSIGNED': 'FLOAT[LEN].UNSIGNED',
FLOAT: 'FLOAT[LEN]',
'BIGINT UNSIGNED ZEORFILL': 'BIGINT[LEN].UNSIGNED.ZEROFILL',
'BIGINT ZEROFILL': 'BIGINT[LEN].ZEROFILL',
'BIGINT UNSIGNED': 'BIGINT[LEN].UNSIGNED',
BIGINT: 'BIGINT[LEN]',
DECIMAL: 'DECIMAL[LEN]',
ENUM: 'ENUM'
},
mapKeys = Object.keys(map);
strip = strip || [];
strip.push('Model');
// convert and format to Sequelize Model Type.
function getType(type, len, name) {
if(!type) return undefined;
type = type.split('(')[0];
if(map[type]){
var tmp = map[type];
if(len && !_.contains([255, 11], len)) len = '(' + len + ')';
else len = '';
type = tmp.replace('[LEN]', len);
}
return type;
}
// iterate properties.
for(var prop in attrs) {
if(attrs.hasOwnProperty(prop)){
var attr = attrs[prop],
type = attr.type,
prec = type._precision && type._scale ? type._precision + ',' + type._scale : false,
len = prec ? prec : type._length || false;
// strip properties.
strip.forEach(function (s) {
if(attr[s]) delete attr[s];
});
if(attr.validate && attr.validate._checkEnum)
type = 'ENUM';
if(!type._binary && type._length)
type = 'VARCHAR';
if(type._binary)
type = 'VARCHAR BINARY';
if(_.contains(['INTEGER', 'FLOAT', 'BIGINT'], type._typeName)){
var tmp = '';
tmp = type._unsigned ? tmp += ' UNSIGNED' : tmp;
tmp = type._zerofill ? tmp += ' ZEROFILL' : tmp;
type = type._typeName + tmp;
}
if(_.isObject(type))
type = type._typeName;
attrs[prop].type = getType(type, len, attr.fieldName);
}
}
return attrs;
} | [
"function",
"normalizeAttributes",
"(",
"attrs",
",",
"strip",
")",
"{",
"var",
"map",
"=",
"{",
"TINYINT",
":",
"'BOOLEAN'",
",",
"DATETIME",
":",
"'DATE'",
",",
"TIMESTAMP",
":",
"'DATE'",
",",
"'VARCHAR BINARY'",
":",
"'STRING.BINARY'",
",",
"'TINYBLOB'",
":",
"'BLOB'",
",",
"VARCHAR",
":",
"'STRING[LEN]'",
",",
"'INTEGER UNSIGNED ZEORFILL'",
":",
"'INTEGER[LEN].UNSIGNED.ZEROFILL'",
",",
"'INTEGER UNSIGNED'",
":",
"'INTEGER[LEN].UNSIGNED'",
",",
"'INTEGER ZEROFILL'",
":",
"'INTEGER[LEN].ZEROFILL'",
",",
"INTEGER",
":",
"'INTEGER[LEN]'",
",",
"'FLOAT UNSIGNED ZEORFILL'",
":",
"'FLOAT[LEN].UNSIGNED.ZEROFILL'",
",",
"'FLOAT ZEROFILL'",
":",
"'FLOAT[LEN].ZEROFILL'",
",",
"'FLOAT UNSIGNED'",
":",
"'FLOAT[LEN].UNSIGNED'",
",",
"FLOAT",
":",
"'FLOAT[LEN]'",
",",
"'BIGINT UNSIGNED ZEORFILL'",
":",
"'BIGINT[LEN].UNSIGNED.ZEROFILL'",
",",
"'BIGINT ZEROFILL'",
":",
"'BIGINT[LEN].ZEROFILL'",
",",
"'BIGINT UNSIGNED'",
":",
"'BIGINT[LEN].UNSIGNED'",
",",
"BIGINT",
":",
"'BIGINT[LEN]'",
",",
"DECIMAL",
":",
"'DECIMAL[LEN]'",
",",
"ENUM",
":",
"'ENUM'",
"}",
",",
"mapKeys",
"=",
"Object",
".",
"keys",
"(",
"map",
")",
";",
"strip",
"=",
"strip",
"||",
"[",
"]",
";",
"strip",
".",
"push",
"(",
"'Model'",
")",
";",
"function",
"getType",
"(",
"type",
",",
"len",
",",
"name",
")",
"{",
"if",
"(",
"!",
"type",
")",
"return",
"undefined",
";",
"type",
"=",
"type",
".",
"split",
"(",
"'('",
")",
"[",
"0",
"]",
";",
"if",
"(",
"map",
"[",
"type",
"]",
")",
"{",
"var",
"tmp",
"=",
"map",
"[",
"type",
"]",
";",
"if",
"(",
"len",
"&&",
"!",
"_",
".",
"contains",
"(",
"[",
"255",
",",
"11",
"]",
",",
"len",
")",
")",
"len",
"=",
"'('",
"+",
"len",
"+",
"')'",
";",
"else",
"len",
"=",
"''",
";",
"type",
"=",
"tmp",
".",
"replace",
"(",
"'[LEN]'",
",",
"len",
")",
";",
"}",
"return",
"type",
";",
"}",
"for",
"(",
"var",
"prop",
"in",
"attrs",
")",
"{",
"if",
"(",
"attrs",
".",
"hasOwnProperty",
"(",
"prop",
")",
")",
"{",
"var",
"attr",
"=",
"attrs",
"[",
"prop",
"]",
",",
"type",
"=",
"attr",
".",
"type",
",",
"prec",
"=",
"type",
".",
"_precision",
"&&",
"type",
".",
"_scale",
"?",
"type",
".",
"_precision",
"+",
"','",
"+",
"type",
".",
"_scale",
":",
"false",
",",
"len",
"=",
"prec",
"?",
"prec",
":",
"type",
".",
"_length",
"||",
"false",
";",
"strip",
".",
"forEach",
"(",
"function",
"(",
"s",
")",
"{",
"if",
"(",
"attr",
"[",
"s",
"]",
")",
"delete",
"attr",
"[",
"s",
"]",
";",
"}",
")",
";",
"if",
"(",
"attr",
".",
"validate",
"&&",
"attr",
".",
"validate",
".",
"_checkEnum",
")",
"type",
"=",
"'ENUM'",
";",
"if",
"(",
"!",
"type",
".",
"_binary",
"&&",
"type",
".",
"_length",
")",
"type",
"=",
"'VARCHAR'",
";",
"if",
"(",
"type",
".",
"_binary",
")",
"type",
"=",
"'VARCHAR BINARY'",
";",
"if",
"(",
"_",
".",
"contains",
"(",
"[",
"'INTEGER'",
",",
"'FLOAT'",
",",
"'BIGINT'",
"]",
",",
"type",
".",
"_typeName",
")",
")",
"{",
"var",
"tmp",
"=",
"''",
";",
"tmp",
"=",
"type",
".",
"_unsigned",
"?",
"tmp",
"+=",
"' UNSIGNED'",
":",
"tmp",
";",
"tmp",
"=",
"type",
".",
"_zerofill",
"?",
"tmp",
"+=",
"' ZEROFILL'",
":",
"tmp",
";",
"type",
"=",
"type",
".",
"_typeName",
"+",
"tmp",
";",
"}",
"if",
"(",
"_",
".",
"isObject",
"(",
"type",
")",
")",
"type",
"=",
"type",
".",
"_typeName",
";",
"attrs",
"[",
"prop",
"]",
".",
"type",
"=",
"getType",
"(",
"type",
",",
"len",
",",
"attr",
".",
"fieldName",
")",
";",
"}",
"}",
"return",
"attrs",
";",
"}"
] | Normalize property attributes primarily the type.
@memberof Helpers
@param {object} attrs - the attributes to be parsed.
@param {array} strip - an array of keys to strip/remove.
@returns {object} | [
"Normalize",
"property",
"attributes",
"primarily",
"the",
"type",
"."
] | f9e1108997b484cd2d57504a7db9cee3220d46ef | https://github.com/origin1tech/sequelize-cmd/blob/f9e1108997b484cd2d57504a7db9cee3220d46ef/lib/utils/helpers.js#L146-L234 | train |
origin1tech/sequelize-cmd | lib/utils/helpers.js | getType | function getType(type, len, name) {
if(!type) return undefined;
type = type.split('(')[0];
if(map[type]){
var tmp = map[type];
if(len && !_.contains([255, 11], len)) len = '(' + len + ')';
else len = '';
type = tmp.replace('[LEN]', len);
}
return type;
} | javascript | function getType(type, len, name) {
if(!type) return undefined;
type = type.split('(')[0];
if(map[type]){
var tmp = map[type];
if(len && !_.contains([255, 11], len)) len = '(' + len + ')';
else len = '';
type = tmp.replace('[LEN]', len);
}
return type;
} | [
"function",
"getType",
"(",
"type",
",",
"len",
",",
"name",
")",
"{",
"if",
"(",
"!",
"type",
")",
"return",
"undefined",
";",
"type",
"=",
"type",
".",
"split",
"(",
"'('",
")",
"[",
"0",
"]",
";",
"if",
"(",
"map",
"[",
"type",
"]",
")",
"{",
"var",
"tmp",
"=",
"map",
"[",
"type",
"]",
";",
"if",
"(",
"len",
"&&",
"!",
"_",
".",
"contains",
"(",
"[",
"255",
",",
"11",
"]",
",",
"len",
")",
")",
"len",
"=",
"'('",
"+",
"len",
"+",
"')'",
";",
"else",
"len",
"=",
"''",
";",
"type",
"=",
"tmp",
".",
"replace",
"(",
"'[LEN]'",
",",
"len",
")",
";",
"}",
"return",
"type",
";",
"}"
] | convert and format to Sequelize Model Type. | [
"convert",
"and",
"format",
"to",
"Sequelize",
"Model",
"Type",
"."
] | f9e1108997b484cd2d57504a7db9cee3220d46ef | https://github.com/origin1tech/sequelize-cmd/blob/f9e1108997b484cd2d57504a7db9cee3220d46ef/lib/utils/helpers.js#L177-L190 | train |
origin1tech/sequelize-cmd | lib/utils/helpers.js | normalizeOptions | function normalizeOptions(options, include) {
_.forEach(options, function (v,k) {
if(!_.contains(include, k))
delete options[k];
});
return options;
} | javascript | function normalizeOptions(options, include) {
_.forEach(options, function (v,k) {
if(!_.contains(include, k))
delete options[k];
});
return options;
} | [
"function",
"normalizeOptions",
"(",
"options",
",",
"include",
")",
"{",
"_",
".",
"forEach",
"(",
"options",
",",
"function",
"(",
"v",
",",
"k",
")",
"{",
"if",
"(",
"!",
"_",
".",
"contains",
"(",
"include",
",",
"k",
")",
")",
"delete",
"options",
"[",
"k",
"]",
";",
"}",
")",
";",
"return",
"options",
";",
"}"
] | Normalize options including only required.
@memberof Helpers
@param {object} options - the options object.
@param {array} include - an array of keys to include.
@returns {object} | [
"Normalize",
"options",
"including",
"only",
"required",
"."
] | f9e1108997b484cd2d57504a7db9cee3220d46ef | https://github.com/origin1tech/sequelize-cmd/blob/f9e1108997b484cd2d57504a7db9cee3220d46ef/lib/utils/helpers.js#L243-L249 | train |
node-ffi-napi/ref-array-di | lib/array.js | ArrayType | function ArrayType (data, length) {
if (!(this instanceof ArrayType)) {
return new ArrayType(data, length)
}
debug('creating new array instance')
ArrayIndex.call(this)
var item_size = ArrayType.BYTES_PER_ELEMENT
if (0 === arguments.length) {
// new IntArray()
// use the "fixedLength" if provided, otherwise throw an Error
if (fixedLength > 0) {
this.length = fixedLength
this.buffer = new Buffer(this.length * item_size)
} else {
throw new Error('A "length", "array" or "buffer" must be passed as the first argument')
}
} else if ('number' == typeof data) {
// new IntArray(69)
this.length = data
this.buffer = new Buffer(this.length * item_size)
} else if (isArray(data)) {
// new IntArray([ 1, 2, 3, 4, 5 ], {len})
// use optional "length" if provided, otherwise use "fixedLength, otherwise
// use the Array's .length
var len = 0
if (null != length) {
len = length
} else if (fixedLength > 0) {
len = fixedLength
} else {
len = data.length
}
if (data.length < len) {
throw new Error('array length must be at least ' + len + ', got ' + data.length)
}
this.length = len
this.buffer = new Buffer(len * item_size)
for (var i = 0; i < len; i++) {
this[i] = data[i]
}
} else if (Buffer.isBuffer(data)) {
// new IntArray(Buffer(8))
var len = 0
if (null != length) {
len = length
} else if (fixedLength > 0) {
len = fixedLength
} else {
len = data.length / item_size | 0
}
var expectedLength = item_size * len
this.length = len
if (data.length != expectedLength) {
if (data.length < expectedLength) {
throw new Error('buffer length must be at least ' + expectedLength + ', got ' + data.length)
} else {
debug('resizing buffer from %d to %d', data.length, expectedLength)
data = data.slice(0, expectedLength)
}
}
this.buffer = data
}
} | javascript | function ArrayType (data, length) {
if (!(this instanceof ArrayType)) {
return new ArrayType(data, length)
}
debug('creating new array instance')
ArrayIndex.call(this)
var item_size = ArrayType.BYTES_PER_ELEMENT
if (0 === arguments.length) {
// new IntArray()
// use the "fixedLength" if provided, otherwise throw an Error
if (fixedLength > 0) {
this.length = fixedLength
this.buffer = new Buffer(this.length * item_size)
} else {
throw new Error('A "length", "array" or "buffer" must be passed as the first argument')
}
} else if ('number' == typeof data) {
// new IntArray(69)
this.length = data
this.buffer = new Buffer(this.length * item_size)
} else if (isArray(data)) {
// new IntArray([ 1, 2, 3, 4, 5 ], {len})
// use optional "length" if provided, otherwise use "fixedLength, otherwise
// use the Array's .length
var len = 0
if (null != length) {
len = length
} else if (fixedLength > 0) {
len = fixedLength
} else {
len = data.length
}
if (data.length < len) {
throw new Error('array length must be at least ' + len + ', got ' + data.length)
}
this.length = len
this.buffer = new Buffer(len * item_size)
for (var i = 0; i < len; i++) {
this[i] = data[i]
}
} else if (Buffer.isBuffer(data)) {
// new IntArray(Buffer(8))
var len = 0
if (null != length) {
len = length
} else if (fixedLength > 0) {
len = fixedLength
} else {
len = data.length / item_size | 0
}
var expectedLength = item_size * len
this.length = len
if (data.length != expectedLength) {
if (data.length < expectedLength) {
throw new Error('buffer length must be at least ' + expectedLength + ', got ' + data.length)
} else {
debug('resizing buffer from %d to %d', data.length, expectedLength)
data = data.slice(0, expectedLength)
}
}
this.buffer = data
}
} | [
"function",
"ArrayType",
"(",
"data",
",",
"length",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"ArrayType",
")",
")",
"{",
"return",
"new",
"ArrayType",
"(",
"data",
",",
"length",
")",
"}",
"debug",
"(",
"'creating new array instance'",
")",
"ArrayIndex",
".",
"call",
"(",
"this",
")",
"var",
"item_size",
"=",
"ArrayType",
".",
"BYTES_PER_ELEMENT",
"if",
"(",
"0",
"===",
"arguments",
".",
"length",
")",
"{",
"if",
"(",
"fixedLength",
">",
"0",
")",
"{",
"this",
".",
"length",
"=",
"fixedLength",
"this",
".",
"buffer",
"=",
"new",
"Buffer",
"(",
"this",
".",
"length",
"*",
"item_size",
")",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'A \"length\", \"array\" or \"buffer\" must be passed as the first argument'",
")",
"}",
"}",
"else",
"if",
"(",
"'number'",
"==",
"typeof",
"data",
")",
"{",
"this",
".",
"length",
"=",
"data",
"this",
".",
"buffer",
"=",
"new",
"Buffer",
"(",
"this",
".",
"length",
"*",
"item_size",
")",
"}",
"else",
"if",
"(",
"isArray",
"(",
"data",
")",
")",
"{",
"var",
"len",
"=",
"0",
"if",
"(",
"null",
"!=",
"length",
")",
"{",
"len",
"=",
"length",
"}",
"else",
"if",
"(",
"fixedLength",
">",
"0",
")",
"{",
"len",
"=",
"fixedLength",
"}",
"else",
"{",
"len",
"=",
"data",
".",
"length",
"}",
"if",
"(",
"data",
".",
"length",
"<",
"len",
")",
"{",
"throw",
"new",
"Error",
"(",
"'array length must be at least '",
"+",
"len",
"+",
"', got '",
"+",
"data",
".",
"length",
")",
"}",
"this",
".",
"length",
"=",
"len",
"this",
".",
"buffer",
"=",
"new",
"Buffer",
"(",
"len",
"*",
"item_size",
")",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"this",
"[",
"i",
"]",
"=",
"data",
"[",
"i",
"]",
"}",
"}",
"else",
"if",
"(",
"Buffer",
".",
"isBuffer",
"(",
"data",
")",
")",
"{",
"var",
"len",
"=",
"0",
"if",
"(",
"null",
"!=",
"length",
")",
"{",
"len",
"=",
"length",
"}",
"else",
"if",
"(",
"fixedLength",
">",
"0",
")",
"{",
"len",
"=",
"fixedLength",
"}",
"else",
"{",
"len",
"=",
"data",
".",
"length",
"/",
"item_size",
"|",
"0",
"}",
"var",
"expectedLength",
"=",
"item_size",
"*",
"len",
"this",
".",
"length",
"=",
"len",
"if",
"(",
"data",
".",
"length",
"!=",
"expectedLength",
")",
"{",
"if",
"(",
"data",
".",
"length",
"<",
"expectedLength",
")",
"{",
"throw",
"new",
"Error",
"(",
"'buffer length must be at least '",
"+",
"expectedLength",
"+",
"', got '",
"+",
"data",
".",
"length",
")",
"}",
"else",
"{",
"debug",
"(",
"'resizing buffer from %d to %d'",
",",
"data",
".",
"length",
",",
"expectedLength",
")",
"data",
"=",
"data",
".",
"slice",
"(",
"0",
",",
"expectedLength",
")",
"}",
"}",
"this",
".",
"buffer",
"=",
"data",
"}",
"}"
] | This is the ArrayType "constructor" that gets returned. | [
"This",
"is",
"the",
"ArrayType",
"constructor",
"that",
"gets",
"returned",
"."
] | a0699e21be2d2dab80fb356bb67cf2244c33ea52 | https://github.com/node-ffi-napi/ref-array-di/blob/a0699e21be2d2dab80fb356bb67cf2244c33ea52/lib/array.js#L28-L90 | train |
node-ffi-napi/ref-array-di | lib/array.js | set | function set (buffer, offset, value) {
debug('Array "type" setter for buffer at offset', buffer, offset, value)
var array = this.get(buffer, offset)
var isInstance = value instanceof this
if (isInstance || isArray(value)) {
for (var i = 0; i < value.length; i++) {
array[i] = value[i]
}
} else {
throw new Error('not sure how to set into Array: ' + value)
}
} | javascript | function set (buffer, offset, value) {
debug('Array "type" setter for buffer at offset', buffer, offset, value)
var array = this.get(buffer, offset)
var isInstance = value instanceof this
if (isInstance || isArray(value)) {
for (var i = 0; i < value.length; i++) {
array[i] = value[i]
}
} else {
throw new Error('not sure how to set into Array: ' + value)
}
} | [
"function",
"set",
"(",
"buffer",
",",
"offset",
",",
"value",
")",
"{",
"debug",
"(",
"'Array \"type\" setter for buffer at offset'",
",",
"buffer",
",",
"offset",
",",
"value",
")",
"var",
"array",
"=",
"this",
".",
"get",
"(",
"buffer",
",",
"offset",
")",
"var",
"isInstance",
"=",
"value",
"instanceof",
"this",
"if",
"(",
"isInstance",
"||",
"isArray",
"(",
"value",
")",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"value",
".",
"length",
";",
"i",
"++",
")",
"{",
"array",
"[",
"i",
"]",
"=",
"value",
"[",
"i",
"]",
"}",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'not sure how to set into Array: '",
"+",
"value",
")",
"}",
"}"
] | The "set" function of the Array "type" interface.
Most likely invoked when setting within a "ref-struct" type. | [
"The",
"set",
"function",
"of",
"the",
"Array",
"type",
"interface",
".",
"Most",
"likely",
"invoked",
"when",
"setting",
"within",
"a",
"ref",
"-",
"struct",
"type",
"."
] | a0699e21be2d2dab80fb356bb67cf2244c33ea52 | https://github.com/node-ffi-napi/ref-array-di/blob/a0699e21be2d2dab80fb356bb67cf2244c33ea52/lib/array.js#L180-L191 | train |
node-ffi-napi/ref-array-di | lib/array.js | setRef | function setRef (buffer, offset, value) {
debug('Array reference "type" setter for buffer at offset', offset)
var ptr
if (value instanceof this) {
ptr = value.buffer
} else {
ptr = new this(value).buffer
}
_ref.writePointer(buffer, offset, ptr)
} | javascript | function setRef (buffer, offset, value) {
debug('Array reference "type" setter for buffer at offset', offset)
var ptr
if (value instanceof this) {
ptr = value.buffer
} else {
ptr = new this(value).buffer
}
_ref.writePointer(buffer, offset, ptr)
} | [
"function",
"setRef",
"(",
"buffer",
",",
"offset",
",",
"value",
")",
"{",
"debug",
"(",
"'Array reference \"type\" setter for buffer at offset'",
",",
"offset",
")",
"var",
"ptr",
"if",
"(",
"value",
"instanceof",
"this",
")",
"{",
"ptr",
"=",
"value",
".",
"buffer",
"}",
"else",
"{",
"ptr",
"=",
"new",
"this",
"(",
"value",
")",
".",
"buffer",
"}",
"_ref",
".",
"writePointer",
"(",
"buffer",
",",
"offset",
",",
"ptr",
")",
"}"
] | Most likely invoked when passing an array instance as an argument to an FFI'd
function. | [
"Most",
"likely",
"invoked",
"when",
"passing",
"an",
"array",
"instance",
"as",
"an",
"argument",
"to",
"an",
"FFI",
"d",
"function",
"."
] | a0699e21be2d2dab80fb356bb67cf2244c33ea52 | https://github.com/node-ffi-napi/ref-array-di/blob/a0699e21be2d2dab80fb356bb67cf2244c33ea52/lib/array.js#L210-L219 | train |
node-ffi-napi/ref-array-di | lib/array.js | ref | function ref () {
debug('ref()')
var type = this.constructor
var origSize = this.buffer.length
var r = _ref.ref(this.buffer)
r.type = Object.create(_ref.types.CString)
r.type.get = function (buf, offset) {
return new type(_ref.readPointer(buf, offset | 0, origSize))
}
r.type.set = function () {
assert(0, 'implement!!!')
}
return r
} | javascript | function ref () {
debug('ref()')
var type = this.constructor
var origSize = this.buffer.length
var r = _ref.ref(this.buffer)
r.type = Object.create(_ref.types.CString)
r.type.get = function (buf, offset) {
return new type(_ref.readPointer(buf, offset | 0, origSize))
}
r.type.set = function () {
assert(0, 'implement!!!')
}
return r
} | [
"function",
"ref",
"(",
")",
"{",
"debug",
"(",
"'ref()'",
")",
"var",
"type",
"=",
"this",
".",
"constructor",
"var",
"origSize",
"=",
"this",
".",
"buffer",
".",
"length",
"var",
"r",
"=",
"_ref",
".",
"ref",
"(",
"this",
".",
"buffer",
")",
"r",
".",
"type",
"=",
"Object",
".",
"create",
"(",
"_ref",
".",
"types",
".",
"CString",
")",
"r",
".",
"type",
".",
"get",
"=",
"function",
"(",
"buf",
",",
"offset",
")",
"{",
"return",
"new",
"type",
"(",
"_ref",
".",
"readPointer",
"(",
"buf",
",",
"offset",
"|",
"0",
",",
"origSize",
")",
")",
"}",
"r",
".",
"type",
".",
"set",
"=",
"function",
"(",
")",
"{",
"assert",
"(",
"0",
",",
"'implement!!!'",
")",
"}",
"return",
"r",
"}"
] | Returns a reference to the backing buffer of this Array instance.
i.e. if the array represents `int[]` (a.k.a. `int *`),
then the returned Buffer represents `int (*)[]` (a.k.a. `int **`) | [
"Returns",
"a",
"reference",
"to",
"the",
"backing",
"buffer",
"of",
"this",
"Array",
"instance",
"."
] | a0699e21be2d2dab80fb356bb67cf2244c33ea52 | https://github.com/node-ffi-napi/ref-array-di/blob/a0699e21be2d2dab80fb356bb67cf2244c33ea52/lib/array.js#L228-L241 | train |
node-ffi-napi/ref-array-di | lib/array.js | getter | function getter (index) {
debug('getting array[%d]', index)
var size = this.constructor.BYTES_PER_ELEMENT
var baseType = this.constructor.type
var offset = size * index
var end = offset + size
var buffer = this.buffer
if (buffer.length < end) {
debug('reinterpreting buffer from %d to %d', buffer.length, end)
buffer = _ref.reinterpret(buffer, end)
}
return _ref.get(buffer, offset, baseType)
} | javascript | function getter (index) {
debug('getting array[%d]', index)
var size = this.constructor.BYTES_PER_ELEMENT
var baseType = this.constructor.type
var offset = size * index
var end = offset + size
var buffer = this.buffer
if (buffer.length < end) {
debug('reinterpreting buffer from %d to %d', buffer.length, end)
buffer = _ref.reinterpret(buffer, end)
}
return _ref.get(buffer, offset, baseType)
} | [
"function",
"getter",
"(",
"index",
")",
"{",
"debug",
"(",
"'getting array[%d]'",
",",
"index",
")",
"var",
"size",
"=",
"this",
".",
"constructor",
".",
"BYTES_PER_ELEMENT",
"var",
"baseType",
"=",
"this",
".",
"constructor",
".",
"type",
"var",
"offset",
"=",
"size",
"*",
"index",
"var",
"end",
"=",
"offset",
"+",
"size",
"var",
"buffer",
"=",
"this",
".",
"buffer",
"if",
"(",
"buffer",
".",
"length",
"<",
"end",
")",
"{",
"debug",
"(",
"'reinterpreting buffer from %d to %d'",
",",
"buffer",
".",
"length",
",",
"end",
")",
"buffer",
"=",
"_ref",
".",
"reinterpret",
"(",
"buffer",
",",
"end",
")",
"}",
"return",
"_ref",
".",
"get",
"(",
"buffer",
",",
"offset",
",",
"baseType",
")",
"}"
] | The "getter" implementation for the "array-index" interface. | [
"The",
"getter",
"implementation",
"for",
"the",
"array",
"-",
"index",
"interface",
"."
] | a0699e21be2d2dab80fb356bb67cf2244c33ea52 | https://github.com/node-ffi-napi/ref-array-di/blob/a0699e21be2d2dab80fb356bb67cf2244c33ea52/lib/array.js#L247-L259 | train |
node-ffi-napi/ref-array-di | lib/array.js | setter | function setter (index, value) {
debug('setting array[%d]', index)
var size = this.constructor.BYTES_PER_ELEMENT
var baseType = this.constructor.type
var offset = size * index
var end = offset + size
var buffer = this.buffer
if (buffer.length < end) {
debug('reinterpreting buffer from %d to %d', buffer.length, end)
buffer = _ref.reinterpret(buffer, end)
}
// TODO: DRY with getter()
_ref.set(buffer, offset, value, baseType)
return value
} | javascript | function setter (index, value) {
debug('setting array[%d]', index)
var size = this.constructor.BYTES_PER_ELEMENT
var baseType = this.constructor.type
var offset = size * index
var end = offset + size
var buffer = this.buffer
if (buffer.length < end) {
debug('reinterpreting buffer from %d to %d', buffer.length, end)
buffer = _ref.reinterpret(buffer, end)
}
// TODO: DRY with getter()
_ref.set(buffer, offset, value, baseType)
return value
} | [
"function",
"setter",
"(",
"index",
",",
"value",
")",
"{",
"debug",
"(",
"'setting array[%d]'",
",",
"index",
")",
"var",
"size",
"=",
"this",
".",
"constructor",
".",
"BYTES_PER_ELEMENT",
"var",
"baseType",
"=",
"this",
".",
"constructor",
".",
"type",
"var",
"offset",
"=",
"size",
"*",
"index",
"var",
"end",
"=",
"offset",
"+",
"size",
"var",
"buffer",
"=",
"this",
".",
"buffer",
"if",
"(",
"buffer",
".",
"length",
"<",
"end",
")",
"{",
"debug",
"(",
"'reinterpreting buffer from %d to %d'",
",",
"buffer",
".",
"length",
",",
"end",
")",
"buffer",
"=",
"_ref",
".",
"reinterpret",
"(",
"buffer",
",",
"end",
")",
"}",
"_ref",
".",
"set",
"(",
"buffer",
",",
"offset",
",",
"value",
",",
"baseType",
")",
"return",
"value",
"}"
] | The "setter" implementation for the "array-index" interface. | [
"The",
"setter",
"implementation",
"for",
"the",
"array",
"-",
"index",
"interface",
"."
] | a0699e21be2d2dab80fb356bb67cf2244c33ea52 | https://github.com/node-ffi-napi/ref-array-di/blob/a0699e21be2d2dab80fb356bb67cf2244c33ea52/lib/array.js#L265-L280 | train |
node-ffi-napi/ref-array-di | lib/array.js | slice | function slice (start, end) {
var data
if (end) {
debug('slicing array from %d to %d', start, end)
data = this.buffer.slice(start*this.constructor.BYTES_PER_ELEMENT, end*this.constructor.BYTES_PER_ELEMENT)
} else {
debug('slicing array from %d', start)
data = this.buffer.slice(start*this.constructor.BYTES_PER_ELEMENT)
}
return new this.constructor(data)
} | javascript | function slice (start, end) {
var data
if (end) {
debug('slicing array from %d to %d', start, end)
data = this.buffer.slice(start*this.constructor.BYTES_PER_ELEMENT, end*this.constructor.BYTES_PER_ELEMENT)
} else {
debug('slicing array from %d', start)
data = this.buffer.slice(start*this.constructor.BYTES_PER_ELEMENT)
}
return new this.constructor(data)
} | [
"function",
"slice",
"(",
"start",
",",
"end",
")",
"{",
"var",
"data",
"if",
"(",
"end",
")",
"{",
"debug",
"(",
"'slicing array from %d to %d'",
",",
"start",
",",
"end",
")",
"data",
"=",
"this",
".",
"buffer",
".",
"slice",
"(",
"start",
"*",
"this",
".",
"constructor",
".",
"BYTES_PER_ELEMENT",
",",
"end",
"*",
"this",
".",
"constructor",
".",
"BYTES_PER_ELEMENT",
")",
"}",
"else",
"{",
"debug",
"(",
"'slicing array from %d'",
",",
"start",
")",
"data",
"=",
"this",
".",
"buffer",
".",
"slice",
"(",
"start",
"*",
"this",
".",
"constructor",
".",
"BYTES_PER_ELEMENT",
")",
"}",
"return",
"new",
"this",
".",
"constructor",
"(",
"data",
")",
"}"
] | The "slice" implementation. | [
"The",
"slice",
"implementation",
"."
] | a0699e21be2d2dab80fb356bb67cf2244c33ea52 | https://github.com/node-ffi-napi/ref-array-di/blob/a0699e21be2d2dab80fb356bb67cf2244c33ea52/lib/array.js#L286-L298 | train |
simoami/mimik | lib/utils.js | function (message, config, cb) {
if(typeof config === 'function') {
cb = config;
config = {};
}
var stdin = config.stdin || process.stdin,
stdout = config.stdout || process.stdout,
prompt = config.prompt || '\u203A';
stdout.write(' ' + message + '\n ' + prompt + ' ');
stdin.resume();
stdin.setEncoding('utf8');
stdin.on('data', function (text) {
text = text.trim().replace(/\r\n|\n/, '');
cb(text);
});
} | javascript | function (message, config, cb) {
if(typeof config === 'function') {
cb = config;
config = {};
}
var stdin = config.stdin || process.stdin,
stdout = config.stdout || process.stdout,
prompt = config.prompt || '\u203A';
stdout.write(' ' + message + '\n ' + prompt + ' ');
stdin.resume();
stdin.setEncoding('utf8');
stdin.on('data', function (text) {
text = text.trim().replace(/\r\n|\n/, '');
cb(text);
});
} | [
"function",
"(",
"message",
",",
"config",
",",
"cb",
")",
"{",
"if",
"(",
"typeof",
"config",
"===",
"'function'",
")",
"{",
"cb",
"=",
"config",
";",
"config",
"=",
"{",
"}",
";",
"}",
"var",
"stdin",
"=",
"config",
".",
"stdin",
"||",
"process",
".",
"stdin",
",",
"stdout",
"=",
"config",
".",
"stdout",
"||",
"process",
".",
"stdout",
",",
"prompt",
"=",
"config",
".",
"prompt",
"||",
"'\\u203A'",
";",
"\\u203A",
"stdout",
".",
"write",
"(",
"' '",
"+",
"message",
"+",
"'\\n '",
"+",
"\\n",
"+",
"prompt",
")",
";",
"' '",
"stdin",
".",
"resume",
"(",
")",
";",
"}"
] | creates a console prompt and calls the passed callback with the anwser | [
"creates",
"a",
"console",
"prompt",
"and",
"calls",
"the",
"passed",
"callback",
"with",
"the",
"anwser"
] | 464a4679bba671d43aea6660485d8db9fa767b1b | https://github.com/simoami/mimik/blob/464a4679bba671d43aea6660485d8db9fa767b1b/lib/utils.js#L259-L274 | train |
|
tgriesser/create-error | create-error.js | attachProps | function attachProps(context, target) {
if (isObject(target)) {
var keys = inheritedKeys(target);
for (var i = 0, l = keys.length; i < l; ++i) {
context[keys[i]] = clone(target[keys[i]]);
}
}
} | javascript | function attachProps(context, target) {
if (isObject(target)) {
var keys = inheritedKeys(target);
for (var i = 0, l = keys.length; i < l; ++i) {
context[keys[i]] = clone(target[keys[i]]);
}
}
} | [
"function",
"attachProps",
"(",
"context",
",",
"target",
")",
"{",
"if",
"(",
"isObject",
"(",
"target",
")",
")",
"{",
"var",
"keys",
"=",
"inheritedKeys",
"(",
"target",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"keys",
".",
"length",
";",
"i",
"<",
"l",
";",
"++",
"i",
")",
"{",
"context",
"[",
"keys",
"[",
"i",
"]",
"]",
"=",
"clone",
"(",
"target",
"[",
"keys",
"[",
"i",
"]",
"]",
")",
";",
"}",
"}",
"}"
] | Used to attach attributes to the error object in the constructor. | [
"Used",
"to",
"attach",
"attributes",
"to",
"the",
"error",
"object",
"in",
"the",
"constructor",
"."
] | 03e4a517a16a115cdf61d84168dac510c550a53c | https://github.com/tgriesser/create-error/blob/03e4a517a16a115cdf61d84168dac510c550a53c/create-error.js#L78-L85 | train |
neyric/aws-swf | lib/activity-task.js | function (result, cb) {
var self = this;
this.swfClient.respondActivityTaskCompleted({
result: stringify(result),
taskToken: this.config.taskToken
}, function (err) {
if (self.onDone) {
self.onDone();
}
if (cb) {
cb(err);
}
});
} | javascript | function (result, cb) {
var self = this;
this.swfClient.respondActivityTaskCompleted({
result: stringify(result),
taskToken: this.config.taskToken
}, function (err) {
if (self.onDone) {
self.onDone();
}
if (cb) {
cb(err);
}
});
} | [
"function",
"(",
"result",
",",
"cb",
")",
"{",
"var",
"self",
"=",
"this",
";",
"this",
".",
"swfClient",
".",
"respondActivityTaskCompleted",
"(",
"{",
"result",
":",
"stringify",
"(",
"result",
")",
",",
"taskToken",
":",
"this",
".",
"config",
".",
"taskToken",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"self",
".",
"onDone",
")",
"{",
"self",
".",
"onDone",
"(",
")",
";",
"}",
"if",
"(",
"cb",
")",
"{",
"cb",
"(",
"err",
")",
";",
"}",
"}",
")",
";",
"}"
] | Sends a "RespondActivityTaskCompleted" to AWS.
@param {Mixed} result - Result of the activity (will get stringified in JSON if not a string)
@param {Function} [cb] - callback | [
"Sends",
"a",
"RespondActivityTaskCompleted",
"to",
"AWS",
"."
] | 31b96c9eef313199465b40204a92909996a85c3d | https://github.com/neyric/aws-swf/blob/31b96c9eef313199465b40204a92909996a85c3d/lib/activity-task.js#L56-L71 | train |
|
neyric/aws-swf | lib/activity-task.js | function (reason, details, cb) {
var self = this;
var o = {
"taskToken": this.config.taskToken
};
if (reason) {
o.reason = reason;
}
if (details) {
o.details = stringify(details);
}
this.swfClient.respondActivityTaskFailed(o, function (err) {
if (self.onDone) {
self.onDone();
}
if (cb) {
cb(err);
}
});
} | javascript | function (reason, details, cb) {
var self = this;
var o = {
"taskToken": this.config.taskToken
};
if (reason) {
o.reason = reason;
}
if (details) {
o.details = stringify(details);
}
this.swfClient.respondActivityTaskFailed(o, function (err) {
if (self.onDone) {
self.onDone();
}
if (cb) {
cb(err);
}
});
} | [
"function",
"(",
"reason",
",",
"details",
",",
"cb",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"o",
"=",
"{",
"\"taskToken\"",
":",
"this",
".",
"config",
".",
"taskToken",
"}",
";",
"if",
"(",
"reason",
")",
"{",
"o",
".",
"reason",
"=",
"reason",
";",
"}",
"if",
"(",
"details",
")",
"{",
"o",
".",
"details",
"=",
"stringify",
"(",
"details",
")",
";",
"}",
"this",
".",
"swfClient",
".",
"respondActivityTaskFailed",
"(",
"o",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"self",
".",
"onDone",
")",
"{",
"self",
".",
"onDone",
"(",
")",
";",
"}",
"if",
"(",
"cb",
")",
"{",
"cb",
"(",
"err",
")",
";",
"}",
"}",
")",
";",
"}"
] | Sends a "RespondActivityTaskFailed" to AWS.
@param {String} reason
@param {String} details
@param {Function} [cb] - callback | [
"Sends",
"a",
"RespondActivityTaskFailed",
"to",
"AWS",
"."
] | 31b96c9eef313199465b40204a92909996a85c3d | https://github.com/neyric/aws-swf/blob/31b96c9eef313199465b40204a92909996a85c3d/lib/activity-task.js#L80-L102 | train |
|
neyric/aws-swf | lib/activity-task.js | function (heartbeat, cb) {
var self = this;
this.swfClient.recordActivityTaskHeartbeat({
taskToken: this.config.taskToken,
details: stringify(heartbeat)
}, function (err) {
if (cb) {
cb(err);
}
});
} | javascript | function (heartbeat, cb) {
var self = this;
this.swfClient.recordActivityTaskHeartbeat({
taskToken: this.config.taskToken,
details: stringify(heartbeat)
}, function (err) {
if (cb) {
cb(err);
}
});
} | [
"function",
"(",
"heartbeat",
",",
"cb",
")",
"{",
"var",
"self",
"=",
"this",
";",
"this",
".",
"swfClient",
".",
"recordActivityTaskHeartbeat",
"(",
"{",
"taskToken",
":",
"this",
".",
"config",
".",
"taskToken",
",",
"details",
":",
"stringify",
"(",
"heartbeat",
")",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"cb",
")",
"{",
"cb",
"(",
"err",
")",
";",
"}",
"}",
")",
";",
"}"
] | Sends a heartbeat to AWS. Needed for long run activity
@param {Mixed} heartbeat - Details of the heartbeat (will get stringified in JSON if not a string)
@param {Function} [cb] - callback | [
"Sends",
"a",
"heartbeat",
"to",
"AWS",
".",
"Needed",
"for",
"long",
"run",
"activity"
] | 31b96c9eef313199465b40204a92909996a85c3d | https://github.com/neyric/aws-swf/blob/31b96c9eef313199465b40204a92909996a85c3d/lib/activity-task.js#L109-L120 | train |
|
quorrajs/Ouch | handler/PrettyPageHandler.js | PrettyPageHandler | function PrettyPageHandler(theme, pageTitle, editor, sendResponse, additionalScripts) {
PrettyPageHandler.super_.call(this);
/**
* @var {String}
* @protected
*/
this.__pageTitle = pageTitle || "Ouch! There was an error.";
/**
* @var {String}
* @protected
*/
this.__theme = theme || "blue";
/**
* A string identifier for a known IDE/text editor, or a closure
* that resolves a string that can be used to open a given file
* in an editor. If the string contains the special substrings
* %file or %line, they will be replaced with the correct data.
*
* @example
* "txmt://open?url=%file&line=%line"
*
* @var {*} editor
* @protected
*/
this.__editor = editor;
/**
* Should Ouch push output directly to the client?
* If this is false, output will be passed to the callback
* provided to the handle method.
* @type {boolean}
* @protected
*/
this.__sendResponse = sendResponse === undefined ? true : Boolean(sendResponse);
/**
* An Array of urls that represent additional javascript resources to include in the rendered template.
*
* @type {Array}
* @protected
*/
this.__additionalScripts = additionalScripts || [];
/**
* A list of known editor strings
*
* @var Object
* @protected
*/
this.__editors = {
"sublime": "subl://open?url=file://%file&line=%line",
"textmate": "txmt://open?url=file://%file&line=%line",
"emacs": "emacs://open?url=file://%file&line=%line",
"macvim": "mvim://open/?url=file://%file&line=%line"
};
} | javascript | function PrettyPageHandler(theme, pageTitle, editor, sendResponse, additionalScripts) {
PrettyPageHandler.super_.call(this);
/**
* @var {String}
* @protected
*/
this.__pageTitle = pageTitle || "Ouch! There was an error.";
/**
* @var {String}
* @protected
*/
this.__theme = theme || "blue";
/**
* A string identifier for a known IDE/text editor, or a closure
* that resolves a string that can be used to open a given file
* in an editor. If the string contains the special substrings
* %file or %line, they will be replaced with the correct data.
*
* @example
* "txmt://open?url=%file&line=%line"
*
* @var {*} editor
* @protected
*/
this.__editor = editor;
/**
* Should Ouch push output directly to the client?
* If this is false, output will be passed to the callback
* provided to the handle method.
* @type {boolean}
* @protected
*/
this.__sendResponse = sendResponse === undefined ? true : Boolean(sendResponse);
/**
* An Array of urls that represent additional javascript resources to include in the rendered template.
*
* @type {Array}
* @protected
*/
this.__additionalScripts = additionalScripts || [];
/**
* A list of known editor strings
*
* @var Object
* @protected
*/
this.__editors = {
"sublime": "subl://open?url=file://%file&line=%line",
"textmate": "txmt://open?url=file://%file&line=%line",
"emacs": "emacs://open?url=file://%file&line=%line",
"macvim": "mvim://open/?url=file://%file&line=%line"
};
} | [
"function",
"PrettyPageHandler",
"(",
"theme",
",",
"pageTitle",
",",
"editor",
",",
"sendResponse",
",",
"additionalScripts",
")",
"{",
"PrettyPageHandler",
".",
"super_",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"__pageTitle",
"=",
"pageTitle",
"||",
"\"Ouch! There was an error.\"",
";",
"this",
".",
"__theme",
"=",
"theme",
"||",
"\"blue\"",
";",
"this",
".",
"__editor",
"=",
"editor",
";",
"this",
".",
"__sendResponse",
"=",
"sendResponse",
"===",
"undefined",
"?",
"true",
":",
"Boolean",
"(",
"sendResponse",
")",
";",
"this",
".",
"__additionalScripts",
"=",
"additionalScripts",
"||",
"[",
"]",
";",
"this",
".",
"__editors",
"=",
"{",
"\"sublime\"",
":",
"\"subl://open?url=file://%file&line=%line\"",
",",
"\"textmate\"",
":",
"\"txmt://open?url=file://%file&line=%line\"",
",",
"\"emacs\"",
":",
"\"emacs://open?url=file://%file&line=%line\"",
",",
"\"macvim\"",
":",
"\"mvim://open/?url=file://%file&line=%line\"",
"}",
";",
"}"
] | Prettifies a javascript error stack.
@param theme
@param pageTitle
@param editor
@param sendResponse
@param [additionalScripts]
@class | [
"Prettifies",
"a",
"javascript",
"error",
"stack",
"."
] | cbadf54eaa78633761e295c8566a36bb1567d130 | https://github.com/quorrajs/Ouch/blob/cbadf54eaa78633761e295c8566a36bb1567d130/handler/PrettyPageHandler.js#L31-L90 | train |
quorrajs/Ouch | exception/frame.js | frame | function frame(frame) {
frame.__comments = [];
frame.__proto__ = {
__proto__: frame.__proto__,
/**
* Returns the contents of the file for this frame as an
* array of lines, and optionally as a clamped range of lines.
*
* NOTE: lines are 0-indexed
*
* @throws RangeError if length is less than or equal to 0
* @param start
* @param length
* @returns {Array|undefined}
*/
getFileLines: function (start, length) {
if (!start) {
start = 0;
}
var contents = this.getFileContents();
if (null !== contents) {
var lines = (contents).split("\n");
// Get a subset of lines from $start to $end
if (length !== null) {
start = parseInt(start);
length = parseInt(length);
if (start < 0) {
start = 0;
}
if (length <= 0) {
throw new RangeError(
"length cannot be lower or equal to 0"
);
}
lines = lines.slice(start, start + length);
}
return lines;
}
},
/**
* Returns the full contents of the file for this frame, if it's known.
*
* @returns {*}
*/
getFileContents: function () {
var filePath = this.getFileName();
if (!this.__fileContentsCache && filePath) {
// Leave the stage early when 'Unknown' is passed
// this would otherwise raise an exception when
// open_basedir is enabled.
if (filePath === "Unknown") {
return null;
}
// Return null if the file doesn't actually exist.
if (!fs.existsSync(filePath)) {
if (process.env.NVM_DIR && process.versions.node) {
filePath = path.join(process.env.NVM_DIR, 'src/node-v' + process.versions.node, 'lib', filePath);
if (!fs.existsSync(filePath)) {
return null;
}
} else {
return null;
}
}
this.__fileContentsCache = fs.readFileSync(filePath, 'utf-8');
}
return this.__fileContentsCache;
},
/**
* Adds a comment to this frame, that can be received and used by other handlers. For example, the PrettyPage
* handler can attach these comments under the code for each frame.
* An interesting use for this would be, for example, code analysis & annotations.
*
* @param {String} comment
* @param {String} context Optional string identifying the origin of the comment
*/
addComment: function (comment, context) {
context = context || 'global';
this.__comments.push({
'comment': comment,
'context': context
});
},
/**
* Returns all comments for this frame. Optionally allows a filter to only retrieve comments from a specific
* context.
*
* @param {String} filter
* @returns {Array}
*/
getComments: function (filter) {
if (!filter) {
filter = null;
}
var comments = this.__comments;
if (filter !== null) {
comments = comments.filter(function (c) {
return c.context === filter;
});
}
return comments;
}
};
return frame;
} | javascript | function frame(frame) {
frame.__comments = [];
frame.__proto__ = {
__proto__: frame.__proto__,
/**
* Returns the contents of the file for this frame as an
* array of lines, and optionally as a clamped range of lines.
*
* NOTE: lines are 0-indexed
*
* @throws RangeError if length is less than or equal to 0
* @param start
* @param length
* @returns {Array|undefined}
*/
getFileLines: function (start, length) {
if (!start) {
start = 0;
}
var contents = this.getFileContents();
if (null !== contents) {
var lines = (contents).split("\n");
// Get a subset of lines from $start to $end
if (length !== null) {
start = parseInt(start);
length = parseInt(length);
if (start < 0) {
start = 0;
}
if (length <= 0) {
throw new RangeError(
"length cannot be lower or equal to 0"
);
}
lines = lines.slice(start, start + length);
}
return lines;
}
},
/**
* Returns the full contents of the file for this frame, if it's known.
*
* @returns {*}
*/
getFileContents: function () {
var filePath = this.getFileName();
if (!this.__fileContentsCache && filePath) {
// Leave the stage early when 'Unknown' is passed
// this would otherwise raise an exception when
// open_basedir is enabled.
if (filePath === "Unknown") {
return null;
}
// Return null if the file doesn't actually exist.
if (!fs.existsSync(filePath)) {
if (process.env.NVM_DIR && process.versions.node) {
filePath = path.join(process.env.NVM_DIR, 'src/node-v' + process.versions.node, 'lib', filePath);
if (!fs.existsSync(filePath)) {
return null;
}
} else {
return null;
}
}
this.__fileContentsCache = fs.readFileSync(filePath, 'utf-8');
}
return this.__fileContentsCache;
},
/**
* Adds a comment to this frame, that can be received and used by other handlers. For example, the PrettyPage
* handler can attach these comments under the code for each frame.
* An interesting use for this would be, for example, code analysis & annotations.
*
* @param {String} comment
* @param {String} context Optional string identifying the origin of the comment
*/
addComment: function (comment, context) {
context = context || 'global';
this.__comments.push({
'comment': comment,
'context': context
});
},
/**
* Returns all comments for this frame. Optionally allows a filter to only retrieve comments from a specific
* context.
*
* @param {String} filter
* @returns {Array}
*/
getComments: function (filter) {
if (!filter) {
filter = null;
}
var comments = this.__comments;
if (filter !== null) {
comments = comments.filter(function (c) {
return c.context === filter;
});
}
return comments;
}
};
return frame;
} | [
"function",
"frame",
"(",
"frame",
")",
"{",
"frame",
".",
"__comments",
"=",
"[",
"]",
";",
"frame",
".",
"__proto__",
"=",
"{",
"__proto__",
":",
"frame",
".",
"__proto__",
",",
"getFileLines",
":",
"function",
"(",
"start",
",",
"length",
")",
"{",
"if",
"(",
"!",
"start",
")",
"{",
"start",
"=",
"0",
";",
"}",
"var",
"contents",
"=",
"this",
".",
"getFileContents",
"(",
")",
";",
"if",
"(",
"null",
"!==",
"contents",
")",
"{",
"var",
"lines",
"=",
"(",
"contents",
")",
".",
"split",
"(",
"\"\\n\"",
")",
";",
"\\n",
"if",
"(",
"length",
"!==",
"null",
")",
"{",
"start",
"=",
"parseInt",
"(",
"start",
")",
";",
"length",
"=",
"parseInt",
"(",
"length",
")",
";",
"if",
"(",
"start",
"<",
"0",
")",
"{",
"start",
"=",
"0",
";",
"}",
"if",
"(",
"length",
"<=",
"0",
")",
"{",
"throw",
"new",
"RangeError",
"(",
"\"length cannot be lower or equal to 0\"",
")",
";",
"}",
"lines",
"=",
"lines",
".",
"slice",
"(",
"start",
",",
"start",
"+",
"length",
")",
";",
"}",
"}",
"}",
",",
"return",
"lines",
";",
",",
"getFileContents",
":",
"function",
"(",
")",
"{",
"var",
"filePath",
"=",
"this",
".",
"getFileName",
"(",
")",
";",
"if",
"(",
"!",
"this",
".",
"__fileContentsCache",
"&&",
"filePath",
")",
"{",
"if",
"(",
"filePath",
"===",
"\"Unknown\"",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"filePath",
")",
")",
"{",
"if",
"(",
"process",
".",
"env",
".",
"NVM_DIR",
"&&",
"process",
".",
"versions",
".",
"node",
")",
"{",
"filePath",
"=",
"path",
".",
"join",
"(",
"process",
".",
"env",
".",
"NVM_DIR",
",",
"'src/node-v'",
"+",
"process",
".",
"versions",
".",
"node",
",",
"'lib'",
",",
"filePath",
")",
";",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"filePath",
")",
")",
"{",
"return",
"null",
";",
"}",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}",
"this",
".",
"__fileContentsCache",
"=",
"fs",
".",
"readFileSync",
"(",
"filePath",
",",
"'utf-8'",
")",
";",
"}",
"return",
"this",
".",
"__fileContentsCache",
";",
"}",
",",
"addComment",
":",
"function",
"(",
"comment",
",",
"context",
")",
"{",
"context",
"=",
"context",
"||",
"'global'",
";",
"this",
".",
"__comments",
".",
"push",
"(",
"{",
"'comment'",
":",
"comment",
",",
"'context'",
":",
"context",
"}",
")",
";",
"}",
"}",
";",
"getComments",
":",
"function",
"(",
"filter",
")",
"{",
"if",
"(",
"!",
"filter",
")",
"{",
"filter",
"=",
"null",
";",
"}",
"var",
"comments",
"=",
"this",
".",
"__comments",
";",
"if",
"(",
"filter",
"!==",
"null",
")",
"{",
"comments",
"=",
"comments",
".",
"filter",
"(",
"function",
"(",
"c",
")",
"{",
"return",
"c",
".",
"context",
"===",
"filter",
";",
"}",
")",
";",
"}",
"return",
"comments",
";",
"}",
"}"
] | Adds additional prototypes to CallSite objects returned by stack-trace module.
@param frame
@returns frame | [
"Adds",
"additional",
"prototypes",
"to",
"CallSite",
"objects",
"returned",
"by",
"stack",
"-",
"trace",
"module",
"."
] | cbadf54eaa78633761e295c8566a36bb1567d130 | https://github.com/quorrajs/Ouch/blob/cbadf54eaa78633761e295c8566a36bb1567d130/exception/frame.js#L18-L137 | train |
quorrajs/Ouch | exception/frame.js | function (start, length) {
if (!start) {
start = 0;
}
var contents = this.getFileContents();
if (null !== contents) {
var lines = (contents).split("\n");
// Get a subset of lines from $start to $end
if (length !== null) {
start = parseInt(start);
length = parseInt(length);
if (start < 0) {
start = 0;
}
if (length <= 0) {
throw new RangeError(
"length cannot be lower or equal to 0"
);
}
lines = lines.slice(start, start + length);
}
return lines;
}
} | javascript | function (start, length) {
if (!start) {
start = 0;
}
var contents = this.getFileContents();
if (null !== contents) {
var lines = (contents).split("\n");
// Get a subset of lines from $start to $end
if (length !== null) {
start = parseInt(start);
length = parseInt(length);
if (start < 0) {
start = 0;
}
if (length <= 0) {
throw new RangeError(
"length cannot be lower or equal to 0"
);
}
lines = lines.slice(start, start + length);
}
return lines;
}
} | [
"function",
"(",
"start",
",",
"length",
")",
"{",
"if",
"(",
"!",
"start",
")",
"{",
"start",
"=",
"0",
";",
"}",
"var",
"contents",
"=",
"this",
".",
"getFileContents",
"(",
")",
";",
"if",
"(",
"null",
"!==",
"contents",
")",
"{",
"var",
"lines",
"=",
"(",
"contents",
")",
".",
"split",
"(",
"\"\\n\"",
")",
";",
"\\n",
"if",
"(",
"length",
"!==",
"null",
")",
"{",
"start",
"=",
"parseInt",
"(",
"start",
")",
";",
"length",
"=",
"parseInt",
"(",
"length",
")",
";",
"if",
"(",
"start",
"<",
"0",
")",
"{",
"start",
"=",
"0",
";",
"}",
"if",
"(",
"length",
"<=",
"0",
")",
"{",
"throw",
"new",
"RangeError",
"(",
"\"length cannot be lower or equal to 0\"",
")",
";",
"}",
"lines",
"=",
"lines",
".",
"slice",
"(",
"start",
",",
"start",
"+",
"length",
")",
";",
"}",
"}",
"}"
] | Returns the contents of the file for this frame as an
array of lines, and optionally as a clamped range of lines.
NOTE: lines are 0-indexed
@throws RangeError if length is less than or equal to 0
@param start
@param length
@returns {Array|undefined} | [
"Returns",
"the",
"contents",
"of",
"the",
"file",
"for",
"this",
"frame",
"as",
"an",
"array",
"of",
"lines",
"and",
"optionally",
"as",
"a",
"clamped",
"range",
"of",
"lines",
"."
] | cbadf54eaa78633761e295c8566a36bb1567d130 | https://github.com/quorrajs/Ouch/blob/cbadf54eaa78633761e295c8566a36bb1567d130/exception/frame.js#L35-L62 | train |
|
quorrajs/Ouch | exception/frame.js | function () {
var filePath = this.getFileName();
if (!this.__fileContentsCache && filePath) {
// Leave the stage early when 'Unknown' is passed
// this would otherwise raise an exception when
// open_basedir is enabled.
if (filePath === "Unknown") {
return null;
}
// Return null if the file doesn't actually exist.
if (!fs.existsSync(filePath)) {
if (process.env.NVM_DIR && process.versions.node) {
filePath = path.join(process.env.NVM_DIR, 'src/node-v' + process.versions.node, 'lib', filePath);
if (!fs.existsSync(filePath)) {
return null;
}
} else {
return null;
}
}
this.__fileContentsCache = fs.readFileSync(filePath, 'utf-8');
}
return this.__fileContentsCache;
} | javascript | function () {
var filePath = this.getFileName();
if (!this.__fileContentsCache && filePath) {
// Leave the stage early when 'Unknown' is passed
// this would otherwise raise an exception when
// open_basedir is enabled.
if (filePath === "Unknown") {
return null;
}
// Return null if the file doesn't actually exist.
if (!fs.existsSync(filePath)) {
if (process.env.NVM_DIR && process.versions.node) {
filePath = path.join(process.env.NVM_DIR, 'src/node-v' + process.versions.node, 'lib', filePath);
if (!fs.existsSync(filePath)) {
return null;
}
} else {
return null;
}
}
this.__fileContentsCache = fs.readFileSync(filePath, 'utf-8');
}
return this.__fileContentsCache;
} | [
"function",
"(",
")",
"{",
"var",
"filePath",
"=",
"this",
".",
"getFileName",
"(",
")",
";",
"if",
"(",
"!",
"this",
".",
"__fileContentsCache",
"&&",
"filePath",
")",
"{",
"if",
"(",
"filePath",
"===",
"\"Unknown\"",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"filePath",
")",
")",
"{",
"if",
"(",
"process",
".",
"env",
".",
"NVM_DIR",
"&&",
"process",
".",
"versions",
".",
"node",
")",
"{",
"filePath",
"=",
"path",
".",
"join",
"(",
"process",
".",
"env",
".",
"NVM_DIR",
",",
"'src/node-v'",
"+",
"process",
".",
"versions",
".",
"node",
",",
"'lib'",
",",
"filePath",
")",
";",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"filePath",
")",
")",
"{",
"return",
"null",
";",
"}",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}",
"this",
".",
"__fileContentsCache",
"=",
"fs",
".",
"readFileSync",
"(",
"filePath",
",",
"'utf-8'",
")",
";",
"}",
"return",
"this",
".",
"__fileContentsCache",
";",
"}"
] | Returns the full contents of the file for this frame, if it's known.
@returns {*} | [
"Returns",
"the",
"full",
"contents",
"of",
"the",
"file",
"for",
"this",
"frame",
"if",
"it",
"s",
"known",
"."
] | cbadf54eaa78633761e295c8566a36bb1567d130 | https://github.com/quorrajs/Ouch/blob/cbadf54eaa78633761e295c8566a36bb1567d130/exception/frame.js#L69-L95 | train |
|
quorrajs/Ouch | exception/frame.js | function (filter) {
if (!filter) {
filter = null;
}
var comments = this.__comments;
if (filter !== null) {
comments = comments.filter(function (c) {
return c.context === filter;
});
}
return comments;
} | javascript | function (filter) {
if (!filter) {
filter = null;
}
var comments = this.__comments;
if (filter !== null) {
comments = comments.filter(function (c) {
return c.context === filter;
});
}
return comments;
} | [
"function",
"(",
"filter",
")",
"{",
"if",
"(",
"!",
"filter",
")",
"{",
"filter",
"=",
"null",
";",
"}",
"var",
"comments",
"=",
"this",
".",
"__comments",
";",
"if",
"(",
"filter",
"!==",
"null",
")",
"{",
"comments",
"=",
"comments",
".",
"filter",
"(",
"function",
"(",
"c",
")",
"{",
"return",
"c",
".",
"context",
"===",
"filter",
";",
"}",
")",
";",
"}",
"return",
"comments",
";",
"}"
] | Returns all comments for this frame. Optionally allows a filter to only retrieve comments from a specific
context.
@param {String} filter
@returns {Array} | [
"Returns",
"all",
"comments",
"for",
"this",
"frame",
".",
"Optionally",
"allows",
"a",
"filter",
"to",
"only",
"retrieve",
"comments",
"from",
"a",
"specific",
"context",
"."
] | cbadf54eaa78633761e295c8566a36bb1567d130 | https://github.com/quorrajs/Ouch/blob/cbadf54eaa78633761e295c8566a36bb1567d130/exception/frame.js#L120-L133 | train |
|
doggan/diablo-file-formats | lib/cel_decode.js | getPixelSetter | function getPixelSetter() {
var offset = 0;
return function(colors, c) {
colors[offset] = c.r;
colors[offset + 1] = c.g;
colors[offset + 2] = c.b;
colors[offset + 3] = c.a;
offset += 4;
};
} | javascript | function getPixelSetter() {
var offset = 0;
return function(colors, c) {
colors[offset] = c.r;
colors[offset + 1] = c.g;
colors[offset + 2] = c.b;
colors[offset + 3] = c.a;
offset += 4;
};
} | [
"function",
"getPixelSetter",
"(",
")",
"{",
"var",
"offset",
"=",
"0",
";",
"return",
"function",
"(",
"colors",
",",
"c",
")",
"{",
"colors",
"[",
"offset",
"]",
"=",
"c",
".",
"r",
";",
"colors",
"[",
"offset",
"+",
"1",
"]",
"=",
"c",
".",
"g",
";",
"colors",
"[",
"offset",
"+",
"2",
"]",
"=",
"c",
".",
"b",
";",
"colors",
"[",
"offset",
"+",
"3",
"]",
"=",
"c",
".",
"a",
";",
"offset",
"+=",
"4",
";",
"}",
";",
"}"
] | Utility for setting pixels. | [
"Utility",
"for",
"setting",
"pixels",
"."
] | 1c468868361752b01a1164d6135939621e18dab5 | https://github.com/doggan/diablo-file-formats/blob/1c468868361752b01a1164d6135939621e18dab5/lib/cel_decode.js#L9-L18 | train |
doggan/diablo-file-formats | lib/cel_decode.js | isType0 | function isType0(celName, frameNum) {
// These special frames are type 1.
switch (celName) {
case 'l1':
switch (frameNum) {
case 148: case 159: case 181: case 186: case 188:
return false;
}
break;
case 'l2':
switch (frameNum) {
case 47: case 1397: case 1399: case 1411:
return false;
}
break;
case 'l4':
switch (frameNum) {
case 336: case 639:
return false;
}
break;
case 'town':
switch (frameNum) {
case 2328: case 2367: case 2593:
return false;
}
}
return true;
} | javascript | function isType0(celName, frameNum) {
// These special frames are type 1.
switch (celName) {
case 'l1':
switch (frameNum) {
case 148: case 159: case 181: case 186: case 188:
return false;
}
break;
case 'l2':
switch (frameNum) {
case 47: case 1397: case 1399: case 1411:
return false;
}
break;
case 'l4':
switch (frameNum) {
case 336: case 639:
return false;
}
break;
case 'town':
switch (frameNum) {
case 2328: case 2367: case 2593:
return false;
}
}
return true;
} | [
"function",
"isType0",
"(",
"celName",
",",
"frameNum",
")",
"{",
"switch",
"(",
"celName",
")",
"{",
"case",
"'l1'",
":",
"switch",
"(",
"frameNum",
")",
"{",
"case",
"148",
":",
"case",
"159",
":",
"case",
"181",
":",
"case",
"186",
":",
"case",
"188",
":",
"return",
"false",
";",
"}",
"break",
";",
"case",
"'l2'",
":",
"switch",
"(",
"frameNum",
")",
"{",
"case",
"47",
":",
"case",
"1397",
":",
"case",
"1399",
":",
"case",
"1411",
":",
"return",
"false",
";",
"}",
"break",
";",
"case",
"'l4'",
":",
"switch",
"(",
"frameNum",
")",
"{",
"case",
"336",
":",
"case",
"639",
":",
"return",
"false",
";",
"}",
"break",
";",
"case",
"'town'",
":",
"switch",
"(",
"frameNum",
")",
"{",
"case",
"2328",
":",
"case",
"2367",
":",
"case",
"2593",
":",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Returns true if the image is a plain 32x32. | [
"Returns",
"true",
"if",
"the",
"image",
"is",
"a",
"plain",
"32x32",
"."
] | 1c468868361752b01a1164d6135939621e18dab5 | https://github.com/doggan/diablo-file-formats/blob/1c468868361752b01a1164d6135939621e18dab5/lib/cel_decode.js#L23-L52 | train |
doggan/diablo-file-formats | lib/cel_decode.js | DecodeFrameType0 | function DecodeFrameType0(frameData, width, height, palFile) {
var colors = new Uint8Array(width * height * BYTES_PER_PIXEL);
var setPixel = getPixelSetter();
for (var i = 0; i < frameData.length; i++) {
setPixel(colors, palFile.colors[frameData[i]]);
}
return {
width: width,
height: height,
colors: colors
};
} | javascript | function DecodeFrameType0(frameData, width, height, palFile) {
var colors = new Uint8Array(width * height * BYTES_PER_PIXEL);
var setPixel = getPixelSetter();
for (var i = 0; i < frameData.length; i++) {
setPixel(colors, palFile.colors[frameData[i]]);
}
return {
width: width,
height: height,
colors: colors
};
} | [
"function",
"DecodeFrameType0",
"(",
"frameData",
",",
"width",
",",
"height",
",",
"palFile",
")",
"{",
"var",
"colors",
"=",
"new",
"Uint8Array",
"(",
"width",
"*",
"height",
"*",
"BYTES_PER_PIXEL",
")",
";",
"var",
"setPixel",
"=",
"getPixelSetter",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"frameData",
".",
"length",
";",
"i",
"++",
")",
"{",
"setPixel",
"(",
"colors",
",",
"palFile",
".",
"colors",
"[",
"frameData",
"[",
"i",
"]",
"]",
")",
";",
"}",
"return",
"{",
"width",
":",
"width",
",",
"height",
":",
"height",
",",
"colors",
":",
"colors",
"}",
";",
"}"
] | Type0 corresponds to plain 32x32 images with no transparency.
1) Range through the frame, one byte at the time.
- Each byte corresponds to a color index of the palette.
- Set one regular pixel per byte, using the color index to locate the
color in the palette. | [
"Type0",
"corresponds",
"to",
"plain",
"32x32",
"images",
"with",
"no",
"transparency",
"."
] | 1c468868361752b01a1164d6135939621e18dab5 | https://github.com/doggan/diablo-file-formats/blob/1c468868361752b01a1164d6135939621e18dab5/lib/cel_decode.js#L90-L102 | train |
doggan/diablo-file-formats | lib/cel_decode.js | _getCelFrameDecoder | function _getCelFrameDecoder(celName, frameData, frameNum) {
var frameSize = frameData.length;
switch (celName) {
case 'l1': case 'l2': case 'l3': case 'l4': case 'town':
// Some regular (type 1) CEL images just happen to have a frame size of
// exactly 0x220, 0x320 or 0x400. Therefore the isType* functions are
// required to figure out the appropriate decoding function.
switch (frameSize) {
case 0x400:
if (isType0(celName, frameNum)) {
return DecodeFrameType0;
}
break;
case 0x220:
if (isType2or4(frameData)) {
return DecodeFrameType2;
} else if (isType3or5(frameData)) {
return DecodeFrameType3;
}
break;
case 0x320:
if (isType2or4(frameData)) {
return DecodeFrameType4;
} else if (isType3or5(frameData)) {
return DecodeFrameType5;
}
}
}
return DecodeFrameType1;
} | javascript | function _getCelFrameDecoder(celName, frameData, frameNum) {
var frameSize = frameData.length;
switch (celName) {
case 'l1': case 'l2': case 'l3': case 'l4': case 'town':
// Some regular (type 1) CEL images just happen to have a frame size of
// exactly 0x220, 0x320 or 0x400. Therefore the isType* functions are
// required to figure out the appropriate decoding function.
switch (frameSize) {
case 0x400:
if (isType0(celName, frameNum)) {
return DecodeFrameType0;
}
break;
case 0x220:
if (isType2or4(frameData)) {
return DecodeFrameType2;
} else if (isType3or5(frameData)) {
return DecodeFrameType3;
}
break;
case 0x320:
if (isType2or4(frameData)) {
return DecodeFrameType4;
} else if (isType3or5(frameData)) {
return DecodeFrameType5;
}
}
}
return DecodeFrameType1;
} | [
"function",
"_getCelFrameDecoder",
"(",
"celName",
",",
"frameData",
",",
"frameNum",
")",
"{",
"var",
"frameSize",
"=",
"frameData",
".",
"length",
";",
"switch",
"(",
"celName",
")",
"{",
"case",
"'l1'",
":",
"case",
"'l2'",
":",
"case",
"'l3'",
":",
"case",
"'l4'",
":",
"case",
"'town'",
":",
"switch",
"(",
"frameSize",
")",
"{",
"case",
"0x400",
":",
"if",
"(",
"isType0",
"(",
"celName",
",",
"frameNum",
")",
")",
"{",
"return",
"DecodeFrameType0",
";",
"}",
"break",
";",
"case",
"0x220",
":",
"if",
"(",
"isType2or4",
"(",
"frameData",
")",
")",
"{",
"return",
"DecodeFrameType2",
";",
"}",
"else",
"if",
"(",
"isType3or5",
"(",
"frameData",
")",
")",
"{",
"return",
"DecodeFrameType3",
";",
"}",
"break",
";",
"case",
"0x320",
":",
"if",
"(",
"isType2or4",
"(",
"frameData",
")",
")",
"{",
"return",
"DecodeFrameType4",
";",
"}",
"else",
"if",
"(",
"isType3or5",
"(",
"frameData",
")",
")",
"{",
"return",
"DecodeFrameType5",
";",
"}",
"}",
"}",
"return",
"DecodeFrameType1",
";",
"}"
] | Gets the appropriate frame decoder for the particular frame. | [
"Gets",
"the",
"appropriate",
"frame",
"decoder",
"for",
"the",
"particular",
"frame",
"."
] | 1c468868361752b01a1164d6135939621e18dab5 | https://github.com/doggan/diablo-file-formats/blob/1c468868361752b01a1164d6135939621e18dab5/lib/cel_decode.js#L546-L577 | train |
simoami/mimik | runner/Session.js | function(config) {
var me = this;
me.id = me.getId();
var Driver = DriverFactory.get(config.profile.driver);
me.driver = new Driver({
session: me,
options: config.options,
profile: config.profile
});
me.featureFile = config.featureFile;
me.profile = config.profile;
me.testRunner = null;
me.feature = null;
me.options = config.options;
me.context = {};
me.aborted = false;
me.state = 'stopped';
me.init();
} | javascript | function(config) {
var me = this;
me.id = me.getId();
var Driver = DriverFactory.get(config.profile.driver);
me.driver = new Driver({
session: me,
options: config.options,
profile: config.profile
});
me.featureFile = config.featureFile;
me.profile = config.profile;
me.testRunner = null;
me.feature = null;
me.options = config.options;
me.context = {};
me.aborted = false;
me.state = 'stopped';
me.init();
} | [
"function",
"(",
"config",
")",
"{",
"var",
"me",
"=",
"this",
";",
"me",
".",
"id",
"=",
"me",
".",
"getId",
"(",
")",
";",
"var",
"Driver",
"=",
"DriverFactory",
".",
"get",
"(",
"config",
".",
"profile",
".",
"driver",
")",
";",
"me",
".",
"driver",
"=",
"new",
"Driver",
"(",
"{",
"session",
":",
"me",
",",
"options",
":",
"config",
".",
"options",
",",
"profile",
":",
"config",
".",
"profile",
"}",
")",
";",
"me",
".",
"featureFile",
"=",
"config",
".",
"featureFile",
";",
"me",
".",
"profile",
"=",
"config",
".",
"profile",
";",
"me",
".",
"testRunner",
"=",
"null",
";",
"me",
".",
"feature",
"=",
"null",
";",
"me",
".",
"options",
"=",
"config",
".",
"options",
";",
"me",
".",
"context",
"=",
"{",
"}",
";",
"me",
".",
"aborted",
"=",
"false",
";",
"me",
".",
"state",
"=",
"'stopped'",
";",
"me",
".",
"init",
"(",
")",
";",
"}"
] | Error.stackTraceLimit = Infinity; | [
"Error",
".",
"stackTraceLimit",
"=",
"Infinity",
";"
] | 464a4679bba671d43aea6660485d8db9fa767b1b | https://github.com/simoami/mimik/blob/464a4679bba671d43aea6660485d8db9fa767b1b/runner/Session.js#L16-L34 | train |
|
laxa1986/gulp-angular-embed-templates | index.js | transform | function transform(file, enc, cb) {
// ignore empty files
if (file.isNull()) {
cb(null, file);
return;
}
if (file.isStream()) {
throw new PluginError(PLUGIN_NAME, 'Streaming not supported. particular file: ' + file.path);
}
logger.debug('\n\nfile.path: %s', file.path || 'fake');
if (skipFiles(file)) {
logger.info('skip file %s', file.path);
cb(null, file);
return;
}
var pipe = this;
processorEngine.process(file, cb, function onErr(msg) {
pipe.emit('error', new PluginError(PLUGIN_NAME, msg));
});
} | javascript | function transform(file, enc, cb) {
// ignore empty files
if (file.isNull()) {
cb(null, file);
return;
}
if (file.isStream()) {
throw new PluginError(PLUGIN_NAME, 'Streaming not supported. particular file: ' + file.path);
}
logger.debug('\n\nfile.path: %s', file.path || 'fake');
if (skipFiles(file)) {
logger.info('skip file %s', file.path);
cb(null, file);
return;
}
var pipe = this;
processorEngine.process(file, cb, function onErr(msg) {
pipe.emit('error', new PluginError(PLUGIN_NAME, msg));
});
} | [
"function",
"transform",
"(",
"file",
",",
"enc",
",",
"cb",
")",
"{",
"if",
"(",
"file",
".",
"isNull",
"(",
")",
")",
"{",
"cb",
"(",
"null",
",",
"file",
")",
";",
"return",
";",
"}",
"if",
"(",
"file",
".",
"isStream",
"(",
")",
")",
"{",
"throw",
"new",
"PluginError",
"(",
"PLUGIN_NAME",
",",
"'Streaming not supported. particular file: '",
"+",
"file",
".",
"path",
")",
";",
"}",
"logger",
".",
"debug",
"(",
"'\\n\\nfile.path: %s'",
",",
"\\n",
")",
";",
"\\n",
"file",
".",
"path",
"||",
"'fake'",
"if",
"(",
"skipFiles",
"(",
"file",
")",
")",
"{",
"logger",
".",
"info",
"(",
"'skip file %s'",
",",
"file",
".",
"path",
")",
";",
"cb",
"(",
"null",
",",
"file",
")",
";",
"return",
";",
"}",
"}"
] | This function is 'through' callback, so it has predefined arguments
@param {File} file file to analyse
@param {String} enc encoding (unused)
@param {Function} cb callback | [
"This",
"function",
"is",
"through",
"callback",
"so",
"it",
"has",
"predefined",
"arguments"
] | f82f03ba8a89d6a2df3aa4d59a5b9bc659258d72 | https://github.com/laxa1986/gulp-angular-embed-templates/blob/f82f03ba8a89d6a2df3aa4d59a5b9bc659258d72/index.js#L62-L85 | train |
laxa1986/gulp-angular-embed-templates | lib/utils.js | recursiveCycle | function recursiveCycle(arr, onIteration, onEnd) {
var i=0;
function next() {
if (i >= arr.length) {
onEnd();
return;
}
var item = arr[i];
i++;
onIteration(item, next, onEnd);
}
next();
} | javascript | function recursiveCycle(arr, onIteration, onEnd) {
var i=0;
function next() {
if (i >= arr.length) {
onEnd();
return;
}
var item = arr[i];
i++;
onIteration(item, next, onEnd);
}
next();
} | [
"function",
"recursiveCycle",
"(",
"arr",
",",
"onIteration",
",",
"onEnd",
")",
"{",
"var",
"i",
"=",
"0",
";",
"function",
"next",
"(",
")",
"{",
"if",
"(",
"i",
">=",
"arr",
".",
"length",
")",
"{",
"onEnd",
"(",
")",
";",
"return",
";",
"}",
"var",
"item",
"=",
"arr",
"[",
"i",
"]",
";",
"i",
"++",
";",
"onIteration",
"(",
"item",
",",
"next",
",",
"onEnd",
")",
";",
"}",
"next",
"(",
")",
";",
"}"
] | Helper function to walk recursively through arr
@param arr
@param onIteration
@param onEnd | [
"Helper",
"function",
"to",
"walk",
"recursively",
"through",
"arr"
] | f82f03ba8a89d6a2df3aa4d59a5b9bc659258d72 | https://github.com/laxa1986/gulp-angular-embed-templates/blob/f82f03ba8a89d6a2df3aa4d59a5b9bc659258d72/lib/utils.js#L30-L42 | train |
laxa1986/gulp-angular-embed-templates | lib/utils.js | createLogger | function createLogger(logger) {
var result = logger ? objectAssign({}, logger) : {};
if (!result.debug) result.debug = console.log;
if (!result.info) result.info = console.info;
if (!result.warn) result.warn = console.warn;
if (!result.error) result.error = console.error;
return result;
} | javascript | function createLogger(logger) {
var result = logger ? objectAssign({}, logger) : {};
if (!result.debug) result.debug = console.log;
if (!result.info) result.info = console.info;
if (!result.warn) result.warn = console.warn;
if (!result.error) result.error = console.error;
return result;
} | [
"function",
"createLogger",
"(",
"logger",
")",
"{",
"var",
"result",
"=",
"logger",
"?",
"objectAssign",
"(",
"{",
"}",
",",
"logger",
")",
":",
"{",
"}",
";",
"if",
"(",
"!",
"result",
".",
"debug",
")",
"result",
".",
"debug",
"=",
"console",
".",
"log",
";",
"if",
"(",
"!",
"result",
".",
"info",
")",
"result",
".",
"info",
"=",
"console",
".",
"info",
";",
"if",
"(",
"!",
"result",
".",
"warn",
")",
"result",
".",
"warn",
"=",
"console",
".",
"warn",
";",
"if",
"(",
"!",
"result",
".",
"error",
")",
"result",
".",
"error",
"=",
"console",
".",
"error",
";",
"return",
"result",
";",
"}"
] | create a logger object based on passed logger. If passed logger has no some methods then add them
@param {Object} [logger] object with methods .debug, .warn, .error. Can be
@return {Object} | [
"create",
"a",
"logger",
"object",
"based",
"on",
"passed",
"logger",
".",
"If",
"passed",
"logger",
"has",
"no",
"some",
"methods",
"then",
"add",
"them"
] | f82f03ba8a89d6a2df3aa4d59a5b9bc659258d72 | https://github.com/laxa1986/gulp-angular-embed-templates/blob/f82f03ba8a89d6a2df3aa4d59a5b9bc659258d72/lib/utils.js#L50-L57 | train |
burl/mock-env | index.js | delVars | function delVars(origEnv, deleteVars) {
var i;
if (!Array.isArray(deleteVars))
return;
for (i = 0; i < deleteVars.length; i++) {
if (!has(origEnv, deleteVars[i])) {
origEnv[deleteVars[i]] = [
!!has(process.env, deleteVars[i]),
process.env[deleteVars[i]]
];
}
delete process.env[deleteVars[i]];
}
return;
} | javascript | function delVars(origEnv, deleteVars) {
var i;
if (!Array.isArray(deleteVars))
return;
for (i = 0; i < deleteVars.length; i++) {
if (!has(origEnv, deleteVars[i])) {
origEnv[deleteVars[i]] = [
!!has(process.env, deleteVars[i]),
process.env[deleteVars[i]]
];
}
delete process.env[deleteVars[i]];
}
return;
} | [
"function",
"delVars",
"(",
"origEnv",
",",
"deleteVars",
")",
"{",
"var",
"i",
";",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"deleteVars",
")",
")",
"return",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"deleteVars",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"has",
"(",
"origEnv",
",",
"deleteVars",
"[",
"i",
"]",
")",
")",
"{",
"origEnv",
"[",
"deleteVars",
"[",
"i",
"]",
"]",
"=",
"[",
"!",
"!",
"has",
"(",
"process",
".",
"env",
",",
"deleteVars",
"[",
"i",
"]",
")",
",",
"process",
".",
"env",
"[",
"deleteVars",
"[",
"i",
"]",
"]",
"]",
";",
"}",
"delete",
"process",
".",
"env",
"[",
"deleteVars",
"[",
"i",
"]",
"]",
";",
"}",
"return",
";",
"}"
] | remove vars from env
@arg {Object} origEnv - place to save state of original env
@arg {Array} deleteVars - names of env vars to remove from env
@function | [
"remove",
"vars",
"from",
"env"
] | 90a2b585c957a08007c3f8e23a257aa416e8e6e1 | https://github.com/burl/mock-env/blob/90a2b585c957a08007c3f8e23a257aa416e8e6e1/index.js#L43-L57 | train |
burl/mock-env | index.js | restoreEnv | function restoreEnv(origEnv) {
var key;
for (key in origEnv) {
if (origEnv[key][0]) {
process.env[key] = origEnv[key][1];
} else {
delete process.env[key];
}
}
return;
} | javascript | function restoreEnv(origEnv) {
var key;
for (key in origEnv) {
if (origEnv[key][0]) {
process.env[key] = origEnv[key][1];
} else {
delete process.env[key];
}
}
return;
} | [
"function",
"restoreEnv",
"(",
"origEnv",
")",
"{",
"var",
"key",
";",
"for",
"(",
"key",
"in",
"origEnv",
")",
"{",
"if",
"(",
"origEnv",
"[",
"key",
"]",
"[",
"0",
"]",
")",
"{",
"process",
".",
"env",
"[",
"key",
"]",
"=",
"origEnv",
"[",
"key",
"]",
"[",
"1",
"]",
";",
"}",
"else",
"{",
"delete",
"process",
".",
"env",
"[",
"key",
"]",
";",
"}",
"}",
"return",
";",
"}"
] | restore environment to original state
@arg {Object} origEnv - delta/state of process.env from prior morphing
@function | [
"restore",
"environment",
"to",
"original",
"state"
] | 90a2b585c957a08007c3f8e23a257aa416e8e6e1 | https://github.com/burl/mock-env/blob/90a2b585c957a08007c3f8e23a257aa416e8e6e1/index.js#L64-L74 | train |
burl/mock-env | index.js | callbackInModifiedEnv | function callbackInModifiedEnv(callback, setInEnv, removeFromEnv) {
var origEnv = {};
var result;
setVars(origEnv, setInEnv);
delVars(origEnv, removeFromEnv);
result = callback();
restoreEnv(origEnv);
return result;
} | javascript | function callbackInModifiedEnv(callback, setInEnv, removeFromEnv) {
var origEnv = {};
var result;
setVars(origEnv, setInEnv);
delVars(origEnv, removeFromEnv);
result = callback();
restoreEnv(origEnv);
return result;
} | [
"function",
"callbackInModifiedEnv",
"(",
"callback",
",",
"setInEnv",
",",
"removeFromEnv",
")",
"{",
"var",
"origEnv",
"=",
"{",
"}",
";",
"var",
"result",
";",
"setVars",
"(",
"origEnv",
",",
"setInEnv",
")",
";",
"delVars",
"(",
"origEnv",
",",
"removeFromEnv",
")",
";",
"result",
"=",
"callback",
"(",
")",
";",
"restoreEnv",
"(",
"origEnv",
")",
";",
"return",
"result",
";",
"}"
] | calls callback within context of modified environment
@callback callback - function to be called while environment is modified
@arg {Object} setInEnv - vars to set in current env
@arg {Array} removeFromEnv - array of variable names to remove from env
@function | [
"calls",
"callback",
"within",
"context",
"of",
"modified",
"environment"
] | 90a2b585c957a08007c3f8e23a257aa416e8e6e1 | https://github.com/burl/mock-env/blob/90a2b585c957a08007c3f8e23a257aa416e8e6e1/index.js#L83-L91 | train |
quorrajs/Ouch | handler/CallbackHandler.js | CallbackHandler | function CallbackHandler(callable) {
CallbackHandler.super_.call(this);
if (!_.isFunction(callable)) {
throw new TypeError(
'Argument must be valid callable'
);
}
this.__callable = callable;
} | javascript | function CallbackHandler(callable) {
CallbackHandler.super_.call(this);
if (!_.isFunction(callable)) {
throw new TypeError(
'Argument must be valid callable'
);
}
this.__callable = callable;
} | [
"function",
"CallbackHandler",
"(",
"callable",
")",
"{",
"CallbackHandler",
".",
"super_",
".",
"call",
"(",
"this",
")",
";",
"if",
"(",
"!",
"_",
".",
"isFunction",
"(",
"callable",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Argument must be valid callable'",
")",
";",
"}",
"this",
".",
"__callable",
"=",
"callable",
";",
"}"
] | Wrapper for Closures passed as handlers. Can be used
directly, or will be instantiated automagically by Ouch
if passed to ouchInstance.pushHandler
@param {function} callable
@constructor
@throws TypeError if argument is not callable | [
"Wrapper",
"for",
"Closures",
"passed",
"as",
"handlers",
".",
"Can",
"be",
"used",
"directly",
"or",
"will",
"be",
"instantiated",
"automagically",
"by",
"Ouch",
"if",
"passed",
"to",
"ouchInstance",
".",
"pushHandler"
] | cbadf54eaa78633761e295c8566a36bb1567d130 | https://github.com/quorrajs/Ouch/blob/cbadf54eaa78633761e295c8566a36bb1567d130/handler/CallbackHandler.js#L22-L32 | train |
Planeshifter/node-wordnet-magic | lib/rules_of_detachment.js | rulesOfDetachment | function rulesOfDetachment( word, pos, substitutions, dictionary ) {
var newEnding;
var recResult;
var newWord;
var result = [];
var suffix;
var elem;
var i;
for ( i = 0; i < dictionary.length; i++ ) {
elem = dictionary[ i ];
if ( elem.lemma === word ) {
if ( elem.pos === pos ) {
var obj = new this.Word( elem.lemma );
obj.part_of_speech = elem.pos;
result.push( obj );
}
}
}
for ( i = 0; i < substitutions.length; i++ ) {
suffix = substitutions[ i ].suffix;
newEnding = substitutions[ i ].ending;
if ( word.endsWith(suffix) === true ) {
newWord = word.substring( 0, word.length - suffix.length ) + newEnding;
substitutions.splice( i, 1 );
if ( newWord.endsWith( 'e' ) && !word.endsWith( 'e' )){
substitutions.push( {
suffix: 'e',
ending: ''
} );
}
recResult = rulesOfDetachment( newWord, pos, substitutions, dictionary );
if ( Array.isArray( recResult ) ) {
result = result.concat( recResult );
} else {
result.push( recResult );
}
}
}
return result;
} | javascript | function rulesOfDetachment( word, pos, substitutions, dictionary ) {
var newEnding;
var recResult;
var newWord;
var result = [];
var suffix;
var elem;
var i;
for ( i = 0; i < dictionary.length; i++ ) {
elem = dictionary[ i ];
if ( elem.lemma === word ) {
if ( elem.pos === pos ) {
var obj = new this.Word( elem.lemma );
obj.part_of_speech = elem.pos;
result.push( obj );
}
}
}
for ( i = 0; i < substitutions.length; i++ ) {
suffix = substitutions[ i ].suffix;
newEnding = substitutions[ i ].ending;
if ( word.endsWith(suffix) === true ) {
newWord = word.substring( 0, word.length - suffix.length ) + newEnding;
substitutions.splice( i, 1 );
if ( newWord.endsWith( 'e' ) && !word.endsWith( 'e' )){
substitutions.push( {
suffix: 'e',
ending: ''
} );
}
recResult = rulesOfDetachment( newWord, pos, substitutions, dictionary );
if ( Array.isArray( recResult ) ) {
result = result.concat( recResult );
} else {
result.push( recResult );
}
}
}
return result;
} | [
"function",
"rulesOfDetachment",
"(",
"word",
",",
"pos",
",",
"substitutions",
",",
"dictionary",
")",
"{",
"var",
"newEnding",
";",
"var",
"recResult",
";",
"var",
"newWord",
";",
"var",
"result",
"=",
"[",
"]",
";",
"var",
"suffix",
";",
"var",
"elem",
";",
"var",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"dictionary",
".",
"length",
";",
"i",
"++",
")",
"{",
"elem",
"=",
"dictionary",
"[",
"i",
"]",
";",
"if",
"(",
"elem",
".",
"lemma",
"===",
"word",
")",
"{",
"if",
"(",
"elem",
".",
"pos",
"===",
"pos",
")",
"{",
"var",
"obj",
"=",
"new",
"this",
".",
"Word",
"(",
"elem",
".",
"lemma",
")",
";",
"obj",
".",
"part_of_speech",
"=",
"elem",
".",
"pos",
";",
"result",
".",
"push",
"(",
"obj",
")",
";",
"}",
"}",
"}",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"substitutions",
".",
"length",
";",
"i",
"++",
")",
"{",
"suffix",
"=",
"substitutions",
"[",
"i",
"]",
".",
"suffix",
";",
"newEnding",
"=",
"substitutions",
"[",
"i",
"]",
".",
"ending",
";",
"if",
"(",
"word",
".",
"endsWith",
"(",
"suffix",
")",
"===",
"true",
")",
"{",
"newWord",
"=",
"word",
".",
"substring",
"(",
"0",
",",
"word",
".",
"length",
"-",
"suffix",
".",
"length",
")",
"+",
"newEnding",
";",
"substitutions",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"if",
"(",
"newWord",
".",
"endsWith",
"(",
"'e'",
")",
"&&",
"!",
"word",
".",
"endsWith",
"(",
"'e'",
")",
")",
"{",
"substitutions",
".",
"push",
"(",
"{",
"suffix",
":",
"'e'",
",",
"ending",
":",
"''",
"}",
")",
";",
"}",
"recResult",
"=",
"rulesOfDetachment",
"(",
"newWord",
",",
"pos",
",",
"substitutions",
",",
"dictionary",
")",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"recResult",
")",
")",
"{",
"result",
"=",
"result",
".",
"concat",
"(",
"recResult",
")",
";",
"}",
"else",
"{",
"result",
".",
"push",
"(",
"recResult",
")",
";",
"}",
"}",
"}",
"return",
"result",
";",
"}"
] | Apply rules of detachment to obtain base forms for supplied word.
@param {string} word - input word
@param {string} pos - part of speech
@param {Array} substitutions - Morphy substitutions
@param {Array} dictionary - WordNet dictionary
@returns {Array} base forms | [
"Apply",
"rules",
"of",
"detachment",
"to",
"obtain",
"base",
"forms",
"for",
"supplied",
"word",
"."
] | a7c6000bd63c79562ebb1e9a85820809a9a17058 | https://github.com/Planeshifter/node-wordnet-magic/blob/a7c6000bd63c79562ebb1e9a85820809a9a17058/lib/rules_of_detachment.js#L13-L55 | train |
pavben/WebIRC | static/js/statechanges.js | function(element, sortedList, sortFunction) {
var lo = 0;
var hi = sortedList.length - 1;
var mid, result;
while (lo <= hi) {
mid = lo + Math.floor((hi - lo) / 2);
result = sortFunction(element, sortedList[mid]);
if (result < 0) {
// mid is too high
hi = mid - 1;
} else if (result > 0) {
// mid is too low
lo = mid + 1;
} else {
// mid is the exact index of element
return mid;
}
}
return null;
} | javascript | function(element, sortedList, sortFunction) {
var lo = 0;
var hi = sortedList.length - 1;
var mid, result;
while (lo <= hi) {
mid = lo + Math.floor((hi - lo) / 2);
result = sortFunction(element, sortedList[mid]);
if (result < 0) {
// mid is too high
hi = mid - 1;
} else if (result > 0) {
// mid is too low
lo = mid + 1;
} else {
// mid is the exact index of element
return mid;
}
}
return null;
} | [
"function",
"(",
"element",
",",
"sortedList",
",",
"sortFunction",
")",
"{",
"var",
"lo",
"=",
"0",
";",
"var",
"hi",
"=",
"sortedList",
".",
"length",
"-",
"1",
";",
"var",
"mid",
",",
"result",
";",
"while",
"(",
"lo",
"<=",
"hi",
")",
"{",
"mid",
"=",
"lo",
"+",
"Math",
".",
"floor",
"(",
"(",
"hi",
"-",
"lo",
")",
"/",
"2",
")",
";",
"result",
"=",
"sortFunction",
"(",
"element",
",",
"sortedList",
"[",
"mid",
"]",
")",
";",
"if",
"(",
"result",
"<",
"0",
")",
"{",
"hi",
"=",
"mid",
"-",
"1",
";",
"}",
"else",
"if",
"(",
"result",
">",
"0",
")",
"{",
"lo",
"=",
"mid",
"+",
"1",
";",
"}",
"else",
"{",
"return",
"mid",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | returns the index of the element if found, or null otherwise | [
"returns",
"the",
"index",
"of",
"the",
"element",
"if",
"found",
"or",
"null",
"otherwise"
] | 518e311f87a6190c620e9b405855b8557b672bd6 | https://github.com/pavben/WebIRC/blob/518e311f87a6190c620e9b405855b8557b672bd6/static/js/statechanges.js#L565-L588 | train |
|
pavben/WebIRC | static/js/statechanges.js | function(element, sortedList, sortFunction) {
// p(index) = val at index is same or larger than element
function p(index) {
return (sortFunction(element, sortedList[index]) <= 0);
}
var lo = 0;
var hi = sortedList.length - 1;
var mid, result;
while (lo < hi) {
mid = lo + Math.floor((hi - lo) / 2);
result = p(mid);
if (result) {
// mid is too high or just right
hi = mid;
} else {
// mid is too low
lo = mid + 1;
}
}
if (lo < sortedList.length && p(lo)) {
return lo;
} else {
// the element was not found and belongs at the end of the list (possibly 0 if the list is empty)
return sortedList.length;
}
} | javascript | function(element, sortedList, sortFunction) {
// p(index) = val at index is same or larger than element
function p(index) {
return (sortFunction(element, sortedList[index]) <= 0);
}
var lo = 0;
var hi = sortedList.length - 1;
var mid, result;
while (lo < hi) {
mid = lo + Math.floor((hi - lo) / 2);
result = p(mid);
if (result) {
// mid is too high or just right
hi = mid;
} else {
// mid is too low
lo = mid + 1;
}
}
if (lo < sortedList.length && p(lo)) {
return lo;
} else {
// the element was not found and belongs at the end of the list (possibly 0 if the list is empty)
return sortedList.length;
}
} | [
"function",
"(",
"element",
",",
"sortedList",
",",
"sortFunction",
")",
"{",
"function",
"p",
"(",
"index",
")",
"{",
"return",
"(",
"sortFunction",
"(",
"element",
",",
"sortedList",
"[",
"index",
"]",
")",
"<=",
"0",
")",
";",
"}",
"var",
"lo",
"=",
"0",
";",
"var",
"hi",
"=",
"sortedList",
".",
"length",
"-",
"1",
";",
"var",
"mid",
",",
"result",
";",
"while",
"(",
"lo",
"<",
"hi",
")",
"{",
"mid",
"=",
"lo",
"+",
"Math",
".",
"floor",
"(",
"(",
"hi",
"-",
"lo",
")",
"/",
"2",
")",
";",
"result",
"=",
"p",
"(",
"mid",
")",
";",
"if",
"(",
"result",
")",
"{",
"hi",
"=",
"mid",
";",
"}",
"else",
"{",
"lo",
"=",
"mid",
"+",
"1",
";",
"}",
"}",
"if",
"(",
"lo",
"<",
"sortedList",
".",
"length",
"&&",
"p",
"(",
"lo",
")",
")",
"{",
"return",
"lo",
";",
"}",
"else",
"{",
"return",
"sortedList",
".",
"length",
";",
"}",
"}"
] | returns the index at which the element should be inserted | [
"returns",
"the",
"index",
"at",
"which",
"the",
"element",
"should",
"be",
"inserted"
] | 518e311f87a6190c620e9b405855b8557b672bd6 | https://github.com/pavben/WebIRC/blob/518e311f87a6190c620e9b405855b8557b672bd6/static/js/statechanges.js#L590-L620 | train |
|
Alhadis/Print | print.js | print | function print(input, opts = {}, /* …Internal:*/ name = "", refs = null){
// Handle options and defaults
let {
ampedSymbols,
escapeChars,
invokeGetters,
maxArrayLength,
showAll,
showArrayIndices,
showArrayLength,
sortProps,
} = opts;
ampedSymbols = undefined === ampedSymbols ? true : ampedSymbols;
escapeChars = undefined === escapeChars ? /(?!\x20)\s|\\/g : escapeChars;
sortProps = undefined === sortProps ? true : sortProps;
maxArrayLength = undefined === maxArrayLength ? 100 : (!+maxArrayLength ? false : maxArrayLength);
if(escapeChars && "function" !== typeof escapeChars)
escapeChars = (function(pattern){
return function(input){
return input.replace(pattern, function(char){
switch(char){
case "\f": return "\\f";
case "\n": return "\\n";
case "\r": return "\\r";
case "\t": return "\\t";
case "\v": return "\\v";
case "\\": return "\\\\";
}
const cp = char.codePointAt(0);
const hex = cp.toString(16).toUpperCase();
if(cp < 0xFF) return "\\x" + hex;
return "\\u{" + hex + "}";
});
};
}(escapeChars));
// Only thing that can't be checked with obvious methods
if(Number.isNaN(input)) return "NaN";
// Exact match
switch(input){
// Primitives
case null: return "null";
case undefined: return "undefined";
case true: return "true";
case false: return "false";
// "Special" values
case Math.E: return "Math.E";
case Math.LN10: return "Math.LN10";
case Math.LN2: return "Math.LN2";
case Math.LOG10E: return "Math.LOG10E";
case Math.LOG2E: return "Math.LOG2E";
case Math.PI: return "Math.PI";
case Math.SQRT1_2: return "Math.SQRT1_2";
case Math.SQRT2: return "Math.SQRT2";
case Number.EPSILON: return "Number.EPSILON";
case Number.MIN_VALUE: return "Number.MIN_VALUE";
case Number.MAX_VALUE: return "Number.MAX_VALUE";
case Number.MIN_SAFE_INTEGER: return "Number.MIN_SAFE_INTEGER";
case Number.MAX_SAFE_INTEGER: return "Number.MAX_SAFE_INTEGER";
case Number.NEGATIVE_INFINITY: return "Number.NEGATIVE_INFINITY";
case Number.POSITIVE_INFINITY: return "Number.POSITIVE_INFINITY";
}
// Basic data types
const type = Object.prototype.toString.call(input);
switch(type){
case "[object Number]":
if("number" !== typeof input) break;
return input.toString();
case "[object Symbol]":
if("symbol" !== typeof input) break;
return input.toString();
case "[object String]":
if("string" !== typeof input) break;
if(escapeChars)
input = escapeChars(input);
return `"${input}"`;
}
// Guard against circular references
refs = refs || new Map();
if(refs.has(input))
return "-> " + (refs.get(input) || "{input}");
refs.set(input, name);
// Begin compiling some serious output
let output = "";
let typeName = "";
let arrayLike;
let isFunc;
let ignoreNumbers;
let padBeforeProps;
// Resolve which properties get displayed in the output
const descriptors = [
...Object.getOwnPropertyNames(input),
...Object.getOwnPropertySymbols(input),
].map(key => [key, Object.getOwnPropertyDescriptor(input, key)]);
let normalKeys = [];
let symbolKeys = [];
for(const [key, descriptor] of descriptors){
const {enumerable, get, set} = descriptor;
// Skip non-enumerable properties
if(!showAll && !enumerable) continue;
if(!get && !set || invokeGetters && get)
"symbol" === typeof key
? symbolKeys.push(key)
: normalKeys.push(key);
}
// Maps
if("[object Map]" === type){
typeName = "Map";
if(input.size){
padBeforeProps = true;
let index = 0;
for(let [key, value] of input.entries()){
const namePrefix = (name ? name : "Map") + ".entries";
const keyString = `${index}.key`;
const valueString = `${index}.value`;
key = print(key, opts, `${namePrefix}[${keyString}]`, refs);
value = print(value, opts, `${namePrefix}[${valueString}]`, refs);
output += keyString + (/^->\s/.test(key) ? " " : " => ") + key + "\n";
output += valueString + (/^->\s/.test(value) ? " " : " => ") + value + "\n\n";
++index;
}
output = "\n" + output.replace(/\s+$/, "");
}
}
// Sets
else if("[object Set]" === type){
typeName = "Set";
if(input.size){
padBeforeProps = true;
let index = 0;
for(let value of input.values()){
const valueName = (name ? name : "{input}") + ".entries[" + index + "]";
value = print(value, opts, valueName, refs);
const delim = /^->\s/.test(value) ? " " : " => ";
output += index + delim + value + "\n";
++index;
}
output = "\n" + output.replace(/\s+$/, "");
}
}
// Dates
else if(input instanceof Date){
typeName = "Date";
padBeforeProps = true;
if("Invalid Date" === input.toString())
output = "\nInvalid Date";
else{
output = "\n" + input.toISOString()
.replace(/T/, " ")
.replace(/\.?0*Z$/m, " GMT")
+ "\n";
let delta = Date.now() - input.getTime();
let future = delta < 0;
const units = [
[1000, "second"],
[60000, "minute"],
[3600000, "hour"],
[86400000, "day"],
[2628e6, "month"],
[31536e6, "year"],
];
delta = Math.abs(delta);
for(let i = 0, l = units.length; i < l; ++i){
const nextUnit = units[i + 1];
if(!nextUnit || delta < nextUnit[0]){
let [value, name] = units[i];
// Only bother with floating-point values if it's within the last week
delta = (i > 0 && delta < 6048e5)
? (delta / value).toFixed(1).replace(/\.?0+$/, "")
: Math.round(delta / value);
output += `${delta} ${name}`;
if(delta != 1)
output += "s";
break;
}
}
output += future ? " from now" : " ago";
}
}
// Objects and functions
else switch(type){
// Number objects
case "[object Number]":
output = "\n" + print(Number.prototype.valueOf.call(input), opts);
padBeforeProps = true;
break;
// String objects
case "[object String]":
output = "\n" + print(String.prototype.toString.call(input), opts);
padBeforeProps = true;
break;
// Boolean objects
case "[object Boolean]":
output = "\n" + Boolean.prototype.toString.call(input);
padBeforeProps = true;
break;
// Regular expressions
case "[object RegExp]":{
const {lastIndex, source, flags} = input;
output = `/${source}/${flags}`;
// Return early if RegExp isn't subclassed and has no unusual properties
if(RegExp === input.constructor && 0 === lastIndex && 0 === normalKeys.length)
return output;
else{
output = "\n" + output;
padBeforeProps = true;
if(0 !== lastIndex)
normalKeys.push("lastIndex");
}
break;
}
// Anything else
default:
arrayLike = "function" === typeof input[Symbol.iterator];
isFunc = "function" === typeof input;
ignoreNumbers = !showArrayIndices && arrayLike;
}
// Functions: Include name and arity
if(isFunc){
if(-1 === normalKeys.indexOf("name")) normalKeys.push("name");
if(-1 === normalKeys.indexOf("length")) normalKeys.push("length");
}
// Errors: Include name and message
else if(input instanceof Error){
if(-1 === normalKeys.indexOf("name")) normalKeys.push("name");
if(-1 === normalKeys.indexOf("message")) normalKeys.push("message");
}
// Arrays: Handle length property
else if(arrayLike){
const index = normalKeys.indexOf("length");
if(showArrayLength && -1 === index)
normalKeys.push("length");
else if(!showArrayLength && -1 !== index)
normalKeys.splice(index, 1);
}
// Clip lengthy arrays to a sensible limit
let truncationNote = null;
if(maxArrayLength !== false && arrayLike && input.length > maxArrayLength){
normalKeys = normalKeys.filter(k => +k != k || +k < maxArrayLength);
truncationNote = `\n\n… ${input.length - maxArrayLength} more values not shown\n`;
}
// Alphabetise each property name
if(sortProps) normalKeys = normalKeys.sort((a, b) => {
let A, B;
// Numbers: Compare algebraically
if(("0" == a || +a == a) && ("0" == b || +b == b)){
A = +a;
B = +b;
}
// Anything else: Convert to lowercase
else{
A = a.toLowerCase();
B = b.toLowerCase();
}
if(A < B) return -1;
if(A > B) return 1;
return 0;
});
// Insert a blank line if existing lines have been printed for this object
if(padBeforeProps && normalKeys.length)
output += "\n";
// Regular properties
normalKeys = Array.from(new Set(normalKeys));
for(let i = 0, l = normalKeys.length; i < l; ++i){
let key = normalKeys[i];
// Array's been truncated, and this is the first non-numeric key
if(null !== truncationNote && +key != key){
output += truncationNote;
truncationNote = null;
}
let accessor = /\W|^\d+$/.test(key) ? `[${key}]` : (name ? "."+key : key);
let value = print(input[key], opts, name + accessor, refs);
output += "\n";
// Arrays: Check if each value's index should be omitted
if(ignoreNumbers && /^\d+$/.test(key))
output += value;
// Name: Value
else output += `${key}: ${value}`;
}
// If we still have a truncation notice, it means there were only numerics to list
if(null !== truncationNote)
output += truncationNote.replace(/\n+$/, "");
// Properties keyed by Symbols
symbolKeys = Array.from(new Set(symbolKeys));
if(sortProps) symbolKeys = symbolKeys.sort((a, b) => {
const A = a.toString().toLowerCase();
const B = b.toString().toLowerCase();
if(A < B) return -1;
if(A > B) return 1;
return 0;
});
for(let i = 0, l = symbolKeys.length; i < l; ++i){
const symbol = symbolKeys[i];
let accessor = symbol.toString();
let valName = "[" + accessor + "]";
// Use a @@-prefixed form to represent Symbols in property lists
if(ampedSymbols){
accessor = "@@" + accessor.replace(/^Symbol\(|\)$/g, "");
valName = (name ? "." : "") + accessor;
}
const value = print(input[symbol], opts, name + valName, refs);
output += `\n${accessor}: ${value}`;
}
// Tweak output based on the value's type
if("[object Arguments]" === type)
typeName = "Arguments";
else{
const ctr = input.constructor ? input.constructor.name : "";
switch(ctr){
case "AsyncGeneratorFunction":
typeName = "async function*()";
break;
case "AsyncFunction":
typeName = "async function()";
break;
case "GeneratorFunction":
typeName = "function*()";
break;
case "Function":
typeName = "function()";
break;
case "Array":
case "Object":
typeName = "";
break;
default:
typeName = ctr;
break;
}
}
output = output ? output.replace(/\n/g, "\n\t") + "\n" : "";
return typeName + (arrayLike
? "[" + output + "]"
: "{" + output + "}");
} | javascript | function print(input, opts = {}, /* …Internal:*/ name = "", refs = null){
// Handle options and defaults
let {
ampedSymbols,
escapeChars,
invokeGetters,
maxArrayLength,
showAll,
showArrayIndices,
showArrayLength,
sortProps,
} = opts;
ampedSymbols = undefined === ampedSymbols ? true : ampedSymbols;
escapeChars = undefined === escapeChars ? /(?!\x20)\s|\\/g : escapeChars;
sortProps = undefined === sortProps ? true : sortProps;
maxArrayLength = undefined === maxArrayLength ? 100 : (!+maxArrayLength ? false : maxArrayLength);
if(escapeChars && "function" !== typeof escapeChars)
escapeChars = (function(pattern){
return function(input){
return input.replace(pattern, function(char){
switch(char){
case "\f": return "\\f";
case "\n": return "\\n";
case "\r": return "\\r";
case "\t": return "\\t";
case "\v": return "\\v";
case "\\": return "\\\\";
}
const cp = char.codePointAt(0);
const hex = cp.toString(16).toUpperCase();
if(cp < 0xFF) return "\\x" + hex;
return "\\u{" + hex + "}";
});
};
}(escapeChars));
// Only thing that can't be checked with obvious methods
if(Number.isNaN(input)) return "NaN";
// Exact match
switch(input){
// Primitives
case null: return "null";
case undefined: return "undefined";
case true: return "true";
case false: return "false";
// "Special" values
case Math.E: return "Math.E";
case Math.LN10: return "Math.LN10";
case Math.LN2: return "Math.LN2";
case Math.LOG10E: return "Math.LOG10E";
case Math.LOG2E: return "Math.LOG2E";
case Math.PI: return "Math.PI";
case Math.SQRT1_2: return "Math.SQRT1_2";
case Math.SQRT2: return "Math.SQRT2";
case Number.EPSILON: return "Number.EPSILON";
case Number.MIN_VALUE: return "Number.MIN_VALUE";
case Number.MAX_VALUE: return "Number.MAX_VALUE";
case Number.MIN_SAFE_INTEGER: return "Number.MIN_SAFE_INTEGER";
case Number.MAX_SAFE_INTEGER: return "Number.MAX_SAFE_INTEGER";
case Number.NEGATIVE_INFINITY: return "Number.NEGATIVE_INFINITY";
case Number.POSITIVE_INFINITY: return "Number.POSITIVE_INFINITY";
}
// Basic data types
const type = Object.prototype.toString.call(input);
switch(type){
case "[object Number]":
if("number" !== typeof input) break;
return input.toString();
case "[object Symbol]":
if("symbol" !== typeof input) break;
return input.toString();
case "[object String]":
if("string" !== typeof input) break;
if(escapeChars)
input = escapeChars(input);
return `"${input}"`;
}
// Guard against circular references
refs = refs || new Map();
if(refs.has(input))
return "-> " + (refs.get(input) || "{input}");
refs.set(input, name);
// Begin compiling some serious output
let output = "";
let typeName = "";
let arrayLike;
let isFunc;
let ignoreNumbers;
let padBeforeProps;
// Resolve which properties get displayed in the output
const descriptors = [
...Object.getOwnPropertyNames(input),
...Object.getOwnPropertySymbols(input),
].map(key => [key, Object.getOwnPropertyDescriptor(input, key)]);
let normalKeys = [];
let symbolKeys = [];
for(const [key, descriptor] of descriptors){
const {enumerable, get, set} = descriptor;
// Skip non-enumerable properties
if(!showAll && !enumerable) continue;
if(!get && !set || invokeGetters && get)
"symbol" === typeof key
? symbolKeys.push(key)
: normalKeys.push(key);
}
// Maps
if("[object Map]" === type){
typeName = "Map";
if(input.size){
padBeforeProps = true;
let index = 0;
for(let [key, value] of input.entries()){
const namePrefix = (name ? name : "Map") + ".entries";
const keyString = `${index}.key`;
const valueString = `${index}.value`;
key = print(key, opts, `${namePrefix}[${keyString}]`, refs);
value = print(value, opts, `${namePrefix}[${valueString}]`, refs);
output += keyString + (/^->\s/.test(key) ? " " : " => ") + key + "\n";
output += valueString + (/^->\s/.test(value) ? " " : " => ") + value + "\n\n";
++index;
}
output = "\n" + output.replace(/\s+$/, "");
}
}
// Sets
else if("[object Set]" === type){
typeName = "Set";
if(input.size){
padBeforeProps = true;
let index = 0;
for(let value of input.values()){
const valueName = (name ? name : "{input}") + ".entries[" + index + "]";
value = print(value, opts, valueName, refs);
const delim = /^->\s/.test(value) ? " " : " => ";
output += index + delim + value + "\n";
++index;
}
output = "\n" + output.replace(/\s+$/, "");
}
}
// Dates
else if(input instanceof Date){
typeName = "Date";
padBeforeProps = true;
if("Invalid Date" === input.toString())
output = "\nInvalid Date";
else{
output = "\n" + input.toISOString()
.replace(/T/, " ")
.replace(/\.?0*Z$/m, " GMT")
+ "\n";
let delta = Date.now() - input.getTime();
let future = delta < 0;
const units = [
[1000, "second"],
[60000, "minute"],
[3600000, "hour"],
[86400000, "day"],
[2628e6, "month"],
[31536e6, "year"],
];
delta = Math.abs(delta);
for(let i = 0, l = units.length; i < l; ++i){
const nextUnit = units[i + 1];
if(!nextUnit || delta < nextUnit[0]){
let [value, name] = units[i];
// Only bother with floating-point values if it's within the last week
delta = (i > 0 && delta < 6048e5)
? (delta / value).toFixed(1).replace(/\.?0+$/, "")
: Math.round(delta / value);
output += `${delta} ${name}`;
if(delta != 1)
output += "s";
break;
}
}
output += future ? " from now" : " ago";
}
}
// Objects and functions
else switch(type){
// Number objects
case "[object Number]":
output = "\n" + print(Number.prototype.valueOf.call(input), opts);
padBeforeProps = true;
break;
// String objects
case "[object String]":
output = "\n" + print(String.prototype.toString.call(input), opts);
padBeforeProps = true;
break;
// Boolean objects
case "[object Boolean]":
output = "\n" + Boolean.prototype.toString.call(input);
padBeforeProps = true;
break;
// Regular expressions
case "[object RegExp]":{
const {lastIndex, source, flags} = input;
output = `/${source}/${flags}`;
// Return early if RegExp isn't subclassed and has no unusual properties
if(RegExp === input.constructor && 0 === lastIndex && 0 === normalKeys.length)
return output;
else{
output = "\n" + output;
padBeforeProps = true;
if(0 !== lastIndex)
normalKeys.push("lastIndex");
}
break;
}
// Anything else
default:
arrayLike = "function" === typeof input[Symbol.iterator];
isFunc = "function" === typeof input;
ignoreNumbers = !showArrayIndices && arrayLike;
}
// Functions: Include name and arity
if(isFunc){
if(-1 === normalKeys.indexOf("name")) normalKeys.push("name");
if(-1 === normalKeys.indexOf("length")) normalKeys.push("length");
}
// Errors: Include name and message
else if(input instanceof Error){
if(-1 === normalKeys.indexOf("name")) normalKeys.push("name");
if(-1 === normalKeys.indexOf("message")) normalKeys.push("message");
}
// Arrays: Handle length property
else if(arrayLike){
const index = normalKeys.indexOf("length");
if(showArrayLength && -1 === index)
normalKeys.push("length");
else if(!showArrayLength && -1 !== index)
normalKeys.splice(index, 1);
}
// Clip lengthy arrays to a sensible limit
let truncationNote = null;
if(maxArrayLength !== false && arrayLike && input.length > maxArrayLength){
normalKeys = normalKeys.filter(k => +k != k || +k < maxArrayLength);
truncationNote = `\n\n… ${input.length - maxArrayLength} more values not shown\n`;
}
// Alphabetise each property name
if(sortProps) normalKeys = normalKeys.sort((a, b) => {
let A, B;
// Numbers: Compare algebraically
if(("0" == a || +a == a) && ("0" == b || +b == b)){
A = +a;
B = +b;
}
// Anything else: Convert to lowercase
else{
A = a.toLowerCase();
B = b.toLowerCase();
}
if(A < B) return -1;
if(A > B) return 1;
return 0;
});
// Insert a blank line if existing lines have been printed for this object
if(padBeforeProps && normalKeys.length)
output += "\n";
// Regular properties
normalKeys = Array.from(new Set(normalKeys));
for(let i = 0, l = normalKeys.length; i < l; ++i){
let key = normalKeys[i];
// Array's been truncated, and this is the first non-numeric key
if(null !== truncationNote && +key != key){
output += truncationNote;
truncationNote = null;
}
let accessor = /\W|^\d+$/.test(key) ? `[${key}]` : (name ? "."+key : key);
let value = print(input[key], opts, name + accessor, refs);
output += "\n";
// Arrays: Check if each value's index should be omitted
if(ignoreNumbers && /^\d+$/.test(key))
output += value;
// Name: Value
else output += `${key}: ${value}`;
}
// If we still have a truncation notice, it means there were only numerics to list
if(null !== truncationNote)
output += truncationNote.replace(/\n+$/, "");
// Properties keyed by Symbols
symbolKeys = Array.from(new Set(symbolKeys));
if(sortProps) symbolKeys = symbolKeys.sort((a, b) => {
const A = a.toString().toLowerCase();
const B = b.toString().toLowerCase();
if(A < B) return -1;
if(A > B) return 1;
return 0;
});
for(let i = 0, l = symbolKeys.length; i < l; ++i){
const symbol = symbolKeys[i];
let accessor = symbol.toString();
let valName = "[" + accessor + "]";
// Use a @@-prefixed form to represent Symbols in property lists
if(ampedSymbols){
accessor = "@@" + accessor.replace(/^Symbol\(|\)$/g, "");
valName = (name ? "." : "") + accessor;
}
const value = print(input[symbol], opts, name + valName, refs);
output += `\n${accessor}: ${value}`;
}
// Tweak output based on the value's type
if("[object Arguments]" === type)
typeName = "Arguments";
else{
const ctr = input.constructor ? input.constructor.name : "";
switch(ctr){
case "AsyncGeneratorFunction":
typeName = "async function*()";
break;
case "AsyncFunction":
typeName = "async function()";
break;
case "GeneratorFunction":
typeName = "function*()";
break;
case "Function":
typeName = "function()";
break;
case "Array":
case "Object":
typeName = "";
break;
default:
typeName = ctr;
break;
}
}
output = output ? output.replace(/\n/g, "\n\t") + "\n" : "";
return typeName + (arrayLike
? "[" + output + "]"
: "{" + output + "}");
} | [
"function",
"print",
"(",
"input",
",",
"opts",
"=",
"{",
"}",
",",
"me =",
"\"",
", ",
",",
" ",
"r",
"fs =",
"n",
"ll){"
] | Generate a human-readable representation of a value.
@param {Mixed} input - Value to print
@param {Object} opts - Optional parameters
@param {Boolean} opts.ampedSymbols - Prefix Symbol-keyed properties with @@
@param {Mixed} opts.escapeChars - Which characters to escape in string values
@param {Boolean} opts.invokeGetters - Show the values of properties defined by getter functions
@param {Number} opts.maxArrayLength - Maximum number of array values to show before truncating
@param {Boolean} opts.showAll - Display non-enumerable properties
@param {Boolean} opts.showArrayIndices - Show the index of each element in an array
@param {Boolean} opts.showArrayLength - Display an array's "length" property after its values
@param {Boolean} opts.sortProps - Alphabetise the properties of printed objects
@return {String} | [
"Generate",
"a",
"human",
"-",
"readable",
"representation",
"of",
"a",
"value",
"."
] | c289a04a25669370e7038ce3db8bc343d5e87347 | https://github.com/Alhadis/Print/blob/c289a04a25669370e7038ce3db8bc343d5e87347/print.js#L18-L437 | train |
neyric/aws-swf | lib/event-list.js | function (scheduledEventId) {
var i;
for (i = 0; i < this._events.length; i++) {
var evt = this._events[i];
if (evt.eventId === scheduledEventId) {
return evt.activityTaskScheduledEventAttributes.activityId;
}
}
return false;
} | javascript | function (scheduledEventId) {
var i;
for (i = 0; i < this._events.length; i++) {
var evt = this._events[i];
if (evt.eventId === scheduledEventId) {
return evt.activityTaskScheduledEventAttributes.activityId;
}
}
return false;
} | [
"function",
"(",
"scheduledEventId",
")",
"{",
"var",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"_events",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"evt",
"=",
"this",
".",
"_events",
"[",
"i",
"]",
";",
"if",
"(",
"evt",
".",
"eventId",
"===",
"scheduledEventId",
")",
"{",
"return",
"evt",
".",
"activityTaskScheduledEventAttributes",
".",
"activityId",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Return the activityId given the scheduledEventId
@param {String} scheduledEventId
@returns {String} activityId - The activityId if found, false otherwise | [
"Return",
"the",
"activityId",
"given",
"the",
"scheduledEventId"
] | 31b96c9eef313199465b40204a92909996a85c3d | https://github.com/neyric/aws-swf/blob/31b96c9eef313199465b40204a92909996a85c3d/lib/event-list.js#L19-L28 | train |
|
neyric/aws-swf | lib/event-list.js | function (eventId) {
var i;
for (i = 0; i < this._events.length; i++) {
var evt = this._events[i];
if (evt.eventId === eventId) {
return evt;
}
}
return false;
} | javascript | function (eventId) {
var i;
for (i = 0; i < this._events.length; i++) {
var evt = this._events[i];
if (evt.eventId === eventId) {
return evt;
}
}
return false;
} | [
"function",
"(",
"eventId",
")",
"{",
"var",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"_events",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"evt",
"=",
"this",
".",
"_events",
"[",
"i",
"]",
";",
"if",
"(",
"evt",
".",
"eventId",
"===",
"eventId",
")",
"{",
"return",
"evt",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Return the activityId
@param {Integer} eventId
@returns {Object} evt - The event if found, false otherwise | [
"Return",
"the",
"activityId"
] | 31b96c9eef313199465b40204a92909996a85c3d | https://github.com/neyric/aws-swf/blob/31b96c9eef313199465b40204a92909996a85c3d/lib/event-list.js#L35-L44 | train |
|
neyric/aws-swf | lib/event-list.js | function(eventType, attributeKey, attributeValue) {
var attrsKey = this._event_attributes_key(eventType);
for(var i = 0; i < this._events.length ; i++) {
var evt = this._events[i];
if ( (evt.eventType === eventType) && (evt[attrsKey][attributeKey] === attributeValue) ) {
return evt;
}
}
return null;
} | javascript | function(eventType, attributeKey, attributeValue) {
var attrsKey = this._event_attributes_key(eventType);
for(var i = 0; i < this._events.length ; i++) {
var evt = this._events[i];
if ( (evt.eventType === eventType) && (evt[attrsKey][attributeKey] === attributeValue) ) {
return evt;
}
}
return null;
} | [
"function",
"(",
"eventType",
",",
"attributeKey",
",",
"attributeValue",
")",
"{",
"var",
"attrsKey",
"=",
"this",
".",
"_event_attributes_key",
"(",
"eventType",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"_events",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"evt",
"=",
"this",
".",
"_events",
"[",
"i",
"]",
";",
"if",
"(",
"(",
"evt",
".",
"eventType",
"===",
"eventType",
")",
"&&",
"(",
"evt",
"[",
"attrsKey",
"]",
"[",
"attributeKey",
"]",
"===",
"attributeValue",
")",
")",
"{",
"return",
"evt",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | Return the Event for the given type that has the given attribute value
@param {String} eventType
@param {String} attributeKey
@param {String} attributeValue
@returns {Object} evt - The event if found, null otherwise | [
"Return",
"the",
"Event",
"for",
"the",
"given",
"type",
"that",
"has",
"the",
"given",
"attribute",
"value"
] | 31b96c9eef313199465b40204a92909996a85c3d | https://github.com/neyric/aws-swf/blob/31b96c9eef313199465b40204a92909996a85c3d/lib/event-list.js#L63-L72 | train |
|
neyric/aws-swf | lib/event-list.js | function(eventType, activityId) {
var attrsKey = this._event_attributes_key(eventType);
return this._events.some(function (evt) {
if (evt.eventType === eventType) {
if (this.activityIdFor(evt[attrsKey].scheduledEventId) === activityId) {
return true;
}
}
}, this);
} | javascript | function(eventType, activityId) {
var attrsKey = this._event_attributes_key(eventType);
return this._events.some(function (evt) {
if (evt.eventType === eventType) {
if (this.activityIdFor(evt[attrsKey].scheduledEventId) === activityId) {
return true;
}
}
}, this);
} | [
"function",
"(",
"eventType",
",",
"activityId",
")",
"{",
"var",
"attrsKey",
"=",
"this",
".",
"_event_attributes_key",
"(",
"eventType",
")",
";",
"return",
"this",
".",
"_events",
".",
"some",
"(",
"function",
"(",
"evt",
")",
"{",
"if",
"(",
"evt",
".",
"eventType",
"===",
"eventType",
")",
"{",
"if",
"(",
"this",
".",
"activityIdFor",
"(",
"evt",
"[",
"attrsKey",
"]",
".",
"scheduledEventId",
")",
"===",
"activityId",
")",
"{",
"return",
"true",
";",
"}",
"}",
"}",
",",
"this",
")",
";",
"}"
] | Search for an event with the corresponding type that matches the scheduled activityId
@param {String} eventType
@param {String} activityId
@returns {Boolean} | [
"Search",
"for",
"an",
"event",
"with",
"the",
"corresponding",
"type",
"that",
"matches",
"the",
"scheduled",
"activityId"
] | 31b96c9eef313199465b40204a92909996a85c3d | https://github.com/neyric/aws-swf/blob/31b96c9eef313199465b40204a92909996a85c3d/lib/event-list.js#L102-L111 | train |
|
neyric/aws-swf | lib/event-list.js | function(control) {
return this._events.some(function (evt) {
if (evt.eventType === "StartChildWorkflowExecutionInitiated") {
if (evt.startChildWorkflowExecutionInitiatedEventAttributes.control === control) {
return true;
}
}
});
} | javascript | function(control) {
return this._events.some(function (evt) {
if (evt.eventType === "StartChildWorkflowExecutionInitiated") {
if (evt.startChildWorkflowExecutionInitiatedEventAttributes.control === control) {
return true;
}
}
});
} | [
"function",
"(",
"control",
")",
"{",
"return",
"this",
".",
"_events",
".",
"some",
"(",
"function",
"(",
"evt",
")",
"{",
"if",
"(",
"evt",
".",
"eventType",
"===",
"\"StartChildWorkflowExecutionInitiated\"",
")",
"{",
"if",
"(",
"evt",
".",
"startChildWorkflowExecutionInitiatedEventAttributes",
".",
"control",
"===",
"control",
")",
"{",
"return",
"true",
";",
"}",
"}",
"}",
")",
";",
"}"
] | lookup for StartChildWorkflowExecutionInitiated
@param {String} control
@returns {Boolean} | [
"lookup",
"for",
"StartChildWorkflowExecutionInitiated"
] | 31b96c9eef313199465b40204a92909996a85c3d | https://github.com/neyric/aws-swf/blob/31b96c9eef313199465b40204a92909996a85c3d/lib/event-list.js#L156-L164 | train |
|
neyric/aws-swf | lib/event-list.js | function(control) {
return this._events.some(function (evt) {
if (evt.eventType === "ChildWorkflowExecutionCompleted") {
var initiatedEventId = evt.childWorkflowExecutionCompletedEventAttributes.initiatedEventId;
var initiatedEvent = this.eventById(initiatedEventId);
if (initiatedEvent.startChildWorkflowExecutionInitiatedEventAttributes.control === control) {
return true;
}
}
}, this);
} | javascript | function(control) {
return this._events.some(function (evt) {
if (evt.eventType === "ChildWorkflowExecutionCompleted") {
var initiatedEventId = evt.childWorkflowExecutionCompletedEventAttributes.initiatedEventId;
var initiatedEvent = this.eventById(initiatedEventId);
if (initiatedEvent.startChildWorkflowExecutionInitiatedEventAttributes.control === control) {
return true;
}
}
}, this);
} | [
"function",
"(",
"control",
")",
"{",
"return",
"this",
".",
"_events",
".",
"some",
"(",
"function",
"(",
"evt",
")",
"{",
"if",
"(",
"evt",
".",
"eventType",
"===",
"\"ChildWorkflowExecutionCompleted\"",
")",
"{",
"var",
"initiatedEventId",
"=",
"evt",
".",
"childWorkflowExecutionCompletedEventAttributes",
".",
"initiatedEventId",
";",
"var",
"initiatedEvent",
"=",
"this",
".",
"eventById",
"(",
"initiatedEventId",
")",
";",
"if",
"(",
"initiatedEvent",
".",
"startChildWorkflowExecutionInitiatedEventAttributes",
".",
"control",
"===",
"control",
")",
"{",
"return",
"true",
";",
"}",
"}",
"}",
",",
"this",
")",
";",
"}"
] | Return true if the child workflow is completed
@param {String} control
@returns {Boolean} | [
"Return",
"true",
"if",
"the",
"child",
"workflow",
"is",
"completed"
] | 31b96c9eef313199465b40204a92909996a85c3d | https://github.com/neyric/aws-swf/blob/31b96c9eef313199465b40204a92909996a85c3d/lib/event-list.js#L171-L182 | train |
|
neyric/aws-swf | lib/event-list.js | function(control) {
var initiatedEventId, initiatedEvent;
return this._events.some(function (evt) {
if (evt.eventType === "StartChildWorkflowExecutionFailed") {
initiatedEventId = evt.startChildWorkflowExecutionFailedEventAttributes.initiatedEventId;
initiatedEvent = this.eventById(initiatedEventId);
if (initiatedEvent.startChildWorkflowExecutionInitiatedEventAttributes.control === control) {
return true;
}
} else if (evt.eventType === "ChildWorkflowExecutionFailed") {
initiatedEventId = evt.childWorkflowExecutionFailedEventAttributes.initiatedEventId;
initiatedEvent = this.eventById(initiatedEventId);
if (initiatedEvent.startChildWorkflowExecutionInitiatedEventAttributes.control === control) {
return true;
}
}
}, this);
} | javascript | function(control) {
var initiatedEventId, initiatedEvent;
return this._events.some(function (evt) {
if (evt.eventType === "StartChildWorkflowExecutionFailed") {
initiatedEventId = evt.startChildWorkflowExecutionFailedEventAttributes.initiatedEventId;
initiatedEvent = this.eventById(initiatedEventId);
if (initiatedEvent.startChildWorkflowExecutionInitiatedEventAttributes.control === control) {
return true;
}
} else if (evt.eventType === "ChildWorkflowExecutionFailed") {
initiatedEventId = evt.childWorkflowExecutionFailedEventAttributes.initiatedEventId;
initiatedEvent = this.eventById(initiatedEventId);
if (initiatedEvent.startChildWorkflowExecutionInitiatedEventAttributes.control === control) {
return true;
}
}
}, this);
} | [
"function",
"(",
"control",
")",
"{",
"var",
"initiatedEventId",
",",
"initiatedEvent",
";",
"return",
"this",
".",
"_events",
".",
"some",
"(",
"function",
"(",
"evt",
")",
"{",
"if",
"(",
"evt",
".",
"eventType",
"===",
"\"StartChildWorkflowExecutionFailed\"",
")",
"{",
"initiatedEventId",
"=",
"evt",
".",
"startChildWorkflowExecutionFailedEventAttributes",
".",
"initiatedEventId",
";",
"initiatedEvent",
"=",
"this",
".",
"eventById",
"(",
"initiatedEventId",
")",
";",
"if",
"(",
"initiatedEvent",
".",
"startChildWorkflowExecutionInitiatedEventAttributes",
".",
"control",
"===",
"control",
")",
"{",
"return",
"true",
";",
"}",
"}",
"else",
"if",
"(",
"evt",
".",
"eventType",
"===",
"\"ChildWorkflowExecutionFailed\"",
")",
"{",
"initiatedEventId",
"=",
"evt",
".",
"childWorkflowExecutionFailedEventAttributes",
".",
"initiatedEventId",
";",
"initiatedEvent",
"=",
"this",
".",
"eventById",
"(",
"initiatedEventId",
")",
";",
"if",
"(",
"initiatedEvent",
".",
"startChildWorkflowExecutionInitiatedEventAttributes",
".",
"control",
"===",
"control",
")",
"{",
"return",
"true",
";",
"}",
"}",
"}",
",",
"this",
")",
";",
"}"
] | Return true if the child workflow has failed
@param {String} control
@returns {Boolean} | [
"Return",
"true",
"if",
"the",
"child",
"workflow",
"has",
"failed"
] | 31b96c9eef313199465b40204a92909996a85c3d | https://github.com/neyric/aws-swf/blob/31b96c9eef313199465b40204a92909996a85c3d/lib/event-list.js#L189-L206 | train |
|
neyric/aws-swf | lib/event-list.js | function (signalName) {
var evt = this._event_find('WorkflowExecutionSignaled', 'signalName', signalName);
if(!evt) {
return null;
}
var signalInput = evt.workflowExecutionSignaledEventAttributes.input;
try {
var d = JSON.parse(signalInput);
return d;
} catch (ex) {
return signalInput;
}
} | javascript | function (signalName) {
var evt = this._event_find('WorkflowExecutionSignaled', 'signalName', signalName);
if(!evt) {
return null;
}
var signalInput = evt.workflowExecutionSignaledEventAttributes.input;
try {
var d = JSON.parse(signalInput);
return d;
} catch (ex) {
return signalInput;
}
} | [
"function",
"(",
"signalName",
")",
"{",
"var",
"evt",
"=",
"this",
".",
"_event_find",
"(",
"'WorkflowExecutionSignaled'",
",",
"'signalName'",
",",
"signalName",
")",
";",
"if",
"(",
"!",
"evt",
")",
"{",
"return",
"null",
";",
"}",
"var",
"signalInput",
"=",
"evt",
".",
"workflowExecutionSignaledEventAttributes",
".",
"input",
";",
"try",
"{",
"var",
"d",
"=",
"JSON",
".",
"parse",
"(",
"signalInput",
")",
";",
"return",
"d",
";",
"}",
"catch",
"(",
"ex",
")",
"{",
"return",
"signalInput",
";",
"}",
"}"
] | Returns the signal input or null if the signal is not found or doesn't have JSON input
@param {String} signalName
@returns {Mixed} | [
"Returns",
"the",
"signal",
"input",
"or",
"null",
"if",
"the",
"signal",
"is",
"not",
"found",
"or",
"doesn",
"t",
"have",
"JSON",
"input"
] | 31b96c9eef313199465b40204a92909996a85c3d | https://github.com/neyric/aws-swf/blob/31b96c9eef313199465b40204a92909996a85c3d/lib/event-list.js#L278-L292 | train |
|
neyric/aws-swf | lib/event-list.js | function () {
var i;
for (i = 0; i < arguments.length; i++) {
if (!this.is_activity_scheduled(arguments[i])) {
return false;
}
}
return true;
} | javascript | function () {
var i;
for (i = 0; i < arguments.length; i++) {
if (!this.is_activity_scheduled(arguments[i])) {
return false;
}
}
return true;
} | [
"function",
"(",
")",
"{",
"var",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"arguments",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"this",
".",
"is_activity_scheduled",
"(",
"arguments",
"[",
"i",
"]",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Return true if the arguments are all scheduled
@param {String} [...]
@returns {Boolean} | [
"Return",
"true",
"if",
"the",
"arguments",
"are",
"all",
"scheduled"
] | 31b96c9eef313199465b40204a92909996a85c3d | https://github.com/neyric/aws-swf/blob/31b96c9eef313199465b40204a92909996a85c3d/lib/event-list.js#L328-L336 | train |
|
neyric/aws-swf | lib/event-list.js | function () {
var i;
for (i = 0; i < arguments.length; i++) {
if (!this.is_lambda_scheduled(arguments[i])) {
return false;
}
}
return true;
} | javascript | function () {
var i;
for (i = 0; i < arguments.length; i++) {
if (!this.is_lambda_scheduled(arguments[i])) {
return false;
}
}
return true;
} | [
"function",
"(",
")",
"{",
"var",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"arguments",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"this",
".",
"is_lambda_scheduled",
"(",
"arguments",
"[",
"i",
"]",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Return true if the arguments are all scheduled lambda functions
@param {String} [...]
@returns {Boolean} | [
"Return",
"true",
"if",
"the",
"arguments",
"are",
"all",
"scheduled",
"lambda",
"functions"
] | 31b96c9eef313199465b40204a92909996a85c3d | https://github.com/neyric/aws-swf/blob/31b96c9eef313199465b40204a92909996a85c3d/lib/event-list.js#L343-L351 | train |
|
neyric/aws-swf | lib/event-list.js | function () {
var i;
for (i = 0; i < arguments.length; i++) {
if ( ! (this.has_activity_completed(arguments[i]) || this.has_lambda_completed(arguments[i]) || this.childworkflow_completed(arguments[i]) || this.timer_fired(arguments[i]) ) ) {
return false;
}
}
return true;
} | javascript | function () {
var i;
for (i = 0; i < arguments.length; i++) {
if ( ! (this.has_activity_completed(arguments[i]) || this.has_lambda_completed(arguments[i]) || this.childworkflow_completed(arguments[i]) || this.timer_fired(arguments[i]) ) ) {
return false;
}
}
return true;
} | [
"function",
"(",
")",
"{",
"var",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"arguments",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"(",
"this",
".",
"has_activity_completed",
"(",
"arguments",
"[",
"i",
"]",
")",
"||",
"this",
".",
"has_lambda_completed",
"(",
"arguments",
"[",
"i",
"]",
")",
"||",
"this",
".",
"childworkflow_completed",
"(",
"arguments",
"[",
"i",
"]",
")",
"||",
"this",
".",
"timer_fired",
"(",
"arguments",
"[",
"i",
"]",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Return true if all the arguments are completed
@param {String} [...]
@returns {Boolean} | [
"Return",
"true",
"if",
"all",
"the",
"arguments",
"are",
"completed"
] | 31b96c9eef313199465b40204a92909996a85c3d | https://github.com/neyric/aws-swf/blob/31b96c9eef313199465b40204a92909996a85c3d/lib/event-list.js#L424-L432 | train |
|
neyric/aws-swf | lib/event-list.js | function () {
var wfInput = this._events[0].workflowExecutionStartedEventAttributes.input;
try {
var d = JSON.parse(wfInput);
return d;
} catch (ex) {
return wfInput;
}
} | javascript | function () {
var wfInput = this._events[0].workflowExecutionStartedEventAttributes.input;
try {
var d = JSON.parse(wfInput);
return d;
} catch (ex) {
return wfInput;
}
} | [
"function",
"(",
")",
"{",
"var",
"wfInput",
"=",
"this",
".",
"_events",
"[",
"0",
"]",
".",
"workflowExecutionStartedEventAttributes",
".",
"input",
";",
"try",
"{",
"var",
"d",
"=",
"JSON",
".",
"parse",
"(",
"wfInput",
")",
";",
"return",
"d",
";",
"}",
"catch",
"(",
"ex",
")",
"{",
"return",
"wfInput",
";",
"}",
"}"
] | Get the input parameters of the workflow
@returns {Mixed} | [
"Get",
"the",
"input",
"parameters",
"of",
"the",
"workflow"
] | 31b96c9eef313199465b40204a92909996a85c3d | https://github.com/neyric/aws-swf/blob/31b96c9eef313199465b40204a92909996a85c3d/lib/event-list.js#L438-L448 | train |
|
neyric/aws-swf | lib/event-list.js | function (activityId) {
var i;
for (i = 0; i < this._events.length; i++) {
var evt = this._events[i];
if (evt.eventType === "ActivityTaskCompleted") {
if (this.activityIdFor(evt.activityTaskCompletedEventAttributes.scheduledEventId) === activityId) {
var result = evt.activityTaskCompletedEventAttributes.result;
try {
var d = JSON.parse(result);
return d;
} catch (ex) {
return result;
}
}
}
}
return null;
} | javascript | function (activityId) {
var i;
for (i = 0; i < this._events.length; i++) {
var evt = this._events[i];
if (evt.eventType === "ActivityTaskCompleted") {
if (this.activityIdFor(evt.activityTaskCompletedEventAttributes.scheduledEventId) === activityId) {
var result = evt.activityTaskCompletedEventAttributes.result;
try {
var d = JSON.parse(result);
return d;
} catch (ex) {
return result;
}
}
}
}
return null;
} | [
"function",
"(",
"activityId",
")",
"{",
"var",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"_events",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"evt",
"=",
"this",
".",
"_events",
"[",
"i",
"]",
";",
"if",
"(",
"evt",
".",
"eventType",
"===",
"\"ActivityTaskCompleted\"",
")",
"{",
"if",
"(",
"this",
".",
"activityIdFor",
"(",
"evt",
".",
"activityTaskCompletedEventAttributes",
".",
"scheduledEventId",
")",
"===",
"activityId",
")",
"{",
"var",
"result",
"=",
"evt",
".",
"activityTaskCompletedEventAttributes",
".",
"result",
";",
"try",
"{",
"var",
"d",
"=",
"JSON",
".",
"parse",
"(",
"result",
")",
";",
"return",
"d",
";",
"}",
"catch",
"(",
"ex",
")",
"{",
"return",
"result",
";",
"}",
"}",
"}",
"}",
"return",
"null",
";",
"}"
] | Get the results for the given activityId
@param {String} activityId
@returns {Mixed} | [
"Get",
"the",
"results",
"for",
"the",
"given",
"activityId"
] | 31b96c9eef313199465b40204a92909996a85c3d | https://github.com/neyric/aws-swf/blob/31b96c9eef313199465b40204a92909996a85c3d/lib/event-list.js#L456-L478 | train |
|
neyric/aws-swf | lib/event-list.js | function(control) {
var i;
for (i = 0; i < this._events.length; i++) {
var evt = this._events[i];
if (evt.eventType === "ChildWorkflowExecutionCompleted") {
var initiatedEventId = evt.childWorkflowExecutionCompletedEventAttributes.initiatedEventId;
var initiatedEvent = this.eventById(initiatedEventId);
if (initiatedEvent.startChildWorkflowExecutionInitiatedEventAttributes.control === control) {
var result = evt.childWorkflowExecutionCompletedEventAttributes.result;
try {
result = JSON.parse(result);
}
catch(ex) {}
return result;
}
}
}
return null;
} | javascript | function(control) {
var i;
for (i = 0; i < this._events.length; i++) {
var evt = this._events[i];
if (evt.eventType === "ChildWorkflowExecutionCompleted") {
var initiatedEventId = evt.childWorkflowExecutionCompletedEventAttributes.initiatedEventId;
var initiatedEvent = this.eventById(initiatedEventId);
if (initiatedEvent.startChildWorkflowExecutionInitiatedEventAttributes.control === control) {
var result = evt.childWorkflowExecutionCompletedEventAttributes.result;
try {
result = JSON.parse(result);
}
catch(ex) {}
return result;
}
}
}
return null;
} | [
"function",
"(",
"control",
")",
"{",
"var",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"_events",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"evt",
"=",
"this",
".",
"_events",
"[",
"i",
"]",
";",
"if",
"(",
"evt",
".",
"eventType",
"===",
"\"ChildWorkflowExecutionCompleted\"",
")",
"{",
"var",
"initiatedEventId",
"=",
"evt",
".",
"childWorkflowExecutionCompletedEventAttributes",
".",
"initiatedEventId",
";",
"var",
"initiatedEvent",
"=",
"this",
".",
"eventById",
"(",
"initiatedEventId",
")",
";",
"if",
"(",
"initiatedEvent",
".",
"startChildWorkflowExecutionInitiatedEventAttributes",
".",
"control",
"===",
"control",
")",
"{",
"var",
"result",
"=",
"evt",
".",
"childWorkflowExecutionCompletedEventAttributes",
".",
"result",
";",
"try",
"{",
"result",
"=",
"JSON",
".",
"parse",
"(",
"result",
")",
";",
"}",
"catch",
"(",
"ex",
")",
"{",
"}",
"return",
"result",
";",
"}",
"}",
"}",
"return",
"null",
";",
"}"
] | Get the results of a completed child workflow
@param {String} control
@returns {Mixed} | [
"Get",
"the",
"results",
"of",
"a",
"completed",
"child",
"workflow"
] | 31b96c9eef313199465b40204a92909996a85c3d | https://github.com/neyric/aws-swf/blob/31b96c9eef313199465b40204a92909996a85c3d/lib/event-list.js#L486-L512 | train |
|
neyric/aws-swf | lib/event-list.js | function (markerName) {
var i, finalDetail;
var lastEventId = 0;
for (i = 0; i < this._events.length; i++) {
var evt = this._events[i];
if ((evt.eventType === 'MarkerRecorded') && (evt.markerRecordedEventAttributes.markerName === markerName) && (parseInt(evt.eventId, 10) > lastEventId)) {
finalDetail = evt.markerRecordedEventAttributes.details;
lastEventId = evt.eventId;
}
}
return finalDetail;
} | javascript | function (markerName) {
var i, finalDetail;
var lastEventId = 0;
for (i = 0; i < this._events.length; i++) {
var evt = this._events[i];
if ((evt.eventType === 'MarkerRecorded') && (evt.markerRecordedEventAttributes.markerName === markerName) && (parseInt(evt.eventId, 10) > lastEventId)) {
finalDetail = evt.markerRecordedEventAttributes.details;
lastEventId = evt.eventId;
}
}
return finalDetail;
} | [
"function",
"(",
"markerName",
")",
"{",
"var",
"i",
",",
"finalDetail",
";",
"var",
"lastEventId",
"=",
"0",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"_events",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"evt",
"=",
"this",
".",
"_events",
"[",
"i",
"]",
";",
"if",
"(",
"(",
"evt",
".",
"eventType",
"===",
"'MarkerRecorded'",
")",
"&&",
"(",
"evt",
".",
"markerRecordedEventAttributes",
".",
"markerName",
"===",
"markerName",
")",
"&&",
"(",
"parseInt",
"(",
"evt",
".",
"eventId",
",",
"10",
")",
">",
"lastEventId",
")",
")",
"{",
"finalDetail",
"=",
"evt",
".",
"markerRecordedEventAttributes",
".",
"details",
";",
"lastEventId",
"=",
"evt",
".",
"eventId",
";",
"}",
"}",
"return",
"finalDetail",
";",
"}"
] | Get the details of the last marker with the given name
@param {String} markerName
@returns {Mixed} | [
"Get",
"the",
"details",
"of",
"the",
"last",
"marker",
"with",
"the",
"given",
"name"
] | 31b96c9eef313199465b40204a92909996a85c3d | https://github.com/neyric/aws-swf/blob/31b96c9eef313199465b40204a92909996a85c3d/lib/event-list.js#L519-L531 | train |
|
neyric/aws-swf | lib/event-list.js | function(){
var i;
for (i = 0; i < this._events.length; i++) {
var evt = this._events[i];
if (evt.eventType === "WorkflowExecutionCancelRequested") {
return true;
}
}
return false;
} | javascript | function(){
var i;
for (i = 0; i < this._events.length; i++) {
var evt = this._events[i];
if (evt.eventType === "WorkflowExecutionCancelRequested") {
return true;
}
}
return false;
} | [
"function",
"(",
")",
"{",
"var",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"_events",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"evt",
"=",
"this",
".",
"_events",
"[",
"i",
"]",
";",
"if",
"(",
"evt",
".",
"eventType",
"===",
"\"WorkflowExecutionCancelRequested\"",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Return true if cancel request has arrived
@returns {boolean} | [
"Return",
"true",
"if",
"cancel",
"request",
"has",
"arrived"
] | 31b96c9eef313199465b40204a92909996a85c3d | https://github.com/neyric/aws-swf/blob/31b96c9eef313199465b40204a92909996a85c3d/lib/event-list.js#L545-L555 | train |
|
langholz/dtw | lib/dtw.js | function (options) {
var state = { distanceCostMatrix: null };
if (typeof options === 'undefined') {
state.distance = require('./distanceFunctions/squaredEuclidean').distance;
} else {
validateOptions(options);
if (typeof options.distanceMetric === 'string') {
state.distance = retrieveDistanceFunction(options.distanceMetric);
} else if (typeof options.distanceFunction === 'function') {
state.distance = options.distanceFunction;
}
}
this.compute = function (firstSequence, secondSequence, window) {
var cost = Number.POSITIVE_INFINITY;
if (typeof window === 'undefined') {
cost = computeOptimalPath(firstSequence, secondSequence, state);
} else if (typeof window === 'number') {
cost = computeOptimalPathWithWindow(firstSequence, secondSequence, window, state);
} else {
throw new TypeError('Invalid window parameter type: expected a number');
}
return cost;
};
this.path = function () {
var path = null;
if (state.distanceCostMatrix instanceof Array) {
path = retrieveOptimalPath(state);
}
return path;
};
} | javascript | function (options) {
var state = { distanceCostMatrix: null };
if (typeof options === 'undefined') {
state.distance = require('./distanceFunctions/squaredEuclidean').distance;
} else {
validateOptions(options);
if (typeof options.distanceMetric === 'string') {
state.distance = retrieveDistanceFunction(options.distanceMetric);
} else if (typeof options.distanceFunction === 'function') {
state.distance = options.distanceFunction;
}
}
this.compute = function (firstSequence, secondSequence, window) {
var cost = Number.POSITIVE_INFINITY;
if (typeof window === 'undefined') {
cost = computeOptimalPath(firstSequence, secondSequence, state);
} else if (typeof window === 'number') {
cost = computeOptimalPathWithWindow(firstSequence, secondSequence, window, state);
} else {
throw new TypeError('Invalid window parameter type: expected a number');
}
return cost;
};
this.path = function () {
var path = null;
if (state.distanceCostMatrix instanceof Array) {
path = retrieveOptimalPath(state);
}
return path;
};
} | [
"function",
"(",
"options",
")",
"{",
"var",
"state",
"=",
"{",
"distanceCostMatrix",
":",
"null",
"}",
";",
"if",
"(",
"typeof",
"options",
"===",
"'undefined'",
")",
"{",
"state",
".",
"distance",
"=",
"require",
"(",
"'./distanceFunctions/squaredEuclidean'",
")",
".",
"distance",
";",
"}",
"else",
"{",
"validateOptions",
"(",
"options",
")",
";",
"if",
"(",
"typeof",
"options",
".",
"distanceMetric",
"===",
"'string'",
")",
"{",
"state",
".",
"distance",
"=",
"retrieveDistanceFunction",
"(",
"options",
".",
"distanceMetric",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"options",
".",
"distanceFunction",
"===",
"'function'",
")",
"{",
"state",
".",
"distance",
"=",
"options",
".",
"distanceFunction",
";",
"}",
"}",
"this",
".",
"compute",
"=",
"function",
"(",
"firstSequence",
",",
"secondSequence",
",",
"window",
")",
"{",
"var",
"cost",
"=",
"Number",
".",
"POSITIVE_INFINITY",
";",
"if",
"(",
"typeof",
"window",
"===",
"'undefined'",
")",
"{",
"cost",
"=",
"computeOptimalPath",
"(",
"firstSequence",
",",
"secondSequence",
",",
"state",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"window",
"===",
"'number'",
")",
"{",
"cost",
"=",
"computeOptimalPathWithWindow",
"(",
"firstSequence",
",",
"secondSequence",
",",
"window",
",",
"state",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"TypeError",
"(",
"'Invalid window parameter type: expected a number'",
")",
";",
"}",
"return",
"cost",
";",
"}",
";",
"this",
".",
"path",
"=",
"function",
"(",
")",
"{",
"var",
"path",
"=",
"null",
";",
"if",
"(",
"state",
".",
"distanceCostMatrix",
"instanceof",
"Array",
")",
"{",
"path",
"=",
"retrieveOptimalPath",
"(",
"state",
")",
";",
"}",
"return",
"path",
";",
"}",
";",
"}"
] | Create a DTW object
@class DTW
Initializes a new instance of the `DTW`. If no options are provided the squared euclidean distance function is used.
@function DTW
@param {DTWOptions} [options] The options to initialize the dynamic time warping instance with.
Computes the optimal match between two provided sequences.
@method compute
@param {number[]} firstSequence The first sequence.
@param {number[]} secondSequence The second sequence.
@param {number} [window] The window parameter (for the locality constraint) to use.
@returns {number} The similarity between the provided temporal sequences.
Retrieves the optimal match between two provided sequences.
@method path
@returns {number[]} The array containing the optimal path points. | [
"Create",
"a",
"DTW",
"object"
] | fe0f3fdfa6dbbcfb0714056a744a9b9f633e74be | https://github.com/langholz/dtw/blob/fe0f3fdfa6dbbcfb0714056a744a9b9f633e74be/lib/dtw.js#L72-L106 | train |
|
lautr3k/lw.raster-to-gcode | dist/webworker_example/index.js | loadFile | function loadFile(file) {
console.log('loadFile:', file);
// <file> can be Image, File URL object or URL string (http://* or data:image/*)
rasterToGcode.load(file).then(function(rtg) {
console.log('rasterToGcode:', rtg);
})
.catch(function(error) {
console.error('error:', error);
});
} | javascript | function loadFile(file) {
console.log('loadFile:', file);
// <file> can be Image, File URL object or URL string (http://* or data:image/*)
rasterToGcode.load(file).then(function(rtg) {
console.log('rasterToGcode:', rtg);
})
.catch(function(error) {
console.error('error:', error);
});
} | [
"function",
"loadFile",
"(",
"file",
")",
"{",
"console",
".",
"log",
"(",
"'loadFile:'",
",",
"file",
")",
";",
"rasterToGcode",
".",
"load",
"(",
"file",
")",
".",
"then",
"(",
"function",
"(",
"rtg",
")",
"{",
"console",
".",
"log",
"(",
"'rasterToGcode:'",
",",
"rtg",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"error",
")",
"{",
"console",
".",
"error",
"(",
"'error:'",
",",
"error",
")",
";",
"}",
")",
";",
"}"
] | Load the input file | [
"Load",
"the",
"input",
"file"
] | f1f8f4d992b6f9450904ed560bc6d4ea1462fe2e | https://github.com/lautr3k/lw.raster-to-gcode/blob/f1f8f4d992b6f9450904ed560bc6d4ea1462fe2e/dist/webworker_example/index.js#L39-L49 | train |
lautr3k/lw.raster-to-gcode | dist/webworker_example/index.js | createWorker | function createWorker() {
var worker = new Worker('worker.js');
// On worker messsage
worker.onmessage = function(event) {
if (event.data.event === 'done') {
console.log('done:', event.data.data);
$('#start').show();
$('#abort').hide();
}
else if (event.data.event === 'progress') {
console.log('progress:', event.data.data.percent, '%');
}
};
return worker;
} | javascript | function createWorker() {
var worker = new Worker('worker.js');
// On worker messsage
worker.onmessage = function(event) {
if (event.data.event === 'done') {
console.log('done:', event.data.data);
$('#start').show();
$('#abort').hide();
}
else if (event.data.event === 'progress') {
console.log('progress:', event.data.data.percent, '%');
}
};
return worker;
} | [
"function",
"createWorker",
"(",
")",
"{",
"var",
"worker",
"=",
"new",
"Worker",
"(",
"'worker.js'",
")",
";",
"worker",
".",
"onmessage",
"=",
"function",
"(",
"event",
")",
"{",
"if",
"(",
"event",
".",
"data",
".",
"event",
"===",
"'done'",
")",
"{",
"console",
".",
"log",
"(",
"'done:'",
",",
"event",
".",
"data",
".",
"data",
")",
";",
"$",
"(",
"'#start'",
")",
".",
"show",
"(",
")",
";",
"$",
"(",
"'#abort'",
")",
".",
"hide",
"(",
")",
";",
"}",
"else",
"if",
"(",
"event",
".",
"data",
".",
"event",
"===",
"'progress'",
")",
"{",
"console",
".",
"log",
"(",
"'progress:'",
",",
"event",
".",
"data",
".",
"data",
".",
"percent",
",",
"'%'",
")",
";",
"}",
"}",
";",
"return",
"worker",
";",
"}"
] | Create and return the Worker object | [
"Create",
"and",
"return",
"the",
"Worker",
"object"
] | f1f8f4d992b6f9450904ed560bc6d4ea1462fe2e | https://github.com/lautr3k/lw.raster-to-gcode/blob/f1f8f4d992b6f9450904ed560bc6d4ea1462fe2e/dist/webworker_example/index.js#L52-L68 | train |
lautr3k/lw.raster-to-gcode | dist/example/index.js | toHeightMap | function toHeightMap() {
if (rasterToGcode.running) {
return rasterToGcode.abort();
}
console.log('toHeightMap:', file.name);
$toHeightMap.text('Abort').addClass('btn-danger');
$progressBar.removeClass('progress-bar-danger');
$progressBar.parent().show();
rasterToGcode.getHeightMap();
} | javascript | function toHeightMap() {
if (rasterToGcode.running) {
return rasterToGcode.abort();
}
console.log('toHeightMap:', file.name);
$toHeightMap.text('Abort').addClass('btn-danger');
$progressBar.removeClass('progress-bar-danger');
$progressBar.parent().show();
rasterToGcode.getHeightMap();
} | [
"function",
"toHeightMap",
"(",
")",
"{",
"if",
"(",
"rasterToGcode",
".",
"running",
")",
"{",
"return",
"rasterToGcode",
".",
"abort",
"(",
")",
";",
"}",
"console",
".",
"log",
"(",
"'toHeightMap:'",
",",
"file",
".",
"name",
")",
";",
"$toHeightMap",
".",
"text",
"(",
"'Abort'",
")",
".",
"addClass",
"(",
"'btn-danger'",
")",
";",
"$progressBar",
".",
"removeClass",
"(",
"'progress-bar-danger'",
")",
";",
"$progressBar",
".",
"parent",
"(",
")",
".",
"show",
"(",
")",
";",
"rasterToGcode",
".",
"getHeightMap",
"(",
")",
";",
"}"
] | To height-map | [
"To",
"height",
"-",
"map"
] | f1f8f4d992b6f9450904ed560bc6d4ea1462fe2e | https://github.com/lautr3k/lw.raster-to-gcode/blob/f1f8f4d992b6f9450904ed560bc6d4ea1462fe2e/dist/example/index.js#L194-L204 | train |
lautr3k/lw.raster-to-gcode | dist/example/index.js | downloadHeightMap | function downloadHeightMap() {
console.log('downloadHeightMap:', file.name);
var heightMapFile = new Blob([heightMap], { type: 'text/plain;charset=utf-8' });
saveAs(heightMapFile, file.name + '.height-map.txt');
} | javascript | function downloadHeightMap() {
console.log('downloadHeightMap:', file.name);
var heightMapFile = new Blob([heightMap], { type: 'text/plain;charset=utf-8' });
saveAs(heightMapFile, file.name + '.height-map.txt');
} | [
"function",
"downloadHeightMap",
"(",
")",
"{",
"console",
".",
"log",
"(",
"'downloadHeightMap:'",
",",
"file",
".",
"name",
")",
";",
"var",
"heightMapFile",
"=",
"new",
"Blob",
"(",
"[",
"heightMap",
"]",
",",
"{",
"type",
":",
"'text/plain;charset=utf-8'",
"}",
")",
";",
"saveAs",
"(",
"heightMapFile",
",",
"file",
".",
"name",
"+",
"'.height-map.txt'",
")",
";",
"}"
] | Download height-map | [
"Download",
"height",
"-",
"map"
] | f1f8f4d992b6f9450904ed560bc6d4ea1462fe2e | https://github.com/lautr3k/lw.raster-to-gcode/blob/f1f8f4d992b6f9450904ed560bc6d4ea1462fe2e/dist/example/index.js#L207-L211 | train |
strophe/strophejs-plugin-pubsub | src/strophe.pubsub.js | function(conn) {
this._connection = conn;
/*
Function used to setup plugin.
*/
/* extend name space
* NS.PUBSUB - XMPP Publish Subscribe namespace
* from XEP 60.
*
* NS.PUBSUB_SUBSCRIBE_OPTIONS - XMPP pubsub
* options namespace from XEP 60.
*/
Strophe.addNamespace('PUBSUB',"http://jabber.org/protocol/pubsub");
Strophe.addNamespace('PUBSUB_SUBSCRIBE_OPTIONS',
Strophe.NS.PUBSUB+"#subscribe_options");
Strophe.addNamespace('PUBSUB_ERRORS',Strophe.NS.PUBSUB+"#errors");
Strophe.addNamespace('PUBSUB_EVENT',Strophe.NS.PUBSUB+"#event");
Strophe.addNamespace('PUBSUB_OWNER',Strophe.NS.PUBSUB+"#owner");
Strophe.addNamespace('PUBSUB_AUTO_CREATE',
Strophe.NS.PUBSUB+"#auto-create");
Strophe.addNamespace('PUBSUB_PUBLISH_OPTIONS',
Strophe.NS.PUBSUB+"#publish-options");
Strophe.addNamespace('PUBSUB_NODE_CONFIG',
Strophe.NS.PUBSUB+"#node_config");
Strophe.addNamespace('PUBSUB_CREATE_AND_CONFIGURE',
Strophe.NS.PUBSUB+"#create-and-configure");
Strophe.addNamespace('PUBSUB_SUBSCRIBE_AUTHORIZATION',
Strophe.NS.PUBSUB+"#subscribe_authorization");
Strophe.addNamespace('PUBSUB_GET_PENDING',
Strophe.NS.PUBSUB+"#get-pending");
Strophe.addNamespace('PUBSUB_MANAGE_SUBSCRIPTIONS',
Strophe.NS.PUBSUB+"#manage-subscriptions");
Strophe.addNamespace('PUBSUB_META_DATA',
Strophe.NS.PUBSUB+"#meta-data");
Strophe.addNamespace('ATOM', "http://www.w3.org/2005/Atom");
if (conn.disco)
conn.disco.addFeature(Strophe.NS.PUBSUB);
} | javascript | function(conn) {
this._connection = conn;
/*
Function used to setup plugin.
*/
/* extend name space
* NS.PUBSUB - XMPP Publish Subscribe namespace
* from XEP 60.
*
* NS.PUBSUB_SUBSCRIBE_OPTIONS - XMPP pubsub
* options namespace from XEP 60.
*/
Strophe.addNamespace('PUBSUB',"http://jabber.org/protocol/pubsub");
Strophe.addNamespace('PUBSUB_SUBSCRIBE_OPTIONS',
Strophe.NS.PUBSUB+"#subscribe_options");
Strophe.addNamespace('PUBSUB_ERRORS',Strophe.NS.PUBSUB+"#errors");
Strophe.addNamespace('PUBSUB_EVENT',Strophe.NS.PUBSUB+"#event");
Strophe.addNamespace('PUBSUB_OWNER',Strophe.NS.PUBSUB+"#owner");
Strophe.addNamespace('PUBSUB_AUTO_CREATE',
Strophe.NS.PUBSUB+"#auto-create");
Strophe.addNamespace('PUBSUB_PUBLISH_OPTIONS',
Strophe.NS.PUBSUB+"#publish-options");
Strophe.addNamespace('PUBSUB_NODE_CONFIG',
Strophe.NS.PUBSUB+"#node_config");
Strophe.addNamespace('PUBSUB_CREATE_AND_CONFIGURE',
Strophe.NS.PUBSUB+"#create-and-configure");
Strophe.addNamespace('PUBSUB_SUBSCRIBE_AUTHORIZATION',
Strophe.NS.PUBSUB+"#subscribe_authorization");
Strophe.addNamespace('PUBSUB_GET_PENDING',
Strophe.NS.PUBSUB+"#get-pending");
Strophe.addNamespace('PUBSUB_MANAGE_SUBSCRIPTIONS',
Strophe.NS.PUBSUB+"#manage-subscriptions");
Strophe.addNamespace('PUBSUB_META_DATA',
Strophe.NS.PUBSUB+"#meta-data");
Strophe.addNamespace('ATOM', "http://www.w3.org/2005/Atom");
if (conn.disco)
conn.disco.addFeature(Strophe.NS.PUBSUB);
} | [
"function",
"(",
"conn",
")",
"{",
"this",
".",
"_connection",
"=",
"conn",
";",
"Strophe",
".",
"addNamespace",
"(",
"'PUBSUB'",
",",
"\"http://jabber.org/protocol/pubsub\"",
")",
";",
"Strophe",
".",
"addNamespace",
"(",
"'PUBSUB_SUBSCRIBE_OPTIONS'",
",",
"Strophe",
".",
"NS",
".",
"PUBSUB",
"+",
"\"#subscribe_options\"",
")",
";",
"Strophe",
".",
"addNamespace",
"(",
"'PUBSUB_ERRORS'",
",",
"Strophe",
".",
"NS",
".",
"PUBSUB",
"+",
"\"#errors\"",
")",
";",
"Strophe",
".",
"addNamespace",
"(",
"'PUBSUB_EVENT'",
",",
"Strophe",
".",
"NS",
".",
"PUBSUB",
"+",
"\"#event\"",
")",
";",
"Strophe",
".",
"addNamespace",
"(",
"'PUBSUB_OWNER'",
",",
"Strophe",
".",
"NS",
".",
"PUBSUB",
"+",
"\"#owner\"",
")",
";",
"Strophe",
".",
"addNamespace",
"(",
"'PUBSUB_AUTO_CREATE'",
",",
"Strophe",
".",
"NS",
".",
"PUBSUB",
"+",
"\"#auto-create\"",
")",
";",
"Strophe",
".",
"addNamespace",
"(",
"'PUBSUB_PUBLISH_OPTIONS'",
",",
"Strophe",
".",
"NS",
".",
"PUBSUB",
"+",
"\"#publish-options\"",
")",
";",
"Strophe",
".",
"addNamespace",
"(",
"'PUBSUB_NODE_CONFIG'",
",",
"Strophe",
".",
"NS",
".",
"PUBSUB",
"+",
"\"#node_config\"",
")",
";",
"Strophe",
".",
"addNamespace",
"(",
"'PUBSUB_CREATE_AND_CONFIGURE'",
",",
"Strophe",
".",
"NS",
".",
"PUBSUB",
"+",
"\"#create-and-configure\"",
")",
";",
"Strophe",
".",
"addNamespace",
"(",
"'PUBSUB_SUBSCRIBE_AUTHORIZATION'",
",",
"Strophe",
".",
"NS",
".",
"PUBSUB",
"+",
"\"#subscribe_authorization\"",
")",
";",
"Strophe",
".",
"addNamespace",
"(",
"'PUBSUB_GET_PENDING'",
",",
"Strophe",
".",
"NS",
".",
"PUBSUB",
"+",
"\"#get-pending\"",
")",
";",
"Strophe",
".",
"addNamespace",
"(",
"'PUBSUB_MANAGE_SUBSCRIPTIONS'",
",",
"Strophe",
".",
"NS",
".",
"PUBSUB",
"+",
"\"#manage-subscriptions\"",
")",
";",
"Strophe",
".",
"addNamespace",
"(",
"'PUBSUB_META_DATA'",
",",
"Strophe",
".",
"NS",
".",
"PUBSUB",
"+",
"\"#meta-data\"",
")",
";",
"Strophe",
".",
"addNamespace",
"(",
"'ATOM'",
",",
"\"http://www.w3.org/2005/Atom\"",
")",
";",
"if",
"(",
"conn",
".",
"disco",
")",
"conn",
".",
"disco",
".",
"addFeature",
"(",
"Strophe",
".",
"NS",
".",
"PUBSUB",
")",
";",
"}"
] | The plugin must have the init function. | [
"The",
"plugin",
"must",
"have",
"the",
"init",
"function",
"."
] | fc12f60570bdd2b73cc87077a884a102bc32f3be | https://github.com/strophe/strophejs-plugin-pubsub/blob/fc12f60570bdd2b73cc87077a884a102bc32f3be/src/strophe.pubsub.js#L98-L140 | train |
|
strophe/strophejs-plugin-pubsub | src/strophe.pubsub.js | function (status, condition) {
var that = this._connection;
if (this._autoService && status === Strophe.Status.CONNECTED) {
this.service = 'pubsub.'+Strophe.getDomainFromJid(that.jid);
this.jid = that.jid;
}
} | javascript | function (status, condition) {
var that = this._connection;
if (this._autoService && status === Strophe.Status.CONNECTED) {
this.service = 'pubsub.'+Strophe.getDomainFromJid(that.jid);
this.jid = that.jid;
}
} | [
"function",
"(",
"status",
",",
"condition",
")",
"{",
"var",
"that",
"=",
"this",
".",
"_connection",
";",
"if",
"(",
"this",
".",
"_autoService",
"&&",
"status",
"===",
"Strophe",
".",
"Status",
".",
"CONNECTED",
")",
"{",
"this",
".",
"service",
"=",
"'pubsub.'",
"+",
"Strophe",
".",
"getDomainFromJid",
"(",
"that",
".",
"jid",
")",
";",
"this",
".",
"jid",
"=",
"that",
".",
"jid",
";",
"}",
"}"
] | Called by Strophe on connection event | [
"Called",
"by",
"Strophe",
"on",
"connection",
"event"
] | fc12f60570bdd2b73cc87077a884a102bc32f3be | https://github.com/strophe/strophejs-plugin-pubsub/blob/fc12f60570bdd2b73cc87077a884a102bc32f3be/src/strophe.pubsub.js#L143-L149 | train |
|
ucscXena/static-interval-tree | js/index.js | toTree | function toTree(arr, low, high) {
if (low >= high) {
return undefined;
}
var mid = Math.floor((high + low) / 2);
return {
el: arr[mid],
right: toTree(arr, mid + 1, high),
left: toTree(arr, low, mid)
};
} | javascript | function toTree(arr, low, high) {
if (low >= high) {
return undefined;
}
var mid = Math.floor((high + low) / 2);
return {
el: arr[mid],
right: toTree(arr, mid + 1, high),
left: toTree(arr, low, mid)
};
} | [
"function",
"toTree",
"(",
"arr",
",",
"low",
",",
"high",
")",
"{",
"if",
"(",
"low",
">=",
"high",
")",
"{",
"return",
"undefined",
";",
"}",
"var",
"mid",
"=",
"Math",
".",
"floor",
"(",
"(",
"high",
"+",
"low",
")",
"/",
"2",
")",
";",
"return",
"{",
"el",
":",
"arr",
"[",
"mid",
"]",
",",
"right",
":",
"toTree",
"(",
"arr",
",",
"mid",
"+",
"1",
",",
"high",
")",
",",
"left",
":",
"toTree",
"(",
"arr",
",",
"low",
",",
"mid",
")",
"}",
";",
"}"
] | Build a balanced binary tree from an ordered array. | [
"Build",
"a",
"balanced",
"binary",
"tree",
"from",
"an",
"ordered",
"array",
"."
] | 5cbe1e5b35a8b9fa27f1530a820def21d3ca037b | https://github.com/ucscXena/static-interval-tree/blob/5cbe1e5b35a8b9fa27f1530a820def21d3ca037b/js/index.js#L12-L22 | train |
ucscXena/static-interval-tree | js/index.js | findEnd | function findEnd(node) {
if (!node) {
return undefined;
}
var {left, right, el} = node;
findEnd(left);
findEnd(right);
node.high = Math.max(getHigh(left), getHigh(right), el.end);
return node;
} | javascript | function findEnd(node) {
if (!node) {
return undefined;
}
var {left, right, el} = node;
findEnd(left);
findEnd(right);
node.high = Math.max(getHigh(left), getHigh(right), el.end);
return node;
} | [
"function",
"findEnd",
"(",
"node",
")",
"{",
"if",
"(",
"!",
"node",
")",
"{",
"return",
"undefined",
";",
"}",
"var",
"{",
"left",
",",
"right",
",",
"el",
"}",
"=",
"node",
";",
"findEnd",
"(",
"left",
")",
";",
"findEnd",
"(",
"right",
")",
";",
"node",
".",
"high",
"=",
"Math",
".",
"max",
"(",
"getHigh",
"(",
"left",
")",
",",
"getHigh",
"(",
"right",
")",
",",
"el",
".",
"end",
")",
";",
"return",
"node",
";",
"}"
] | Find the highest end value of each node. Mutates its input. | [
"Find",
"the",
"highest",
"end",
"value",
"of",
"each",
"node",
".",
"Mutates",
"its",
"input",
"."
] | 5cbe1e5b35a8b9fa27f1530a820def21d3ca037b | https://github.com/ucscXena/static-interval-tree/blob/5cbe1e5b35a8b9fa27f1530a820def21d3ca037b/js/index.js#L27-L36 | train |
groupon/assertive | src/assertive.js | getNameOfType | function getNameOfType(x) {
switch (false) {
case !(x == null):
return `${x}`; // null / undefined
case !is.String(x):
return x;
case !is.Function(x):
return x.name;
case !is.NaN(x):
return 'NaN';
default:
return x;
}
} | javascript | function getNameOfType(x) {
switch (false) {
case !(x == null):
return `${x}`; // null / undefined
case !is.String(x):
return x;
case !is.Function(x):
return x.name;
case !is.NaN(x):
return 'NaN';
default:
return x;
}
} | [
"function",
"getNameOfType",
"(",
"x",
")",
"{",
"switch",
"(",
"false",
")",
"{",
"case",
"!",
"(",
"x",
"==",
"null",
")",
":",
"return",
"`",
"${",
"x",
"}",
"`",
";",
"case",
"!",
"is",
".",
"String",
"(",
"x",
")",
":",
"return",
"x",
";",
"case",
"!",
"is",
".",
"Function",
"(",
"x",
")",
":",
"return",
"x",
".",
"name",
";",
"case",
"!",
"is",
".",
"NaN",
"(",
"x",
")",
":",
"return",
"'NaN'",
";",
"default",
":",
"return",
"x",
";",
"}",
"}"
] | translates any argument we were meant to interpret as a type, into its name | [
"translates",
"any",
"argument",
"we",
"were",
"meant",
"to",
"interpret",
"as",
"a",
"type",
"into",
"its",
"name"
] | 4118ffca647260914494183d9ebbc5bde735a574 | https://github.com/groupon/assertive/blob/4118ffca647260914494183d9ebbc5bde735a574/src/assertive.js#L223-L236 | train |
simonepri/phc-argon2 | index.js | hash | function hash(password, options) {
options = options || {};
let variant = options.variant || defaults.variant;
const iterations = options.iterations || defaults.iterations;
const memory = options.memory || defaults.memory;
const parallelism = options.parallelism || defaults.parallelism;
const saltSize = options.saltSize || defaults.saltSize;
const version = versions[versions.length - 1];
// Iterations Validation
if (typeof iterations !== 'number' || !Number.isInteger(iterations)) {
return Promise.reject(
new TypeError("The 'iterations' option must be an integer")
);
}
if (iterations < 1 || iterations > MAX_UINT32) {
return Promise.reject(
new TypeError(
`The 'iterations' option must be in the range (1 <= iterations <= ${MAX_UINT32})`
)
);
}
// Parallelism Validation
if (typeof parallelism !== 'number' || !Number.isInteger(parallelism)) {
return Promise.reject(
new TypeError("The 'parallelism' option must be an integer")
);
}
if (parallelism < 1 || parallelism > MAX_UINT24) {
return Promise.reject(
new TypeError(
`The 'parallelism' option must be in the range (1 <= parallelism <= ${MAX_UINT24})`
)
);
}
// Memory Validation
if (typeof memory !== 'number' || !Number.isInteger(memory)) {
return Promise.reject(
new TypeError("The 'memory' option must be an integer")
);
}
const minmem = 8 * parallelism;
if (memory < minmem || memory > MAX_UINT32) {
return Promise.reject(
new TypeError(
`The 'memory' option must be in the range (${minmem} <= memory <= ${MAX_UINT32})`
)
);
}
// Variant Validation
if (typeof variant !== 'string') {
return Promise.reject(
new TypeError("The 'variant' option must be a string")
);
}
variant = variant.toLowerCase();
if (!Object.prototype.hasOwnProperty.call(variants, variant)) {
return Promise.reject(
new TypeError(
`The 'variant' option must be one of: ${Object.keys(variants)}`
)
);
}
// Salt Size Validation
if (saltSize < 8 || saltSize > 1024) {
return Promise.reject(
new TypeError(
"The 'saltSize' option must be in the range (8 <= parallelism <= 1023)"
)
);
}
return gensalt(saltSize).then(salt => {
const params = {
version,
type: variants[variant],
timeCost: iterations,
memoryCost: memory,
parallelism,
salt,
raw: true
};
return argon2.hash(password, params).then(hash => {
const phcstr = phc.serialize({
id: `argon2${variant}`,
version,
params: {
t: iterations,
m: memory,
p: parallelism
},
salt,
hash
});
return phcstr;
});
});
} | javascript | function hash(password, options) {
options = options || {};
let variant = options.variant || defaults.variant;
const iterations = options.iterations || defaults.iterations;
const memory = options.memory || defaults.memory;
const parallelism = options.parallelism || defaults.parallelism;
const saltSize = options.saltSize || defaults.saltSize;
const version = versions[versions.length - 1];
// Iterations Validation
if (typeof iterations !== 'number' || !Number.isInteger(iterations)) {
return Promise.reject(
new TypeError("The 'iterations' option must be an integer")
);
}
if (iterations < 1 || iterations > MAX_UINT32) {
return Promise.reject(
new TypeError(
`The 'iterations' option must be in the range (1 <= iterations <= ${MAX_UINT32})`
)
);
}
// Parallelism Validation
if (typeof parallelism !== 'number' || !Number.isInteger(parallelism)) {
return Promise.reject(
new TypeError("The 'parallelism' option must be an integer")
);
}
if (parallelism < 1 || parallelism > MAX_UINT24) {
return Promise.reject(
new TypeError(
`The 'parallelism' option must be in the range (1 <= parallelism <= ${MAX_UINT24})`
)
);
}
// Memory Validation
if (typeof memory !== 'number' || !Number.isInteger(memory)) {
return Promise.reject(
new TypeError("The 'memory' option must be an integer")
);
}
const minmem = 8 * parallelism;
if (memory < minmem || memory > MAX_UINT32) {
return Promise.reject(
new TypeError(
`The 'memory' option must be in the range (${minmem} <= memory <= ${MAX_UINT32})`
)
);
}
// Variant Validation
if (typeof variant !== 'string') {
return Promise.reject(
new TypeError("The 'variant' option must be a string")
);
}
variant = variant.toLowerCase();
if (!Object.prototype.hasOwnProperty.call(variants, variant)) {
return Promise.reject(
new TypeError(
`The 'variant' option must be one of: ${Object.keys(variants)}`
)
);
}
// Salt Size Validation
if (saltSize < 8 || saltSize > 1024) {
return Promise.reject(
new TypeError(
"The 'saltSize' option must be in the range (8 <= parallelism <= 1023)"
)
);
}
return gensalt(saltSize).then(salt => {
const params = {
version,
type: variants[variant],
timeCost: iterations,
memoryCost: memory,
parallelism,
salt,
raw: true
};
return argon2.hash(password, params).then(hash => {
const phcstr = phc.serialize({
id: `argon2${variant}`,
version,
params: {
t: iterations,
m: memory,
p: parallelism
},
salt,
hash
});
return phcstr;
});
});
} | [
"function",
"hash",
"(",
"password",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"let",
"variant",
"=",
"options",
".",
"variant",
"||",
"defaults",
".",
"variant",
";",
"const",
"iterations",
"=",
"options",
".",
"iterations",
"||",
"defaults",
".",
"iterations",
";",
"const",
"memory",
"=",
"options",
".",
"memory",
"||",
"defaults",
".",
"memory",
";",
"const",
"parallelism",
"=",
"options",
".",
"parallelism",
"||",
"defaults",
".",
"parallelism",
";",
"const",
"saltSize",
"=",
"options",
".",
"saltSize",
"||",
"defaults",
".",
"saltSize",
";",
"const",
"version",
"=",
"versions",
"[",
"versions",
".",
"length",
"-",
"1",
"]",
";",
"if",
"(",
"typeof",
"iterations",
"!==",
"'number'",
"||",
"!",
"Number",
".",
"isInteger",
"(",
"iterations",
")",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"TypeError",
"(",
"\"The 'iterations' option must be an integer\"",
")",
")",
";",
"}",
"if",
"(",
"iterations",
"<",
"1",
"||",
"iterations",
">",
"MAX_UINT32",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"TypeError",
"(",
"`",
"${",
"MAX_UINT32",
"}",
"`",
")",
")",
";",
"}",
"if",
"(",
"typeof",
"parallelism",
"!==",
"'number'",
"||",
"!",
"Number",
".",
"isInteger",
"(",
"parallelism",
")",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"TypeError",
"(",
"\"The 'parallelism' option must be an integer\"",
")",
")",
";",
"}",
"if",
"(",
"parallelism",
"<",
"1",
"||",
"parallelism",
">",
"MAX_UINT24",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"TypeError",
"(",
"`",
"${",
"MAX_UINT24",
"}",
"`",
")",
")",
";",
"}",
"if",
"(",
"typeof",
"memory",
"!==",
"'number'",
"||",
"!",
"Number",
".",
"isInteger",
"(",
"memory",
")",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"TypeError",
"(",
"\"The 'memory' option must be an integer\"",
")",
")",
";",
"}",
"const",
"minmem",
"=",
"8",
"*",
"parallelism",
";",
"if",
"(",
"memory",
"<",
"minmem",
"||",
"memory",
">",
"MAX_UINT32",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"TypeError",
"(",
"`",
"${",
"minmem",
"}",
"${",
"MAX_UINT32",
"}",
"`",
")",
")",
";",
"}",
"if",
"(",
"typeof",
"variant",
"!==",
"'string'",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"TypeError",
"(",
"\"The 'variant' option must be a string\"",
")",
")",
";",
"}",
"variant",
"=",
"variant",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"!",
"Object",
".",
"prototype",
".",
"hasOwnProperty",
".",
"call",
"(",
"variants",
",",
"variant",
")",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"TypeError",
"(",
"`",
"${",
"Object",
".",
"keys",
"(",
"variants",
")",
"}",
"`",
")",
")",
";",
"}",
"if",
"(",
"saltSize",
"<",
"8",
"||",
"saltSize",
">",
"1024",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"TypeError",
"(",
"\"The 'saltSize' option must be in the range (8 <= parallelism <= 1023)\"",
")",
")",
";",
"}",
"return",
"gensalt",
"(",
"saltSize",
")",
".",
"then",
"(",
"salt",
"=>",
"{",
"const",
"params",
"=",
"{",
"version",
",",
"type",
":",
"variants",
"[",
"variant",
"]",
",",
"timeCost",
":",
"iterations",
",",
"memoryCost",
":",
"memory",
",",
"parallelism",
",",
"salt",
",",
"raw",
":",
"true",
"}",
";",
"return",
"argon2",
".",
"hash",
"(",
"password",
",",
"params",
")",
".",
"then",
"(",
"hash",
"=>",
"{",
"const",
"phcstr",
"=",
"phc",
".",
"serialize",
"(",
"{",
"id",
":",
"`",
"${",
"variant",
"}",
"`",
",",
"version",
",",
"params",
":",
"{",
"t",
":",
"iterations",
",",
"m",
":",
"memory",
",",
"p",
":",
"parallelism",
"}",
",",
"salt",
",",
"hash",
"}",
")",
";",
"return",
"phcstr",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Computes the hash string of the given password in the PHC format using argon2
package.
@public
@param {string} password The password to hash.
@param {Object} [options] Optional configurations related to the hashing
function.
@param {number} [options.variant=id] Optinal variant of argon2 to use.
Can be one of [`'d'`, `'i'`, `'id'`] for argon2d, argon2i and argon2id
respectively.
@param {number} [options.iterations=3] Optional number of iterations to use.
Must be an integer within the range (`1` <= `iterations` <= `2^32-1`).
@param {number} [options.memory=4096] Optional amount of memory to use in
kibibytes.
Must be an integer within the range (`8` <= `memory` <= `2^32-1`).
@param {number} [options.parallelism=1] Optional degree of parallelism to
use.
Must be an integer within the range (`1` <= `parallelism` <= `2^24-1`).
@param {number} [options.saltSize=16] Optional number of bytes to use when
autogenerating new salts.
Must be an integer within the range (`1` <= `saltSize` <= `2^10-1`).
@return {Promise.<string>} The generated secure hash string in the PHC
format. | [
"Computes",
"the",
"hash",
"string",
"of",
"the",
"given",
"password",
"in",
"the",
"PHC",
"format",
"using",
"argon2",
"package",
"."
] | 900c5aea9185b69a677ce27ce06aa8a9526222fd | https://github.com/simonepri/phc-argon2/blob/900c5aea9185b69a677ce27ce06aa8a9526222fd/index.js#L81-L182 | train |
posthtml/posthtml-postcss-modules | index.js | processContentWithPostCSS | function processContentWithPostCSS(options, href) {
/**
* @param {String} content [css to process]
* @return {Object} [object with css tokens and css itself]
*/
return function (content) {
if (options.generateScopedName) {
options.generateScopedName = typeof options.generateScopedName === 'function' ?
/* istanbul ignore next */
options.generateScopedName :
genericNames(options.generateScopedName, {context: options.root});
} else {
options.generateScopedName = function (local, filename) {
return Scope.generateScopedName(local, path.relative(options.root, filename));
};
}
// Setup css-modules plugins 💼
var runner = postcss([
Values,
LocalByDefault,
ExtractImports,
new Scope({generateScopedName: options.generateScopedName}),
new Parser({fetch: fetch})
].concat(options.plugins));
function fetch(_to, _from) {
// Seems ok 👏
var filePath = normalizePath(_to, options.root, _from);
return new Promise(function (resolve, reject) {
return fs.readFile(filePath, 'utf8', function (err, content) {
/* istanbul ignore next: just error handler */
if (err) {
return reject(err);
}
return runner.process(content, {from: filePath})
.then(function (result) {
return resolve(result.root.tokens);
}).catch(reject);
});
});
}
return runner.process(content, {from: normalizePath(href, options.root, options.from)});
};
} | javascript | function processContentWithPostCSS(options, href) {
/**
* @param {String} content [css to process]
* @return {Object} [object with css tokens and css itself]
*/
return function (content) {
if (options.generateScopedName) {
options.generateScopedName = typeof options.generateScopedName === 'function' ?
/* istanbul ignore next */
options.generateScopedName :
genericNames(options.generateScopedName, {context: options.root});
} else {
options.generateScopedName = function (local, filename) {
return Scope.generateScopedName(local, path.relative(options.root, filename));
};
}
// Setup css-modules plugins 💼
var runner = postcss([
Values,
LocalByDefault,
ExtractImports,
new Scope({generateScopedName: options.generateScopedName}),
new Parser({fetch: fetch})
].concat(options.plugins));
function fetch(_to, _from) {
// Seems ok 👏
var filePath = normalizePath(_to, options.root, _from);
return new Promise(function (resolve, reject) {
return fs.readFile(filePath, 'utf8', function (err, content) {
/* istanbul ignore next: just error handler */
if (err) {
return reject(err);
}
return runner.process(content, {from: filePath})
.then(function (result) {
return resolve(result.root.tokens);
}).catch(reject);
});
});
}
return runner.process(content, {from: normalizePath(href, options.root, options.from)});
};
} | [
"function",
"processContentWithPostCSS",
"(",
"options",
",",
"href",
")",
"{",
"return",
"function",
"(",
"content",
")",
"{",
"if",
"(",
"options",
".",
"generateScopedName",
")",
"{",
"options",
".",
"generateScopedName",
"=",
"typeof",
"options",
".",
"generateScopedName",
"===",
"'function'",
"?",
"options",
".",
"generateScopedName",
":",
"genericNames",
"(",
"options",
".",
"generateScopedName",
",",
"{",
"context",
":",
"options",
".",
"root",
"}",
")",
";",
"}",
"else",
"{",
"options",
".",
"generateScopedName",
"=",
"function",
"(",
"local",
",",
"filename",
")",
"{",
"return",
"Scope",
".",
"generateScopedName",
"(",
"local",
",",
"path",
".",
"relative",
"(",
"options",
".",
"root",
",",
"filename",
")",
")",
";",
"}",
";",
"}",
"var",
"runner",
"=",
"postcss",
"(",
"[",
"Values",
",",
"LocalByDefault",
",",
"ExtractImports",
",",
"new",
"Scope",
"(",
"{",
"generateScopedName",
":",
"options",
".",
"generateScopedName",
"}",
")",
",",
"new",
"Parser",
"(",
"{",
"fetch",
":",
"fetch",
"}",
")",
"]",
".",
"concat",
"(",
"options",
".",
"plugins",
")",
")",
";",
"function",
"fetch",
"(",
"_to",
",",
"_from",
")",
"{",
"var",
"filePath",
"=",
"normalizePath",
"(",
"_to",
",",
"options",
".",
"root",
",",
"_from",
")",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"return",
"fs",
".",
"readFile",
"(",
"filePath",
",",
"'utf8'",
",",
"function",
"(",
"err",
",",
"content",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"reject",
"(",
"err",
")",
";",
"}",
"return",
"runner",
".",
"process",
"(",
"content",
",",
"{",
"from",
":",
"filePath",
"}",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"return",
"resolve",
"(",
"result",
".",
"root",
".",
"tokens",
")",
";",
"}",
")",
".",
"catch",
"(",
"reject",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"return",
"runner",
".",
"process",
"(",
"content",
",",
"{",
"from",
":",
"normalizePath",
"(",
"href",
",",
"options",
".",
"root",
",",
"options",
".",
"from",
")",
"}",
")",
";",
"}",
";",
"}"
] | processes css with css-modules plugins
@param {Object} options [plugin's options]
@return {Function} | [
"processes",
"css",
"with",
"css",
"-",
"modules",
"plugins"
] | f524f87cb8e1a478cdc4ae35a0c150e91b855547 | https://github.com/posthtml/posthtml-postcss-modules/blob/f524f87cb8e1a478cdc4ae35a0c150e91b855547/index.js#L50-L97 | train |
TomFrost/node-phonetic | lib/phonetic.js | getDerivative | function getDerivative(num) {
var derivative = 1;
while (num != 0) {
derivative += num % 7;
num = Math.floor(num / 7);
}
return derivative;
} | javascript | function getDerivative(num) {
var derivative = 1;
while (num != 0) {
derivative += num % 7;
num = Math.floor(num / 7);
}
return derivative;
} | [
"function",
"getDerivative",
"(",
"num",
")",
"{",
"var",
"derivative",
"=",
"1",
";",
"while",
"(",
"num",
"!=",
"0",
")",
"{",
"derivative",
"+=",
"num",
"%",
"7",
";",
"num",
"=",
"Math",
".",
"floor",
"(",
"num",
"/",
"7",
")",
";",
"}",
"return",
"derivative",
";",
"}"
] | Gets a derivative of a number by repeatedly dividing it by 7 and adding the
remainders together. It's useful to base decisions on a derivative rather
than the wordObj's current numeric, as it avoids making the same decisions
around the same phonetics.
@param {number} num A number from which a derivative should be calculated
@returns {number} The derivative. | [
"Gets",
"a",
"derivative",
"of",
"a",
"number",
"by",
"repeatedly",
"dividing",
"it",
"by",
"7",
"and",
"adding",
"the",
"remainders",
"together",
".",
"It",
"s",
"useful",
"to",
"base",
"decisions",
"on",
"a",
"derivative",
"rather",
"than",
"the",
"wordObj",
"s",
"current",
"numeric",
"as",
"it",
"avoids",
"making",
"the",
"same",
"decisions",
"around",
"the",
"same",
"phonetics",
"."
] | bd67e91664210b04087c536ebc3831e4cceafb0a | https://github.com/TomFrost/node-phonetic/blob/bd67e91664210b04087c536ebc3831e4cceafb0a/lib/phonetic.js#L146-L153 | train |
TomFrost/node-phonetic | lib/phonetic.js | getNextPhonetic | function getNextPhonetic(phoneticSet, simpleCap, wordObj, forceSimple) {
var deriv = getDerivative(wordObj.numeric),
simple = (wordObj.numeric + deriv) % wordObj.opts.phoneticSimplicity > 0,
cap = simple || forceSimple ? simpleCap : phoneticSet.length,
phonetic = phoneticSet[wordObj.numeric % cap];
wordObj.numeric = getNumericHash(wordObj.numeric + wordObj.word);
return phonetic;
} | javascript | function getNextPhonetic(phoneticSet, simpleCap, wordObj, forceSimple) {
var deriv = getDerivative(wordObj.numeric),
simple = (wordObj.numeric + deriv) % wordObj.opts.phoneticSimplicity > 0,
cap = simple || forceSimple ? simpleCap : phoneticSet.length,
phonetic = phoneticSet[wordObj.numeric % cap];
wordObj.numeric = getNumericHash(wordObj.numeric + wordObj.word);
return phonetic;
} | [
"function",
"getNextPhonetic",
"(",
"phoneticSet",
",",
"simpleCap",
",",
"wordObj",
",",
"forceSimple",
")",
"{",
"var",
"deriv",
"=",
"getDerivative",
"(",
"wordObj",
".",
"numeric",
")",
",",
"simple",
"=",
"(",
"wordObj",
".",
"numeric",
"+",
"deriv",
")",
"%",
"wordObj",
".",
"opts",
".",
"phoneticSimplicity",
">",
"0",
",",
"cap",
"=",
"simple",
"||",
"forceSimple",
"?",
"simpleCap",
":",
"phoneticSet",
".",
"length",
",",
"phonetic",
"=",
"phoneticSet",
"[",
"wordObj",
".",
"numeric",
"%",
"cap",
"]",
";",
"wordObj",
".",
"numeric",
"=",
"getNumericHash",
"(",
"wordObj",
".",
"numeric",
"+",
"wordObj",
".",
"word",
")",
";",
"return",
"phonetic",
";",
"}"
] | Gets the next pseudo-random phonetic from a given phonetic set,
intelligently determining whether to include "complex" phonetics in that
set based on the options.phoneticSimplicity.
@param {Array} phoneticSet The array of phonetics from which to choose
@param {number} simpleCap The number of 'simple' phonetics at the beginning
of the phoneticSet
@param {{word, numeric, lastSkippedPre, lastSkippedPost, opts}} wordObj The
wordObj for which the phonetic is being chosen
@param {boolean} [forceSimple] true to force a simple phonetic to be
chosen; otherwise, the function will choose whether to include complex
phonetics based on the derivative of wordObj.numeric.
@returns {string} The chosen phonetic. | [
"Gets",
"the",
"next",
"pseudo",
"-",
"random",
"phonetic",
"from",
"a",
"given",
"phonetic",
"set",
"intelligently",
"determining",
"whether",
"to",
"include",
"complex",
"phonetics",
"in",
"that",
"set",
"based",
"on",
"the",
"options",
".",
"phoneticSimplicity",
"."
] | bd67e91664210b04087c536ebc3831e4cceafb0a | https://github.com/TomFrost/node-phonetic/blob/bd67e91664210b04087c536ebc3831e4cceafb0a/lib/phonetic.js#L206-L213 | train |
TomFrost/node-phonetic | lib/phonetic.js | getNumericHash | function getNumericHash(data) {
var hash = crypto.createHash('md5'),
numeric = 0,
buf;
hash.update(data + '-Phonetic');
buf = hash.digest();
for (var i = 0; i <= 12; i += 4)
numeric += buf.readUInt32LE(i);
return numeric;
} | javascript | function getNumericHash(data) {
var hash = crypto.createHash('md5'),
numeric = 0,
buf;
hash.update(data + '-Phonetic');
buf = hash.digest();
for (var i = 0; i <= 12; i += 4)
numeric += buf.readUInt32LE(i);
return numeric;
} | [
"function",
"getNumericHash",
"(",
"data",
")",
"{",
"var",
"hash",
"=",
"crypto",
".",
"createHash",
"(",
"'md5'",
")",
",",
"numeric",
"=",
"0",
",",
"buf",
";",
"hash",
".",
"update",
"(",
"data",
"+",
"'-Phonetic'",
")",
";",
"buf",
"=",
"hash",
".",
"digest",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<=",
"12",
";",
"i",
"+=",
"4",
")",
"numeric",
"+=",
"buf",
".",
"readUInt32LE",
"(",
"i",
")",
";",
"return",
"numeric",
";",
"}"
] | Generates a numeric hash based on the input data. The hash is an md5, with
each block of 32 bits converted to an integer and added together.
@param {string|number} data The string or number to be hashed.
@returns {number} | [
"Generates",
"a",
"numeric",
"hash",
"based",
"on",
"the",
"input",
"data",
".",
"The",
"hash",
"is",
"an",
"md5",
"with",
"each",
"block",
"of",
"32",
"bits",
"converted",
"to",
"an",
"integer",
"and",
"added",
"together",
"."
] | bd67e91664210b04087c536ebc3831e4cceafb0a | https://github.com/TomFrost/node-phonetic/blob/bd67e91664210b04087c536ebc3831e4cceafb0a/lib/phonetic.js#L222-L231 | train |
TomFrost/node-phonetic | lib/phonetic.js | postProcess | function postProcess(wordObj) {
var regex;
for (var i in REPLACEMENTS) {
if (REPLACEMENTS.hasOwnProperty(i)) {
regex = new RegExp(i);
wordObj.word = wordObj.word.replace(regex, REPLACEMENTS[i]);
}
}
if (wordObj.opts.capFirst)
return capFirst(wordObj.word);
return wordObj.word;
} | javascript | function postProcess(wordObj) {
var regex;
for (var i in REPLACEMENTS) {
if (REPLACEMENTS.hasOwnProperty(i)) {
regex = new RegExp(i);
wordObj.word = wordObj.word.replace(regex, REPLACEMENTS[i]);
}
}
if (wordObj.opts.capFirst)
return capFirst(wordObj.word);
return wordObj.word;
} | [
"function",
"postProcess",
"(",
"wordObj",
")",
"{",
"var",
"regex",
";",
"for",
"(",
"var",
"i",
"in",
"REPLACEMENTS",
")",
"{",
"if",
"(",
"REPLACEMENTS",
".",
"hasOwnProperty",
"(",
"i",
")",
")",
"{",
"regex",
"=",
"new",
"RegExp",
"(",
"i",
")",
";",
"wordObj",
".",
"word",
"=",
"wordObj",
".",
"word",
".",
"replace",
"(",
"regex",
",",
"REPLACEMENTS",
"[",
"i",
"]",
")",
";",
"}",
"}",
"if",
"(",
"wordObj",
".",
"opts",
".",
"capFirst",
")",
"return",
"capFirst",
"(",
"wordObj",
".",
"word",
")",
";",
"return",
"wordObj",
".",
"word",
";",
"}"
] | Applies post-processing to a word after it has already been generated. In
this phase, the REPLACEMENTS are executed, applying language intelligence
that can make generated words more pronounceable. The first letter is
also capitalized.
@param {{word, numeric, lastSkippedPre, lastSkippedPost, opts}} wordObj The
word object to be processed.
@returns {string} The processed word. | [
"Applies",
"post",
"-",
"processing",
"to",
"a",
"word",
"after",
"it",
"has",
"already",
"been",
"generated",
".",
"In",
"this",
"phase",
"the",
"REPLACEMENTS",
"are",
"executed",
"applying",
"language",
"intelligence",
"that",
"can",
"make",
"generated",
"words",
"more",
"pronounceable",
".",
"The",
"first",
"letter",
"is",
"also",
"capitalized",
"."
] | bd67e91664210b04087c536ebc3831e4cceafb0a | https://github.com/TomFrost/node-phonetic/blob/bd67e91664210b04087c536ebc3831e4cceafb0a/lib/phonetic.js#L243-L254 | train |
amida-tech/blue-button-generate | lib/sectionLevel2.js | function (input) {
var value = bbuo.deepValue(input, 'product.product.name');
if (!bbuo.exists(value)) {
value = bbuo.deepValue(input, 'product.unencoded_name');
}
if (!bbuo.exists(value)) {
return "";
} else {
return value;
}
} | javascript | function (input) {
var value = bbuo.deepValue(input, 'product.product.name');
if (!bbuo.exists(value)) {
value = bbuo.deepValue(input, 'product.unencoded_name');
}
if (!bbuo.exists(value)) {
return "";
} else {
return value;
}
} | [
"function",
"(",
"input",
")",
"{",
"var",
"value",
"=",
"bbuo",
".",
"deepValue",
"(",
"input",
",",
"'product.product.name'",
")",
";",
"if",
"(",
"!",
"bbuo",
".",
"exists",
"(",
"value",
")",
")",
"{",
"value",
"=",
"bbuo",
".",
"deepValue",
"(",
"input",
",",
"'product.unencoded_name'",
")",
";",
"}",
"if",
"(",
"!",
"bbuo",
".",
"exists",
"(",
"value",
")",
")",
"{",
"return",
"\"\"",
";",
"}",
"else",
"{",
"return",
"value",
";",
"}",
"}"
] | Name, did not find class in the medication blue-button-data | [
"Name",
"did",
"not",
"find",
"class",
"in",
"the",
"medication",
"blue",
"-",
"button",
"-",
"data"
] | 20515d9ac03384bac7197dca0df7d43523c8c3df | https://github.com/amida-tech/blue-button-generate/blob/20515d9ac03384bac7197dca0df7d43523c8c3df/lib/sectionLevel2.js#L113-L123 | train |
|
sheebz/phantom-proxy | lib/webpage.js | function (propertyName, callbackFn) {
var self = this;
request.post(this.options.hostAndPort + '/page/properties/get', {form:{ propertyName:propertyName}},
function (error, response, body) {
error && console.error(error);
if (response && response.statusCode === 200) {
callbackFn && callbackFn.call(self, body);
}
else {
console.log('error in response %s'.red.bold, body);
callbackFn && callbackFn.call(self, false, body);
}
});
} | javascript | function (propertyName, callbackFn) {
var self = this;
request.post(this.options.hostAndPort + '/page/properties/get', {form:{ propertyName:propertyName}},
function (error, response, body) {
error && console.error(error);
if (response && response.statusCode === 200) {
callbackFn && callbackFn.call(self, body);
}
else {
console.log('error in response %s'.red.bold, body);
callbackFn && callbackFn.call(self, false, body);
}
});
} | [
"function",
"(",
"propertyName",
",",
"callbackFn",
")",
"{",
"var",
"self",
"=",
"this",
";",
"request",
".",
"post",
"(",
"this",
".",
"options",
".",
"hostAndPort",
"+",
"'/page/properties/get'",
",",
"{",
"form",
":",
"{",
"propertyName",
":",
"propertyName",
"}",
"}",
",",
"function",
"(",
"error",
",",
"response",
",",
"body",
")",
"{",
"error",
"&&",
"console",
".",
"error",
"(",
"error",
")",
";",
"if",
"(",
"response",
"&&",
"response",
".",
"statusCode",
"===",
"200",
")",
"{",
"callbackFn",
"&&",
"callbackFn",
".",
"call",
"(",
"self",
",",
"body",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"'error in response %s'",
".",
"red",
".",
"bold",
",",
"body",
")",
";",
"callbackFn",
"&&",
"callbackFn",
".",
"call",
"(",
"self",
",",
"false",
",",
"body",
")",
";",
"}",
"}",
")",
";",
"}"
] | gets property value ex. version | [
"gets",
"property",
"value",
"ex",
".",
"version"
] | a4963662205400e542668938ce5cf1ab9a66fba0 | https://github.com/sheebz/phantom-proxy/blob/a4963662205400e542668938ce5cf1ab9a66fba0/lib/webpage.js#L63-L77 | train |
|
sheebz/phantom-proxy | lib/webpage.js | function (expressionFn, callbackFn) {
var self = this,
url = self.options.hostAndPort + '/page/functions/evaluate';
self.options.debug && console.log('calling url: %s', url);
request.post(url, {
form:{expressionFn:expressionFn.toString(), args:JSON.stringify(Array.prototype.slice.call(arguments, 2, arguments.length), null, 4)}
},
function (error, response, body) {
if (response && response.statusCode === 200) {
callbackFn && callbackFn.call(self, JSON.parse(body));
}
else {
console.error(body);
callbackFn && callbackFn.call(self, body);
}
});
} | javascript | function (expressionFn, callbackFn) {
var self = this,
url = self.options.hostAndPort + '/page/functions/evaluate';
self.options.debug && console.log('calling url: %s', url);
request.post(url, {
form:{expressionFn:expressionFn.toString(), args:JSON.stringify(Array.prototype.slice.call(arguments, 2, arguments.length), null, 4)}
},
function (error, response, body) {
if (response && response.statusCode === 200) {
callbackFn && callbackFn.call(self, JSON.parse(body));
}
else {
console.error(body);
callbackFn && callbackFn.call(self, body);
}
});
} | [
"function",
"(",
"expressionFn",
",",
"callbackFn",
")",
"{",
"var",
"self",
"=",
"this",
",",
"url",
"=",
"self",
".",
"options",
".",
"hostAndPort",
"+",
"'/page/functions/evaluate'",
";",
"self",
".",
"options",
".",
"debug",
"&&",
"console",
".",
"log",
"(",
"'calling url: %s'",
",",
"url",
")",
";",
"request",
".",
"post",
"(",
"url",
",",
"{",
"form",
":",
"{",
"expressionFn",
":",
"expressionFn",
".",
"toString",
"(",
")",
",",
"args",
":",
"JSON",
".",
"stringify",
"(",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"2",
",",
"arguments",
".",
"length",
")",
",",
"null",
",",
"4",
")",
"}",
"}",
",",
"function",
"(",
"error",
",",
"response",
",",
"body",
")",
"{",
"if",
"(",
"response",
"&&",
"response",
".",
"statusCode",
"===",
"200",
")",
"{",
"callbackFn",
"&&",
"callbackFn",
".",
"call",
"(",
"self",
",",
"JSON",
".",
"parse",
"(",
"body",
")",
")",
";",
"}",
"else",
"{",
"console",
".",
"error",
"(",
"body",
")",
";",
"callbackFn",
"&&",
"callbackFn",
".",
"call",
"(",
"self",
",",
"body",
")",
";",
"}",
"}",
")",
";",
"}"
] | Evaluates the given function in the context of the web page. The execution is sandboxed, the web page has no access to the phantom object and it can't probe its own setting. | [
"Evaluates",
"the",
"given",
"function",
"in",
"the",
"context",
"of",
"the",
"web",
"page",
".",
"The",
"execution",
"is",
"sandboxed",
"the",
"web",
"page",
"has",
"no",
"access",
"to",
"the",
"phantom",
"object",
"and",
"it",
"can",
"t",
"probe",
"its",
"own",
"setting",
"."
] | a4963662205400e542668938ce5cf1ab9a66fba0 | https://github.com/sheebz/phantom-proxy/blob/a4963662205400e542668938ce5cf1ab9a66fba0/lib/webpage.js#L177-L195 | train |
|
sheebz/phantom-proxy | lib/webpage.js | function (filename, callbackFn) {
var self = this,
url = self.options.hostAndPort + '/page/functions/render';
self.options.debug && console.log('calling url: %s', url);
request.post(url, {form:{ args:JSON.stringify(
[
filename
], null, 4)}},
function (error, response, body) {
error && console.error(error);
if (response && response.statusCode === 200) {
callbackFn && callbackFn.call(self, !!body);
}
else {
console.error(body);
callbackFn && callbackFn.call(self, body);
}
}
);
} | javascript | function (filename, callbackFn) {
var self = this,
url = self.options.hostAndPort + '/page/functions/render';
self.options.debug && console.log('calling url: %s', url);
request.post(url, {form:{ args:JSON.stringify(
[
filename
], null, 4)}},
function (error, response, body) {
error && console.error(error);
if (response && response.statusCode === 200) {
callbackFn && callbackFn.call(self, !!body);
}
else {
console.error(body);
callbackFn && callbackFn.call(self, body);
}
}
);
} | [
"function",
"(",
"filename",
",",
"callbackFn",
")",
"{",
"var",
"self",
"=",
"this",
",",
"url",
"=",
"self",
".",
"options",
".",
"hostAndPort",
"+",
"'/page/functions/render'",
";",
"self",
".",
"options",
".",
"debug",
"&&",
"console",
".",
"log",
"(",
"'calling url: %s'",
",",
"url",
")",
";",
"request",
".",
"post",
"(",
"url",
",",
"{",
"form",
":",
"{",
"args",
":",
"JSON",
".",
"stringify",
"(",
"[",
"filename",
"]",
",",
"null",
",",
"4",
")",
"}",
"}",
",",
"function",
"(",
"error",
",",
"response",
",",
"body",
")",
"{",
"error",
"&&",
"console",
".",
"error",
"(",
"error",
")",
";",
"if",
"(",
"response",
"&&",
"response",
".",
"statusCode",
"===",
"200",
")",
"{",
"callbackFn",
"&&",
"callbackFn",
".",
"call",
"(",
"self",
",",
"!",
"!",
"body",
")",
";",
"}",
"else",
"{",
"console",
".",
"error",
"(",
"body",
")",
";",
"callbackFn",
"&&",
"callbackFn",
".",
"call",
"(",
"self",
",",
"body",
")",
";",
"}",
"}",
")",
";",
"}"
] | Renders the web page to an image buffer and save it as the specified file. Currently the output format is automatically set based on the file extension. Supported formats are PNG, GIF, JPEG, and PDF. | [
"Renders",
"the",
"web",
"page",
"to",
"an",
"image",
"buffer",
"and",
"save",
"it",
"as",
"the",
"specified",
"file",
".",
"Currently",
"the",
"output",
"format",
"is",
"automatically",
"set",
"based",
"on",
"the",
"file",
"extension",
".",
"Supported",
"formats",
"are",
"PNG",
"GIF",
"JPEG",
"and",
"PDF",
"."
] | a4963662205400e542668938ce5cf1ab9a66fba0 | https://github.com/sheebz/phantom-proxy/blob/a4963662205400e542668938ce5cf1ab9a66fba0/lib/webpage.js#L219-L239 | train |
|
sheebz/phantom-proxy | lib/webpage.js | function (format, callbackFn) {
var self = this,
args =
[
format
],
url = this.options.hostAndPort + '/page/functions/renderBase64';
this.options.debug && console.log('calling execute method for %s and with %d params: %s'.grey, url, args.length, JSON.stringify(args));
request.post(url, {form:{ args:JSON.stringify(args)}},
function (error, response, body) {
error && console.error(error);
if (response && response.statusCode === 200) {
callbackFn && callbackFn.call(self, body);
}
else {
console.log('error in response %s'.red.bold, body);
callbackFn && callbackFn.call(self, false, body);
}
});
return this;
} | javascript | function (format, callbackFn) {
var self = this,
args =
[
format
],
url = this.options.hostAndPort + '/page/functions/renderBase64';
this.options.debug && console.log('calling execute method for %s and with %d params: %s'.grey, url, args.length, JSON.stringify(args));
request.post(url, {form:{ args:JSON.stringify(args)}},
function (error, response, body) {
error && console.error(error);
if (response && response.statusCode === 200) {
callbackFn && callbackFn.call(self, body);
}
else {
console.log('error in response %s'.red.bold, body);
callbackFn && callbackFn.call(self, false, body);
}
});
return this;
} | [
"function",
"(",
"format",
",",
"callbackFn",
")",
"{",
"var",
"self",
"=",
"this",
",",
"args",
"=",
"[",
"format",
"]",
",",
"url",
"=",
"this",
".",
"options",
".",
"hostAndPort",
"+",
"'/page/functions/renderBase64'",
";",
"this",
".",
"options",
".",
"debug",
"&&",
"console",
".",
"log",
"(",
"'calling execute method for %s and with %d params: %s'",
".",
"grey",
",",
"url",
",",
"args",
".",
"length",
",",
"JSON",
".",
"stringify",
"(",
"args",
")",
")",
";",
"request",
".",
"post",
"(",
"url",
",",
"{",
"form",
":",
"{",
"args",
":",
"JSON",
".",
"stringify",
"(",
"args",
")",
"}",
"}",
",",
"function",
"(",
"error",
",",
"response",
",",
"body",
")",
"{",
"error",
"&&",
"console",
".",
"error",
"(",
"error",
")",
";",
"if",
"(",
"response",
"&&",
"response",
".",
"statusCode",
"===",
"200",
")",
"{",
"callbackFn",
"&&",
"callbackFn",
".",
"call",
"(",
"self",
",",
"body",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"'error in response %s'",
".",
"red",
".",
"bold",
",",
"body",
")",
";",
"callbackFn",
"&&",
"callbackFn",
".",
"call",
"(",
"self",
",",
"false",
",",
"body",
")",
";",
"}",
"}",
")",
";",
"return",
"this",
";",
"}"
] | Renders the web page to an image buffer and returns the result as a base64-encoded string representation of that image. Supported formats are PNG, GIF, and JPEG. | [
"Renders",
"the",
"web",
"page",
"to",
"an",
"image",
"buffer",
"and",
"returns",
"the",
"result",
"as",
"a",
"base64",
"-",
"encoded",
"string",
"representation",
"of",
"that",
"image",
".",
"Supported",
"formats",
"are",
"PNG",
"GIF",
"and",
"JPEG",
"."
] | a4963662205400e542668938ce5cf1ab9a66fba0 | https://github.com/sheebz/phantom-proxy/blob/a4963662205400e542668938ce5cf1ab9a66fba0/lib/webpage.js#L242-L263 | train |
|
sheebz/phantom-proxy | lib/webpage.js | function (selector, callbackFn, timeout) {
var self = this,
startTime = Date.now(),
timeoutInterval = 150,
testRunning = false,
//if evaluate succeeds, invokes callback w/ true, if timeout,
// invokes w/ false, otherwise just exits
testForSelector = function () {
var elapsedTime = Date.now() - startTime;
if (elapsedTime > timeout) {
self.options.debug && console.log('warning: timeout occurred while waiting for selector:"%s"'.yellow, selector);
callbackFn(false);
return;
}
self.evaluate(function (selectorToEvaluate) {
return document.querySelectorAll(selectorToEvaluate).length;
}, function (result) {
testRunning = false;
if (result > 0) {//selector found
callbackFn(true);
}
else {
setTimeout(testForSelector, timeoutInterval);
}
}, selector);
};
timeout = timeout || 10000; //default timeout is 2 sec;
setTimeout(testForSelector, timeoutInterval);
} | javascript | function (selector, callbackFn, timeout) {
var self = this,
startTime = Date.now(),
timeoutInterval = 150,
testRunning = false,
//if evaluate succeeds, invokes callback w/ true, if timeout,
// invokes w/ false, otherwise just exits
testForSelector = function () {
var elapsedTime = Date.now() - startTime;
if (elapsedTime > timeout) {
self.options.debug && console.log('warning: timeout occurred while waiting for selector:"%s"'.yellow, selector);
callbackFn(false);
return;
}
self.evaluate(function (selectorToEvaluate) {
return document.querySelectorAll(selectorToEvaluate).length;
}, function (result) {
testRunning = false;
if (result > 0) {//selector found
callbackFn(true);
}
else {
setTimeout(testForSelector, timeoutInterval);
}
}, selector);
};
timeout = timeout || 10000; //default timeout is 2 sec;
setTimeout(testForSelector, timeoutInterval);
} | [
"function",
"(",
"selector",
",",
"callbackFn",
",",
"timeout",
")",
"{",
"var",
"self",
"=",
"this",
",",
"startTime",
"=",
"Date",
".",
"now",
"(",
")",
",",
"timeoutInterval",
"=",
"150",
",",
"testRunning",
"=",
"false",
",",
"testForSelector",
"=",
"function",
"(",
")",
"{",
"var",
"elapsedTime",
"=",
"Date",
".",
"now",
"(",
")",
"-",
"startTime",
";",
"if",
"(",
"elapsedTime",
">",
"timeout",
")",
"{",
"self",
".",
"options",
".",
"debug",
"&&",
"console",
".",
"log",
"(",
"'warning: timeout occurred while waiting for selector:\"%s\"'",
".",
"yellow",
",",
"selector",
")",
";",
"callbackFn",
"(",
"false",
")",
";",
"return",
";",
"}",
"self",
".",
"evaluate",
"(",
"function",
"(",
"selectorToEvaluate",
")",
"{",
"return",
"document",
".",
"querySelectorAll",
"(",
"selectorToEvaluate",
")",
".",
"length",
";",
"}",
",",
"function",
"(",
"result",
")",
"{",
"testRunning",
"=",
"false",
";",
"if",
"(",
"result",
">",
"0",
")",
"{",
"callbackFn",
"(",
"true",
")",
";",
"}",
"else",
"{",
"setTimeout",
"(",
"testForSelector",
",",
"timeoutInterval",
")",
";",
"}",
"}",
",",
"selector",
")",
";",
"}",
";",
"timeout",
"=",
"timeout",
"||",
"10000",
";",
"setTimeout",
"(",
"testForSelector",
",",
"timeoutInterval",
")",
";",
"}"
] | additional methods not in phantomjs api waits for selector to appear, then executes callbackFn | [
"additional",
"methods",
"not",
"in",
"phantomjs",
"api",
"waits",
"for",
"selector",
"to",
"appear",
"then",
"executes",
"callbackFn"
] | a4963662205400e542668938ce5cf1ab9a66fba0 | https://github.com/sheebz/phantom-proxy/blob/a4963662205400e542668938ce5cf1ab9a66fba0/lib/webpage.js#L267-L299 | train |
|
addthis/fluxthis | src/Dispatcher.es6.js | dispatchToStores | function dispatchToStores(ids = new Set()) {
ids.forEach((storeID) => {
if (this[IS_PENDING][storeID]) {
return true;
}
invokeCallback.call(this, storeID);
});
} | javascript | function dispatchToStores(ids = new Set()) {
ids.forEach((storeID) => {
if (this[IS_PENDING][storeID]) {
return true;
}
invokeCallback.call(this, storeID);
});
} | [
"function",
"dispatchToStores",
"(",
"ids",
"=",
"new",
"Set",
"(",
")",
")",
"{",
"ids",
".",
"forEach",
"(",
"(",
"storeID",
")",
"=>",
"{",
"if",
"(",
"this",
"[",
"IS_PENDING",
"]",
"[",
"storeID",
"]",
")",
"{",
"return",
"true",
";",
"}",
"invokeCallback",
".",
"call",
"(",
"this",
",",
"storeID",
")",
";",
"}",
")",
";",
"}"
] | This method takes an array of store id's and iterates
over them to determine if we should invoke a dispatch
of the action.
@param {Set} ids | [
"This",
"method",
"takes",
"an",
"array",
"of",
"store",
"id",
"s",
"and",
"iterates",
"over",
"them",
"to",
"determine",
"if",
"we",
"should",
"invoke",
"a",
"dispatch",
"of",
"the",
"action",
"."
] | ccd399554ecac886d7389ffe9d6e72519d92c481 | https://github.com/addthis/fluxthis/blob/ccd399554ecac886d7389ffe9d6e72519d92c481/src/Dispatcher.es6.js#L293-L301 | train |
addthis/fluxthis | src/Dispatcher.es6.js | invokeCallback | function invokeCallback(id) {
this[IS_PENDING][id] = true;
this[CALLBACKS][id](this[PENDING_ACTION]);
this[EMIT_CHANGE_CALLBACK].get(id)();
this[IS_HANDLED][id] = true;
} | javascript | function invokeCallback(id) {
this[IS_PENDING][id] = true;
this[CALLBACKS][id](this[PENDING_ACTION]);
this[EMIT_CHANGE_CALLBACK].get(id)();
this[IS_HANDLED][id] = true;
} | [
"function",
"invokeCallback",
"(",
"id",
")",
"{",
"this",
"[",
"IS_PENDING",
"]",
"[",
"id",
"]",
"=",
"true",
";",
"this",
"[",
"CALLBACKS",
"]",
"[",
"id",
"]",
"(",
"this",
"[",
"PENDING_ACTION",
"]",
")",
";",
"this",
"[",
"EMIT_CHANGE_CALLBACK",
"]",
".",
"get",
"(",
"id",
")",
"(",
")",
";",
"this",
"[",
"IS_HANDLED",
"]",
"[",
"id",
"]",
"=",
"true",
";",
"}"
] | Call the callback stored with the given id. Also do some internal
bookkeeping.
@param {string} id
@internal | [
"Call",
"the",
"callback",
"stored",
"with",
"the",
"given",
"id",
".",
"Also",
"do",
"some",
"internal",
"bookkeeping",
"."
] | ccd399554ecac886d7389ffe9d6e72519d92c481 | https://github.com/addthis/fluxthis/blob/ccd399554ecac886d7389ffe9d6e72519d92c481/src/Dispatcher.es6.js#L310-L315 | train |
addthis/fluxthis | src/Dispatcher.es6.js | startDispatching | function startDispatching(action) {
require('./debug.es6').logDispatch(action);
Object.keys(this[CALLBACKS]).forEach((id) => {
this[IS_PENDING][id] = false;
this[IS_HANDLED][id] = false;
});
this[PENDING_ACTION] = action;
this[IS_DISPATCHING] = true;
} | javascript | function startDispatching(action) {
require('./debug.es6').logDispatch(action);
Object.keys(this[CALLBACKS]).forEach((id) => {
this[IS_PENDING][id] = false;
this[IS_HANDLED][id] = false;
});
this[PENDING_ACTION] = action;
this[IS_DISPATCHING] = true;
} | [
"function",
"startDispatching",
"(",
"action",
")",
"{",
"require",
"(",
"'./debug.es6'",
")",
".",
"logDispatch",
"(",
"action",
")",
";",
"Object",
".",
"keys",
"(",
"this",
"[",
"CALLBACKS",
"]",
")",
".",
"forEach",
"(",
"(",
"id",
")",
"=>",
"{",
"this",
"[",
"IS_PENDING",
"]",
"[",
"id",
"]",
"=",
"false",
";",
"this",
"[",
"IS_HANDLED",
"]",
"[",
"id",
"]",
"=",
"false",
";",
"}",
")",
";",
"this",
"[",
"PENDING_ACTION",
"]",
"=",
"action",
";",
"this",
"[",
"IS_DISPATCHING",
"]",
"=",
"true",
";",
"}"
] | Set up bookkeeping needed when dispatching.
@param {object} action
@internal | [
"Set",
"up",
"bookkeeping",
"needed",
"when",
"dispatching",
"."
] | ccd399554ecac886d7389ffe9d6e72519d92c481 | https://github.com/addthis/fluxthis/blob/ccd399554ecac886d7389ffe9d6e72519d92c481/src/Dispatcher.es6.js#L323-L333 | train |
addthis/fluxthis | lib/implore.es6.js | makeQueryString | function makeQueryString(obj, prefix='') {
const str = [];
let prop;
let key;
let value;
for (prop in obj) {
if (obj.hasOwnProperty(prop)) {
key = prefix ?
prefix + '[' + prop + ']' :
prop;
value = obj[prop];
str.push(typeof value === 'object' ?
makeQueryString(value, key) :
encodeURIComponent(key) + '=' + encodeURIComponent(value));
}
}
return str.join('&');
} | javascript | function makeQueryString(obj, prefix='') {
const str = [];
let prop;
let key;
let value;
for (prop in obj) {
if (obj.hasOwnProperty(prop)) {
key = prefix ?
prefix + '[' + prop + ']' :
prop;
value = obj[prop];
str.push(typeof value === 'object' ?
makeQueryString(value, key) :
encodeURIComponent(key) + '=' + encodeURIComponent(value));
}
}
return str.join('&');
} | [
"function",
"makeQueryString",
"(",
"obj",
",",
"prefix",
"=",
"''",
")",
"{",
"const",
"str",
"=",
"[",
"]",
";",
"let",
"prop",
";",
"let",
"key",
";",
"let",
"value",
";",
"for",
"(",
"prop",
"in",
"obj",
")",
"{",
"if",
"(",
"obj",
".",
"hasOwnProperty",
"(",
"prop",
")",
")",
"{",
"key",
"=",
"prefix",
"?",
"prefix",
"+",
"'['",
"+",
"prop",
"+",
"']'",
":",
"prop",
";",
"value",
"=",
"obj",
"[",
"prop",
"]",
";",
"str",
".",
"push",
"(",
"typeof",
"value",
"===",
"'object'",
"?",
"makeQueryString",
"(",
"value",
",",
"key",
")",
":",
"encodeURIComponent",
"(",
"key",
")",
"+",
"'='",
"+",
"encodeURIComponent",
"(",
"value",
")",
")",
";",
"}",
"}",
"return",
"str",
".",
"join",
"(",
"'&'",
")",
";",
"}"
] | Take a simple object and turn it into a queryString, recursively.
@param {object} obj - query object
@param {string} prefix - used in recursive calls to keep track of the parent
@return {string} queryString without the '?'' | [
"Take",
"a",
"simple",
"object",
"and",
"turn",
"it",
"into",
"a",
"queryString",
"recursively",
"."
] | ccd399554ecac886d7389ffe9d6e72519d92c481 | https://github.com/addthis/fluxthis/blob/ccd399554ecac886d7389ffe9d6e72519d92c481/lib/implore.es6.js#L246-L265 | train |
zynga/atom | atom.js | removeListener | function removeListener(listeners) {
for (var i = listeners.length; --i >= 0;) {
// There should only be ONE exhausted listener.
if (!listeners[i].calls) {
return listeners.splice(i, 1);
}
}
} | javascript | function removeListener(listeners) {
for (var i = listeners.length; --i >= 0;) {
// There should only be ONE exhausted listener.
if (!listeners[i].calls) {
return listeners.splice(i, 1);
}
}
} | [
"function",
"removeListener",
"(",
"listeners",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"listeners",
".",
"length",
";",
"--",
"i",
">=",
"0",
";",
")",
"{",
"if",
"(",
"!",
"listeners",
"[",
"i",
"]",
".",
"calls",
")",
"{",
"return",
"listeners",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"}",
"}",
"}"
] | Helper to remove an exausted listener from the listeners array | [
"Helper",
"to",
"remove",
"an",
"exausted",
"listener",
"from",
"the",
"listeners",
"array"
] | cf204967e9267df47d51c2b5b628261c7ed0cec7 | https://github.com/zynga/atom/blob/cf204967e9267df47d51c2b5b628261c7ed0cec7/atom.js#L70-L77 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.