_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 27
233k
| 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)) {
|
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$/
|
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) {
/*
|
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) {
|
javascript
|
{
"resource": ""
}
|
q6204
|
Kona
|
train
|
function Kona(options) {
// call the koa constructor here
Koa.call(this);
options = options || {};
// setup kona root and
|
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, '..'));
|
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',
|
javascript
|
{
"resource": ""
}
|
|
q6207
|
train
|
function () {
this.middlewarePaths.forEach(function (mwPath) {
require(mwPath)(this);
debug(format('mounted
|
javascript
|
{
"resource": ""
}
|
|
q6208
|
train
|
function (name, object) {
if (global[name] && this.env !== 'test') {
debug(format('global "%s"
|
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:
|
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;
}
|
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
|
javascript
|
{
"resource": ""
}
|
q6212
|
train
|
function (config, cb) {
var w = new WorkflowExecution(this.swfClient, this.config);
|
javascript
|
{
"resource": ""
}
|
|
q6213
|
train
|
function (cb) {
this.swfClient.registerWorkflowType({
"domain": this.config.domain,
"name": this.config.workflowType.name,
|
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' : '';
|
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' : '';
|
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 {
|
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]));
|
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){
|
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')
|
javascript
|
{
"resource": ""
}
|
q6220
|
camelToUnderscore
|
train
|
function camelToUnderscore(str) {
return s.split(/(?=[A-Z])/).map(function (p) {
|
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
|
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 = '('
|
javascript
|
{
"resource": ""
}
|
q6223
|
normalizeOptions
|
train
|
function normalizeOptions(options, include) {
_.forEach(options, function (v,k) {
if(!_.contains(include, k))
|
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)
}
|
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
|
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
|
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) {
|
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
|
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) {
|
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 {
|
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 '
|
javascript
|
{
"resource": ""
}
|
|
q6232
|
attachProps
|
train
|
function attachProps(context, target) {
if (isObject(target)) {
var keys = inheritedKeys(target);
|
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) {
|
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);
}
|
javascript
|
{
"resource": ""
}
|
|
q6235
|
train
|
function (heartbeat, cb) {
var self = this;
this.swfClient.recordActivityTaskHeartbeat({
taskToken: this.config.taskToken,
details: stringify(heartbeat)
|
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"
*
|
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) {
|
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) {
|
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 =
|
javascript
|
{
"resource": ""
}
|
|
q6240
|
train
|
function (filter) {
if (!filter) {
filter = null;
}
var comments = this.__comments;
if (filter !== null) {
comments = comments.filter(function (c) {
|
javascript
|
{
"resource": ""
}
|
|
q6241
|
getPixelSetter
|
train
|
function getPixelSetter() {
var offset = 0;
return function(colors, c) {
colors[offset] = c.r;
colors[offset + 1] = c.g;
|
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':
|
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++) {
|
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) {
|
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,
|
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);
|
javascript
|
{
"resource": ""
}
|
q6247
|
recursiveCycle
|
train
|
function recursiveCycle(arr, onIteration, onEnd) {
var i=0;
function next() {
if (i >= arr.length) {
onEnd();
return;
}
|
javascript
|
{
"resource": ""
}
|
q6248
|
createLogger
|
train
|
function createLogger(logger) {
var result = logger ? objectAssign({}, logger) : {};
if (!result.debug) result.debug = console.log;
|
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]] = [
|
javascript
|
{
"resource": ""
}
|
q6250
|
restoreEnv
|
train
|
function restoreEnv(origEnv) {
var key;
for (key in origEnv) {
if (origEnv[key][0]) {
process.env[key] =
|
javascript
|
{
"resource": ""
}
|
q6251
|
callbackInModifiedEnv
|
train
|
function callbackInModifiedEnv(callback, setInEnv, removeFromEnv) {
var origEnv = {};
var
|
javascript
|
{
"resource": ""
}
|
q6252
|
CallbackHandler
|
train
|
function CallbackHandler(callable) {
CallbackHandler.super_.call(this);
if (!_.isFunction(callable)) {
throw new TypeError(
|
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
|
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;
|
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
|
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 =
|
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) {
|
javascript
|
{
"resource": ""
}
|
|
q6258
|
train
|
function (eventId) {
var i;
for (i = 0; i < this._events.length; i++) {
var evt = this._events[i];
if (evt.eventId ===
|
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];
|
javascript
|
{
"resource": ""
}
|
|
q6260
|
train
|
function(eventType, activityId) {
var attrsKey = this._event_attributes_key(eventType);
return this._events.some(function (evt) {
if (evt.eventType === eventType) {
|
javascript
|
{
"resource": ""
}
|
|
q6261
|
train
|
function(control) {
return this._events.some(function (evt) {
if (evt.eventType === "StartChildWorkflowExecutionInitiated") {
|
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);
|
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) {
|
javascript
|
{
"resource": ""
}
|
|
q6264
|
train
|
function (signalName) {
var evt = this._event_find('WorkflowExecutionSignaled', 'signalName', signalName);
if(!evt) {
return null;
|
javascript
|
{
"resource": ""
}
|
|
q6265
|
train
|
function () {
var i;
for (i = 0; i < arguments.length; i++) {
if (!this.is_activity_scheduled(arguments[i])) {
|
javascript
|
{
"resource": ""
}
|
|
q6266
|
train
|
function () {
var i;
for (i = 0; i < arguments.length; i++) {
|
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])
|
javascript
|
{
"resource": ""
}
|
|
q6268
|
train
|
function () {
var wfInput = this._events[0].workflowExecutionStartedEventAttributes.input;
|
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;
|
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) {
|
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)) {
|
javascript
|
{
"resource": ""
}
|
|
q6272
|
train
|
function(){
var i;
for (i = 0; i < this._events.length; i++) {
var evt = this._events[i];
|
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);
|
javascript
|
{
"resource": ""
}
|
|
q6274
|
loadFile
|
train
|
function loadFile(file) {
console.log('loadFile:', file);
// <file> can be Image, File URL object or URL string (http://* or
|
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();
|
javascript
|
{
"resource": ""
}
|
q6276
|
toHeightMap
|
train
|
function toHeightMap() {
if (rasterToGcode.running) {
return rasterToGcode.abort();
}
console.log('toHeightMap:', file.name);
$toHeightMap.text('Abort').addClass('btn-danger');
|
javascript
|
{
"resource": ""
}
|
q6277
|
downloadHeightMap
|
train
|
function downloadHeightMap() {
console.log('downloadHeightMap:', file.name);
var heightMapFile = new Blob([heightMap], {
|
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',
|
javascript
|
{
"resource": ""
}
|
|
q6279
|
train
|
function (status, condition) {
var that = this._connection;
if (this._autoService && status === Strophe.Status.CONNECTED) {
this.service =
|
javascript
|
{
"resource": ""
}
|
|
q6280
|
toTree
|
train
|
function toTree(arr, low, high) {
if (low >= high) {
return undefined;
}
var mid = Math.floor((high + low) / 2);
return {
|
javascript
|
{
"resource": ""
}
|
q6281
|
findEnd
|
train
|
function findEnd(node) {
if (!node) {
return undefined;
}
var {left, right, el} = node;
findEnd(left);
findEnd(right);
node.high =
|
javascript
|
{
"resource": ""
}
|
q6282
|
getNameOfType
|
train
|
function getNameOfType(x) {
switch (false) {
case !(x == null):
return `${x}`; // null / undefined
case !is.String(x):
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})`
)
);
|
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);
|
javascript
|
{
"resource": ""
}
|
q6285
|
getDerivative
|
train
|
function getDerivative(num) {
var derivative = 1;
while (num != 0) {
derivative += num %
|
javascript
|
{
"resource": ""
}
|
q6286
|
getNextPhonetic
|
train
|
function getNextPhonetic(phoneticSet, simpleCap, wordObj, forceSimple) {
var deriv = getDerivative(wordObj.numeric),
simple = (wordObj.numeric + deriv) % wordObj.opts.phoneticSimplicity >
|
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
|
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,
|
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');
|
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);
|
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)}
|
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
|
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
|
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);
|
javascript
|
{
"resource": ""
}
|
|
q6295
|
dispatchToStores
|
train
|
function dispatchToStores(ids = new Set()) {
ids.forEach((storeID) => {
if (this[IS_PENDING][storeID]) {
|
javascript
|
{
"resource": ""
}
|
q6296
|
invokeCallback
|
train
|
function invokeCallback(id) {
this[IS_PENDING][id] = true;
this[CALLBACKS][id](this[PENDING_ACTION]);
|
javascript
|
{
"resource": ""
}
|
q6297
|
startDispatching
|
train
|
function startDispatching(action) {
require('./debug.es6').logDispatch(action);
Object.keys(this[CALLBACKS]).forEach((id) => {
this[IS_PENDING][id] = false;
|
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' ?
|
javascript
|
{
"resource": ""
}
|
q6299
|
removeListener
|
train
|
function removeListener(listeners) {
for (var i = listeners.length; --i >= 0;) {
// There should only be ONE exhausted listener.
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.