_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q33000 | bodyParser | train | function bodyParser (options) {
var opts = {}
// exclude type option
if (options) {
for (var prop in options) {
if (prop !== 'type') {
opts[prop] = options[prop]
}
}
}
var _urlencoded = exports.urlencoded(opts)
var _json = exports.json(opts)
return function bodyParser (req, res, next) {
_json(req, res, function (err) {
if (err) return next(err)
_urlencoded(req, res, next)
})
}
} | javascript | {
"resource": ""
} |
q33001 | loadParser | train | function loadParser (parserName) {
var parser = parsers[parserName]
if (parser !== undefined) {
return parser
}
// this uses a switch for static require analysis
switch (parserName) {
case 'json':
parser = require('./lib/types/json')
break
case 'raw':
parser = require('./lib/types/raw')
break
case 'text':
parser = require('./lib/types/text')
break
case 'urlencoded':
parser = require('./lib/types/urlencoded')
break
}
// store to prevent invoking require()
return (parsers[parserName] = parser)
} | javascript | {
"resource": ""
} |
q33002 | train | function( term ) {
var split_term = term.split(' ');
var matchers = [];
for (var i=0; i < split_term.length; i++) {
if ( split_term[i].length > 0 ) {
var matcher = {};
matcher['partial'] = new RegExp( $.ui.autocomplete.escapeRegex( split_term[i] ), "i" );
if ( context.settings['relevancy-sorting'] ) {
matcher['strict'] = new RegExp( "^" + $.ui.autocomplete.escapeRegex( split_term[i] ), "i" );
}
matchers.push( matcher );
}
};
return $.grep( context.options, function( option ) {
var partial_matches = 0;
if ( context.settings['relevancy-sorting'] ) {
var strict_match = false;
var split_option_matches = option.matches.split(' ');
}
for ( var i=0; i < matchers.length; i++ ) {
if ( matchers[i]['partial'].test( option.matches ) ) {
partial_matches++;
}
if ( context.settings['relevancy-sorting'] ) {
for (var q=0; q < split_option_matches.length; q++) {
if ( matchers[i]['strict'].test( split_option_matches[q] ) ) {
strict_match = true;
break;
}
};
}
};
if ( context.settings['relevancy-sorting'] ) {
var option_score = 0;
option_score += partial_matches * context.settings['relevancy-sorting-partial-match-value'];
if ( strict_match ) {
option_score += context.settings['relevancy-sorting-strict-match-value'];
}
option_score = option_score * option['relevancy-score-booster'];
option['relevancy-score'] = option_score;
}
return (!term || matchers.length === partial_matches );
});
} | javascript | {
"resource": ""
} | |
q33003 | train | function( option ) {
if ( option ) {
if ( context.$select_field.val() !== option['real-value'] ) {
context.$select_field.val( option['real-value'] );
context.$select_field.change();
}
} else {
var option_name = context.$text_field.val().toLowerCase();
var matching_option = { 'real-value': false };
for (var i=0; i < context.options.length; i++) {
if ( option_name === context.options[i]['label'].toLowerCase() ) {
matching_option = context.options[i];
break;
}
};
if ( context.$select_field.val() !== matching_option['real-value'] ) {
context.$select_field.val( matching_option['real-value'] || '' );
context.$select_field.change();
}
if ( matching_option['real-value'] ) {
context.$text_field.val( matching_option['label'] );
}
if ( typeof context.settings['handle_invalid_input'] === 'function' && context.$select_field.val() === '' ) {
context.settings['handle_invalid_input']( context );
}
}
} | javascript | {
"resource": ""
} | |
q33004 | coerce | train | function coerce(promise) {
var deferred = defer();
nextTick(function () {
try {
promise.then(deferred.resolve, deferred.reject, deferred.notify);
} catch (exception) {
deferred.reject(exception);
}
});
return deferred.promise;
} | javascript | {
"resource": ""
} |
q33005 | iterDeps | train | function iterDeps(method, obj, depKey, seen, meta) {
var guid = guidFor(obj);
if (!seen[guid]) seen[guid] = {};
if (seen[guid][depKey]) return;
seen[guid][depKey] = true;
var deps = meta.deps;
deps = deps && deps[depKey];
if (deps) {
for(var key in deps) {
if (DEP_SKIP[key]) continue;
method(obj, key);
}
}
} | javascript | {
"resource": ""
} |
q33006 | actionSetFor | train | function actionSetFor(obj, eventName, target, writable) {
return metaPath(obj, ['listeners', eventName, guidFor(target)], writable);
} | javascript | {
"resource": ""
} |
q33007 | targetSetFor | train | function targetSetFor(obj, eventName) {
var listenerSet = meta(obj, false).listeners;
if (!listenerSet) { return false; }
return listenerSet[eventName] || false;
} | javascript | {
"resource": ""
} |
q33008 | addListener | train | function addListener(obj, eventName, target, method) {
Ember.assert("You must pass at least an object and event name to Ember.addListener", !!obj && !!eventName);
if (!method && 'function' === typeof target) {
method = target;
target = null;
}
var actionSet = actionSetFor(obj, eventName, target, true),
methodGuid = guidFor(method);
if (!actionSet[methodGuid]) {
actionSet[methodGuid] = { target: target, method: method };
}
if ('function' === typeof obj.didAddListener) {
obj.didAddListener(eventName, target, method);
}
} | javascript | {
"resource": ""
} |
q33009 | watchedEvents | train | function watchedEvents(obj) {
var listeners = meta(obj, false).listeners, ret = [];
if (listeners) {
for(var eventName in listeners) {
if (!SKIP_PROPERTIES[eventName] && listeners[eventName]) {
ret.push(eventName);
}
}
}
return ret;
} | javascript | {
"resource": ""
} |
q33010 | train | function(str) {
return str.replace(STRING_CAMELIZE_REGEXP, function(match, separator, chr) {
return chr ? chr.toUpperCase() : '';
});
} | javascript | {
"resource": ""
} | |
q33011 | train | function() {
if (this.isDestroying) { return; }
this.isDestroying = true;
if (this.willDestroy) { this.willDestroy(); }
set(this, 'isDestroyed', true);
Ember.run.schedule('destroy', this, this._scheduledDestroy);
return this;
} | javascript | {
"resource": ""
} | |
q33012 | train | function(router) {
var properties = Ember.A(Ember.keys(this)),
injections = get(this.constructor, 'injections'),
namespace = this, controller, name;
if (!router && Ember.Router.detect(namespace['Router'])) {
router = namespace['Router'].create();
this._createdRouter = router;
}
if (router) {
set(this, 'router', router);
// By default, the router's namespace is the current application.
//
// This allows it to find model classes when a state has a
// route like `/posts/:post_id`. In that case, it would first
// convert `post_id` into `Post`, and then look it up on its
// namespace.
set(router, 'namespace', this);
}
Ember.runLoadHooks('application', this);
injections.forEach(function(injection) {
properties.forEach(function(property) {
injection[1](namespace, router, property);
});
});
if (router && router instanceof Ember.Router) {
this.startRouting(router);
}
} | javascript | {
"resource": ""
} | |
q33013 | train | function(tagName, parent, fn, other) {
var buffer = new Ember._RenderBuffer(tagName);
buffer.parentBuffer = parent;
if (other) { Ember.$.extend(buffer, other); }
if (fn) { fn.call(this, buffer); }
return buffer;
} | javascript | {
"resource": ""
} | |
q33014 | train | function(newBuffer) {
var parent = this.parentBuffer;
if (!parent) { return; }
var childBuffers = parent.childBuffers;
var index = indexOf.call(childBuffers, this);
if (newBuffer) {
childBuffers.splice(index, 1, newBuffer);
} else {
childBuffers.splice(index, 1);
}
} | javascript | {
"resource": ""
} | |
q33015 | train | function(tagName) {
var parentBuffer = get(this, 'parentBuffer');
return this.newBuffer(tagName, parentBuffer, function(buffer) {
var siblings = parentBuffer.childBuffers;
var index = indexOf.call(siblings, this);
siblings.splice(index + 1, 0, buffer);
});
} | javascript | {
"resource": ""
} | |
q33016 | train | function(name, context) {
// Normalize arguments. Supported arguments:
//
// name
// name, context
// outletName, name
// outletName, name, context
// options
//
// The options hash has the following keys:
//
// name: the name of the controller and view
// to use. If this is passed, the name
// determines the view and controller.
// outletName: the name of the outlet to
// fill in. default: 'view'
// viewClass: the class of the view to instantiate
// controller: the controller instance to pass
// to the view
// context: an object that should become the
// controller's `content` and thus the
// template's context.
var outletName, viewClass, view, controller, options;
if (Ember.typeOf(context) === 'string') {
outletName = name;
name = context;
context = arguments[2];
}
if (arguments.length === 1) {
if (Ember.typeOf(name) === 'object') {
options = name;
outletName = options.outletName;
name = options.name;
viewClass = options.viewClass;
controller = options.controller;
context = options.context;
}
} else {
options = {};
}
outletName = outletName || 'view';
Ember.assert("You must supply a name or a view class to connectOutlets, but not both", (!!name && !viewClass && !controller) || (!name && !!viewClass));
if (name) {
var namespace = get(this, 'namespace'),
controllers = get(this, 'controllers');
var viewClassName = name.charAt(0).toUpperCase() + name.substr(1) + "View";
viewClass = get(namespace, viewClassName);
controller = get(controllers, name + 'Controller');
Ember.assert("The name you supplied " + name + " did not resolve to a view " + viewClassName, !!viewClass);
Ember.assert("The name you supplied " + name + " did not resolve to a controller " + name + 'Controller', (!!controller && !!context) || !context);
}
if (controller && context) { controller.set('content', context); }
view = viewClass.create();
if (controller) { set(view, 'controller', controller); }
set(this, outletName, view);
return view;
} | javascript | {
"resource": ""
} | |
q33017 | train | function() {
var controllers = get(this, 'controllers'),
controllerNames = Array.prototype.slice.apply(arguments),
controllerName;
for (var i=0, l=controllerNames.length; i<l; i++) {
controllerName = controllerNames[i] + 'Controller';
set(this, controllerName, get(controllers, controllerName));
}
} | javascript | {
"resource": ""
} | |
q33018 | train | function(buffer) {
var attributeBindings = get(this, 'attributeBindings'),
attributeValue, elem, type;
if (!attributeBindings) { return; }
a_forEach(attributeBindings, function(binding) {
var split = binding.split(':'),
property = split[0],
attributeName = split[1] || property;
// Create an observer to add/remove/change the attribute if the
// JavaScript property changes.
var observer = function() {
elem = this.$();
if (!elem) { return; }
attributeValue = get(this, property);
Ember.View.applyAttributeBindings(elem, attributeName, attributeValue);
};
addObserver(this, property, observer);
// Determine the current value and add it to the render buffer
// if necessary.
attributeValue = get(this, property);
Ember.View.applyAttributeBindings(buffer, attributeName, attributeValue);
}, this);
} | javascript | {
"resource": ""
} | |
q33019 | train | function(tagName) {
tagName = tagName || get(this, 'tagName');
// Explicitly check for null or undefined, as tagName
// may be an empty string, which would evaluate to false.
if (tagName === null || tagName === undefined) {
tagName = 'div';
}
return Ember.RenderBuffer(tagName);
} | javascript | {
"resource": ""
} | |
q33020 | train | function(view) {
Ember.deprecate("Something you did caused a view to re-render after it rendered but before it was inserted into the DOM. Because this is avoidable and the cause of significant performance issues in applications, this behavior is deprecated. If you want to use the debugger to find out what caused this, you can set ENV.RAISE_ON_DEPRECATION to true.");
view._notifyWillRerender();
view.clearRenderedChildren();
view.renderToBuffer(view.buffer, 'replaceWith');
} | javascript | {
"resource": ""
} | |
q33021 | train | function(views, start, removed) {
if (removed === 0) { return; }
var changedViews = views.slice(start, start+removed);
this.initializeViews(changedViews, null, null);
this.invokeForState('childViewsWillChange', views, start, removed);
} | javascript | {
"resource": ""
} | |
q33022 | train | function(views, start, removed, added) {
var len = get(views, 'length');
// No new child views were added; bail out.
if (added === 0) return;
var changedViews = views.slice(start, start+added);
this.initializeViews(changedViews, this, get(this, 'templateData'));
// Let the current state handle the changes
this.invokeForState('childViewsDidChange', views, start, added);
} | javascript | {
"resource": ""
} | |
q33023 | train | function(view, prev) {
if (prev) {
prev.domManager.after(prev, view);
} else {
this.domManager.prepend(this, view);
}
} | javascript | {
"resource": ""
} | |
q33024 | train | function() {
this._super();
set(this, 'stateMeta', Ember.Map.create());
var initialState = get(this, 'initialState');
if (!initialState && get(this, 'states.start')) {
initialState = 'start';
}
if (initialState) {
this.transitionTo(initialState);
Ember.assert('Failed to transition to initial state "' + initialState + '"', !!get(this, 'currentState'));
}
} | javascript | {
"resource": ""
} | |
q33025 | train | function(root, path) {
var parts = path.split('.'),
state = root;
for (var i=0, l=parts.length; i<l; i++) {
state = get(get(state, 'states'), parts[i]);
if (!state) { break; }
}
return state;
} | javascript | {
"resource": ""
} | |
q33026 | train | function(manager, params) {
var modelClass, routeMatcher, param;
if (modelClass = this.modelClassFor(get(manager, 'namespace'))) {
Ember.assert("Expected "+modelClass.toString()+" to implement `find` for use in '"+this.get('path')+"' `deserialize`. Please implement the `find` method or overwrite `deserialize`.", modelClass.find);
return modelClass.find(params[paramForClass(modelClass)]);
}
return params;
} | javascript | {
"resource": ""
} | |
q33027 | train | function(manager, context) {
var modelClass, routeMatcher, namespace, param, id;
if (Ember.empty(context)) { return ''; }
if (modelClass = this.modelClassFor(get(manager, 'namespace'))) {
param = paramForClass(modelClass);
id = get(context, 'id');
context = {};
context[param] = id;
}
return context;
} | javascript | {
"resource": ""
} | |
q33028 | train | function(root, parsedPath, options) {
var val,
path = parsedPath.path;
if (path === 'this') {
val = root;
} else if (path === '') {
val = true;
} else {
val = getPath(root, path, options);
}
return Ember.View._classStringForValue(path, val, parsedPath.className, parsedPath.falsyClassName);
} | javascript | {
"resource": ""
} | |
q33029 | inherit | train | function inherit (base) {
if (typeof base === 'function') {
return initClass(protoize.apply(null, arguments), [], 0);
} else {
return initClass(Object.create(base), arguments, 1);
}
} | javascript | {
"resource": ""
} |
q33030 | getChalk | train | function getChalk(code) {
if (code.slice(0, 1) === 'I') {
return chalk.blue;
} else if (code.slice(0, 1) === 'W') {
return chalk.yellow;
} else {
return chalk.red;
}
} | javascript | {
"resource": ""
} |
q33031 | reporter | train | function reporter(error, file) {
// _JS Hint_ can sometimes call the reporter function with no error. This is
// simply ignored.
if (!error) {
return;
}
if (!(error.code in errors)) {
errors[error.code] = { reason: error.raw, count: 0 };
}
errors[error.code].count++;
totalErrors++;
console.log(getChalk(error.code)('%s: line %d, col %d, %s'),
file, error.line, error.character, error.reason);
if (error.evidence !== undefined) {
var evidence = error.evidence.trim();
console.log(chalk.grey(' %s'), evidence);
}
} | javascript | {
"resource": ""
} |
q33032 | displaySummary | train | function displaySummary(errorCode) {
var error = errors[errorCode];
if (error.count > 1) {
console.log(getChalk(errorCode)('%s: %s (%d instances)'),
errorCode, error.reason, error.count);
} else {
console.log(getChalk(errorCode)('%s: %s (1 instance)'),
errorCode, error.reason);
}
} | javascript | {
"resource": ""
} |
q33033 | callback | train | function callback(err, hasError) {
if (err !== null) {
console.log(chalk.red('Error running JSHint over project: %j\n'), err);
}
if (hasError) {
console.log(chalk.blue('\nSummary\n=======\n'));
for (var errorCode in errors) {
if (errors.hasOwnProperty(errorCode)) {
displaySummary(errorCode);
}
}
console.log('');
if (totalErrors > 1) {
console.log(chalk.red('Found %d errors.\n'), totalErrors);
} else {
console.log(chalk.red('Found 1 error.\n'));
}
} else {
console.log(chalk.green('No JSHint errors found.\n'));
}
} | javascript | {
"resource": ""
} |
q33034 | Keyboard | train | function Keyboard(keyMap) {
/**
* The current key states.
* @member {object}
* @private
*/
this.keys = {};
var self = this;
for (var kc in keyMap) {
if (keyMap.hasOwnProperty(kc)) {
this.keys[keyMap[kc]] = 0;
}
}
window.addEventListener("keydown", function(event) {
if (keyMap.hasOwnProperty(event.keyCode)) {
if (self.keys[keyMap[event.keyCode]] === 0) {
self.keys[keyMap[event.keyCode]] = 2;
}
return false;
}
});
window.addEventListener("keyup", function(event) {
if (keyMap.hasOwnProperty(event.keyCode)) {
self.keys[keyMap[event.keyCode]] = 0;
return false;
}
});
} | javascript | {
"resource": ""
} |
q33035 | merge | train | function merge (schema, doc, self) {
var keys = Object.keys(doc);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var type;
// if nothing in schema yet, just assign
if ('undefined' == typeof schema[key]) {
var type = self.getType(doc, key);
if (undefined !== type) {
schema[key] = type;
}
continue;
}
// exists in schema and incoming is an object?
if (isObject(doc[key])) {
if (isObject(schema[key])) {
merge(schema[key], doc[key], self);
} else {
type = self.getType(doc, key);
if (undefined !== type) {
if ('null' == schema[key]) {
schema[key] = type;
} else if (type != schema[key]) {
schema[key] = 'Mixed';
}
}
}
} else {
// exists in schema and incoming is not an object.
var type = self.getType(doc, key);
if (undefined === type) {
continue;
}
if ('null' == schema[key]) {
schema[key] = type;
} else if ('null' == type) {
// ignore
} else if (Array.isArray(schema[key]) && Array.isArray(type)) {
if (0 === schema[key].length) {
schema[key] = type;
} else if (schema[key][0] instanceof Schema && isObject(type[0])) {
// merge schemas
schema[key][0].combine(type[0]);
} else if (!equalType(schema[key], type)) {
schema[key] = ['Mixed'];
}
} else if (!equalType(schema[key], type)) {
schema[key] = 'Mixed';
}
}
}
} | javascript | {
"resource": ""
} |
q33036 | equalType | train | function equalType (a, b) {
if (Array.isArray(a) && Array.isArray(b)) {
if (0 === a.length || 0 === b.length) {
return true;
}
return equalType(a[0], b[0]);
}
if ('null' == a || 'null' == b) {
return true;
}
return a == b;
} | javascript | {
"resource": ""
} |
q33037 | getArrayType | train | function getArrayType (arr, self) {
var compareDocs = false;
var type = self.getType(arr, 0);
if (isObject(type)) {
type = new Schema(arr[0]);
compareDocs = true;
}
var match = true;
var element;
var err;
for (var i = 1; i < arr.length; ++i) {
element = arr[i];
if (isObject(element)) {
if (compareDocs) {
err = type.consume(element);
if (err) throw err;
continue;
}
if ('null' == type) {
type = new Schema(element);
compareDocs = true;
continue;
}
match = false;
break;
}
if (!equalType(self.getType(arr, i), type)) {
match = false;
break;
}
}
if (match) return [type];
return ['Mixed'];
} | javascript | {
"resource": ""
} |
q33038 | convertObject | train | function convertObject (schema, self) {
var keys = Object.keys(schema);
var ret = {};
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
ret[key] = convertElement(schema[key], self);
}
return ret;
} | javascript | {
"resource": ""
} |
q33039 | convertElement | train | function convertElement (el, self) {
if (el instanceof Schema) {
return el.toObject(self);
}
if (isObject(el)) {
return convertObject(el, self);
}
if (Array.isArray(el)) {
return el.map(function (item) {
return convertElement(item, self);
})
}
return el;
} | javascript | {
"resource": ""
} |
q33040 | stylesheets | train | function stylesheets(options) {
return this.stylesheets.reduce(function reduce(links, sheet) {
return links + options.fn(sheet);
}, '');
} | javascript | {
"resource": ""
} |
q33041 | define | train | function define() {
if (!('canonical' in this.data)) {
this.data.canonical = [
'https://',
pkg.subdomain,
'.nodejitsu.com',
url.parse(this.defaults.canonical).pathname
].join('');
}
return this;
} | javascript | {
"resource": ""
} |
q33042 | SlideChangeEvent | train | function SlideChangeEvent(fromIndex, toIndex) {
check(fromIndex, 'fromIndex').is.aNumber();
check(toIndex, 'toIndex').is.aNumber();
var pub = Object.create(SlideChangeEvent.prototype);
/**
* Index of previous slide.
*
* @type Number
* @access read-only
* @fqn SlideChangeEvent.prototype.fromIndex
*/
pub.fromIndex = fromIndex;
/**
* Index of current slide.
*
* @type Number
* @access read-only
* @fqn SlideChangeEvent.prototype.toIndex
*/
pub.toIndex = toIndex;
return pub;
} | javascript | {
"resource": ""
} |
q33043 | train | function (backendAddress) {
backendAddress = backendAddress || {};
var country = {
value: safeUse(backendAddress.country),
label: safeUse(backendAddress.countryname)
};
return {
company: safeUse(backendAddress.company),
salutation: safeUse(backendAddress.salutation),
surname: safeUse(backendAddress.lastname),
name: safeUse(backendAddress.firstname),
street: safeUse(backendAddress.street1),
zip: safeUse(backendAddress.zip),
city: safeUse(backendAddress.city),
country: !country.value ? null : country,
email: safeUse(backendAddress.email),
telephone: safeUse(backendAddress.telephone)
};
} | javascript | {
"resource": ""
} | |
q33044 | train | function (products, categoryUrlId) {
return products.map(function (product) {
product.categoryUrlId = categoryUrlId;
// the backend is sending us prices as strings.
// we need to fix that up for sorting and other things to work
product.price = parseFloat(product.price, 10);
return sofa.Util.extend(new sofa.models.Product(), product);
});
} | javascript | {
"resource": ""
} | |
q33045 | train | function () {
var activeCoupons = basketService.getActiveCoupons();
var oldCouponCodes = activeCoupons.map(function (activeCoupon) {
return activeCoupon.code;
});
basketService.clearCoupons();
oldCouponCodes.forEach(function (couponCode) {
self.submitCode(couponCode);
});
} | javascript | {
"resource": ""
} | |
q33046 | get | train | function get(params, cb) {
var resourcePath = "/appforms/config";
var method = "GET";
var data = {};
params.resourcePath = resourcePath;
params.method = method;
params.data = data;
mbaasRequest.app(params, cb);
} | javascript | {
"resource": ""
} |
q33047 | serializeFile | train | function serializeFile(file) {
// preserve path, source, and file-save props
var o = u.pick(file, 'path', '_oldtext', '_dirty');
// recreate file.text from serialized fragments
// new or modifified fragments should delete file.text
o.text = file.text || serializeTextFragments(file);
return o;
} | javascript | {
"resource": ""
} |
q33048 | clone | train | function clone() {
var arr = [];
this.each(function(el) {
arr.push(el.cloneNode(true));
});
return this.air(arr);
} | javascript | {
"resource": ""
} |
q33049 | Result | train | function Result(cmd, err, stdout, stderr) {
this.cmd = cmd;
this.err = err;
this.stdout = strip(stdout);
this.stderr = strip(stderr);
} | javascript | {
"resource": ""
} |
q33050 | _errorCb | train | function _errorCb(err, result) {
// if there is a conflict error, retrieve the document's revision first
function _successCb(err, result) {
// use the revision to update the existing documents
// NOTE: it is not impossible that the revision of this document
// is modified by other operations right before updating, Couchpenter
// will only try once to avoid any possibility of retrying infinitely.
doc._rev = result._rev;
self.couch.use(dbName).insert(doc, self._handle(cb, {
dbName: dbName,
docId: doc._id,
message: 'updated'
}));
}
self.couch.use(dbName).get(doc._id, self._handle(cb, {
dbName: dbName,
docId: doc._id,
successCb: _successCb
}));
} | javascript | {
"resource": ""
} |
q33051 | _successCb | train | function _successCb(err, result) {
self.couch.use(dbName).destroy(result._id, result._rev, self._handle(cb, {
dbName: dbName,
docId: doc._id,
message: 'deleted'
}));
} | javascript | {
"resource": ""
} |
q33052 | _result | train | function _result(err, dbName, docId, message) {
var result = {
id: util.format('%s%s%s', dbName, (docId) ? '/' : '', docId || ''),
message: message || util.format('%s (%s)', err.error, err.status_code)
};
if (err) {
result.error = err;
}
return result;
} | javascript | {
"resource": ""
} |
q33053 | matter | train | function matter(file) {
var parsed = gm(file.contents.toString());
file.contents = new Buffer(parsed.content);
return parsed.data;
} | javascript | {
"resource": ""
} |
q33054 | lazyBuildObjectTree | train | function lazyBuildObjectTree(priv, formatted) {
definePropertyGetters(formatted, {
children: lazy(function() { return priv.fqnMap.getChildrenOf(formatted.fqn); }),
fields: lazy(function() { return formatted.children.filter(Filter.ofType('property')); }),
methods: lazy(function() { return formatted.children.filter(Filter.ofType('function')); }),
parent: lazy(function() { return priv.fqnMap.getParentOf(formatted.fqn); }),
parentElement: lazy(function() { return priv.fqnMap.get(formatted.idTags['parent-element']); }),
});
} | javascript | {
"resource": ""
} |
q33055 | toGithubHash | train | function toGithubHash(title) {
var GITHUB_ILLEGAL = new RegExp('[\\[\\]{}()<>^$#@!%&*+\/\\|~`"\':;,.]', 'g');
return title.toLowerCase().replace(/ /g, '-').replace(GITHUB_ILLEGAL, '');
} | javascript | {
"resource": ""
} |
q33056 | bindableProperty | train | function bindableProperty(target, key) {
// property value
var _val = this[key];
var keyName = "_" + key;
this[keyName] = _val;
// property getter
var getter = function () {
// console.log(`Get: ${key} => ${_val}`);
return this[keyName];
};
// property setter
var setter = function (newVal) {
// console.log(`Set: ${key} => ${newVal}`);
// debugger;
var oldValue = this[keyName];
// tslint:disable-next-line:triple-equals
if (oldValue == newVal) {
return;
}
this[keyName] = newVal;
var c = this._$_supressRefresh;
if (!(c && c[key])) {
Atom.refresh(this, key);
}
if (this.onPropertyChanged) {
this.onPropertyChanged(key);
}
};
// delete property
if (delete this[key]) {
// create new property with getter and setter
Object.defineProperty(target, key, {
get: getter,
set: setter,
enumerable: true,
configurable: true
});
// tslint:disable-next-line:no-string-literal
if (target.constructor.prototype["get_atomParent"]) {
target["get_" + key] = getter;
target["set_" + key] = setter;
}
}
} | javascript | {
"resource": ""
} |
q33057 | AtomWatcher | train | function AtomWatcher(target, path, runAfterSetup, forValidation) {
var _this = this;
this._isExecuting = false;
this.target = target;
var e = false;
if (forValidation === true) {
this.forValidation = true;
}
if (path instanceof Function) {
var f = path;
path = parsePath(path);
e = true;
this.func = f;
this.funcText = f.toString();
}
this.runEvaluate = function () {
_this.evaluate();
};
this.runEvaluate.watcher = this;
this.path = path.map(function (x) { return x.split(".").map(function (y) { return new ObjectProperty(y); }); });
if (e) {
if (runAfterSetup) {
this.evaluate();
}
// else {
// // setup watcher...
// for(var p of this.path) {
// this.evaluatePath(this.target,p);
// }
// }
}
} | javascript | {
"resource": ""
} |
q33058 | train | function () {
return {
href: location.href,
hash: location.hash,
host: location.host,
hostName: location.hostname,
port: location.port,
protocol: location.protocol
};
} | javascript | {
"resource": ""
} | |
q33059 | previewfile | train | function previewfile(file) {
if (false && tests.filereader === true) {
var reader = new FileReader();
reader.onload = function (event) {
var image = new Image();
image.src = event.target.result;
image.width = 250; // a fake resize
holder.appendChild(image);
};
reader.readAsDataURL(file);
} else {
holder.innerHTML += '<p>Uploaded ' + file.name + ' ' + (file.size ? (file.size/1024|0) + 'K' : '');
// console.log(file);
}
} | javascript | {
"resource": ""
} |
q33060 | handleExit | train | function handleExit (canCancel, signal, code) {
var i = 0,
sub;
while ((sub = subs[i++])) {
if (sub[0].call(sub[1], canCancel, signal, code) === false && canCancel) {
return;
}
}
if (canCancel) {
process.exit(code);
}
} | javascript | {
"resource": ""
} |
q33061 | exitHook | train | function exitHook (context, func) {
if (!func) {
func = context;
context = func;
}
if (typeof func === 'function') {
subs.push([func, context])
}
return exitHook;
} | javascript | {
"resource": ""
} |
q33062 | SendMessage | train | function SendMessage (auth, apiVersion) {
if (!(this instanceof SendMessage)) return new SendMessage(auth, apiVersion)
this._noopCallback = function () {}
this._headers = {
'Accept': 'application/json',
'Authorization': 'Basic ' + auth.basicAuth
}
this.versionNumber = apiVersion || 'v3'
this.lastQueryTime = 0
this.setContextPath()
} | javascript | {
"resource": ""
} |
q33063 | Init | train | function Init(appGlobal, pathsList) {
debug("Initializing Boot");
loadFinder = new Finder();
loadProvider = new Provider();
loadNamespace = new Namespace();
global = appGlobal;
global.App = {};
global.Modules = {};
global.Config = {};
this.initProviders(sortProvider);
this.initApplication();
this.initModules();
var mainApp = require("../express");
this.boot(mainApp);
mainApp.boot = function (nameProvider, userApp) {
debug("Booting Manual Provider");
loadProvider.bootProvider(nameProvider, userApp ? userApp : mainApp);
};
mainApp.provider = function (nameProvider) {
debug("Getting " + nameProvider + " Provider");
return loadProvider.providerByName(nameProvider).instance;
};
return mainApp;
} | javascript | {
"resource": ""
} |
q33064 | assign | train | function assign( destination ) {
destination = destination || {};
for ( let i = 1, len = arguments.length; i < len; i++ ) {
const source = arguments[i] || {};
for ( const key in source ) {
if ( Object.prototype.hasOwnProperty.call( source, key ) ) {
const value = source[key];
if ( _isPlainObject( value ) ) {
assign( destination[key] || ( destination[key] = {} ), value );
} else {
destination[key] = value;
}
}
}
}
return destination;
} | javascript | {
"resource": ""
} |
q33065 | train | function(dbg, raFn, subName, g, name, argv_, context, outerCallback, callback) {
var argv = _.extend({}, argv_);
g[name] = {};
return raFn(argv, context, function(err, result_) {
if (err) { return sg.die(err, outerCallback, 'fetching '+name); }
var result = subName ? result_[subName] : result_;
if (_.isArray(result)) {
g[name] = [];
_.each(result, function(value) {
g[name].push(value);
});
} else {
_.each(result, function(value, key) {
g[name][key] = value;
});
}
// Get from prod
var argv2 = _.extend({}, argv_, jsaws.getAcct('pub', process.env.JSAWS_AWS_ACCT_EXTRA_CREDS), {session:'prod'});
return raFn(argv2, context, function(err, result_) {
if (err) { return sg.die(err, outerCallback, 'fetching '+name); }
var result = subName ? result_[subName] : result_;
if (_.isArray(result)) {
_.each(result, function(value) {
g[name].push(value);
});
} else {
_.each(result, function(value, key) {
g[name][key] = value;
});
}
return callback.apply(this, arguments);
});
});
} | javascript | {
"resource": ""
} | |
q33066 | getUserdata0_ | train | function getUserdata0_(username, upNamespace, envVars_, origUsername) {
var envVars = cleanEnvVars(upNamespace, envVars_);
var script = [
"#!/bin/bash -ex",
format("if ! [ -d /home/%s ]; then", username),
format(" usermod -l %s %s", username, origUsername),
format(" groupmod -n %s %s", username, origUsername),
format(" usermod -d /home/%s -m %s", username, username),
"fi",
format("if [ -f /etc/sudoers.d/90-cloudimg-%s ]; then", origUsername),
format(" mv /etc/sudoers.d/90-cloudimg-%s /etc/sudoers.d/90-cloud-init-users", origUsername),
"fi",
format("perl -pi -e 's/%s/%s/g;' /etc/sudoers.d/90-cloud-init-users", origUsername, username),
"if ! grep `hostname` /etc/hosts; then",
" echo \"127.0.0.1 `hostname`\" | sudo tee -a /etc/hosts",
"fi",
""
];
_.each(envVars, function(value, key) {
script.push("echo "+key+"="+value+" | sudo tee -a /etc/environment");
});
script.push( "");
console.error(script);
return script;
} | javascript | {
"resource": ""
} |
q33067 | getUserdataForAmi_ | train | function getUserdataForAmi_(username, upNamespace, envVars_, origUsername) {
var envVars = cleanEnvVars(upNamespace, envVars_);
var script = [
"#!/bin/bash -ex",
""
];
_.each(envVars, function(value, key) {
script.push("/usr/local/bin/yoshi-set-env "+key+" "+value);
});
script.push( "");
console.error(script);
return script;
} | javascript | {
"resource": ""
} |
q33068 | taggedAs | train | function taggedAs(taggedItem, name, namespace, namespaceEx) {
var tags = taggedItem.tags || taggedItem.Tags;
if (!namespace) { return /* undefined */; }
if (!tags) { return /* undefined */; }
// The new, improved way (item.namespace=foo && item[name]=value)
if (tags.namespace === namespace) {
if (name in tags) { return tags[name]; }
}
if (tags[namespace] && (name in tags[namespace])) { return tags[namespace][name]; }
if (!namespaceEx) { return /* undefined */; }
if (tags[namespaceEx] && (name in tags[namespaceEx])) { return tags[namespaceEx][name]; }
return /* undefined */;
} | javascript | {
"resource": ""
} |
q33069 | isTaggedAs | train | function isTaggedAs(taggedItem, name, value, namespace, namespaceEx) {
return taggedAs(taggedItem, name, namespace, namespaceEx) == value; // == is intentional
} | javascript | {
"resource": ""
} |
q33070 | createWritable | train | function createWritable() {
var $args = arguments;return new Promise(function ($return, $error) {
var file, ws;
file = $args.length > 0 && $args[0] !== undefined ? $args[0] : getTempFile();
return Promise.resolve(openFileForWrite(file)).then(function ($await_2) {
try {
ws = $await_2;
return $return(ws);
} catch ($boundEx) {
return $error($boundEx);
}
}.bind(this), $error);
}.bind(this));
} | javascript | {
"resource": ""
} |
q33071 | list | train | function list(params, cb) {
var resourcePath = config.addURIParams(constants.FORMS_BASE_PATH + "/submissions", params);
var method = "GET";
var data = {};
params.resourcePath = resourcePath;
params.method = method;
params.data = data;
mbaasRequest.admin(params, cb);
} | javascript | {
"resource": ""
} |
q33072 | updateFile | train | function updateFile(params, cb) {
var resourcePath = config.addURIParams(constants.FORMS_BASE_PATH + "/submissions/:id/fields/:fieldId/files/:fileId", params);
var method = "PUT";
var data = params.fileDetails;
params.resourcePath = resourcePath;
params.method = method;
params.data = data;
params.fileRequest = true;
params.fileUploadRequest = true;
mbaasRequest.admin(params, cb);
} | javascript | {
"resource": ""
} |
q33073 | filterSubmissions | train | function filterSubmissions(params, cb) {
params.resourcePath = config.addURIParams(constants.FORMS_BASE_PATH + "/submissions/filter", params);
params.method = "POST";
params.data = params.filterParams;
mbaasRequest.admin(params, cb);
} | javascript | {
"resource": ""
} |
q33074 | getSubmissionPDF | train | function getSubmissionPDF(params, cb) {
var resourcePath = config.addURIParams(constants.FORMS_BASE_PATH + "/submissions/:id/exportpdf", params);
var method = "POST";
params.resourcePath = resourcePath;
params.method = method;
params.data = params.data || {};
params.fileRequest = true;
mbaasRequest.admin(params, cb);
} | javascript | {
"resource": ""
} |
q33075 | train | function(key,options){
this.key = key;
var route = "",
dayroute = "",
timeroute = "",
debug = false;
if (!this.key || this.key == "" || this.key == "<YOU-API-KEY>") {
throw new Error('MTA API key missing or incorrect.');
}
if (options.debug){
debug = options.debug;
}
if (options.from.id && options.to.id) {
route = options.from.id + "/" + options.to.id;
}else{
throw new Error('You forgot to provide an origin or a destiny.');
}
//date part
if (options.day >= UTILS.nowDate()) {
let dayParts= options.day.split("-");
dayroute = dayParts[0] + "/" + dayParts[1] + "/" + dayParts[2];
} else {
let dayParts= UTILS.nowDate().split("-");
dayroute = dayParts[0] + "/" + dayParts[1] + "/" + dayParts[2];
}
//time part
if (options.time >= UTILS.nowTime) {
timeroute = options.time.replace(/:/g, '');
} else {
timeroute = UTILS.nowTime().replace(/:/g, '');
}
let json_req_url = API_URL + "/" + API_VER + "/" + route + "/DepartBy/" + dayroute + "/" + timeroute + "/" + this.key + "/" + API_FILE;
return new Promise(function (resolve, reject) {
if(debug==true){
resolve(json_req_url);
}else{
FETCH(json_req_url)
.then(
data => resolve(data.json())
).catch(
err => reject("Error: Unable to parse response as JSON: " + err.message)
);
}
});
} | javascript | {
"resource": ""
} | |
q33076 | transformObject | train | function transformObject (type) {
const transformed = {}
for (let key in type) {
transformed[key] = transformType(type[key])
}
return transformed
} | javascript | {
"resource": ""
} |
q33077 | findType | train | function findType (type) {
let name = ''
const defaultTypes = [
'string',
'number',
'boolean',
'symbol',
'array',
'object'
]
try {
name = type.prototype.constructor.name.toLowerCase()
} catch (err) {}
if (defaultTypes.includes(name)) {
return types[name]()
}
return value => {
if (!(value instanceof type)) {
throw new Error(`is not instance of ${type.prototype.constructor.name}`)
}
return true
}
} | javascript | {
"resource": ""
} |
q33078 | step | train | function step(err, res) {
if (!err && res && res.error) {
console.log('ERR', res);
err = res.error;
}
var nextStep = steps.shift();
if (err && curStep !== 'delIndex') {
console.log('failing on', curStep, err);
console.trace();
callback(err);
return;
}
if (nextStep) {
curStep = nextStep;
var data = stepDefs[curStep].data;
utils.doPostJson(stepDefs[curStep], data, step);
} else {
callback(err, res);
}
} | javascript | {
"resource": ""
} |
q33079 | addURIParams | train | function addURIParams(uri, params) {
uri = uri || "";
params = params || {};
params = _.clone(params);
var keys = _.keys(params);
var separatedPath = uri.split("/");
separatedPath = _.compact(separatedPath);
//Replacing Any Path Elements
separatedPath = _.map(separatedPath, function(pathEntry) {
if (pathEntry.indexOf(":") !== 0) {
return pathEntry;
}
var key = _.find(keys, function(key) {
return (":" + key) === pathEntry;
});
if (key) {
return params[key];
} else {
return {
key: pathEntry.substring(1, pathEntry.length),
error: constants.PROPERTY_NOT_SET
};
}
});
//If the path contains an invalid parameter, return the error object
var invalidParameter = _.findWhere(separatedPath, {error: constants.PROPERTY_NOT_SET});
if (invalidParameter) {
return invalidParameter;
}
var fullPath = "";
_.each(separatedPath, function(pathElem) {
return fullPath += "/" + pathElem;
});
return fullPath;
} | javascript | {
"resource": ""
} |
q33080 | cleanDoclets | train | function cleanDoclets(desc) {
var idx = desc.indexOf('@');
return (idx === -1 ? desc : desc.substr(0, idx)).trim();
} | javascript | {
"resource": ""
} |
q33081 | addDataRequest | train | function addDataRequest(requestDict){
logger.info('Adding request to server');
const dataRequest = _getServerRequest(requestDict);
_addRequestToDb(dataRequest).then(() => {
if (!requestingPost){
_makeRequestToServer();
}
});
} | javascript | {
"resource": ""
} |
q33082 | train | function (bestCaseHours, mostLikelyCaseHours, worstCaseHours, confidencePercent) {
var isVector = (typeof bestCaseHours === 'object')
this.bestCaseHours = isVector ? bestCaseHours[0] : bestCaseHours
this.mostLikelyCaseHours = isVector ? bestCaseHours[1] : mostLikelyCaseHours
this.worstCaseHours = isVector ? bestCaseHours[2] : worstCaseHours
this.confidencePercent = isVector ? bestCaseHours[3] : confidencePercent
} | javascript | {
"resource": ""
} | |
q33083 | createUpdater | train | function createUpdater(actionUpdates) {
if (process.env.NODE_ENV !== 'production') {
// Ensure that all values are functions
Object.getOwnPropertySymbols(actionUpdates).concat(Object.keys(actionUpdates))
.filter(k => typeof actionUpdates[k] !== 'function')
.forEach(k => { throw new Error(`Expected a ((state, payload) => state) function for action '${k.toString()}' but found '${actionUpdates[k].toString()}'`); });
}
// If we have this action as a key, call it's value to update state, otherwise
// pass through the state.
return (state, action, payload) =>
actionUpdates[action] ? actionUpdates[action](state, payload) : state;
} | javascript | {
"resource": ""
} |
q33084 | dispatch | train | function dispatch(action, payload) {
if (process.env.NODE_ENV !== 'production' && dispatching) {
throw new Error(`'${action.toString()}' was dispatched while '${dispatching.toString()}' was still updating. Updaters should be pure functions and must not dispatch actions.`);
}
try {
dispatching = action;
state = updater(state, action, payload);
if (process.env.NODE_ENV !== 'production' && debug) {
console.info(state);
}
} finally {
dispatching = null;
}
updateUI();
} | javascript | {
"resource": ""
} |
q33085 | Bundle | train | function Bundle(transform, req, res) {
this.status = res.__status || 200;
this.body = res.__body || {};
this.apiMethod = res.__apiMethod;
this.apiInstanceMethod = res.__apiInstanceMethod;
this.apiStaticMethod = res.__apiStaticMethod;
this.api = res.__api;
this.modelAPI = res.__modelAPI;
if (this.modelAPI) {
this.model = this.modelAPI.model.modelName;
}
transform.call(this, req, res);
} | javascript | {
"resource": ""
} |
q33086 | transformResponse | train | function transformResponse(transform) {
assert.ok(transform);
assert.ok(transform instanceof Function);
var originalStatus, originalJson, reqClosure;
return function (req, res, next) {
originalStatus = res.status;
originalJson = res.json;
reqClosure = req;
res.status = setStatus;
res.json = sendJson;
return next();
}
function setStatus(status) {
this.__status = status;
return this;
}
function sendJson(body) {
this.__body = body;
var B = new Bundle(transform, reqClosure, this);
originalStatus.call(this, B.status);
return originalJson.call(this, B.body);
}
} | javascript | {
"resource": ""
} |
q33087 | train | function() {
// Construimos los atributos en base a la localización
var attr = Public.unbuild(this._attributes, this.location);
// Si no se encuentra disponible la instancia localización
if (!(this.location instanceof Public))
// La dirección será externa si tiene definido el atributo `protocol` o `host`
return (attr.protocol || attr.host) ? true : false;
// La URL será externa si `protocol` o `host` no coincide con el de localización
return (this.location.attr('protocol') !== attr.protocol || this.location.attr('host') !== attr.host);
} | javascript | {
"resource": ""
} | |
q33088 | train | function() {
var attr = Public.attributes.slice(0),
argv = [].slice.apply(arguments),
buffer = {},
x = argv.length,
y = attr.length;
// Convertimos la matriz de argumentos a objeto
while (x--)
buffer[_toString(argv[x]).toLowerCase()] = 1;
// Si se desea eliminar el atributo `hostname` o `port`
if (buffer.hostname || buffer.port) {
// Eliminamos el atributo `host`, ya que contiene a ambos
buffer.host = 1;
// Si se desea eliminar el atributo `host`
} else if (buffer.host) {
// Eliminamos el atributo `hostname` y `port`, ya que contiene a ambos
buffer.hostname = 1;
buffer.port = 1;
}
// Recorremos los atributos
while (y--)
// Si se encuentra en la lista
if (buffer[attr[y]])
// Lo eliminamos
attr.splice(y, 1);
return _prototypeSelect.apply(this, [attr]);
} | javascript | {
"resource": ""
} | |
q33089 | _isElement | train | function _isElement(input) {
return (typeof HTMLElement === 'function') ?
(input instanceof HTMLElement) :
(input && typeof input === 'object' && input.nodeType === 1 && typeof input.nodeName === 'string');
} | javascript | {
"resource": ""
} |
q33090 | cobble | train | function cobble(){
var args = [], last;
for(var i = 0; i < arguments.length; ++i) {
last = arguments[i];
if( isArray(last) ) args = args.concat(last)
else args[args.length] = last
}
return cobble.into({}, args)
} | javascript | {
"resource": ""
} |
q33091 | LodeRactive | train | function LodeRactive( options ) {
if ( typeof Ractive === 'undefined' ) throw Error('Couldn\'t find an instance of Ractive, you need to have it in order to use this framework.');
if ( options && typeof options.DEBUG !== 'undefined') Ractive.DEBUG = options.DEBUG;
this.router = new Router( options );
} | javascript | {
"resource": ""
} |
q33092 | parent | train | function parent(/*selector*/) {
var arr = [], $ = this.air, slice = this.slice;
this.each(function(el) {
arr = arr.concat(slice.call($(el.parentNode).dom));
});
return $(arr);
} | javascript | {
"resource": ""
} |
q33093 | inspect | train | function inspect(options){
options = normalize(options);
return function(files, metalsmith, done) {
if (options.disable)
return done();
//try {
var bigJSObject = {};
if (options.includeMetalsmith) {
bigJSObject[options.includeMetalsmith] = metalsmith.metadata();
}
Object.keys(files).forEach(function(filePath){
var inData = files[filePath];
if (options.fileFilter(filePath, inData, metalsmith)) {
var outData = {};
Object.keys(inData).forEach(function(key) {
if (options.accept(key, inData)) {
outData[key] = inData[key];
}
});
if (!options.contentsAsBuffer && outData.contents)
outData.contents = inData.contents.toString();
bigJSObject[filePath] = outData;
}
});
options.printfn(bigJSObject);
done();
// }
// catch (err) {
// done(err);
// }
};
/**
* Normalize an `options` dictionary.
*
* @param {Object} options
*/
function normalize(options){
options = options || {};
options.printfn = options.printfn || function(obj) {
console.dir(obj, {colors: true});
};
if (!options.accept) {
if (options.include) {
options.accept = function(propKey) { return options.include.indexOf(propKey) >= 0; };
}
else if (options.exclude){
options.accept = function(propKey) { return options.exclude.indexOf(propKey) < 0; };
}
else {
options.accept = function() { return true; };
}
}
options.fileFilter = fileFilter(options.filter);
return options;
};
/* calculate file filter function */
function fileFilter(filter) {
if (filter) {
if (typeof filter === 'string') {
var regex = new RegExp(filter);
return function(filePath) { return regex.test(filePath); }
}
else if (filter instanceof RegExp)
return function(filePath) { return filter.test(filePath); }
else { // must be a function itself
return filter;
}
}
else // none, return "pass all"
return function() { return true; };
}
} | javascript | {
"resource": ""
} |
q33094 | normalize | train | function normalize(options){
options = options || {};
options.printfn = options.printfn || function(obj) {
console.dir(obj, {colors: true});
};
if (!options.accept) {
if (options.include) {
options.accept = function(propKey) { return options.include.indexOf(propKey) >= 0; };
}
else if (options.exclude){
options.accept = function(propKey) { return options.exclude.indexOf(propKey) < 0; };
}
else {
options.accept = function() { return true; };
}
}
options.fileFilter = fileFilter(options.filter);
return options;
} | javascript | {
"resource": ""
} |
q33095 | write | train | function write(s) {
var err
var args = Array.prototype.slice.call(arguments)
var cb = typeof args[args.length - 1] === 'function' ? args.pop() : null
var cbCounter = 1
if (writeToStdoutEnabled) {
cbCounter++
process.stdout.write(s, stdWr)
}
if (writeStream) {
cbCounter++
writeStream.write(s, wRes)
}
end()
function stdWr(e) {
if (e) {
if (!err) err = e
writeToStdoutEnabled = false
write('stdout error: ' + e.message)
self.emit('error', e)
}
end()
}
function wRes(e) {
if (e) {
if (!err) err = e
writeStream = false
write('stream error: ' + e.message)
self.emit('error', e)
}
end()
}
function end() {
if (!--cbCounter)
if (cb)
if (err) cb(err)
else cb()
}
} | javascript | {
"resource": ""
} |
q33096 | train | function(nm, modules, snooze) {
this.snooze = snooze;
if(nm === null || nm === undefined || nm.length < 1) {
throw new Error('Module name note defined.');
}
this.name = nm;
this.snoozeConfig = this.snooze.getConfig();
this.runs = [];
this.configs = [];
this.modules = modules || [];
this.EntityManager = new EntityManager(this, snooze);
this.importedModules = {};
this.importProcesses = [];
this.configPreprocessors = [];
// TODO: move this to a better location
var self = this;
this.EntityManager.defineReservedInjectable('$config', function() {
return self.getConfig();
});
this.EntityManager.defineReservedInjectable('$entityManager', function() {
return self.EntityManager;
});
} | javascript | {
"resource": ""
} | |
q33097 | train | function (content, properties) {
var lines = content.split(lineEndingRE);
lines = replaceProperties(lines, properties);
lines = replaceSymbols(lines);
return lines.join('\n');
} | javascript | {
"resource": ""
} | |
q33098 | replaceProperties | train | function replaceProperties (lines, properties) {
var filteredLines = [];
lines.forEach((line) => {
for (var prop in properties) {
line = expandReference(line, prop, properties[prop]);
}
filteredLines.push(line);
});
return filteredLines;
} | javascript | {
"resource": ""
} |
q33099 | once | train | function once(eventName, handler, context, args) {
this.on(eventName, handler, context, args, true);
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.