_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q6200
|
train
|
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
|
{
"resource": ""
}
|
|
q6201
|
Migrator
|
train
|
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
|
{
"resource": ""
}
|
q6202
|
watch
|
train
|
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
|
{
"resource": ""
}
|
q6203
|
watchModules
|
train
|
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
|
{
"resource": ""
}
|
q6204
|
Kona
|
train
|
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
|
{
"resource": ""
}
|
q6205
|
train
|
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
|
{
"resource": ""
}
|
|
q6206
|
train
|
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
|
{
"resource": ""
}
|
|
q6207
|
train
|
function () {
this.middlewarePaths.forEach(function (mwPath) {
require(mwPath)(this);
debug(format('mounted middleware/%s', path.basename(mwPath)));
}, this);
}
|
javascript
|
{
"resource": ""
}
|
|
q6208
|
train
|
function (name, object) {
if (global[name] && this.env !== 'test') {
debug(format('global "%s" already exists', name));
}
return (global[name] = object);
}
|
javascript
|
{
"resource": ""
}
|
|
q6209
|
train
|
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
|
{
"resource": ""
}
|
|
q6210
|
train
|
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
|
{
"resource": ""
}
|
|
q6211
|
applyCreate
|
train
|
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
|
{
"resource": ""
}
|
q6212
|
train
|
function (config, cb) {
var w = new WorkflowExecution(this.swfClient, this.config);
w.start(config, cb);
return w;
}
|
javascript
|
{
"resource": ""
}
|
|
q6213
|
train
|
function (cb) {
this.swfClient.registerWorkflowType({
"domain": this.config.domain,
"name": this.config.workflowType.name,
"version": this.config.workflowType.version
}, cb);
}
|
javascript
|
{
"resource": ""
}
|
|
q6214
|
upToString
|
train
|
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
|
{
"resource": ""
}
|
q6215
|
downToString
|
train
|
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
|
{
"resource": ""
}
|
q6216
|
recurseChildOptions
|
train
|
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
|
{
"resource": ""
}
|
q6217
|
parseOptions
|
train
|
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
|
{
"resource": ""
}
|
q6218
|
attributesToString
|
train
|
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
|
{
"resource": ""
}
|
q6219
|
strToCase
|
train
|
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
|
{
"resource": ""
}
|
q6220
|
camelToUnderscore
|
train
|
function camelToUnderscore(str) {
return s.split(/(?=[A-Z])/).map(function (p) {
return p.charAt(0).toUpperCase() + p.slice(1);
}).join('_');
}
|
javascript
|
{
"resource": ""
}
|
q6221
|
normalizeAttributes
|
train
|
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
|
{
"resource": ""
}
|
q6222
|
getType
|
train
|
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
|
{
"resource": ""
}
|
q6223
|
normalizeOptions
|
train
|
function normalizeOptions(options, include) {
_.forEach(options, function (v,k) {
if(!_.contains(include, k))
delete options[k];
});
return options;
}
|
javascript
|
{
"resource": ""
}
|
q6224
|
ArrayType
|
train
|
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
|
{
"resource": ""
}
|
q6225
|
set
|
train
|
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
|
{
"resource": ""
}
|
q6226
|
setRef
|
train
|
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
|
{
"resource": ""
}
|
q6227
|
ref
|
train
|
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
|
{
"resource": ""
}
|
q6228
|
getter
|
train
|
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
|
{
"resource": ""
}
|
q6229
|
setter
|
train
|
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
|
{
"resource": ""
}
|
q6230
|
slice
|
train
|
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
|
{
"resource": ""
}
|
q6231
|
train
|
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
|
{
"resource": ""
}
|
|
q6232
|
attachProps
|
train
|
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
|
{
"resource": ""
}
|
q6233
|
train
|
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
|
{
"resource": ""
}
|
|
q6234
|
train
|
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
|
{
"resource": ""
}
|
|
q6235
|
train
|
function (heartbeat, cb) {
var self = this;
this.swfClient.recordActivityTaskHeartbeat({
taskToken: this.config.taskToken,
details: stringify(heartbeat)
}, function (err) {
if (cb) {
cb(err);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q6236
|
PrettyPageHandler
|
train
|
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
|
{
"resource": ""
}
|
q6237
|
frame
|
train
|
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
|
{
"resource": ""
}
|
q6238
|
train
|
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
|
{
"resource": ""
}
|
|
q6239
|
train
|
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
|
{
"resource": ""
}
|
|
q6240
|
train
|
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
|
{
"resource": ""
}
|
|
q6241
|
getPixelSetter
|
train
|
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
|
{
"resource": ""
}
|
q6242
|
isType0
|
train
|
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
|
{
"resource": ""
}
|
q6243
|
DecodeFrameType0
|
train
|
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
|
{
"resource": ""
}
|
q6244
|
_getCelFrameDecoder
|
train
|
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
|
{
"resource": ""
}
|
q6245
|
train
|
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
|
{
"resource": ""
}
|
|
q6246
|
transform
|
train
|
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
|
{
"resource": ""
}
|
q6247
|
recursiveCycle
|
train
|
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
|
{
"resource": ""
}
|
q6248
|
createLogger
|
train
|
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
|
{
"resource": ""
}
|
q6249
|
delVars
|
train
|
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
|
{
"resource": ""
}
|
q6250
|
restoreEnv
|
train
|
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
|
{
"resource": ""
}
|
q6251
|
callbackInModifiedEnv
|
train
|
function callbackInModifiedEnv(callback, setInEnv, removeFromEnv) {
var origEnv = {};
var result;
setVars(origEnv, setInEnv);
delVars(origEnv, removeFromEnv);
result = callback();
restoreEnv(origEnv);
return result;
}
|
javascript
|
{
"resource": ""
}
|
q6252
|
CallbackHandler
|
train
|
function CallbackHandler(callable) {
CallbackHandler.super_.call(this);
if (!_.isFunction(callable)) {
throw new TypeError(
'Argument must be valid callable'
);
}
this.__callable = callable;
}
|
javascript
|
{
"resource": ""
}
|
q6253
|
rulesOfDetachment
|
train
|
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
|
{
"resource": ""
}
|
q6254
|
train
|
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
|
{
"resource": ""
}
|
|
q6255
|
train
|
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
|
{
"resource": ""
}
|
|
q6256
|
print
|
train
|
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
|
{
"resource": ""
}
|
q6257
|
train
|
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
|
{
"resource": ""
}
|
|
q6258
|
train
|
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
|
{
"resource": ""
}
|
|
q6259
|
train
|
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
|
{
"resource": ""
}
|
|
q6260
|
train
|
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
|
{
"resource": ""
}
|
|
q6261
|
train
|
function(control) {
return this._events.some(function (evt) {
if (evt.eventType === "StartChildWorkflowExecutionInitiated") {
if (evt.startChildWorkflowExecutionInitiatedEventAttributes.control === control) {
return true;
}
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q6262
|
train
|
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
|
{
"resource": ""
}
|
|
q6263
|
train
|
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
|
{
"resource": ""
}
|
|
q6264
|
train
|
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
|
{
"resource": ""
}
|
|
q6265
|
train
|
function () {
var i;
for (i = 0; i < arguments.length; i++) {
if (!this.is_activity_scheduled(arguments[i])) {
return false;
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q6266
|
train
|
function () {
var i;
for (i = 0; i < arguments.length; i++) {
if (!this.is_lambda_scheduled(arguments[i])) {
return false;
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q6267
|
train
|
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
|
{
"resource": ""
}
|
|
q6268
|
train
|
function () {
var wfInput = this._events[0].workflowExecutionStartedEventAttributes.input;
try {
var d = JSON.parse(wfInput);
return d;
} catch (ex) {
return wfInput;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6269
|
train
|
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
|
{
"resource": ""
}
|
|
q6270
|
train
|
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
|
{
"resource": ""
}
|
|
q6271
|
train
|
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
|
{
"resource": ""
}
|
|
q6272
|
train
|
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
|
{
"resource": ""
}
|
|
q6273
|
train
|
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
|
{
"resource": ""
}
|
|
q6274
|
loadFile
|
train
|
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
|
{
"resource": ""
}
|
q6275
|
createWorker
|
train
|
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
|
{
"resource": ""
}
|
q6276
|
toHeightMap
|
train
|
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
|
{
"resource": ""
}
|
q6277
|
downloadHeightMap
|
train
|
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
|
{
"resource": ""
}
|
q6278
|
train
|
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
|
{
"resource": ""
}
|
|
q6279
|
train
|
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
|
{
"resource": ""
}
|
|
q6280
|
toTree
|
train
|
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
|
{
"resource": ""
}
|
q6281
|
findEnd
|
train
|
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
|
{
"resource": ""
}
|
q6282
|
getNameOfType
|
train
|
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
|
{
"resource": ""
}
|
q6283
|
hash
|
train
|
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
|
{
"resource": ""
}
|
q6284
|
processContentWithPostCSS
|
train
|
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
|
{
"resource": ""
}
|
q6285
|
getDerivative
|
train
|
function getDerivative(num) {
var derivative = 1;
while (num != 0) {
derivative += num % 7;
num = Math.floor(num / 7);
}
return derivative;
}
|
javascript
|
{
"resource": ""
}
|
q6286
|
getNextPhonetic
|
train
|
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
|
{
"resource": ""
}
|
q6287
|
getNumericHash
|
train
|
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
|
{
"resource": ""
}
|
q6288
|
postProcess
|
train
|
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
|
{
"resource": ""
}
|
q6289
|
train
|
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
|
{
"resource": ""
}
|
|
q6290
|
train
|
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
|
{
"resource": ""
}
|
|
q6291
|
train
|
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
|
{
"resource": ""
}
|
|
q6292
|
train
|
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
|
{
"resource": ""
}
|
|
q6293
|
train
|
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
|
{
"resource": ""
}
|
|
q6294
|
train
|
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
|
{
"resource": ""
}
|
|
q6295
|
dispatchToStores
|
train
|
function dispatchToStores(ids = new Set()) {
ids.forEach((storeID) => {
if (this[IS_PENDING][storeID]) {
return true;
}
invokeCallback.call(this, storeID);
});
}
|
javascript
|
{
"resource": ""
}
|
q6296
|
invokeCallback
|
train
|
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
|
{
"resource": ""
}
|
q6297
|
startDispatching
|
train
|
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
|
{
"resource": ""
}
|
q6298
|
makeQueryString
|
train
|
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
|
{
"resource": ""
}
|
q6299
|
removeListener
|
train
|
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
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.