_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(this, null);
var onReject = callback.bind(this);
task.apply(this, args).then(onResolve, onReject);
}
} | 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 result from cache
function readCache(hash) {
if (hash in memo) return memo[hash];
return waterfall([task, writeCache]).call(this, value);
// write new result to cache
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 result;
}
// clear expired result
function clearCache() {
delete memo[hash];
delete timers[hash];
}
}
}
} | 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 result;
} | 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.textContent = item;
} else {
clonedItem.innerHTML = Dom( item ).innerHTML;
}
Dom.add( div, clonedItem );
const touchable = new Touchable( clonedItem );
touchable.tap.add( () => {
that.expanded = false;
that.index = index;
} );
} );
return div;
} | 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();
break;
case 'ArrowUp':
selectPrev.call( this );
evt.preventDefault();
break;
case 'Escape':
if ( this.expanded ) {
this.expanded = false;
// Set the value as it was when we expanded the combo.
this.value = this._valueWhenExpanded;
evt.preventDefault();
}
break;
default:
// Do nothing.
}
} | 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, serverId, msg, opts);
return;
}
const filter = filters[index];
if (typeof filter === 'function') {
filter(serverId, msg, opts, (target, message, options) => {
index++;
// compatible for pomelo filter next(err) method
if (utils.getObjectClass(target) === 'Error') {
doFilter(tracer, target, serverId, msg, opts, filters, index, operate, cb);
} else {
doFilter(tracer, null, target || serverId, message || msg, options || opts, filters, index, operate, cb);
}
});
return;
}
if (typeof filter[operate] === 'function') {
filter[operate](serverId, msg, opts, (target, message, options) => {
index++;
if (utils.getObjectClass(target) === 'Error') {
doFilter(tracer, target, serverId, msg, opts, filters, index, operate, cb);
} else {
doFilter(tracer, null, target || serverId, message || msg, options || opts, filters, index, operate, cb);
}
});
return;
}
index++;
doFilter(tracer, err, serverId, msg, opts, filters, index, operate, cb);
} | 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: ${confiJSONFullPath}
${err.toString()}`);
}
} | 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();
break;
case 'lighten':
newValue = newColor.lighten( percentage ).hexString();
break;
case 'rgb':
newValue = newColor.clearer( percentage ).rgbString();
break;
default:
return '';
}
return newValue;
} | 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( '(', ')', colorArgs.body );
// If colorValue is undefined, the value is an rbg or similar color.
if ( undefined !== colorValue ) {
color = colorValue.pre + '( ' + colorValue.body + ' )';
percentage = colorValue.post;
} else {
// The value is an hexadecimal sting or html color
var hexColor = colorArgs.body.split( ',' );
color = hexColor[0].trim();
if ( undefined === hexColor[1] ) {
percentage = '';
} else {
percentage = hexColor[1].trim();
}
}
// Cleans the variable
if ( percentage ) {
percentage = percentage.replace( ',', '' ).trim();
percentage = percentage.replace( '%', '' ) / 100;
} else {
// Check if the percentage is undefine or empty and set it to 0
percentage = '0';
}
return colorConvert( percentage, colorArgs.pre, 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);
return;
}
if(res.statusCode >= 400) {
result.reject(body);
return;
}
var parsed;
try {
parsed = JSON.parse(body);
} catch (e) {
result.reject(e);
}
if(!parsed.feed || !parsed.feed.entry) {
result.reject('invalid format of youtube data');
return;
}
var videos = parsed.feed.entry.map(function(element) {
return {
id: element.id.$t,
link: element.link[0].href
}
});
result.resolve(videos);
});
return result.promise;
} | 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] === "boolean" ? opts[k] : defaults[k];
}
// set descriptor props based on value
if (!opts.forceStatic && typeof val === "function") {
desc.get = val;
} else {
desc.value = val;
desc.writable = false;
}
// define the property
Object.defineProperty(obj, key, desc);
} | 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)) {
_level = Level[level];
} else {
invalidParameter(level);
}
} else {
invalidParameter(level);
}
return createObject();
} | 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.resolve())
.then(function() {
return resolvedArray;
});
} | 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())
.then(function() {
return resolvedObject;
});
} | 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);
} else if (arg && typeof arg === 'object') {
//is an object
if (typeof arg.toString === 'function') {
var value = arg.toString();
if (value !== '[object Object]') {
//with a valid toString
return Promise.resolve(value);
}
}
return resolveObject(arg);
} else {
//Yeah! a value
return Promise.resolve(arg);
}
} | 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.authPt.port,
path: this.options.authPt.base + path,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
postData: lines.join('&')
}, cb);
} | 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));
}
return emit.call(self, 'auth.fail', error_msg + ': ' + JSON.stringify(auth.error));
}
return emit.call(self, 'auth.fail', error_msg + ': ' + JSON.stringify(err));
};
} | 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.assert(sample.params).ignore(undefined).is('array');
var msg = 'NoPg event ' + sample.event + ' in ' + sample.duration + ' ms';
if(sample.query || sample.params) {
msg += ': ';
}
if(sample.query) {
msg += 'query=' + util.inspect(sample.query);
if(sample.params) {
msg += ', ';
}
}
if(sample.params) {
msg += 'params=' + util.inspect(sample.params);
}
debug.log(msg);
} | 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['$'+key] = {};
ARRAY(Object.keys(doc[key])).forEach(function(k) {
if(is.uuid(k)) {
obj['$'+key][k] = _get_result(NoPg.Document)([doc[key][k]]);
} else {
obj['$'+key][k] = doc[key][k];
}
});
return;
}
obj['$'+key] = doc[key];
});
_parse_object_expressions(obj);
return new Type(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 direct for everything else but JSON types!
if(key === '$version') { return 'direct'; }
if(key === '$created') { return 'direct'; }
if(key === '$modified') { return 'direct'; }
if(key === '$name') { return 'direct'; }
if(key === '$type') { return 'direct'; }
if(key === '$validator') { return 'direct'; }
if(key === '$id') { return 'direct'; }
if(key === '$types_id') { return 'direct'; }
if(key === '$documents_id') { return 'direct'; }
} else {
var type;
if(schema && schema.properties && schema.properties.hasOwnProperty(key) && schema.properties[key].type) {
type = schema.properties[key].type;
}
if(type === 'number') {
return 'numeric';
}
if(type === 'boolean') {
return 'boolean';
}
}
return 'text';
} | 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 js_input_params = o.slice(i+1);
debug.assert(input_nopg_keys).is('array');
debug.assert(js_input_params).is('array');
//debug.log('input_nopg_keys = ', input_nopg_keys);
//debug.log('func = ', func);
//debug.log('js_input_params = ', js_input_params);
var _parse_predicate_key_epoch = FUNCTION(_parse_predicate_key).curry(ObjType, {'traits': traits, 'epoch':true});
var input_pg_keys = ARRAY(input_nopg_keys).map(_parse_predicate_key_epoch);
var pg_items = input_pg_keys.map(function(i) { return i.getString(); }).valueOf();
var pg_params = input_pg_keys.map(function(i) { return i.getParams(); }).reduce(function(a, b) { return a.concat(b); });
debug.assert(pg_items).is('array');
debug.assert(pg_params).is('array');
//debug.log('input_pg_keys = ', input_pg_keys);
//var n = arg_params.length;
//arg_params.push(JSON.stringify(FUNCTION(func).stringify()));
//arg_params.push(JSON.stringify(js_input_params));
var call_func = 'nopg.call_func(array_to_json(ARRAY['+pg_items.join(', ')+"]), $::json, $::json)";
var type_cast = parse_predicate_pgcast_by_type(ret_type);
return new Predicate(type_cast(call_func), pg_params.concat( [JSON.stringify(FUNCTION(func).stringify()), JSON.stringify(js_input_params)] ));
} | 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];
}
debug.assert(traits.fields).is('array');
// Order by $created by default
if(!traits.order) {
// FIXME: Check if `$created` exists in the ObjType!
traits.order = ['$created'];
}
// Enable group by
if(traits.hasOwnProperty('group')) {
traits.group = [].concat(traits.group);
}
if(!is.array(traits.order)) {
traits.order = [traits.order];
}
debug.assert(traits.order).is('array');
if(traits.limit) {
if(!traits.order) {
debug.warn('Limit without ordering will yeald unpredictable results!');
}
if((''+traits.limit).toLowerCase() === 'all') {
traits.limit = 'ALL';
} else {
traits.limit = '' + parseInt(traits.limit, 10);
}
}
if(traits.offset) {
traits.offset = parseInt(traits.offset, 10);
}
if(traits.hasOwnProperty('prepareOnly')) {
traits.prepareOnly = traits.prepareOnly === true;
}
if(traits.hasOwnProperty('typeAwareness')) {
traits.typeAwareness = traits.typeAwareness === true;
} else {
traits.typeAwareness = NoPg.defaults.enableTypeAwareness === true;
}
// Append '$documents' to fields if traits.documents is specified and it is missing from there
if((traits.documents || traits.typeAwareness) && (traits.fields.indexOf('$documents') === -1) ) {
traits.fields = traits.fields.concat(['$documents']);
}
if(traits.hasOwnProperty('count')) {
traits.count = traits.count === true;
traits.fields = ['count'];
delete traits.order;
}
return traits;
} | 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 } ];
}
if(is.obj(opts)) {
return [ ((traits.match === 'any') ? 'OR' : 'AND') , opts];
}
return [ "AND", {"$name": ''+opts} ];
} | 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(o[0]);
type = parse_operator_type(o[0], 'text');
rest = o.slice(1);
} else {
key = parse_operator_name(o);
type = parse_operator_type(o, 'text');
rest = [];
}
if(key === 'BIND') {
return _parse_function_predicate(ObjType, q, undefined, rest, type, traits);
}
//debug.log('key = ', key);
var parsed_key = _parse_predicate_key(ObjType, {'traits': traits, 'epoch':true}, key);
//debug.log('parsed_key = ', parsed_key);
var pgcast = parse_predicate_pgcast(ObjType, document_type, key);
//debug.log('pgcast = ', pgcast);
return new Predicate( [pgcast(parsed_key.getString())].concat(rest).join(' '), parsed_key.getParams(), parsed_key.getMetaObject() );
}).valueOf();
} | 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.query);
// debug.log('params = ', result.params);
//}
debug.assert(result).is('object');
debug.assert(result.query).is('string');
debug.assert(result.params).is('array');
var builder;
var type = result.documentType;
if( (result.ObjType === NoPg.Document) &&
is.string(type) &&
self._documentBuilders &&
self._documentBuilders.hasOwnProperty(type) &&
is.func(self._documentBuilders[type]) ) {
builder = self._documentBuilders[type];
}
debug.assert(builder).ignore(undefined).is('function');
return do_query(self, result.query, result.params ).then(get_results(result.ObjType, {
'fieldMap': result.fieldMap
})).then(function(data) {
if(!builder) {
return data;
}
debug.log('data = ', data);
return builder(data);
});
});
});
} | 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 === undefined) {
// FIXME: Check that `obj` is an ORM object
data = obj.valueOf();
} else {
data = (new ObjType(obj)).update(orig_data).valueOf();
}
//debug.log('data = ', data);
// Select only keys that start with $
var keys = ARRAY(ObjType.meta.keys)
// Remove leading '$' character from keys
.filter(first_letter_is_dollar)
.map( parse_keyword_name )
// Ignore keys that aren't going to be changed
.filter(function(key) {
return data.hasOwnProperty(key);
// Ignore keys that were not changed
}).filter(function(key) {
return json_cmp(data[key], obj['$'+key]) ? false : true;
});
//debug.log('keys = ', keys.valueOf());
// Return with the current object if there is no keys to update
if(keys.valueOf().length === 0) {
return do_select(self, ObjType, where);
}
// FIXME: Implement binary content support
query = "UPDATE " + (ObjType.meta.table) + " SET "+ keys.map(function(k, i) { return k + ' = $' + (i+1); }).join(', ') +" WHERE ";
if(where.$id) {
query += "id = $"+ (keys.valueOf().length+1);
} else if(where.$name) {
query += "name = $"+ (keys.valueOf().length+1);
} else {
throw new TypeError("Cannot know what to update!");
}
query += " RETURNING *";
params = keys.map(function(key) {
return data[key];
}).valueOf();
if(where.$id) {
params.push(where.$id);
} else if(where.$name){
params.push(where.$name);
}
return do_query(self, query, params);
});
} | 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, query, params);
});
} | 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: " + name);
}
return (rows.shift()||{}).indexdef;
});
} | 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 !== undefined)) {
if(!typefield) {
throw new TypeError("No typefield set for NoPg.Document!");
}
name = pg_convert_index_name(ObjType.meta.table) + "_" + typefield + "_" + pg_convert_index_name(field_name) + "_index";
} else {
name = pg_convert_index_name(ObjType.meta.table) + "_" + pg_convert_index_name(field_name) + "_index";
}
return name;
} | 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 = "CREATE " + (is_unique?'UNIQUE ':'') + "INDEX "+name+" ON " + (ObjType.meta.table) + " USING btree ";
if( (ObjType === NoPg.Document) && (typefield !== undefined)) {
if(!typefield) {
throw new TypeError("No typefield set for NoPg.Document!");
}
query += "(" + typefield+", "+ wrap_casts(pgcast(colname.getString())) + ")";
} else {
query += "(" + wrap_casts(pgcast(colname.getString())) + ")";
}
return 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, field, typefield, is_unique);
return pg_relation_exists(self, name).then(function(exists) {
if(!exists) {
return pg_create_index(self, ObjType, type, field, typefield, is_unique);
}
return pg_get_indexdef(self, name).then(function(old_indexdef) {
var new_indexdef_v1 = pg_create_index_query_v1(self, ObjType, type, field, typefield, is_unique);
var new_indexdef_v2 = pg_create_index_query_v2(self, ObjType, type, field, typefield, is_unique);
if (new_indexdef_v1 === old_indexdef) return self;
if (new_indexdef_v2 === old_indexdef) return self;
if (NoPg.debug) {
debug.info('Rebuilding index...');
debug.log('old index is: ', old_indexdef);
debug.log('new index is: ', new_indexdef_v1);
}
return pg_drop_index(self, ObjType, type, field, typefield).then(function() {
return pg_create_index(self, ObjType, type, field, typefield, is_unique);
});
});
});
} | 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
});
return db;
});
};
} | 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 timeout.');
w.timeout = undefined;
Q.fcall(function() {
var tr_open, tr_commit, tr_rollback, state, tr_unknown, tr_disconnect;
// NoPg instance
if(w.db === undefined) {
debug.warn("Timeout exceeded and database instance undefined. Nothing done.");
return;
}
if(!(w.db && w.db._tr_state)) {
debug.warn("Timeout exceeded but db was not NoPg instance.");
return;
}
state = w.db._tr_state;
tr_open = (state === 'open') ? true : false;
tr_commit = (state === 'commit') ? true : false;
tr_rollback = (state === 'rollback') ? true : false;
tr_disconnect = (state === 'disconnect') ? true : false;
tr_unknown = ((!tr_open) && (!tr_commit) && (!tr_rollback) && (!tr_disconnect)) ? true : false;
if(tr_unknown) {
debug.warn("Timeout exceeded and transaction state was unknown ("+state+"). Nothing done.");
return;
}
if(tr_open) {
debug.warn("Timeout exceeded and transaction still open. Closing it by rollback.");
return w.db.rollback().fail(function(err) {
debug.error("Rollback failed: " + (err.stack || err) );
});
}
if(tr_disconnect) {
//debug.log('...but .disconnect() was already done.');
return;
}
if(tr_commit) {
//debug.log('...but .commit() was already done.');
return;
}
if(tr_rollback) {
//debug.log('...but .rollback() was already done.');
return;
}
}).fin(function() {
if(w && w.db) {
w.db._events.emit('timeout');
}
}).done();
}, opts.timeout);
/* Set object */
w.reset = function(o) {
debug.assert(o).is('object');
//debug.log('Resetting the watchdog.');
w.db = o;
};
/** Clear the timeout */
w.clear = function() {
if(w.timeout) {
//debug.log('Clearing the watchdog.');
clearTimeout(w.timeout);
w.timeout = undefined;
}
};
return w;
} | 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_mapping[''+payload.table+','+payload.op];
if(!event) {
debug.warn('Could not find event name for payload: ', payload);
return;
}
// Verify we don't emit, if matching id enabled and does not match
if( when.hasOwnProperty('id') && (payload.keys.id !== when.id) ) {
return;
}
// Verify we don't emit, if matching event name enabled and does not match
if( when.hasOwnProperty('name') && (event !== when.name) ) {
return;
}
events.emit(when_str, payload.keys.id, event, when.type);
};
} | 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.parseTCNChannelName(event);
// If we are already listening, just increase the counter.
if(counter.hasOwnProperty(event_name)) {
counter[event_name] += 1;
return;
}
// Create the listener if necessary
var tcn_listener;
if(!tcn_listeners.hasOwnProperty(event_name)) {
tcn_listener = tcn_listeners[event_name] = create_tcn_listener(self._events, event);
} else {
tcn_listener = tcn_listeners[event_name];
}
// Start listening tcn events for this channel
//debug.log('Listening channel ' + channel_name + ' for ' + event_name);
self._db.on(channel_name, tcn_listener);
counter[event_name] = 1;
} | 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 = NoPg.parseTCNChannelName(event);
counter[event_name] -= 1;
if(counter[event_name] === 0) {
//debug.log('Stopped listening channel ' + channel_name + ' for ' + event_name);
self._db.removeListener(channel_name, tcn_listeners[event_name]);
delete counter[event_name];
}
} | 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, isDir, function () {
return _trace.slice(0);
});
}
finally {
_trace = null;
}
if (isDir) {
trace.push(name);
try {
walkSync(file, trace, callback);
}
finally {
trace.pop();
}
}
});
};
/**
* Traverse the directory synchronously.
*
* Parameters
* - dir: A directory to traverse
* - callback: A function to be called for each file recursively
*
* Returns: The list of information of files contained in 'dir'
*/
self.walkSync = function (dir, callback) {
if (typeof callback != 'function') {
throw new Error("'callback' is not a function.");
}
walkSync(dir, [], callback);
};
} | 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 === 'function', 'Model function not privided.');
return Model(app, name);
}
} | 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 = new Service(options);
return 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[name];
}
}
} | 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;
}
});
$injector.invoke(itemsToAttach);
} | 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.updatePageStyle(pageName);
}
} | 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 destroyed along with scope
scope.$on('$destroy', function () {
for (var i = 0; i < fns.length; i++) {
fns[i]();
}
});
} | 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 dev likely made a mistake
if (!angular.isFunction(scope[name])) {
throw new Error(ctrlName + ' has uiEventHandler ' + name + ' that does not return a function');
}
}
}
} | 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;
}
cb(err, collectedStdOut, collectedStdErr, result);
});
_exec.stdout.on('data', function (data) {
if (collectOutput) {
collectedStdOut += data.toString().trim();
} else {
process.stdout.write(colors.green(data.toString()));
}
});
_exec.stderr.on('data', function (data) {
if (collectOutput) {
collectedStdErr += data.toString().trim();
} else {
process.stderr.write(colors.red(data.toString()));
}
});
} | 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()) {
addMatch(item);
} else if (stat.isDirectory()) {
var _items = wrench.readdirSyncRecursive(item);
_items.forEach(function (_item) {
_item = p.join(item, _item);
if (fs.statSync(_item).isFile()) {
addMatch(_item);
}
});
}
});
return data;
} | 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;
/**
* @type {boolean}
* @private
*/
this.fullWindow = true;
/**
* if a path has started - reset when drawing a path
* @type {boolean}
* @private
*/
this.pathStarted = false;
/**
* width of the canvas, in px
* @type {number}
* @public
*/
this.width = 0;
/**
* height of the canvas, in px
* @type {number}
* @public
*/
this.height = 0;
if (canvasElement === undefined) {
canvasElement = document.createElement("canvas");
document.body.appendChild(canvasElement);
}
if (fullWindow === undefined) {
fullWindow = true;
}
if (autoInit === undefined) {
autoInit = true;
}
this.canvas = canvasElement;
this.canvas.classList.add("creenv");
this.context = this.canvas.getContext('2d');
this.fullWindow = fullWindow;
this.onWindowResizeHandler = this.onWindowResizeHandler.bind(this);
if (autoInit) {
this.init();
}
} | 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 conf and settings.
const postCSSConf = [
autoprefixer({
browsers: conf.themeConfig.sass.browserSupport || 'last 2 versions'
})
];
const sassSrc = path.join(conf.themeConfig.root, conf.themeConfig.sass.src, '**', '*.scss');
const sassDest = path.join(conf.themeConfig.root, conf.themeConfig.sass.dest);
// The task itself.
return undertaker.src(sassSrc)
.pipe(gulpIf(!conf.productionMode, sourcemaps.init()))
.pipe(sass(sassConfig).on('error', sass.logError))
.pipe(postcss(postCSSConf))
.pipe(gulpIf(!conf.productionMode, sourcemaps.write('.')))
.pipe(undertaker.dest(sassDest));
} | 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 TypeError("\"origin\" argument is empty");
}
else if ("undefined" === typeof target) {
throw new ReferenceError("Missing \"target\" argument");
}
else if ("string" !== typeof target) {
throw new TypeError("\"target\" argument is not a string");
}
else if ("" === target.trim()) {
throw new Error("\"target\" argument is empty");
}
else if ("undefined" === typeof callback) {
throw new ReferenceError("Missing \"callback\" argument");
}
else if ("function" !== typeof callback) {
throw new TypeError("\"callback\" argument is not a function");
}
else {
isFileProm(origin).then((exists) => {
return exists ? Promise.resolve() : Promise.reject(new Error("There is no origin file \"" + origin + "\""));
}).then(() => {
let error = false;
const writeStream = createWriteStream(target).once("error", (_err) => {
error = true;
writeStream.close();
callback(_err);
}).once("close", () => {
return error ? null : callback(null);
});
createReadStream(origin).once("error", (_err) => {
error = true; callback(_err);
}).pipe(writeStream);
}).catch(callback);
}
} | 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.push(key);
}
this._expires[key] = ms;
rval.e = ms;
return 1;
} | 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;
return 1;
} | 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._ekeys.length);
key = this._ekeys[ind];
if(this._expires[key] <= Date.now()) {
this.emit('expired', key);
this.delKey(key);
count++;
}
}
if(count >= threshold) {
setImmediate(removeExpiredKeys);
}
return count;
}
removeExpiredKeys = removeExpiredKeys.bind(this);
return removeExpiredKeys();
} | 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.entries === 'function') {
var it = iterable.entries();
while (!it.done) {
var tmp = it.next();
this.add.apply(this, tmp);//it.next());
}
}
}
} | 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, 0);
}
};
}
}
p.sequence = new Sequence(newIter);
} | 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) {
newIter = {
entries: function() {
var pi = priv.get(iter);
return new Iterator(pi.sequence.sequence, undefined, function(x) {
return [x, x];
});
}
};
}
}
p.sequence = new Sequence(newIter);
} | 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({ where: {}, multi: true }));
}
});
return Q.all(promises);
} | 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. ',
required: true
}
}
};
// for safety reasons, we can't use this in production
if (config.env === 'production') {
return Q.reject('purging is NOT available for prod.');
}
// prompt the user to confirm they are deleting everything in the database
var deferred = Q.defer();
prompt.start();
prompt.get(promptSchema, function (err, result) {
if (err) {
deferred.reject(err);
}
else if (result.confirm !== 'y') {
log.info('purge cancelled');
deferred.resolve(false);
}
// else user confirmed deletion so do it
else {
deferred.resolve(true);
}
});
return deferred.promise;
} | 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 breaks standard behavior.
catchErrors: false,
// A list of functions that can be called. This list will be used to make
// the proxy functions available when Proxy is not supported. Note that
// this is generally not needed since the worker will also publish its
// known functions.
functionNames: [],
// Call console.time and console.timeEnd for calls sent though the proxy.
timeCalls: false
};
if (opt_options) {
for (var key in opt_options) {
if (!(key in options)) continue;
options[key] = opt_options[key];
}
}
Object.freeze(options);
// Ensure that we have an array of workers (even if only using one worker).
if (typeof Worker != 'undefined' && (workersOrFunctions instanceof Worker)) {
workersOrFunctions = [workersOrFunctions];
}
if (Array.isArray(workersOrFunctions)) {
return sendCallsToWorker(workersOrFunctions, options);
} else {
receiveCallsFromOwner(workersOrFunctions, options);
}
} | 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',
master: noop,
numWorkers: process.env.CLUSTER_WORKERS || os.cpus().length,
killOnError: true,
beforeExit: function (err, done) {
done();
}
});
this._addLogger('info', [this.options.debugScope, 'info'].join(':'));
this._addLogger('warning', [this.options.debugScope, 'warning'].join(':'));
this._addLogger('error', [this.options.debugScope, 'error'].join(':'));
if (!this.options.worker || !isFunction(this.options.worker)) {
throw new Error('Cluster must be provided with a worker closure.');
}
if (!isFunction(this.options.beforeExit)) {
this.log.warning('Before exit callback is not a function, removing.');
this.options.beforeExit = noop;
}
this.workers = [];
// This is here to expose the cluster without having to re-require in the
// script that uses cluster-man
this.cluster = cluster;
} | 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 window.__private__.elementRegistry[identifier];
}
if (typeof identifier === 'function') {
for (let tag in window.__private__.elementRegistry) {
let Class = window.__private__.elementRegistry[tag];
if (Class.__proto__ === identifier) return Class;
}
return null;
}
return window.__private__.elementRegistry;
} | 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.vars = options.vars;
this.media_match = options.media_match;
this.media_extract = options.media_extract;
//not run autoprefixer by default
if (this.browsers) {
string = prefixes(this.browsers).process(string).css;
}
//handle import inlining if any
if (this.import_path) {
var opts = {
path: this.import_path,
base: this.import_base,
target: this.import_filter
};
string = rework(string).use(imprt(opts)).toString();
}
//filter media query if any
if (this.media_match) {
if (!this.media_match.width || !this.media_match.height) {
throw new Error('Must provide device width and device height');
}
var extractOptions = {
deviceOptions: {
width: this.media_match.width,
height: this.media_match.height,
orientation: this.media_match.orientation || 'any'
},
extractQuery: this.media_extract
};
string = rework(string).use(move).use(extract(extractOptions)).toString();
}
if (this.vars) {
string = rework(string).use(vars).toString();
}
return rework(string, options)
.use(hex)
.use(color)
.use(calc)
.toString(options);
} | 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) + ": " +
store.stringify(value) + ",\n";
return fs.appendFileSync(file, item, 'utf-8');
} | 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) + ": " +
store.stringify(value) + ",\n";
var fd = fs.openSync(file, 'a', '0666');
fs.writeSync(fd, item, null, 'utf8');
fs.closeSync(fd);
return true;
} | 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';
options.tokenURL = 'https://api.relayr.io/oauth2/token';
options.scope = 'access-own-user-info+configure-devices';
options.scopeSeparator = options.scopeSeparator || ' ';
OAuth2Strategy.call(this, options, verifyCallback);
this.name = 'relayr';
this._profileURL = options.profileURL || 'https://api.relayr.io/oauth2/user-info';
this._appURL = options.appURL || 'https://api.relayr.io/oauth2/app-info';
this._infocall = options.fetch || 'user';
this._oauth2.useAuthorizationHeaderforGET(true);
} | 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':
return attemptCallback(filePath, callback, --attempts);
default:
throw error;
}
}
} | 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.warn('takeown:', filePath, 'does not exist.');
return;
}
// fs.lstatSync can fail with EPERM on Windows so retry
// after taking control of this specific path.
if (error.code === 'EPERM') {
execSyncElevated('takeown /f "' + filePath + '"');
return takeOwnership(filePath);
}
}
} | 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.