_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q38600 | nodeify | train | function nodeify(task) {
task = promisen(task);
return nodeifyTask;
function nodeifyTask(args, callback) {
args = Array.prototype.slice.call(arguments);
callback = (args[args.length - 1] instanceof Function) && args.pop();
if (!callback) callback = NOP;
var onResolve = callback.bind... | javascript | {
"resource": ""
} |
q38601 | memoize | train | function memoize(task, expire, hasher) {
var memo = memoizeTask.memo = {};
expire -= 0;
var timers = {};
if (!hasher) hasher = JSON.stringify.bind(JSON);
return memoizeTask;
function memoizeTask(value) {
return waterfall([hasher, readCache]).call(this, value);
// read previous resu... | javascript | {
"resource": ""
} |
q38602 | writeCache | train | function writeCache(result) {
result = memo[hash] = resolve(result);
if (expire) {
// cancel previous timer
if (timers[hash]) clearTimeout(timers[hash]);
// add new timer
timers[hash] = setTimeout(clearCache, expire);
}
return resul... | javascript | {
"resource": ""
} |
q38603 | manageIfFewItems | train | function manageIfFewItems() {
const itemsCount = getLength.call( this, this.items );
if ( itemsCount < 2 ) return true;
if ( itemsCount === 2 ) {
this.index = 1 - this.index;
this.expanded = false;
return true;
}
// More than 2 items to manage.
return false;
} | javascript | {
"resource": ""
} |
q38604 | moveList | train | function moveList( collapsedList, expandedList ) {
const
rect = collapsedList.getBoundingClientRect(),
left = rect.left;
let top = rect.top;
while ( top <= 0 ) top += ITEM_HEIGHT;
Dom.css( expandedList, {
left: `${left}px`,
top: `${top}px`
} );
} | javascript | {
"resource": ""
} |
q38605 | copyContentOf | train | function copyContentOf() {
const
that = this,
items = this.items,
div = Dom.div( "thm-ele8" );
items.forEach( function ( item, index ) {
const clonedItem = Dom.div( that.index === index ? "thm-bgSL" : "thm-bg3" );
if ( typeof item === 'string' ) {
clonedItem.t... | javascript | {
"resource": ""
} |
q38606 | onKeyDown | train | function onKeyDown( evt ) {
switch ( evt.key ) {
case 'Space':
this.expanded = !this.expanded;
evt.preventDefault();
break;
case 'Enter':
this.action = this.value;
break;
case 'ArrowDown':
selectNext.call( this );
evt.preventDefault();
brea... | javascript | {
"resource": ""
} |
q38607 | selectNext | train | function selectNext() {
this.index = ( this.index + 1 ) % this.items.length;
if ( this.expanded ) {
collapse.call( this );
expand.call( this, false );
}
} | javascript | {
"resource": ""
} |
q38608 | doFilter | train | function doFilter(tracer, err, serverId, msg, opts, filters, index, operate, cb) {
if (index < filters.length) {
tracer.info('client', __filename, 'doFilter', `do ${operate} filter ${filters[index].name}`);
}
if (index >= filters.length || !!err) {
utils.invokeCallback(cb, tracer, err, serve... | javascript | {
"resource": ""
} |
q38609 | train | function(err, data){
if (err) error = err;
allLayers.push(data);
if (allLayers.length == totalLayers){
callback(error, allLayers);
}
} | javascript | {
"resource": ""
} | |
q38610 | readConfigFile | train | function readConfigFile(configJSONPath) {
var confiJSONFullPath = path.join(process.cwd(), configJSONPath);
try{
var configStr = fs.readFileSync(confiJSONFullPath, {encoding:'utf8'});
return JSON.parse(configStr);
} catch (err){
throw new Error(`Invalid launcher configuration file: ${confiJSONFullP... | javascript | {
"resource": ""
} |
q38611 | colorConvert | train | function colorConvert( percentage, option, colorValue ) {
var color = require( 'color' );
var newColor = color( colorValue.trim() );
var newValue = '';
switch ( option.trim() ) {
case 'darken':
newValue = newColor.darken( percentage ).hexString();
brea... | javascript | {
"resource": ""
} |
q38612 | colorInit | train | function colorInit( oldValue ) {
var color, percentage, colorArgs, colorValue, cssString;
var balanced = require( 'balanced-match' );
//
cssString = balanced( '(', ')', oldValue );
colorArgs = balanced( '(', ')', cssString.body );
colorValue = balanced( '(', ')', color... | javascript | {
"resource": ""
} |
q38613 | train | function(username) {
var result = q.defer();
this.robot.http('https://gdata.youtube.com/feeds/api/users/' + username + '/uploads?alt=json')
.header('Accept', 'application/json')
.get()(function (err, res, body) {
if (err) {
result.reject(err);
... | javascript | {
"resource": ""
} | |
q38614 | assignProps | train | function assignProps(obj, key, val, opts) {
var k;
// accept object syntax
if (typeof key === "object") {
for (k in key) {
if (hasOwn.call(key, k)) assignProps(obj, k, key[k], val);
}
return;
}
var desc = {};
opts = opts || {};
// build base descriptor
for (k in defaults) {
desc[k] = typeof opts[k... | javascript | {
"resource": ""
} |
q38615 | handleResponse | train | function handleResponse(done, err, response, body) {
if (err) return done(err, null);
if (response.statusCode !== 200) return done(new Error(body.msg || 'Unknown error'), null);
done(null, body);
} | javascript | {
"resource": ""
} |
q38616 | setLevel | train | function setLevel(level) {
if (typeof(level) === "number") {
if (level >= 0 && level <= 5) {
_level = level;
} else {
invalidParameter(level);
}
} else if (typeof(level) === 'string') {
if (Level.hasOwnProperty(level)) {
... | javascript | {
"resource": ""
} |
q38617 | resolveArray | train | function resolveArray(arg) {
var resolvedArray = new Array(arg.length);
return arg
.reduce(function(soFar, value, index) {
return soFar
.then(resolveItem.bind(null, value))
.then(function(value) {
resolvedArray[index] = value;
});
}, Promise.reso... | javascript | {
"resource": ""
} |
q38618 | resolveObject | train | function resolveObject(arg) {
var resolvedObject = {};
return Object.keys(arg)
.reduce(function(soFar, key) {
return soFar
.then(resolveItem.bind(null, arg[key]))
.then(function(value) {
resolvedObject[key] = value;
});
}, Promise.resolve())
... | javascript | {
"resource": ""
} |
q38619 | resolveItem | train | function resolveItem(arg) {
if (Array.isArray(arg)) {
return resolveArray(arg);
} else if (Object.prototype.toString.call(arg) === '[object Function]') {
//is a function
return Promise.method(arg)().then(resolveItem);
} else if (isThenable(arg)) {
//is a promise
return arg.then(resolveItem);
... | javascript | {
"resource": ""
} |
q38620 | train | function (path, data, cb) {
var lines = [];
var field;
for (field in data) {
lines.push(field + '=' + encodeURIComponent(data[field]));
}
this.env.req({
method: 'POST',
protocol: this.options.authPt.protocol,
host: this.options.authPt.host,
port: this.options.... | javascript | {
"resource": ""
} | |
q38621 | train | function (error_msg) {
var self = this;
return function (err, resp) {
self._lock_refresh = undefined;
if (!err) {
var auth = JSON.parse(resp);
if (!auth.error) {
setToken.call(self, auth);
return emit.call(self, 'auth.refresh', token.call(self));
}
... | javascript | {
"resource": ""
} | |
q38622 | _get_ms | train | function _get_ms(a, b) {
debug.assert(a).is('date');
debug.assert(b).is('date');
if(a < b) {
return b.getTime() - a.getTime();
}
return a.getTime() - b.getTime();
} | javascript | {
"resource": ""
} |
q38623 | _log_time | train | function _log_time(sample) {
debug.assert(sample).is('object');
debug.assert(sample.event).is('string');
debug.assert(sample.start).is('date');
debug.assert(sample.end).is('date');
debug.assert(sample.duration).ignore(undefined).is('number');
debug.assert(sample.query).ignore(undefined).is('string');
debug.asse... | javascript | {
"resource": ""
} |
q38624 | _get_result | train | function _get_result(Type) {
return function(rows) {
if(!rows) { throw new TypeError("failed to parse result"); }
var doc = rows.shift();
if(!doc) { return; }
if(doc instanceof Type) {
return doc;
}
var obj = {};
ARRAY(Object.keys(doc)).forEach(function(key) {
if(key === 'documents') {
obj['... | javascript | {
"resource": ""
} |
q38625 | parse_predicate_pgtype | train | function parse_predicate_pgtype(ObjType, document_type, key) {
debug.assert(ObjType).is('function');
debug.assert(document_type).ignore(undefined).is('object');
var schema = (document_type && document_type.$schema) || {};
debug.assert(schema).is('object');
if(key[0] === '$') {
// FIXME: Change this to do dir... | javascript | {
"resource": ""
} |
q38626 | _parse_function_predicate | train | function _parse_function_predicate(ObjType, q, def_op, o, ret_type, traits) {
debug.assert(o).is('array');
ret_type = ret_type || 'boolean';
var func = ARRAY(o).find(is.func);
debug.assert(func).is('function');
var i = o.indexOf(func);
debug.assert(i).is('number');
var input_nopg_keys = o.slice(0, i);
var ... | javascript | {
"resource": ""
} |
q38627 | parse_operator_type | train | function parse_operator_type(op, def) {
op = ''+op;
if(op.indexOf(':') === -1) {
return def || 'boolean';
}
return op.split(':')[1];
} | javascript | {
"resource": ""
} |
q38628 | parse_search_traits | train | function parse_search_traits(traits) {
traits = traits || {};
// Initialize fields as all fields
if(!traits.fields) {
traits.fields = ['$*'];
}
// If fields was not an array (but is not negative -- check previous if clause), lets make it that.
if(!is.array(traits.fields)) {
traits.fields = [traits.fields];
... | javascript | {
"resource": ""
} |
q38629 | parse_select_fields | train | function parse_select_fields(ObjType, traits) {
debug.assert(ObjType).is('function');
debug.assert(traits).ignore(undefined).is('object');
return ARRAY(traits.fields).map(function(f) {
return _parse_predicate_key(ObjType, {'traits': traits, 'epoch':false}, f);
}).valueOf();
} | javascript | {
"resource": ""
} |
q38630 | parse_search_opts | train | function parse_search_opts(opts, traits) {
if(opts === undefined) {
return;
}
if(is.array(opts)) {
if( (opts.length >= 1) && is.obj(opts[0]) ) {
return [ ((traits.match === 'any') ? 'OR' : 'AND') ].concat(opts);
}
return opts;
}
if(opts instanceof NoPg.Type) {
return [ "AND", { "$id": opts.$id } ];... | javascript | {
"resource": ""
} |
q38631 | _parse_select_order | train | function _parse_select_order(ObjType, document_type, order, q, traits) {
debug.assert(ObjType).is('function');
debug.assert(document_type).ignore(undefined).is('object');
debug.assert(order).is('array');
return ARRAY(order).map(function(o) {
var key, type, rest;
if(is.array(o)) {
key = parse_operator_name(... | javascript | {
"resource": ""
} |
q38632 | do_select | train | function do_select(self, types, search_opts, traits) {
return nr_fcall("nopg:do_select", function() {
return prepare_select_query(self, types, search_opts, traits).then(function(q) {
var result = q.compile();
// Unnecessary since do_query() does it too
//if(NoPg.debug) {
// debug.log('query = ', result.... | javascript | {
"resource": ""
} |
q38633 | do_insert | train | function do_insert(self, ObjType, data) {
return nr_fcall("nopg:do_insert", function() {
return prepare_insert_query(self, ObjType, data).then(function(q) {
var result = q.compile();
return do_query(self, result.query, result.params);
});
});
} | javascript | {
"resource": ""
} |
q38634 | json_cmp | train | function json_cmp(a, b) {
a = JSON.stringify(a);
b = JSON.stringify(b);
var ret = (a === b) ? true : false;
return ret;
} | javascript | {
"resource": ""
} |
q38635 | do_update | train | function do_update(self, ObjType, obj, orig_data) {
return nr_fcall("nopg:do_update", function() {
var query, params, data, where = {};
if(obj.$id) {
where.$id = obj.$id;
} else if(obj.$name) {
where.$name = obj.$name;
} else {
throw new TypeError("Cannot know what to update!");
}
if(orig_data =... | javascript | {
"resource": ""
} |
q38636 | do_delete | train | function do_delete(self, ObjType, obj) {
return nr_fcall("nopg:do_delete", function() {
if(!(obj && obj.$id)) { throw new TypeError("opts.$id invalid: " + util.inspect(obj) ); }
var query, params;
query = "DELETE FROM " + (ObjType.meta.table) + " WHERE id = $1";
params = [obj.$id];
return do_query(self, quer... | javascript | {
"resource": ""
} |
q38637 | pg_table_exists | train | function pg_table_exists(self, name) {
return do_query(self, 'SELECT * FROM information_schema.tables WHERE table_name = $1 LIMIT 1', [name]).then(function(rows) {
if(!rows) { throw new TypeError("Unexpected result from query: " + util.inspect(rows)); }
return rows.length !== 0;
});
} | javascript | {
"resource": ""
} |
q38638 | pg_get_indexdef | train | function pg_get_indexdef(self, name) {
return do_query(self, 'SELECT indexdef FROM pg_indexes WHERE indexname = $1 LIMIT 1', [name]).then(function(rows) {
if(!rows) { throw new TypeError("Unexpected result from query: " + util.inspect(rows)); }
if(rows.length === 0) {
throw new TypeError("Index does not exist: ... | javascript | {
"resource": ""
} |
q38639 | pg_create_index_name | train | function pg_create_index_name(self, ObjType, type, field, typefield) {
var name;
var colname = _parse_predicate_key(ObjType, {'epoch':false}, field);
var datakey = colname.getMeta('datakey');
var field_name = (datakey ? datakey + '.' : '' ) + colname.getMeta('key');
if( (ObjType === NoPg.Document) && (typefield !=... | javascript | {
"resource": ""
} |
q38640 | wrap_casts | train | function wrap_casts(x) {
x = '' + x;
if(/^\(.+\)$/.test(x)) {
return '(' + x + ')';
}
if(/::[a-z]+$/.test(x)) {
if(/^[a-z]+ \->> /.test(x)) {
return '((' + x + '))';
}
return '(' + x + ')';
}
return x;
} | javascript | {
"resource": ""
} |
q38641 | pg_create_index_query_internal_v1 | train | function pg_create_index_query_internal_v1(self, ObjType, type, field, typefield, is_unique) {
var query;
var pgcast = parse_predicate_pgcast(ObjType, type, field);
var colname = _parse_predicate_key(ObjType, {'epoch':false}, field);
var name = pg_create_index_name(self, ObjType, type, field, typefield);
query = "... | javascript | {
"resource": ""
} |
q38642 | pg_declare_index | train | function pg_declare_index(self, ObjType, type, field, typefield, is_unique) {
var colname = _parse_predicate_key(ObjType, {'epoch':false}, field);
var datakey = colname.getMeta('datakey');
var field_name = (datakey ? datakey + '.' : '' ) + colname.getMeta('key');
var name = pg_create_index_name(self, ObjType, type,... | javascript | {
"resource": ""
} |
q38643 | pg_query | train | function pg_query(query, params) {
return function(db) {
var start_time = new Date();
return do_query(db, query, params).then(function() {
var end_time = new Date();
db._record_sample({
'event': 'query',
'start': start_time,
'end': end_time,
'query': query,
'params': params
});
r... | javascript | {
"resource": ""
} |
q38644 | create_watchdog | train | function create_watchdog(db, opts) {
debug.assert(db).is('object');
opts = opts || {};
debug.assert(opts).is('object');
opts.timeout = opts.timeout || 30000;
debug.assert(opts.timeout).is('number');
var w = {};
w.db = db;
w.opts = opts;
/* Setup */
w.timeout = setTimeout(function() {
debug.warn('Got t... | javascript | {
"resource": ""
} |
q38645 | create_tcn_listener | train | function create_tcn_listener(events, when) {
debug.assert(events).is('object');
debug.assert(when).is('object');
// Normalize event object back to event name
var when_str = NoPg.stringifyEventName(when);
return function tcn_listener(payload) {
payload = NoPg.parseTCNPayload(payload);
var event = tcn_event_m... | javascript | {
"resource": ""
} |
q38646 | new_listener | train | function new_listener(event/*, listener*/) {
// Ignore if not tcn event
if(NoPg.isLocalEventName(event)) {
return;
}
event = NoPg.parseEventName(event);
// Stringifying back the event normalizes the original event name
var event_name = NoPg.stringifyEventName(event);
var channel_name = NoPg... | javascript | {
"resource": ""
} |
q38647 | remove_listener | train | function remove_listener(event/*, listener*/) {
// Ignore if not tcn event
if(NoPg.isLocalEventName(event)) {
return;
}
event = NoPg.parseEventName(event);
// Stringifying back the event normalizes the original event name
var event_name = NoPg.stringifyEventName(event);
var channel_name = N... | javascript | {
"resource": ""
} |
q38648 | pad | train | function pad(num, size) {
var s = num+"";
while (s.length < size) {
s = "0" + s;
}
return s;
} | javascript | {
"resource": ""
} |
q38649 | reset_methods | train | function reset_methods(doc) {
if(is.array(doc)) {
return ARRAY(doc).map(reset_methods).valueOf();
}
if(is.object(doc)) {
ARRAY(methods).forEach(function(method) {
delete doc[method.$name];
});
}
return doc;
} | javascript | {
"resource": ""
} |
q38650 | Walker | train | function Walker () {
var self = this;
var walkSync = function (dir, trace, callback) {
fs.readdirSync(dir).forEach(function (name) {
var file = path.join(dir, name)
, stat = fs.lstatSync(file)
, isDir = stat.isDirectory()
, _trace = trace;
try {
callback(name, file, ... | javascript | {
"resource": ""
} |
q38651 | getModel | train | function getModel (app, name, Model) {
const mongooseClient = app.get('mongoose');
assert(mongooseClient, 'mongoose client not set by app');
const modelNames = mongooseClient.modelNames();
if (modelNames.includes(name)) {
return mongooseClient.model(name);
} else {
assert(Model && typeof Model === 'fu... | javascript | {
"resource": ""
} |
q38652 | createModel | train | function createModel (app, name, options) {
const mongooseClient = app.get('mongoose');
assert(mongooseClient, 'mongoose client not set by app');
const schema = new mongooseClient.Schema({ any: {} }, {strict: false});
return mongooseClient.model(name, schema);
} | javascript | {
"resource": ""
} |
q38653 | createService | train | function createService (app, Service, Model, options) {
Model = options.Model || Model;
if (typeof Model === 'function') {
assert(options.ModelName, 'createService but options.ModelName not provided');
options.Model = Model(app, options.ModelName);
} else {
options.Model = Model;
}
const service =... | javascript | {
"resource": ""
} |
q38654 | setDefaults | train | function setDefaults(scope, defaults) {
if (!defaults) { return; }
// store defaults for use in generateRemodel
scope.defaults = defaults;
for (var name in defaults) {
if (defaults.hasOwnProperty(name) && scope[name] === undefined) {
scope[name] = defaults[n... | javascript | {
"resource": ""
} |
q38655 | addValidations | train | function addValidations(scope, validations) {
for (var name in validations) {
if (validations.hasOwnProperty(name) && validations[name]) {
scope[name] = $injector.invoke(validations[name]);
}
}
} | javascript | {
"resource": ""
} |
q38656 | attachToScope | train | function attachToScope(scope, itemsToAttach) {
if (!itemsToAttach || !itemsToAttach.length) { return; }
itemsToAttach.push(function () {
var i, val;
for (i = 0; i < arguments.length; i++) {
val = arguments[i];
scope[itemsToAttach[i]] = val;
... | javascript | {
"resource": ""
} |
q38657 | addInitModel | train | function addInitModel(scope, initialModel, pageName) {
angular.extend(scope, initialModel);
if (scope.pageHead && scope.pageHead.title) {
var title = scope.pageHead.title;
pageSettings.updateHead(title, scope.pageHead.description || title);
pageSettings.updatePageSt... | javascript | {
"resource": ""
} |
q38658 | registerListeners | train | function registerListeners(scope, listeners) {
var fns = [];
for (var name in listeners) {
if (listeners.hasOwnProperty(name) && listeners[name]) {
fns.push(eventBus.on(name, $injector.invoke(listeners[name])));
}
}
// make sure handlers are dest... | javascript | {
"resource": ""
} |
q38659 | addEventHandlers | train | function addEventHandlers(scope, ctrlName, handlers) {
if (!handlers) { return; }
for (var name in handlers) {
if (handlers.hasOwnProperty(name) && handlers[name]) {
scope[name] = $injector.invoke(handlers[name]);
// if it is not a function, throw error b/c ... | javascript | {
"resource": ""
} |
q38660 | exec | train | function exec(command, fallthrough, cb) {
execute(command, fallthrough, false, function(err, stdOutOuput, stdErrOuput, result) {
// drop stdOutOuput and stdErrOuput parameters to keep exec backwards compatible.
cb(err, result);
});
} | javascript | {
"resource": ""
} |
q38661 | execute | train | function execute(command, fallthrough, collectOutput, cb) {
var collectedStdOut = '';
var collectedStdErr = '';
var _exec = child.exec(command, function (err) {
var result;
if (err && fallthrough) {
// camouflage error to allow other execs to keep running
result = err;
err = null;
}... | javascript | {
"resource": ""
} |
q38662 | exit | train | function exit(err, result) {
if (err) {
console.error(colors.red(err.message || JSON.stringify(err)));
process.exit(1);
} else {
process.exit(0);
}
} | javascript | {
"resource": ""
} |
q38663 | files | train | function files(items, opts) {
opts = opts || {};
var data = [];
function addMatch(item) {
if (opts.match === undefined || (opts.match && item.match(new RegExp(opts.match)))) {
data.push(item);
}
}
items.forEach(function (item) {
var stat = fs.statSync(item);
if (stat.isFile()) {
... | javascript | {
"resource": ""
} |
q38664 | Canvas | train | function Canvas (canvasElement, fullWindow, autoInit) {
if( !(this instanceof Canvas) ) {
return new Canvas.apply(null, arguments);
}
/**
* @type {HTMLCanvasElement}
* @public
*/
this.canvas = null;
/**
* @type {CanvasRenderingContext2D}
* @public
*/
this.context = null;
/**
* ... | javascript | {
"resource": ""
} |
q38665 | train | function (color) {
if (color === undefined) {
this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);
} else {
let fillstyle = this.context.fillStyle;
this.fillStyle(color);
this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.fillStyle(fillstyle);
... | javascript | {
"resource": ""
} | |
q38666 | train | function (x, y) {
if (!this.pathStarted) {
this.context.beginPath();
this.context.moveTo(x,y);
this.pathStarted = true;
} else {
this.context.lineTo(x,y);
}
} | javascript | {
"resource": ""
} | |
q38667 | buildStyles | train | function buildStyles(conf, undertaker) {
// Config that gets passed to node-sass.
const sassConfig = conf.themeConfig.sass.nodeSassConf || {};
// If we're in production mode, then compress the output CSS.
if (conf.productionMode) {
sassConfig.outputStyle = 'compressed';
}
// Any PostCSS... | javascript | {
"resource": ""
} |
q38668 | _copyFile | train | function _copyFile (origin, target, callback) {
if ("undefined" === typeof origin) {
throw new ReferenceError("Missing \"origin\" argument");
}
else if ("string" !== typeof origin) {
throw new TypeError("\"origin\" argument is not a string");
}
else if ("" === origin.trim()) {
throw new... | javascript | {
"resource": ""
} |
q38669 | reduce | train | function reduce(accumulator, iterable, initializer) {
var i, len;
i = 0;
len = iterable.length;
if (len === 0) {
return initializer;
}
for (; i < len; ++i) {
initializer = accumulator(initializer, iterable[i]);
}
return initializer;
} | javascript | {
"resource": ""
} |
q38670 | load | train | function load (location) {
var required = requireAll(location)
var config = {}
for (var key in required) {
config[key.replace(/^array\./, 'array:')] = required[key]
}
var konsole = createConsole(config)
return konsole
} | javascript | {
"resource": ""
} |
q38671 | combine | train | function combine () {
var config = {}
Array.prototype.forEach.call(arguments, function (tconsoleInstance) {
mergeObject(config, tconsoleInstance._tconsoleConfig)
})
return createConsole(config)
} | javascript | {
"resource": ""
} |
q38672 | HashMap | train | function HashMap(source) {
this._rtype = TYPE_NAMES.HASH;
this.reset();
if(source) {
for(var k in source) {
this.setKey(k, source[k]);
}
}
} | javascript | {
"resource": ""
} |
q38673 | setExpiry | train | function setExpiry(key, ms, req) {
var rval = this.getRawKey(key);
if(rval === undefined) return 0;
// expiry is in the past or now, delete immediately
// but return 1 to indicate the expiry was set
if(ms <= Date.now()) {
this.delKey(key, req);
return 1;
}
if(!this._expires[key]) {
this._ekeys... | javascript | {
"resource": ""
} |
q38674 | delExpiry | train | function delExpiry(key, req) {
var rval = this.getRawKey(key);
if(rval === undefined || rval.e === undefined) return 0;
// the code flow ensures we have a valid
// index into the expiring keys array
this._ekeys.splice(ArrayIndex.indexOf(key, this._ekeys), 1);
delete this._expires[key];
delete rval.e;
re... | javascript | {
"resource": ""
} |
q38675 | delExpiredKeys | train | function delExpiredKeys(num, threshold) {
function removeExpiredKeys(count) {
if(!this._ekeys.length) return 0;
var num = num || 100
, threshold = threshold || 25
, count = count || 0
, i
, key
, ind;
for(i = 0;i < num;i++) {
ind = Math.floor(Math.random() * this._eke... | javascript | {
"resource": ""
} |
q38676 | getValueBuffer | train | function getValueBuffer(key, req, stringify) {
var val = this.getKey(key, req);
// should have buffer, string or number
if(val !== undefined) {
if(typeof val === 'number' && !stringify) val = new Buffer([val]);
val = (val instanceof Buffer) ? val : new Buffer('' + val);
}
return val;
} | javascript | {
"resource": ""
} |
q38677 | interleave | train | function interleave(additional) {
return function reduce(reduced, value, i) {
if (i === 0) {
reduced.push(value);
} else {
reduced.push(additional, value);
}
return reduced;
}
} | javascript | {
"resource": ""
} |
q38678 | Node | train | function Node(value, prev, next) {
this.value = value;
this.prev = prev;
this.next = next;
} | javascript | {
"resource": ""
} |
q38679 | Sequence | train | function Sequence(iterable) {
this.sequence = null;
this._size = 0;
this.nodeMap = new rMap();
if (iterable) {
if (typeof iterable.length === 'number') {
for (var i = 0; i < iterable.length; i++) {
this.add.apply(this, iterable[i]);
}
} else if (typeof iterable.entr... | javascript | {
"resource": ""
} |
q38680 | bindHelper | train | function bindHelper(fn) {
return function() {
var p = priv.get(this);
return fn.apply(p.sequence, Array.prototype.slice.call(arguments));
}
} | javascript | {
"resource": ""
} |
q38681 | EnumMap | train | function EnumMap(iter) {
var p = {};
priv.set(this, p);
var newIter = iter;
if(iter && typeof iter.entries === 'function') {
if (iter instanceof EnumSet) {
newIter = {
entries: function() {
var pi = priv.get(iter);
return new Iterator(pi.sequence.sequence,... | javascript | {
"resource": ""
} |
q38682 | EnumSet | train | function EnumSet(iter) {
var p = {};
priv.set(this, p);
var newIter = iter;
if (Array.isArray(iter)) {
newIter = Array.prototype.map.call(iter, function(x) {
return [x, x];
});
} else if(iter && typeof iter.entries === 'function') {
if (iter instanceof EnumMap) {
ne... | javascript | {
"resource": ""
} |
q38683 | loadConfig | train | function loadConfig(path) {
var glob = require('glob');
var object = {};
var key;
glob.sync('*', {cwd: path}).forEach(function(option) {
key = option.replace(/\.js$/,'');
object[key] = require(path + option);
});
return object;
} | javascript | {
"resource": ""
} |
q38684 | clearDatabase | train | function clearDatabase() {
var promises = [];
_.each(resources, function (resource) {
var service = pancakes.getService(resource.name);
if (service.removePermanently) {
log.info('purging ' + resource.name);
promises.push(service.removePermanently(... | javascript | {
"resource": ""
} |
q38685 | confirmClear | train | function confirmClear() {
var promptSchema = {
properties: {
confirm: {
description: 'Delete everything in the ' + config.env.toUpperCase() + ' database? (y or n) ',
pattern: /^[yn]$/,
message: 'Please respond with y or n. '... | javascript | {
"resource": ""
} |
q38686 | createWorkerProxy | train | function createWorkerProxy(workersOrFunctions, opt_options) {
var options = {
// Automatically call the callback after a call if the return value is not
// undefined.
autoCallback: false,
// Catch errors and automatically respond with an error callback. Off by
// default since it break... | javascript | {
"resource": ""
} |
q38687 | Manifest | train | function Manifest(options) {
this.options = options;
this.destDir = options.destDir || process.cwd();
this.content = {};
this.filePath = path.join(this.destDir, MANIFEST_FILENAME);
// get or create manifest content
this.content = this.read();
} | javascript | {
"resource": ""
} |
q38688 | ClusterManager | train | function ClusterManager(opts) {
if (isFunction(opts)) {
opts = { worker: opts };
}
this.options = opts || {};
this.givenNumWorkers =
exists(this.options.numWorkers) ||
exists(process.env.CLUSTER_WORKERS);
defaults(this.options, {
debugScope: process.env.CLUSTER_DEBUG || 'cluster-man',
ma... | javascript | {
"resource": ""
} |
q38689 | train | function(data){
return typeof data === 'object'
? JSON.stringify(data)
: (typeof data === 'string' || typeof data === 'number' ? String(data) : null);
} | javascript | {
"resource": ""
} | |
q38690 | getElementRegistry | train | function getElementRegistry(identifier) {
if (!window.__private__) window.__private__ = {};
if (window.__private__.elementRegistry === undefined) window.__private__.elementRegistry = {};
if (typeof identifier === 'string') {
if (!~identifier.indexOf('-')) identifier = identifier + '-element';
return windo... | javascript | {
"resource": ""
} |
q38691 | validated | train | function validated(invalid){
if (invalid) { return callback(invalid) }
if(options.coerce){crudUtils.coerceData(options,coerced())}
else{coerced(null,options.data)}
} | javascript | {
"resource": ""
} |
q38692 | provecss | train | function provecss(string, options) {
options = options || {};
this.browsers = options.browsers;
if (options.path) {
this.import_path = path.basename(options.path);
this.import_base = options.base || path.dirname(options.path);
}
this.import_filter = options.import_filter;
this.v... | javascript | {
"resource": ""
} |
q38693 | train | function (fileName, key, value) {
var file = fileName || store.filename;
if (!file) {
store.log('You must specify a valid file.', 'ERR');
return false;
}
if (!key) return;
var item = store.stringify(key) + ": " +
... | javascript | {
"resource": ""
} | |
q38694 | train | function (fileName, key, value) {
var file = fileName || store.filename;
if (!file) {
store.log('You must specify a valid file.', 'ERR');
return false;
}
if (!key) return;
var item = store.stringify(key) + ": " +
... | javascript | {
"resource": ""
} | |
q38695 | defaultTask | train | function defaultTask(conf, undertaker, done) {
return undertaker.series(
require('../build/build').bind(null, conf, undertaker),
require('../other/watch').bind(null, conf, undertaker)
)(done);
} | javascript | {
"resource": ""
} |
q38696 | RelayrStrategy | train | function RelayrStrategy(options, verifyCallback) {
if (!verifyCallback) { throw new TypeError('verify callback is required'); }
options = options || {};
options.authorizationURL = options.authorizationURL || 'https://api.relayr.io/oauth2/auth';
options.responseType = options.responseType || 'token';
... | javascript | {
"resource": ""
} |
q38697 | attemptCallback | train | function attemptCallback(filePath, callback, attempts) {
try {
callback();
return;
} catch (error) {
if (attempts === 0) {
console.error('takeown: callback failed - exceeded attempts');
throw error;
}
switch (error.code) {
case 'EPERM':
case 'EACCES':
case 'EBUSY':
case 'ENOTEMPTY':
... | javascript | {
"resource": ""
} |
q38698 | takeOwnership | train | function takeOwnership(filePath) {
try {
var stats = fs.lstatSync(filePath);
if (stats.isDirectory()) {
execSyncElevated('takeown /f "' + filePath + '" /r /d y');
} else {
execSyncElevated('takeown /f "' + filePath + '"');
}
return;
} catch (error) {
if (error.code === 'ENOENT') {
console.w... | javascript | {
"resource": ""
} |
q38699 | expand | train | function expand (node, args, i) {
var n = args.length;
var arg;
for (; i < n; i++) {
arg = args [i];
if (isNodeType (arg, types.MACRO)) {
expand (node, arg, 1);
} else {
node.push (arg);
}
}
return node;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.