_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q11100
train
function(selector, all) { if (!this.querySelector) {bb.warn('Find should be used with DOM elements'); return;} return all && this.querySelectorAll(selector) || this.querySelector(selector); }
javascript
{ "resource": "" }
q11101
train
function(html, tag) { var el = document.createElement(tag || 'div'); el.innerHTML = html; return el; }
javascript
{ "resource": "" }
q11102
Paginator
train
function Paginator(options) { debug('initializing from <%s>', __filename); this.options = options || {}; this.footer = this.options.footer; if (typeof this.footer !== 'string') { this.footer = '(Move up and down to reveal more choices)'; } this.firstRender = true; this.lastIndex = 0; this.position = 0; }
javascript
{ "resource": "" }
q11103
getBinPath
train
function getBinPath(cmd, fn) { which(cmd, function(err, bin) { if (err) { return fn(err); } fs.exists(bin, function(exists) { if (!exists) { return fn(new Error(format( 'Expected file for `%s` does not exist at `%s`', cmd, bin))); } fn(null, bin); }); }); }
javascript
{ "resource": "" }
q11104
run
train
function run(cmd, args, opts, fn) { if (typeof opts === 'function') { fn = opts; opts = {}; } if (typeof args === 'function') { fn = args; args = []; opts = {}; } getBinPath(cmd, function(err, bin) { if (err) { return fn(err); } debug('running', { cmd: cmd, args: args }); var output = []; var proc = spawn(bin, args, opts); proc.stdout.on('data', function(buf) { buf.toString('utf-8').split('\n').map(function(line) { debug(' %s> %s', cmd, line); }); output.push(buf); }); proc.stderr.on('data', function(buf) { buf.toString('utf-8').split('\n').map(function(line) { debug(' %s> %s', cmd, line); }); output.push(buf); }); proc.on('exit', function(code) { if (code !== 0) { debug('command failed!', { cmd: cmd, bin: bin, args: args, opts: opts, code: code, output: Buffer.concat(output).toString('utf-8') }); fn(new Error('Command failed! ' + 'Please try again with debugging enabled.'), Buffer.concat(output).toString('utf-8')); return; } debug('completed! %j', { cmd: cmd, bin: bin, args: args, opts: opts, code: code }); fn(null, Buffer.concat(output).toString('utf-8')); }); }); }
javascript
{ "resource": "" }
q11105
bootstrap
train
function bootstrap(options, cb) { var adapters = options.adapters || {}; var connections = options.connections || {}; var collections = options.collections || {}; Object.keys(adapters).forEach(function(identity) { var def = adapters[identity]; // Make sure our adapter defs have `identity` properties def.identity = def.identity || identity; }); var extendedCollections = []; Object.keys(collections).forEach(function(identity) { var def = collections[identity]; // Make sure our collection defs have `identity` properties def.identity = def.identity || identity; // Fold object of collection definitions into an array // of extended Waterline collections. extendedCollections.push(Waterline.Collection.extend(def)); }); // Instantiate Waterline and load the already-extended // Waterline collections. var waterline = new Waterline(); extendedCollections.forEach(function(collection) { waterline.loadCollection(collection); }); // Initialize Waterline // (and tell it about our adapters) waterline.initialize({ adapters: adapters, connections: connections }, cb); return waterline; }
javascript
{ "resource": "" }
q11106
train
function (name) { return { name: name, component: { render: function render(h) { return h('div'); }, functional: true }, path: '/' + name.replace(/[^\w]/g, "-") }; }
javascript
{ "resource": "" }
q11107
normalizeModules
train
function normalizeModules(modules) { var normalized = {}; Object.keys(modules).forEach(function (key) { var module = modules[key]; // make sure each vuex module has all keys defined normalized[key] = { actions: module.actions || {}, getters: module.getters || {}, modules: module.modules ? normalizeModules(module.modules) : {}, mutations: module.mutations || {}, namespaced: module.namespaced || false, state: {} }; // make sure our state is a fresh object if (typeof module.state === 'function') { normalized[key].state = module.state(); } else if (_typeof(module.state) === 'object') { normalized[key].state = JSON.parse(JSON.stringify(module.state)); } }); return normalized; }
javascript
{ "resource": "" }
q11108
findModule
train
function findModule(store, namespace) { return namespace.split('/').reduce(function (obj, key) { // root modules will exist directly on the store if (obj && obj[key]) { return obj[key]; } // child stores will exist in a modules object if (obj && obj.modules && obj.modules[key]) { return obj.modules[key]; } // if we couldn't find the module, throw an error // istanbul ignore next throw new Error('Could not find module "' + namespace + '" in store.'); }, store); }
javascript
{ "resource": "" }
q11109
patchView
train
function patchView (ExpressView, opts) { var proto = ExpressView.prototype; function View (name, options) { options = options || {}; this.name = name; this.root = options.root; var engines = options.engines; this.defaultEngine = options.defaultEngine; var extensions = (typeof opts.extensions === 'function') ? opts.extensions() : opts.extensions; this.extensions = extensions; var ext = this.ext = extname(name, extensions); if (!ext && !this.defaultEngine) { throw Error('No default engine was specified and no extension was provided.'); } if (!ext) { name += (ext = this.ext = (this.defaultEngine[0] !== '.' ? '.' : '') + this.defaultEngine); } this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express); this.path = this.lookup(name); } View.prototype = proto; function extname (name, extensions) { if (Array.isArray(extensions) && extensions.length > 0) { var ext; for (var i = 0, l = extensions.length; i < l; i += 1) { ext = extensions[i]; if (typeof name === 'string' && name.indexOf(ext) !== -1) { return ext; } } } return PATH.extname(name); } // replace original with new our own proto.lookup = createLookup(proto.lookup, opts); return View; }
javascript
{ "resource": "" }
q11110
ValidationExtension
train
function ValidationExtension() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref$reject = _ref.reject, reject = _ref$reject === undefined ? false : _ref$reject; _classCallCheck(this, ValidationExtension); // Store configuration var _this = _possibleConstructorReturn(this, (ValidationExtension.__proto__ || Object.getPrototypeOf(ValidationExtension)).call(this, { onEntityInstantiate: true, onChangeDetected: true })); _this.rejectInvalidValues = reject; return _this; }
javascript
{ "resource": "" }
q11111
validateProperties
train
function validateProperties(entity, properties, changedPropertyName, changedPropertyValue, currentPropertyValue) { var _this2 = this; // Validate default property values _lodash2.default.forEach(properties, function (propertyConfiguration, propertyName) { if (isValidationProperty(propertyConfiguration)) { // Run validation function var validatedValue = propertyName !== changedPropertyName ? entity[propertyName] : changedPropertyValue, resetValue = propertyName !== changedPropertyName ? null : currentPropertyValue, validation = propertyConfiguration.validate(validatedValue, entity); // Check if validation successful if (validation === undefined) { // Reset validation error delete entity.validation[propertyName]; } else { // Store validation error entity.validation[propertyName] = new ValidationOutput({ property: propertyName, value: validatedValue, message: validation }); // If rejecting invalid values, reset value to current value if (_this2.rejectInvalidValues) { // Unset default value (wrap into EnTTBypassEverythingValue to bypass validation and watchers) entity[propertyName] = new _properties.EnTTBypassEverythingValue(resetValue); } } } }); }
javascript
{ "resource": "" }
q11112
resolve
train
function resolve(opts, done) { debug('resolving paths for globs:\n', JSON.stringify(opts.globs)); var tasks = opts.globs.map(function(pattern) { return function(cb) { debug('resolving `%s`...', pattern); glob(pattern, {}, function(err, files) { if (err) { return cb(err); } debug('resolved %d file(s) for `%s`', files.length, pattern); if (files.length > 0) { opts.files.push.apply(opts.files, files); } cb(); }); }; }); async.parallel(tasks, function(err) { if (err) { return done(err); } debug('checking and removing duplicate paths...'); opts.files = unique(opts.files); debug('final result has `%d` files', opts.files.length); done(null, opts.files); }); }
javascript
{ "resource": "" }
q11113
getPropertyNamesInParentObjectExpression
train
function getPropertyNamesInParentObjectExpression(node) { var objectExpression = obj.get(node, "parent.parent"); var ret = []; if (!objectExpression) { return ret; } objectExpression.properties.forEach(function (p) { if (p.value !== node) { ret.push(p.key.name); } }); return ret; }
javascript
{ "resource": "" }
q11114
toServer
train
function toServer (router) { assert.equal(typeof router, 'function') const syms = getOwnSymbols(router) const sym = syms.length ? syms[0] : router._sym assert.ok(sym, 'router should be an instance of wayfarer') emit._subrouters = router._subrouters emit._routes = router._routes emit[sym] = true emit.emit = emit emit.on = on return emit // match a route and execute the corresponding callback // (obj, obj) -> null // original: {path, params parentDefault} function emit (route, req, res) { assert.equal(typeof route, 'string') assert.ok(req, 'no req specified') if (!req._ssa) { assert.ok(res, 'no res specified') } // handle server init if (isReq(req) && isRes(res)) { const ssa = createSsa({}, req, res) const dft = { node: { cb: [ router._default ] } } return router(route, ssa, dft) } // handle subrouter const params = req const parentDefault = res router(route, params, parentDefault) } // register a new route on a method // (str, obj) -> obj function on (route, methods) { assert.equal(typeof route, 'string') methods = methods || {} // mount subrouter if (methods[sym]) return router.on(route, methods) assert.equal(typeof methods, 'object') // mount http methods router.on(route, function (args) { demuxSsa(args, function (req, res, params) { const meth = methodist(req, defaultFn, methods) meth(req, res, params) // default function to call if methods don't match // null -> null function defaultFn () { router._default(args) } }) }) return emit } }
javascript
{ "resource": "" }
q11115
train
function(location, name) { this.location = location; this.name = name; if (this.isUrl(location)) { if (this.name) this.name = require('sanitize-filename')(this.name, {replacement: '_'}); if (typeof window === 'undefined') this.request = require('request').defaults({headers: {'User-Agent': 'limberest'}}); else this.request = require('browser-request'); } else { this.storage = new Storage(this.location, this.name); } this.path = this.location; if (this.name) this.path += '/' + this.name; }
javascript
{ "resource": "" }
q11116
train
function(opts, argv, error) { var parser = new Parser(opts, argv, error); return parser.parse(); }
javascript
{ "resource": "" }
q11117
PowerRadix
train
function PowerRadix (digits, sourceRadix) { sourceRadix = Array.isArray(sourceRadix) ? sourceRadix : B62.slice(0, sourceRadix); this._digits = Array.isArray(digits) ? digits : (digits+'').split(''); this._sourceRadixLength = new BigInt(sourceRadix.length+''); this._sourceRadixMap = sourceRadix.reduce(function (map, char, i) { map[char+''] = new BigInt(i+''); return map; }, {}); }
javascript
{ "resource": "" }
q11118
makeError
train
function makeError(code, message, data = {}) { const error = new Error(message); return Object.assign(error, {code, data}); }
javascript
{ "resource": "" }
q11119
getIssuerModule
train
function getIssuerModule(parent) { let issuer = parent; while (issuer && (issuer.id === '[eval]' || issuer.id === '<repl>' || !issuer.filename)) { issuer = issuer.parent; } return issuer; }
javascript
{ "resource": "" }
q11120
applyNodeExtensionResolution
train
function applyNodeExtensionResolution(unqualifiedPath, {extensions}) { // We use this "infinite while" so that we can restart the process as long as we hit package folders while (true) { let stat; try { stat = statSync(unqualifiedPath); } catch (error) {} // If the file exists and is a file, we can stop right there if (stat && !stat.isDirectory()) { // If the very last component of the resolved path is a symlink to a file, we then resolve it to a file. We only // do this first the last component, and not the rest of the path! This allows us to support the case of bin // symlinks, where a symlink in "/xyz/pkg-name/.bin/bin-name" will point somewhere else (like "/xyz/pkg-name/index.js"). // In such a case, we want relative requires to be resolved relative to "/xyz/pkg-name/" rather than "/xyz/pkg-name/.bin/". // // Also note that the reason we must use readlink on the last component (instead of realpath on the whole path) // is that we must preserve the other symlinks, in particular those used by pnp to deambiguate packages using // peer dependencies. For example, "/xyz/.pnp/local/pnp-01234569/.bin/bin-name" should see its relative requires // be resolved relative to "/xyz/.pnp/local/pnp-0123456789/" rather than "/xyz/pkg-with-peers/", because otherwise // we would lose the information that would tell us what are the dependencies of pkg-with-peers relative to its // ancestors. if (lstatSync(unqualifiedPath).isSymbolicLink()) { unqualifiedPath = path.normalize(path.resolve(path.dirname(unqualifiedPath), readlinkSync(unqualifiedPath))); } return unqualifiedPath; } // If the file is a directory, we must check if it contains a package.json with a "main" entry if (stat && stat.isDirectory()) { let pkgJson; try { pkgJson = JSON.parse(readFileSync(`${unqualifiedPath}/package.json`, 'utf-8')); } catch (error) {} let nextUnqualifiedPath; if (pkgJson && pkgJson.main) { nextUnqualifiedPath = path.resolve(unqualifiedPath, pkgJson.main); } // If the "main" field changed the path, we start again from this new location if (nextUnqualifiedPath && nextUnqualifiedPath !== unqualifiedPath) { const resolution = applyNodeExtensionResolution(nextUnqualifiedPath, {extensions}); if (resolution !== null) { return resolution; } } } // Otherwise we check if we find a file that match one of the supported extensions const qualifiedPath = extensions .map(extension => { return `${unqualifiedPath}${extension}`; }) .find(candidateFile => { return existsSync(candidateFile); }); if (qualifiedPath) { return qualifiedPath; } // Otherwise, we check if the path is a folder - in such a case, we try to use its index if (stat && stat.isDirectory()) { const indexPath = extensions .map(extension => { return `${unqualifiedPath}/index${extension}`; }) .find(candidateFile => { return existsSync(candidateFile); }); if (indexPath) { return indexPath; } } // Otherwise there's nothing else we can do :( return null; } }
javascript
{ "resource": "" }
q11121
normalizePath
train
function normalizePath(fsPath) { fsPath = path.normalize(fsPath); if (process.platform === 'win32') { fsPath = fsPath.replace(backwardSlashRegExp, '/'); } return fsPath; }
javascript
{ "resource": "" }
q11122
cleanupArray
train
function cleanupArray(obj, name) { var arr = obj[name]; if (!arr) throw new Error(name + ' option is missing'); if (Array.isArray(arr)) { arr = arr.join(','); } if (typeof arr !== 'string') throw new Error(name + ' option must be an Array or a comma separated String'); arr = arr.replace(/_/g, '-').replace(/\s/g, '').toLowerCase().split(','); return arr; }
javascript
{ "resource": "" }
q11123
matchLocale
train
function matchLocale(locale) { var found = false; if (!locale) return false; locale = locale.replace(/_/g, '-').toLowerCase(); if (localesLookup[locale]) return localesLookup[locale]; if (options.matchSubTags) { while (~locale.indexOf('-')) { var index = locale.lastIndexOf('-'); locale = locale.substring(0, index); if (localesLookup[locale]) { found = localesLookup[locale]; break; } } } return found; }
javascript
{ "resource": "" }
q11124
BindableCollection
train
function BindableCollection (source) { BindableObject.call(this, this); this.source = source || []; this._updateInfo(); this.bind("source", _.bind(this._onSourceChange, this)); }
javascript
{ "resource": "" }
q11125
train
function () { var items = Array.prototype.slice.call(arguments); this.source.push.apply(this.source, items); this._updateInfo(); // DEPRECATED this.emit("insert", items[0], this.length - 1); this.emit("update", { insert: items, index: this.length - 1}); }
javascript
{ "resource": "" }
q11126
train
function () { var items = Array.prototype.slice.call(arguments); this.source.unshift.apply(this.source, items); this._updateInfo(); // DEPRECATED this.emit("insert", items[0], 0); this.emit("update", { insert: items }); }
javascript
{ "resource": "" }
q11127
train
function (index, count) { var newItems = Array.prototype.slice.call(arguments, 2), oldItems = this.source.splice.apply(this.source, arguments); this._updateInfo(); // DEPRECATED this.emit("replace", newItems, oldItems, index); this.emit("update", { insert: newItems, remove: oldItems }); }
javascript
{ "resource": "" }
q11128
train
function (item) { var i = this.indexOf(item); if (!~i) return false; this.source.splice(i, 1); this._updateInfo(); this.emit("remove", item, i); this.emit("update", { remove: [item] }); return item; }
javascript
{ "resource": "" }
q11129
paperLoadedInit
train
function paperLoadedInit() { console.log('Paper ready!'); // Set center adjusters based on size of canvas $('#hcenter').attr({ value: 0, min: -(robopaint.canvas.width / 2), max: robopaint.canvas.width / 2 }); $('#vcenter').attr({ value: 0, min: -(robopaint.canvas.height / 2), max: robopaint.canvas.height / 2 }); $(window).resize(); // Use mode settings management on all "managed" class items. This // saves/loads settings from/into the elements on change/init. mode.settings.$manage('.managed'); // With Paper ready, send a single up to fill values for buffer & pen. mode.run('up'); }
javascript
{ "resource": "" }
q11130
fileAppender
train
function fileAppender(config, layout) { const appender = new FileAppender(config, layout); // push file to the stack of open handlers appenderList.push(appender); return appender.write; }
javascript
{ "resource": "" }
q11131
train
function (widgets) { if (!this.storage) { return true; } var serialized = _.map(widgets, function (widget) { var widgetObject = { title: widget.title, name: widget.name, style: widget.style, dataModelOptions: widget.dataModelOptions, storageHash: widget.storageHash, attrs: widget.attrs }; return widgetObject; }); var item = { widgets: serialized, hash: this.hash }; if (this.stringify) { item = JSON.stringify(item); } this.storage.setItem(this.id, item); return true; }
javascript
{ "resource": "" }
q11132
train
function () { if (!this.storage) { return null; } var serialized; // try loading storage item serialized = this.storage.getItem(this.id); if (serialized) { // check for promise if (typeof serialized === 'object' && typeof serialized.then === 'function') { return this._handleAsyncLoad(serialized); } // otherwise handle synchronous load return this._handleSyncLoad(serialized); } else { return null; } }
javascript
{ "resource": "" }
q11133
WidgetModel
train
function WidgetModel(Class, overrides) { var defaults = { title: 'Widget', name: Class.name, attrs: Class.attrs, dataAttrName: Class.dataAttrName, dataModelType: Class.dataModelType, dataModelArgs: Class.dataModelArgs, // used in data model constructor, not serialized //AW Need deep copy of options to support widget options editing dataModelOptions: Class.dataModelOptions, settingsModalOptions: Class.settingsModalOptions, onSettingsClose: Class.onSettingsClose, onSettingsDismiss: Class.onSettingsDismiss, style: Class.style }; overrides = overrides || {}; angular.extend(this, angular.copy(defaults), overrides); this.style = this.style || { width: '33%' }; this.setWidth(this.style.width); if (Class.templateUrl) { this.templateUrl = Class.templateUrl; } else if (Class.template) { this.template = Class.template; } else { var directive = Class.directive || Class.name; this.directive = directive; } }
javascript
{ "resource": "" }
q11134
train
function (e) { var curX = e.clientX; var pixelChange = curX - initX; var newWidth = pixelWidth + pixelChange; $marquee.css('width', newWidth + 'px'); }
javascript
{ "resource": "" }
q11135
train
function (e) { // remove listener and marquee jQuery($window).off('mousemove', mousemove); $marquee.remove(); // calculate change in units var curX = e.clientX; var pixelChange = curX - initX; var unitChange = Math.round(pixelChange * transformMultiplier * 100) / 100; // add to initial unit width var newWidth = unitWidth * 1 + unitChange; widget.setWidth(newWidth + widthUnits); $scope.$emit('widgetChanged', widget); $scope.$apply(); }
javascript
{ "resource": "" }
q11136
onMouseMove
train
function onMouseMove(event) { project.deselectAll(); if (event.item) { event.item.selected = true; } }
javascript
{ "resource": "" }
q11137
Stack
train
function Stack(trace, options) { if (!(this instanceof Stack)) return new Stack(trace, options); if ('object' === typeof trace && !trace.length) { options = trace; trace = null; } options = options || {}; options.guess = 'guess' in options ? options.guess : true; if (!trace) { var imp = new stacktrace.implementation() , err = options.error || options.err || options.e , traced; traced = imp.run(err); trace = options.guess ? imp.guessAnonymousFunctions(traced) : traced; } this.traces = this.parse(trace); }
javascript
{ "resource": "" }
q11138
traceFromNode
train
function traceFromNode(name) { const job = { node: name, isValid: true }; invalidatePendingJobsForNode(pendingJobs, name); // Ensure the job can be tracked pendingJobs.push(job); // Force an asynchronous start to the tracing so that other parts of a // codebase can synchronously trigger the job to be invalidated. This // helps to avoid any unnecessary work that may no longer be relevant process.nextTick(startTracingNode); if (!hasSignalledStart) { hasSignalledStart = true; events.emit('started', {state: state}); } function startTracingNode() { // Handle situations where a job may have been invalidated further // down the stack from where the original call originated from if (!job.isValid) { return; } getDependencies(name) .then(handleDependencies) .catch(handleError) .then(signalIfCompleted); function handleDependencies(dependencies) { // If this job has been invalidated, we can ignore anything that may // have resulted from it if (!job.isValid) { return; } // Indicate that this job is no longer blocking the `completed` stage pull(pendingJobs, job); // Sanity check if (!isArray(dependencies)) { return Promise.reject( new Error(`Dependencies should be specified in an array. Received ${dependencies}`) ); } const previousState = state; if (!isNodeDefined(state, name)) { state = addNode(state, name); } // If there are any dependencies encountered that we don't already // know about, we start tracing them dependencies.forEach(depName => { if ( !isNodeDefined(state, depName) && !isNodePending(pendingJobs, depName) ) { traceFromNode(depName); } if (!isNodeDefined(state, depName)) { state = addNode(state, depName); } state = addEdge(state, name, depName); }); // Enable progress updates events.emit('traced', { node: name, diff: Diff({ from: previousState, to: state }) }); } function handleError(err) { // Indicate that this job is no longer blocking the `completed` stage pull(pendingJobs, job); // If the job has been invalidated, we ignore the error if (!job.isValid) { return; } const signal = { error: err, node: name, state: state }; errors.push(signal); events.emit('error', signal); } } }
javascript
{ "resource": "" }
q11139
pruneNode
train
function pruneNode(name) { const previousState = state; // If the node is still pending, invalidate the associated job so // that it becomes a no-op if (isNodePending(pendingJobs, name)) { invalidatePendingJobsForNode(pendingJobs, name); } if (isNodeDefined(state, name)) { let updatedState = previousState; const node = updatedState.get(name); node.dependents.forEach(dependent => { updatedState = removeEdge(updatedState, dependent, name); }); node.dependencies.forEach(dependency => { updatedState = removeEdge(updatedState, name, dependency); }); updatedState = removeNode(updatedState, name); state = updatedState; } signalIfCompleted(); return Diff({ from: previousState, to: state }); }
javascript
{ "resource": "" }
q11140
pruneDisconnectedNodes
train
function pruneDisconnectedNodes() { const previousState = state; const disconnected = findNodesDisconnectedFromEntryNodes(state); let updatedState = previousState; disconnected.forEach(name => { if (updatedState.has(name)) { const data = pruneNodeAndUniqueDependencies(updatedState, name); updatedState = data.nodes; } }); state = updatedState; return Diff({ from: previousState, to: state }); }
javascript
{ "resource": "" }
q11141
setNodeAsEntry
train
function setNodeAsEntry(name) { const previousState = state; if (!isNodeDefined(state, name)) { state = addNode(state, name); } state = defineEntryNode(state, name); return Diff({ from: previousState, to: state }); }
javascript
{ "resource": "" }
q11142
processActionGroup
train
function processActionGroup(_ref2) { var _ref2$updateSchemaNam = _ref2.updateSchemaName, updateSchemaName = _ref2$updateSchemaNam === undefined ? undefined : _ref2$updateSchemaNam, _ref2$store = _ref2.store, store = _ref2$store === undefined ? _store : _ref2$store, _ref2$error = _ref2.error, error = _ref2$error === undefined ? {} : _ref2$error, _ref2$res = _ref2.res, res = _ref2$res === undefined ? {} : _ref2$res, _ref2$actionGroup = _ref2.actionGroup, actionGroup = _ref2$actionGroup === undefined ? {} : _ref2$actionGroup; if (actionGroup == undefined) return; var actionNames = Object.keys(actionGroup); actionNames.forEach(function (actionName) { var action = actionGroup[actionName]; // TODO: check for required fields: branch, location, operation, value || valueFunction, location || locationFunction // updateIn, update + updateIn, update // destructure action values used in processing var valueFunction = action.valueFunction, value = action.value, shouldDispatch = action.shouldDispatch, uiEventFunction = action.uiEventFunction, updateFunction = action.updateFunction, location = action.location, locationFunction = action.locationFunction, operation = action.operation; // create action to be processed var $action = {}; // update value $action.value = valueFunction ? valueFunction({ error: error, res: res, store: store, value: value }) : value; // update location $action.location = locationFunction ? locationFunction({ error: error, res: res, store: store, value: value }) : location; // add type $action.type = $action.location[0]; // trim first value from location $action.location = $action.location.slice(1); // add name $action.name = actionName; // add update function params $action.updateFunction = updateFunction ? updateFunction.bind(null, { res: res, error: error, store: store, fromJS: _immutable.fromJS, value: value }) : undefined; // add operation if ($action.updateFunction) { $action.operation = 'updateIn'; } else if (!$action.value) { $action.operation = 'deleteIn'; } else { $action.operation = 'setIn'; } // TODO: add meta information about the updateSchemaCreator // dispatch action depending on fire if (shouldDispatch == undefined || shouldDispatch({ error: error, res: res, store: store, value: value })) { // dispatch the action here store.dispatch($action); // fire ui event if (uiEventFunction) uiEventFunction({ action: action, value: value, res: res, error: error, store: store }); } }); }
javascript
{ "resource": "" }
q11143
train
function(year) { var date = this._validate(year, this.minMonth, this.minDay, $.calendars.local.invalidYear); year = date.year(); var baktun = Math.floor(year / 400); year = year % 400; year += (year < 0 ? 400 : 0); var katun = Math.floor(year / 20); return baktun + '.' + katun + '.' + (year % 20); }
javascript
{ "resource": "" }
q11144
train
function(years) { years = years.split('.'); if (years.length < 3) { throw 'Invalid Mayan year'; } var year = 0; for (var i = 0; i < years.length; i++) { var y = parseInt(years[i], 10); if (Math.abs(y) > 19 || (i > 0 && y < 0)) { throw 'Invalid Mayan year'; } year = year * 20 + y; } return year; }
javascript
{ "resource": "" }
q11145
train
function(year, month, day) { var date = this._validate(year, month, day, $.calendars.local.invalidDate); var jd = date.toJD(); var haab = this._toHaab(jd); var tzolkin = this._toTzolkin(jd); return {haabMonthName: this.local.haabMonths[haab[0] - 1], haabMonth: haab[0], haabDay: haab[1], tzolkinDayName: this.local.tzolkinMonths[tzolkin[0] - 1], tzolkinDay: tzolkin[0], tzolkinTrecena: tzolkin[1]}; }
javascript
{ "resource": "" }
q11146
train
function(jd) { jd -= this.jdEpoch; var day = mod(jd + 8 + ((18 - 1) * 20), 365); return [Math.floor(day / 20) + 1, mod(day, 20)]; }
javascript
{ "resource": "" }
q11147
train
function ( source, dest ) { var that = this; if ( source.nodeName.toUpperCase() === "TR" || source.nodeName.toUpperCase() === "TH" || source.nodeName.toUpperCase() === "TD" || source.nodeName.toUpperCase() === "SPAN" ) { dest.className = source.className; } $(source).children().each( function (i) { that._fnClassUpdate( $(source).children()[i], $(dest).children()[i] ); } ); }
javascript
{ "resource": "" }
q11148
train
function ( parent, original, clone ) { var that = this; var originals = $(parent +' tr', original); var height; $(parent+' tr', clone).each( function (k) { height = originals.eq( k ).css('height'); // This is nasty :-(. IE has a sub-pixel error even when setting // the height below (the Firefox fix) which causes the fixed column // to go out of alignment. Need to add a pixel before the assignment // Can this be feature detected? Not sure how... if ( navigator.appName == 'Microsoft Internet Explorer' ) { height = parseInt( height, 10 ) + 1; } $(this).css( 'height', height ); // For Firefox to work, we need to also set the height of the // original row, to the value that we read from it! Otherwise there // is a sub-pixel rounding error originals.eq( k ).css( 'height', height ); } ); }
javascript
{ "resource": "" }
q11149
getCollector
train
function getCollector() { var collector = new Collector(); if (global['__coverage__']) { collector.add(global['__coverage__']); } else { console.error('No global coverage found for the node process'); } return collector; }
javascript
{ "resource": "" }
q11150
template
train
function template(string, options, otherOptions) { // Based on John Resig's `tmpl` implementation (http://ejohn.org/blog/javascript-micro-templating/) // and Laura Doktorova's doT.js (https://github.com/olado/doT). const settings = templateSettings; if (otherOptions && isIterateeCall(string, options, otherOptions)) { options = otherOptions = undefined; } string = baseToString(string); options = extendWith({ ignore: reIgnore }, otherOptions || options, settings, extendDefaults); const imports = extendWith({}, options.imports, settings.imports, extendDefaults); const importsKeys = keys(imports); const importsValues = baseValues(imports, importsKeys); let isEscaping, isEvaluating; let index = 0; const interpolate = options.interpolate || reNoMatch; let source = ["__p[__p.length] = '"]; // Compile the regexp to match each delimiter. const reDelimiters = RegExp( (options.ignore || reNoMatch).source + "|" + (options.escape || reNoMatch).source + "|" + interpolate.source + "|" + (options.esInterpolate !== false && interpolate.source === reInterpolate.source ? reEsTemplate : reNoMatch).source + "|" + (options.evaluate || reNoMatch).source + "|$", "g"); // Use a sourceURL for easier debugging. const sourceURL = "//# sourceURL=" + ("sourceURL" in options ? options.sourceURL : "lodash.templateSources[" + ++templateCounter + "]") + "\n"; string.replace(reDelimiters, function(match, ignoreValue, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { if (!interpolateValue) { interpolateValue = esTemplateValue; } // Escape characters that can't be included in string literals. source.push(string.slice(index, offset).replace(reUnescapedString, escapeStringChar)); if (!ignoreValue) { // Replace delimiters with snippets. if (escapeValue) { isEscaping = true; source.push("' +\n__e(" + escapeValue + ") +\n'"); } if (evaluateValue) { isEvaluating = true; source.push("';\n" + evaluateValue + ";\n__p[__p.length] = '"); } if (interpolateValue) { source.push("' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"); } } index = offset + match.length; // The JS engine embedded in Adobe products requires returning the `match` // string in order to produce the correct `offset` value. return match; }); source.push("';\n"); source = source.join(""); // If `variable` is not specified wrap a with-statement around the generated // code to add the data object to the top of the scope chain. let variable = options.variable; if (variable == null) { source = "with (obj) {\n" + source + "\n}\n"; variable = "obj"; } // Cleanup code by stripping empty strings. source = isEvaluating ? source.replace(reEmptyStringLeading, "") : source; source = source.replace(reEmptyStringMiddle, "$1").replace(reEmptyStringTrailing, "$1;"); // Frame code as the function body. const declaration = options.async ? "async function" : "function"; source = declaration + "(" + variable + ") {\n" + "if (" + variable + " == null) { " + variable + " = {}; }\n" + "var __t, __p = []" + (isEscaping ? ", __e = _.escape" : "") + (isEvaluating ? ", __j = Array.prototype.join;\n" + "function print() { __p[__p.length] = __j.call(arguments, '') }\n" : ";\n" ) + source + "return __p.join(\"\")\n};"; const result = attempt(function() { // eslint-disable-next-line no-new-func return Function(importsKeys, sourceURL + "return " + source).apply(undefined, importsValues); }); // Provide the compiled function's source by its `toString` method or // the `source` property as a convenience for inlining compiled templates. result.source = source; if (isError(result)) { throw result; } return result; }
javascript
{ "resource": "" }
q11151
train
function(ctx, force, deep, collapsed){ // ctx.tree.debug("**** PROFILER nodeRender"); var s = this.options.prefix + "render '" + ctx.node + "'"; /*jshint expr:true */ window.console && window.console.time && window.console.time(s); this._super(ctx, force, deep, collapsed); window.console && window.console.timeEnd && window.console.timeEnd(s); }
javascript
{ "resource": "" }
q11152
createErrorType
train
function createErrorType(initialize = undefined, ErrorClass = undefined, prototype = undefined) { ErrorClass = ErrorClass || Error; let Constructor = function (message) { let error = Object.create(Constructor.prototype); error.message = message; error.stack = (new Error).stack; if (initialize) { initialize(error, message); } return error; }; Constructor.prototype = Object.assign(Object.create(ErrorClass.prototype), prototype); return Constructor; }
javascript
{ "resource": "" }
q11153
train
function(target, namespace, graph) { //if the first param is a string, //we are including the namespace on Sysmo if (typeof target == 'string') { graph = namespace; namespace = target; target = Sysmo; } //create namespace on target Sysmo.namespace(namespace, target); //get inner most object in namespace target = Sysmo.getDeepValue(target, namespace); //merge graph on inner most object in namespace return Sysmo.extend(target, graph); }
javascript
{ "resource": "" }
q11154
train
function(namespace, target) { target = target || {}; var names = namespace.split('.'), context = target; for (var i = 0; i < names.length; i++) { var name = names[i]; context = (name in context) ? context[name] : (context[name] = {}); } return target; }
javascript
{ "resource": "" }
q11155
train
function (target, path, traverseArrays) { // if traversing arrays is enabled and this is an array, loop // may be a "array-like" node list (or similar), in which case it needs to be converted if (traverseArrays && Sysmo.isArrayLike(target)) { target = Sysmo.makeArray(target); var children = []; for (var i = 0; i < target.length; i++) { // recursively loop through children var child = Sysmo.getDeepValue(target[i], path, traverseArrays); // ignore if undefined if (typeof child != "undefined") { //flatten array because the original path points to one flat result set if (Sysmo.isArray(child)) { for (var j = 0; j < child.length; j++) { children.push(child[j]); } } else { children.push(child); } } } return (children.length) ? children : void(0); } var invoke_regex = /\(\)$/, properties = path.split('.'), property; if (target != null && properties.length) { var propertyName = properties.shift(), invoke = invoke_regex.test(propertyName) if (invoke) { propertyName = propertyName.replace(invoke_regex, ""); } if (invoke && propertyName in target) { target = target[propertyName](); } else { target = target[propertyName]; } path = properties.join('.'); if (path) { target = Sysmo.getDeepValue(target, path, traverseArrays); } } return target; }
javascript
{ "resource": "" }
q11156
train
function () { var href = window.location.href, items = parsedItems(), id, index; // get window 'id' if (href.indexOf('#') > -1) { id = window.location.hash.replace('#', ''); } else { id = window.location.pathname.split('/').pop().replace(/\.[^/.]+$/, ''); } // In case the first menu item isn't the index page. if (id === '') { id = 'index'; } // find the window id in the items array index = (items.indexOf(id) > -1) ? items.indexOf(id) : 0; // set the matched item as active fabricator.dom.menuItems[index].classList.add('f-active'); }
javascript
{ "resource": "" }
q11157
sourceRootFn
train
function sourceRootFn (file) { let sourcePath = file.history[0], targetPath = path.join(__dirname, '../src/'), relativePath = path.join(path.relative(sourcePath, targetPath), './src'); return relativePath; }
javascript
{ "resource": "" }
q11158
DynamicPropertiesExtension
train
function DynamicPropertiesExtension() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref$deferred = _ref.deferred, deferred = _ref$deferred === undefined ? false : _ref$deferred; _classCallCheck(this, DynamicPropertiesExtension); return _possibleConstructorReturn(this, (DynamicPropertiesExtension.__proto__ || Object.getPrototypeOf(DynamicPropertiesExtension)).call(this, { processShorthandPropertyConfiguration: true, updatePropertyConfiguration: true, // If not deferred, regenerate dynamic property value on initialization and change detected onEntityInstantiate: !deferred, onChangeDetected: !deferred, // If deferred, regenerate dynamic property value on get interceptPropertyGet: deferred })); }
javascript
{ "resource": "" }
q11159
readFileAsync
train
async function readFileAsync(...args) { return new Promise((resolve, reject) => { fs.readFile(...args, (err, result) => { if (err) { reject(err); } else { resolve(result); } }); }); }
javascript
{ "resource": "" }
q11160
createLoggers
train
function createLoggers(ns) { var debug = (0, _debug2['default'])(ns + ':debug'); debug.log = function () { return console.log.apply(console, arguments); }; var log = (0, _debug2['default'])(ns + ':log'); log.log = function () { return console.log.apply(console, arguments); }; var info = (0, _debug2['default'])(ns + ':info'); info.log = function () { return console.info.apply(console, arguments); }; var warn = (0, _debug2['default'])(ns + ':warn'); warn.log = function () { return console.warn.apply(console, arguments); }; var error = (0, _debug2['default'])(ns + ':error'); error.log = function () { return console.error.apply(console, arguments); }; return { debug: debug, log: log, info: info, warn: warn, error: error }; }
javascript
{ "resource": "" }
q11161
BruteForceList
train
function BruteForceList(capacity) { this.intervals = pool.mallocDouble(2 * capacity) this.index = pool.mallocInt32(capacity) this.count = 0 }
javascript
{ "resource": "" }
q11162
chaiSupportChainPromise
train
function chaiSupportChainPromise(chai, utils){ function copyChainPromise(promise, assertion){ let protoPromise = Object.getPrototypeOf(promise); let protoNames = Object.getOwnPropertyNames(protoPromise); let protoAssertion = Object.getPrototypeOf(assertion); protoNames.forEach(function(protoName){ if(protoName !== 'constructor' && !protoAssertion[protoName]){ assertion[protoName] = promise[protoName].bind(promise); } }); } function doAsserterAsync(asserter, assertion, args){ let self = utils.flag(assertion, "object"); if(self && self.then && typeof self.then === "function"){ let promise = self.then(function(value){ assertion._obj = value; asserter.apply(assertion, args); return value; }, function(error){ assertion._obj = new Error(error); asserter.apply(assertion, args); }); copyChainPromise(promise, assertion); } else{ return asserter.apply(assertion, args); } } let Assertion = chai.Assertion; let propertyNames = Object.getOwnPropertyNames(Assertion.prototype); let propertyDescs = {}; propertyNames.forEach(function (name) { propertyDescs[name] = Object.getOwnPropertyDescriptor(Assertion.prototype, name); }); let methodNames = propertyNames.filter(function (name) { return name !== "assert" && typeof propertyDescs[name].value === "function"; }); methodNames.forEach(function (methodName) { Assertion.overwriteMethod(methodName, function (originalMethod) { return function () { doAsserterAsync(originalMethod, this, arguments); }; }); }); let getterNames = propertyNames.filter(function (name) { return name !== "_obj" && typeof propertyDescs[name].get === "function"; }); getterNames.forEach(function (getterName) { let isChainableMethod = Assertion.prototype.__methods.hasOwnProperty(getterName); if (isChainableMethod) { Assertion.overwriteChainableMethod( getterName, function (originalMethod) { return function() { doAsserterAsync(originalMethod, this, arguments); }; }, function (originalGetter) { return function() { doAsserterAsync(originalGetter, this); }; } ); } else { Assertion.overwriteProperty(getterName, function (originalGetter) { return function () { doAsserterAsync(originalGetter, this); }; }); } }); }
javascript
{ "resource": "" }
q11163
RemovePlugin
train
function RemovePlugin (ext_module_id) { let copy = plugins[ext_module_id] let runPreWorkflowFunctions = function () { if (!plugins[ext_module_id].PreRemovePlugin) throw new Error('Error: PreRemovePlugin function must be implemented.') plugins[ext_module_id].PreRemovePlugin() } let runPostWorkflowFunctions = function () { if (!copy.PostRemovePlugin) throw new Error('Error: PostRemovePlugin function must be implemented.') copy.PostRemovePlugin(module.exports) } runPreWorkflowFunctions() delete plugins[ext_module_id] log.info('Removed Plugin', ext_module_id) runPostWorkflowFunctions() return true }
javascript
{ "resource": "" }
q11164
_InternalAddEnvironment
train
function _InternalAddEnvironment (env = new ent.Environment()) { if (env instanceof ent.Environment) { em.SetEnvironment(env) return true } else { log.warning("'environment' object is not of type Environment") } return false }
javascript
{ "resource": "" }
q11165
AddDetectorToSubEnvironmentOnly
train
function AddDetectorToSubEnvironmentOnly (detector, force = false, subEnvironment) { return em.AddDetectorToSubEnvironmentOnly(detector, force, subEnvironment) }
javascript
{ "resource": "" }
q11166
RemoveNotifier
train
function RemoveNotifier (notifier, silent = false) { let index = em.GetNotifiers().indexOf(notifier) log.info('Removing Notifier...') if (index > -1) { if (!silent) { em.GetNotifiers()[index].notify('Removing Notifier...') } em.GetNotifiers().splice(index, 1) return true } else { log.info(chalk.yellow(`Notifier ${notifier} not found, ignoring and returning false...`)) } return false }
javascript
{ "resource": "" }
q11167
RemoveDetector
train
function RemoveDetector (detector) { let index = motionDetectors.indexOf(detector) log.info('Removing Detector...') if (index > -1) { em.GetEnvironment().unbindDetector(detector) motionDetectors.splice(index, 1) // Redundant: Motion detectors are also copied to environment! em.GetEnvironment().motionDetectors.splice(index, 1) return true } else { log.info(chalk.yellow(`Detector ${detector} not found, ignoring and returning false...`)) } return false }
javascript
{ "resource": "" }
q11168
GetSubEnvironment
train
function GetSubEnvironment (subEnvironmentName) { let e = GetSubEnvironments()[subEnvironmentName] if (!e) { throw new Error('SubEnvironment does not exist.') } if (!(e instanceof ent.Environment)) { throw new Error('SubEnvironment is invalid.') } return e }
javascript
{ "resource": "" }
q11169
GetMotionDetector
train
function GetMotionDetector (name) { // It's assumed the number of motion detectors will be sufficiently small to be ok to iterate without major loss of efficiency console.log("Attention! this function GetMotionDetectors returns a singleton of motion detectors! If you are running several instances only one instance prevails!"); return _.filter(motionDetectors, x => x.name === name)[0] // Another alternative way: lodash.filter(motionDetectors, { 'name': 'Something' } ); }
javascript
{ "resource": "" }
q11170
GetFilters
train
function GetFilters () { let result = [] log.debug(`Fetching filters in the existing ${motionDetectors.length} detector(s)...`) for (let i in motionDetectors) { result = result.concat(motionDetectors[i].filters) } log.debug(`Getting ${result.length} filters...`) return result }
javascript
{ "resource": "" }
q11171
Reset
train
function Reset () { log.info('Reseting environment...') for (let m in motionDetectors) { RemoveDetector(motionDetectors[m]) } for (let n in em.GetNotifiers()) { RemoveNotifier(em.GetNotifiers()[n], true) } em.SetNotifiers([]) if (em.GetEnvironment()) { em.GetEnvironment().removeAllListeners('changedState') em.GetEnvironment().exit() em.SetEnvironment(undefined) } motionDetectors = [] Object.keys(pm.GetPlugins()).forEach(function (key) { let p = pm.GetPlugins()[key] console.log(` Attempting to reset plugin ${p.id} with key ${key}...`) if (p.Reset) { p.Reset() log.info('ok.') } }) pm.ResetPlugins() config = {} log.info('Done Reseting environment.') }
javascript
{ "resource": "" }
q11172
_StartPlugins
train
function _StartPlugins (e, m, n, f) { log.info(`Checking if any plugin exists which should be started...`) let plugins = pm.GetPlugins() Object.keys(plugins).forEach(function (key) { let p = plugins[key] log.info(` Plugin found. Checking plugin signature methods ShouldStart and Start for plugin ${key}...`) if (!p.ShouldStart) throw new Error("A plugin must have a 'ShouldStart' method implemented.") if (!p.Start) throw new Error("A plugin must have a 'Start' method implemented.") // TODO, add a way to call StartWithConfig log.info(' Checking if plugin should start...') if (p.ShouldStart(e, m, n, f, config)) { log.info('Plugin should start = true. Starting plugin...') p.Start(e, m, n, f, config) } else { log.info('Plugin will not start because returned false when asked if it should start.') } console.log('ok.') }) }
javascript
{ "resource": "" }
q11173
SaveAllToConfig
train
function SaveAllToConfig (src, callback, force = false) { let status = 1 let message let resultError = function (message) { message = `Error: ${message}` log.error(message) callback(1, message) } let resultWarning = function (message) { message = `Warn: ${message}` log.warning(message) callback(0, message) } let addConfigDefinitions = function (jsonContent) { return jsonContent = 'profiles = ' + jsonContent + '\nexports.profiles = profiles;' + '\nexports.default = profiles.default;' } if (fs.existsSync(src) && !force) { return resultError('File exists, if you want to overwrite it, use the force attribute') } else { let contents = addConfigDefinitions(_InternalSerializeCurrentContext()) fs.writeFile(src, contents, function (err) { if (err) { return resultError(err) } else { status = 0 message = 'Success' } callback(status, message) }) } }
javascript
{ "resource": "" }
q11174
_InternalSerializeCurrentContext
train
function _InternalSerializeCurrentContext () { let profile = { default: {} } // Separate this function into another utils library. let serializeEntity = function (ent) { if (ent.constructor.name === 'Array') { serializeArray() } else { profile.default[ent.constructor.name] = ent } } let serializeArray = function (ent) { let entityName for (let ei in ent) { // First, it creates as many entries of the same object as existing and initializes as empty arrays if (ent[ei].constructor.name !== entityName) { entityName = ent[ei].constructor.name profile.default[entityName] = [] } } for (let ei in ent) { // Then it reiterates again, this time pushing the contents to the correct array record profile.default[ent[ei].constructor.name].push(ent[ei]) } } serializeEntity(GetEnvironment()) serializeArray(GetMotionDetectors()) serializeArray(GetNotifiers()) serializeArray(GetFilters()) return utils.JSON.stringify(profile) }
javascript
{ "resource": "" }
q11175
train
function (ent) { if (ent.constructor.name === 'Array') { serializeArray() } else { profile.default[ent.constructor.name] = ent } }
javascript
{ "resource": "" }
q11176
train
function(onHover) { return function(picker, calendar, inst) { if ($.isFunction(onHover)) { var target = this; var renderer = inst.options.renderer; picker.find(renderer.daySelector + ' a, ' + renderer.daySelector + ' span'). hover(function() { onHover.apply(target, [$(target).calendarsPicker('retrieveDate', this), this.nodeName.toLowerCase() === 'a']); }, function() { onHover.apply(target, []); }); } }; }
javascript
{ "resource": "" }
q11177
Store
train
function Store(context, app, data) { const state = Object.assign({}, defaultState, data); return { dispatch(key, payload) { const reducers = context.reducers[key]; /* istanbul ignore next */ if (!reducers) return; for (let i = 0, len = reducers.length; i < len; i += 1) { const reducer = reducers[i]; const newState = reducer.method(state[reducer.namespace], payload); if (newState === undefined) { debug( chalk.bold('Reducer did not return a new state:'), chalk.bold.magenta(`${reducer.namespace}.${key}`)); } else { state[reducer.namespace] = newState; } } app.data = Object.assign({}, app.data, state); }, getState() { return state; }, }; }
javascript
{ "resource": "" }
q11178
error
train
function error(original, fileName) { if ( original == null || original.location == null || original.location.start == null ) { return original; } const start = original.location.start; const lineNumber = start.line == null ? 1 : start.line; const columnNumber = start.column == null ? 1 : start.column; const err = new SyntaxError(`Line ${lineNumber}, column ${columnNumber}: ${original.message}`); Object.assign(err, {fileName, lineNumber, columnNumber, original}); if (fileName == null) { return err; } err.stack = `SyntaxError: ${err.message}\n at ${fileName}:${lineNumber}:${columnNumber} `; return err; }
javascript
{ "resource": "" }
q11179
astValue
train
function astValue(node) { switch (node.type) { case 'ExpressionStatement': return astValue(node.expression); case 'ObjectExpression': return node.properties.reduce( (obj, prop) => Object.assign(obj, {[prop.key.value]: astValue(prop.value)}), {} ); case 'ArrayExpression': return node.elements.map(element => astValue(element)); case 'Literal': return node.value; default: throw new Error(`Unexpected ast node type: ${node.type}`); } }
javascript
{ "resource": "" }
q11180
remove
train
function remove(file, options, done) { if (arguments.length === 2 && 'function' === typeof options) { done = options; options = {}; } if ('function' !== typeof done) { done = function() {}; } function callfile(file, stats, done) { fs.unlink(file, done); } function calldir(dir, stats, files, state, done) { if (state === 'end') { if (options.empty && dir === file) { done(); } else { if (stats.isSymbolicLink()) { fs.unlink(dir, done); } else { fs.rmdir(dir, function(er) { if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) { // try in few time, last deletion is not completely ended setTimeout(function() { fs.rmdir(dir, done); }, 10); } else { done(er); } }); } } } else { done(); } } options = Object.assign({ fs: fs, resolve: true, followSymlink: false }, options); _explore(file, callfile, calldir, options, done); }
javascript
{ "resource": "" }
q11181
processFiles
train
function processFiles(bucket, key, transform, cb, currentFileNum=0, lastFileNum=0, arn=null, retries=0) { const maxRetries = 5 var nextFileNum = (currentFileNum < lastFileNum) ? currentFileNum + 1 : null //invokeLambda(bucket, key, currentFileNum, lastFileNum, arn) processFile( bucket, `${key}${currentFileNum}.csv`, transform ).then((n_scenes) => { invokeLambda(bucket, key, nextFileNum, lastFileNum, arn, 0) cb() }).catch((e) => { // if CSV failed, try it again if (retries < maxRetries) { invokeLambda(bucket, key, currentFileNum, lastFileNum, arn, retries + 1) } else { // log and move onto the next one console.log(`error: maxRetries hit in file ${currentFileNum}`) invokeLambda(bucket, key, nextFileNum, lastFileNum, arn, 0) } cb() }) }
javascript
{ "resource": "" }
q11182
processFile
train
function processFile(bucket, key, transform) { // get the csv file s3://${bucket}/${key} console.log(`Processing s3://${bucket}/${key}`) const s3 = new AWS.S3() const csvStream = csv.parse({ headers: true, objectMode: true }) s3.getObject({Bucket: bucket, Key: key}).createReadStream().pipe(csvStream) return es.streamToEs(csvStream, transform, esClient, index) }
javascript
{ "resource": "" }
q11183
invokeLambda
train
function invokeLambda(bucket, key, nextFileNum, lastFileNum, arn, retries) { // figure out if there's a next file to process if (nextFileNum && arn) { const stepfunctions = new AWS.StepFunctions() const params = { stateMachineArn: arn, input: JSON.stringify({ bucket, key, currentFileNum: nextFileNum, lastFileNum, arn, retries}), name: `ingest_${nextFileNum}_${Date.now()}` } stepfunctions.startExecution(params, function(err, data) { if (err) { console.log(err, err.stack) } else { console.log(`launched ${JSON.stringify(params)}`) } }) } }
javascript
{ "resource": "" }
q11184
connect
train
async function connect() { let esConfig let client // use local client if (!process.env.ES_HOST) { client = new elasticsearch.Client({host: 'localhost:9200'}) } else { await new Promise((resolve, reject) => AWS.config.getCredentials((err) => { if (err) return reject(err) resolve() })) esConfig = { host: process.env.ES_HOST, connectionClass: httpAwsEs, amazonES: { region: process.env.AWS_DEFAULT_REGION || 'us-east-1', credentials: AWS.config.credentials }, // Note that this doesn't abort the query. requestTimeout: 120000 // milliseconds } client = new elasticsearch.Client(esConfig) } await new Promise((resolve, reject) => client.ping({requestTimeout: 1000}, (err) => { if (err) { console.log('unable to connect to elasticsearch') reject('unable to connect to elasticsearch') } else { resolve() } })) return client }
javascript
{ "resource": "" }
q11185
_stringsByCharOrder
train
function _stringsByCharOrder(stringToMatch, givenString) { const matchingIndexes = getMatchingStringIndexes(stringToMatch, givenString); if (!matchingIndexes || !matchingIndexes.length) { return _matchRankMap.noMatch; } else { return _matchRankMap.matches; } }
javascript
{ "resource": "" }
q11186
readlin
train
function readlin(options, start, end) { return readline.createInterface({ input: interfac(options, start, end), output: null, terminal: false, }); }
javascript
{ "resource": "" }
q11187
train
function (options) { var clientShell = this, context = {}, // Default settings. defaultSettings = { namespace: 'shotgun', debug: false }; // Override default settings with supplied options. var settings = clientShell.settings = extend(true, {}, defaultSettings, options); // Instruct socket.io to connect to the server. var socket = clientShell.socket = io.connect('/' + settings.namespace); // Proxy any listeners onto the socket itself. clientShell.on = function () { socket.on.apply(socket, arguments); return clientShell; }; // Proxy any emit calls onto the socket itself. clientShell.emit = function () { socket.emit.apply(socket, arguments); return clientShell; }; function getCookies() { var cookies = {}; if (document.cookie.length > 0) document.cookie.split(';').forEach(function (cookie) { var components = cookie.split('='), name = components[0].trim(), value = components[1]; if (name.indexOf(settings.namespace + '-') === 0) { name = name.replace(settings.namespace + '-', ''); cookies[name] = decodeURIComponent(value); } }); return cookies; } clientShell // Save context when it changes. .on('contextChanged', function (contextData) { context = contextData; }) // Create a function for setting cookies in the browser. .on('setCookie', function (name, value, days) { var expiration = new Date(); expiration.setDate(expiration.getDate() + days); value = encodeURIComponent(value) + ((days === null) ? "" : ";expires=" + expiration.toUTCString()); document.cookie = settings.namespace + '-' + name + "=" + value; }) .on('getCookie', function (name, callback) { // Create a cookies property on the context and fill it with all the cookies for this shell. var cookies = getCookies(); callback(cookies[name]); }) .on('getAllCookies', function (callback) { var cookies = getCookies(); callback(cookies); }); // Create an execute function that looks similar to the shotgun shell execute function for ease of use. clientShell.execute = function (cmdStr, contextOverride, options) { // If a context was passed in then override the stored context with it. if (contextOverride) context = contextOverride; socket.emit('execute', cmdStr, context, options); return clientShell; }; return clientShell; }
javascript
{ "resource": "" }
q11188
transpose
train
function transpose(out, a) { // If we are transposing ourselves we can skip a few steps but have to cache some values if (out === a) { var a1 = a[1] out[1] = a[2] out[2] = a1 } else { out[0] = a[0] out[1] = a[2] out[2] = a[1] out[3] = a[3] } return out }
javascript
{ "resource": "" }
q11189
_compile
train
function _compile(str, filename) { var parent = this; try { var requires = detective(str); } catch (ex) { ex.toString = function() { return filename + ':' + this.loc.line + '\n ' + ex.message; } throw ex; } requires.forEach(function(req) { if (modules.isRelative(req)) { Module._load(req, parent); } else { if (!modules.isCore(req)) { dependencies.push(modules.name(req)); } } }); }
javascript
{ "resource": "" }
q11190
store
train
function store(hmap){ var _ = { // data is a two dimensional array // a datapoint gets saved as data[point-x-value][point-y-value] // the value at [point-x-value][point-y-value] is the occurrence of the datapoint data: [], // tight coupling of the heatmap object heatmap: hmap }; // the max occurrence - the heatmaps radial gradient alpha transition is based on it this.max = 1; this.get = function(key){ return _[key]; }; this.set = function(key, value){ _[key] = value; }; }
javascript
{ "resource": "" }
q11191
train
function(x, y){ if(x < 0 || y < 0) return; var me = this, heatmap = me.get("heatmap"), data = me.get("data"); if(!data[x]) data[x] = []; if(!data[x][y]) data[x][y] = 0; // if count parameter is set increment by count otherwise by 1 data[x][y]+=(arguments.length<3)?1:arguments[2]; me.set("data", data); // do we have a new maximum? if(me.max < data[x][y]){ // max changed, we need to redraw all existing(lower) datapoints heatmap.get("actx").clearRect(0,0,heatmap.get("width"),heatmap.get("height")); me.setDataSet({ max: data[x][y], data: data }, true); return; } heatmap.drawAlpha(x, y, data[x][y], true); }
javascript
{ "resource": "" }
q11192
heatmap
train
function heatmap(config){ // private variables var _ = { radius : 40, element : {}, canvas : {}, acanvas: {}, ctx : {}, actx : {}, legend: null, visible : true, width : 0, height : 0, max : false, gradient : false, opacity: 180, premultiplyAlpha: false, bounds: { l: 1000, r: 0, t: 1000, b: 0 }, debug: false }; // heatmap store containing the datapoints and information about the maximum // accessible via instance.store this.store = new store(this); this.get = function(key){ return _[key]; }; this.set = function(key, value){ _[key] = value; }; // configure the heatmap when an instance gets created this.configure(config); // and initialize it this.init(); }
javascript
{ "resource": "" }
q11193
train
function(directoryName, cbUpload, cbError) { this.directory = directoryName; this.name = ''; this.localPath = ''; this.virtualPath = ''; this.onUpload = cbUpload; this.onError = cbError; }
javascript
{ "resource": "" }
q11194
uServicesManager
train
function uServicesManager(){ client.publish('uServicesChannel', 'UPDATE'); listenClient.on('message', function(channel, message) { client.get('uServices', function(err, reply) { if (reply !== null) { uServices = JSON.parse(reply); } }); }); listenClient.on("error", function (err) { console.log("Redis listen "+ err); listenClient.quit(); }); listenClient.subscribe('uServicesChannel'); }
javascript
{ "resource": "" }
q11195
throughWithCallback
train
function throughWithCallback(onData) { return through.obj(function (chunk, enc, next) { if (onData) { onData(null, chunk); } next(null, chunk); }); }
javascript
{ "resource": "" }
q11196
waitObj
train
function waitObj(callback) { var data = []; return pipeline.obj( through.obj( function transform(chunk, enc, next) { data.push(chunk); next(); }, function Flush(next) { this.push(data); next(); } ), throughWithCallback(callback) ); }
javascript
{ "resource": "" }
q11197
wait
train
function wait(callback) { return pipeline.obj( waitObj(), through.obj(function (chunk, enc, next) { next(null, Buffer.concat(chunk.map(function (item) { return new Buffer(item, enc); }))); }), throughWithCallback(callback) ); }
javascript
{ "resource": "" }
q11198
shallowEqual
train
function shallowEqual(actual, expected) { var keys = Object.keys(expected); var _arr2 = keys; for (var _i2 = 0; _i2 < _arr2.length; _i2++) { var key = _arr2[_i2]; if (actual[key] !== expected[key]) { return false; } } return true; }
javascript
{ "resource": "" }
q11199
appendToMemberExpression
train
function appendToMemberExpression(member, append, computed) { member.object = t.memberExpression(member.object, member.property, member.computed); member.property = append; member.computed = !!computed; return member; }
javascript
{ "resource": "" }