_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q38200
train
function (timerId, timerName, t) { if (this.enabled) { if (this._startDate[timerId]) { var duration = (t || (+new Date())) - this._startDate[timerId]; delete this._startDate[timerId]; if (console.profile) { if (this._timerConsoleName[timerId]) { console.profileEnd(this._timerConsoleName[timerId]); delete this._timerConsoleName[timerId]; } } // Already have stats for this method? Update them. if (typeof this.stats[timerName] !== 'undefined') { var stats = this.stats[timerName]; stats.calls += 1; stats.totalMs += duration; if (duration > stats.maxMs) { stats.maxMs = duration; } } else { // It's the first time we profile this method, create the // initial stats. this.stats[timerName] = { calls: 1, totalMs: duration, maxMs: duration }; } console.log('time(' + timerName + ') = ' + duration + 'ms'); } else { console.log('WARNING: invalid profiling timer'); } } }
javascript
{ "resource": "" }
q38201
train
function (options) { this.options = options; // options.back can be used to change view 'Back' link. if (options.back) { this.back = options.back; } this.callSubviews('setOptions', options); this.applyOptions(options); }
javascript
{ "resource": "" }
q38202
train
function (method) { if (this.subviews.length !== 0) { var params = slice.call(arguments); params.shift(); _.each(this.subviews, function (s) { if (s[method]) { s[method].apply(s, params); } }); } }
javascript
{ "resource": "" }
q38203
train
function (e) { e.preventDefault(); var $target = $(e.target); while ($target) { var route = $target.attr('route'); if (route) { // A route has been defined, follow the link using // Jackbone's default router. if (route === 'back') { Jackbone.router.goto(this.back.hash); } else { Jackbone.router.goto(route); } return false; } var parent = $target.parent(); if (parent.length > 0) { $target = parent; } else { $target = false; } } return true; }
javascript
{ "resource": "" }
q38204
train
function () { // Note: Controllers are responsible of setting needRedraw. if (this.needRedraw) { // Create root element for the page var page = document.createElement('div'); page.style.display = 'block'; page.setAttribute('data-role', 'page'); // Create, render and add the header if (this.header) { var header = document.createElement('div'); header.setAttribute('data-role', 'header'); this.header.setElement(header); this.header.render(); page.appendChild(header); } // Create the content element var content = document.createElement('div'); content.setAttribute('data-role', 'content'); content.className = 'content'; // Render the content this.content.setElement(content); this.content.render(); // Make sure content fills the screen to the top/bottom // when no header/footer are provided. if (!this.header) { content.style.top = '0'; } if (!this.footer) { content.style.bottom = '0'; } page.appendChild(content); // Create, render and add the footer if (this.footer) { var footer = document.createElement('div'); footer.setAttribute('data-role', 'footer'); this.footer.setElement(footer); this.footer.render(); page.appendChild(footer); } // Add the page into the DOM. if (this.el.firstChild) { this.el.replaceChild(page, this.el.firstChild); } else { this.el.appendChild(page); } this.needRedraw = false; } }
javascript
{ "resource": "" }
q38205
train
function () { var that = this; var now = +new Date(); var toRemove = _(this.controllers).filter(function (c) { var age = (now - c.lastView); return (age > 60000); // Keep in cache for 1 minute. }); _(toRemove).each(function (c) { if (c.controller !== that.currentController) { delete that.controllers[c.pageUID]; c.controller.destroy(); if (c.controller._rootView) { c.controller._rootView.clean(); c.controller._rootView.remove(); Jackbone.trigger("destroyview", c.controller._rootView); } } }); }
javascript
{ "resource": "" }
q38206
train
function () { var content = ctrl.view; var header = noHeader ? null : new Jackbone.DefaultHeader(); var footer = noFooter ? null : new Jackbone.DefaultFooter(); var view = new JQMView(header, content, footer); // Cache the controller that.controllers[pageUID] = { pageUID: pageUID, controller: ctrl }; ctrl._rootView = view; view.controller = ctrl; doneCreate(); }
javascript
{ "resource": "" }
q38207
train
function (separator, page, args) { // By default, we return page name without arguments. var ret = page; if (typeof args !== 'undefined') { if (args && args.length) { // Some arguments have been provided, add them. if (args.length !== 0) { ret = page + separator + args.join(separator); } } else { // Argument isn't an array, add it. ret = page + separator + args; } } return ret; }
javascript
{ "resource": "" }
q38208
train
function (pageName, page, role) { // Extends Views // Create JQuery Mobile Page var pageid = 'pagename-' + pageName.toLowerCase(); var isExistingPage = $('#' + pageid); // For already existing pages, only delegate events so they can // handle onPageBeforeShow and onPageShow. if (isExistingPage.length === 1) { // Sometimes, controller may have been destroyed but the // HTML stayed in the DOM (in case of an exception). // We can detect that using needRedraw, which indicate // that we have to do a full repaint. if (page.needRedraw) { page.render(); } else { page.refresh(); page.delegateEvents(); } } else { // Create the page, store its page name in an attribute // so it can be retrieved later. page.el.id = 'pagename-' + pageName.toLowerCase(); page.el.className = 'page-container'; // Render it and add it in the DOM. page.render(); if (Jackbone.manualMode) { // Create the new page page._onPageBeforeCreate(); Jackbone.trigger('createview', page); page._onPageManualCreate(); page._onPageCreate(); } // Append to the DOM. document.body.appendChild(page.el); } if (!Jackbone.manualMode) { // Select the transition to apply. var t = this.selectTransition(pageName, role); // Perform transition using JQuery Mobile $.mobile.changePage(page.$el, { changeHash: false, transition: t.transition, reverse: t.reverse, role: role, pageContainer: page.$el }); } else { var currentActivePage = Jackbone.activePage; try { // Hide previous page, show next if (Jackbone.activePage) { Jackbone.activePage._onPageBeforeHide(); } page._onPageBeforeShow(); page.$el.show(); if (Jackbone.activePage) { Jackbone.activePage.$el.hide(); Jackbone.activePage._onPageHide(); } page._onPageShow(); // Update 'activePage' Jackbone.activePage = page; $.mobile.activePage = page.$el; } catch (error) { page.$el.hide(); if (currentActivePage) { currentActivePage.$el.show(); Jackbone.activePage = currentActivePage; $.mobile.activePage = currentActivePage.$el; } throw new Error('Failed to changePage: ' + error); } } // Current hash is stored so a subsequent openView can know // which page it comes from. this.currentHash = Jackbone.history.getFragment(); }
javascript
{ "resource": "" }
q38209
train
function (pageName, role) { var lastPageName = this.currentPageName || ''; var lastPageRole = this.currentPageRole || ''; this.currentPageName = pageName; this.currentPageRole = role; // Known transition, return it. if (_(this.transitions).has(lastPageName + '-->' + pageName)) { return this.transitions[lastPageName + '-->' + pageName]; } // Use JQueryMobile default page transition. var transition = $.mobile.defaultPageTransition; // Except for dialogs. if ((role === 'dialog') || (lastPageRole === 'dialog')) { // Use JQueryMobile default dialog transition. transition = $.mobile.defaultDialogTransition; } // Save the transition this.transitions[lastPageName + '-->' + pageName] = { transition: transition, reverse: false }; this.transitions[pageName + '-->' + lastPageName] = { transition: transition, reverse: true }; // And return it. return { transition: transition, reverse: false }; }
javascript
{ "resource": "" }
q38210
TiqDB
train
function TiqDB(config) { var defaultConfig = { client: 'sqlite3', connection: { host: 'localhost', user: null, password: null, database: 'tiq', filename: path.join(process.env.XDG_DATA_HOME || path.join(process.env.HOME, '.local', 'share'), 'tiq', 'store.db') } }, config = _.merge(defaultConfig, config || {}); // Setup the DB connection Knex.knex = Knex.initialize(config); this.config = config; return this; }
javascript
{ "resource": "" }
q38211
train
function () { this._super.onenter (); if ( this.box.pageY < window.innerHeight ) { this._hilite (); } else { this.tick.time ( function () { this._hilite (); }, 200 ); } }
javascript
{ "resource": "" }
q38212
train
function ( code ) { var text = code.firstChild; if ( text ) { text.data = text.data.substring ( 1 ); // we inserted a # } }
javascript
{ "resource": "" }
q38213
trampoline
train
function trampoline(queue) { index = [0]; stack = [queue]; var queueIndex, queueLength; var stackIndex = 1; // 1-indexed! var stackLength = stack.length; var topOfStack = true; while (stackIndex) { queue = stack[stackIndex - 1]; queueIndex = index[stackIndex - 1]; if (queueIndex === -1) { queueIndex = index[stackIndex - 1] = 0; } queueLength = queue.length; while (queueIndex < queueLength && topOfStack) { queue[queueIndex].resolve( queue[queueIndex + 1], queue[queueIndex + 2], queue[queueIndex + 3]); queueIndex += 4; stackLength = stack.length; topOfStack = stackLength === stackIndex; } if (!topOfStack) { index[stackIndex - 1] = queueIndex; stackIndex = stackLength; topOfStack = true; } else { index.pop(); stack.pop(); stackIndex--; } } stack = index = null; }
javascript
{ "resource": "" }
q38214
enterTurn
train
function enterTurn() { var snapshot; while ((snapshot = queue).length) { queue = []; trampoline(snapshot); } queue = null; }
javascript
{ "resource": "" }
q38215
createForBuild
train
function createForBuild(build) { var exports = {}; function bundles(name, sourceType) { /*jshint validthis: true */ var ml = build.bundles(name, sourceType); return this.markSafe(ml); } exports.bundles = bundles; function link(srcPath, relative) { /*jshint validthis: true */ var ml = build.link(srcPath, relative); return this.markSafe(ml); } exports.link = link; function script(srcPath, relative) { /*jshint validthis: true */ var ml = build.script(srcPath, relative); return this.markSafe(ml); } exports.script = script; function scriptCode(js) { /*jshint validthis: true */ var ml = '<script type="text/javascript">' + js + '</script>'; return this.markSafe(ml); } exports.scriptCode = scriptCode; exports.t = build.translate.bind(build); exports.tn = build.translateNumeric.bind(build); return exports; }
javascript
{ "resource": "" }
q38216
Client
train
function Client (opts) { var self = this typeforce({ url: 'String', otrKey: 'DSA', // byRootHash: 'Function', instanceTag: '?String', autoconnect: '?Boolean' // defaults to true }, opts) EventEmitter.call(this) this.setMaxListeners(0) this._url = parseURL(opts.url) this._autoconnect = opts.autoconnect !== false this._onmessage = this._onmessage.bind(this) this._sessions = {} this._otrKey = opts.otrKey this._fingerprint = opts.otrKey.fingerprint() this._connected = false this._instanceTag = opts.instanceTag this._backoff = backoff.exponential({ initialDelay: 100 }) if (this._autoconnect) this.connect() }
javascript
{ "resource": "" }
q38217
preserveNamespace
train
function preserveNamespace (models) { const prefixedModels = {} if (connector.config.skipModelNamespace) { // if namspace is not applied we do not need to preserve it return models } else { for (var model in models) { prefixedModels[models[model].name] = models[model] } return prefixedModels } }
javascript
{ "resource": "" }
q38218
execute
train
function execute(req, res) { this.state.pubsub.unsubscribe(req.conn, req.args); }
javascript
{ "resource": "" }
q38219
gfmTable
train
function gfmTable (data, options) { options = options || {} if (!data || !data.length) { return '' } data = escapePipes(data) var tableOptions = { nowrap: !options.wrap, padding: { left: '| ', right: ' ' }, columns: options.columns || [], getColumn: function (columnName) { return this.columns.find(function (column) { return columnName === column.name }) }, ignoreEmptyColumns: options.ignoreEmptyColumns } if (options.width) tableOptions.viewWidth = options.width var headerRow = {} var separatorRow = {} var table = new Table(data, tableOptions) table.columns.list .forEach(function (column) { var optionColumn = tableOptions.getColumn(column.name) headerRow[column.name] = (optionColumn && optionColumn.header) || column.name separatorRow[column.name] = function () { return '-'.repeat(this.wrappedContentWidth) } }) data.splice(0, 0, headerRow, separatorRow) table.load(data) var lastColumn = table.columns.list[table.columns.list.length - 1] lastColumn.padding = { left: '| ', right: ' |' } return table.toString() }
javascript
{ "resource": "" }
q38220
installPluginsFromConfigXML
train
function installPluginsFromConfigXML(args) { events.emit('verbose', 'Checking config.xml for saved plugins that haven\'t been added to the project'); //Install plugins that are listed on config.xml var projectRoot = cordova_util.cdProjectRoot(); var configPath = cordova_util.projectConfig(projectRoot); var cfg = new ConfigParser(configPath); var plugins_dir = path.join(projectRoot, 'plugins'); // Get all configured plugins var plugins = cfg.getPluginIdList(); if (0 === plugins.length) { return Q('No plugins found in config.xml that haven\'t been added to the project'); } // Intermediate variable to store current installing plugin name // to be able to create informative warning on plugin failure var pluginName; // CB-9560 : Run `plugin add` serially, one plugin after another // We need to wait for the plugin and its dependencies to be installed // before installing the next root plugin otherwise we can have common // plugin dependencies installed twice which throws a nasty error. return promiseutil.Q_chainmap_graceful(plugins, function(featureId) { var pluginPath = path.join(plugins_dir, featureId); if (fs.existsSync(pluginPath)) { // Plugin already exists return Q(); } events.emit('log', 'Discovered plugin "' + featureId + '" in config.xml. Adding it to the project'); var pluginEntry = cfg.getPlugin(featureId); // Install from given URL if defined or using a plugin id. If spec isn't a valid version or version range, // assume it is the location to install from. var pluginSpec = pluginEntry.spec; pluginName = pluginEntry.name; // CB-10761 If plugin spec is not specified, use plugin name var installFrom = pluginSpec || pluginName; if (pluginSpec && semver.validRange(pluginSpec, true)) installFrom = pluginName + '@' + pluginSpec; // Add feature preferences as CLI variables if have any var options = { cli_variables: pluginEntry.variables, searchpath: args.searchpath, fetch: args.fetch || false, save: args.save || false }; var plugin = require('./plugin'); return plugin('add', installFrom, options); }, function (error) { // CB-10921 emit a warning in case of error var msg = 'Failed to restore plugin \"' + pluginName + '\" from config.xml. ' + 'You might need to try adding it again. Error: ' + error; events.emit('warn', msg); }); }
javascript
{ "resource": "" }
q38221
train
function(grunt, gruntFilesArray, gruntOptions) { /** * @property styleGuideGenerator.grunt * @type {Object} */ this.grunt = grunt; /** * An unexpanded grunt file array * * @property styleGuideGenerator.gruntFilesArray * @type {Array} */ this.gruntFilesArray = gruntFilesArray; /** * Grunt task options * * @property styleGuideGenerator.gruntOptions * @type {Array} */ this.gruntOptions = objectAssign(StyleGuideGenerator.OPTIONS, gruntOptions); /** * An emo-gen instance * * @property styleGuideGenerator.generator */ this.generator = new EMOGen( this.gruntOptions, this.gruntOptions.nunjucksOptions ); }
javascript
{ "resource": "" }
q38222
train
function(obj) { if (typeof obj === "object") { if (Array.isArray(obj) && obj.length > 1) { obj = '[ '+toString(obj[0])+', ... ]'; } } return (obj+''); }
javascript
{ "resource": "" }
q38223
preview
train
function preview (source, line, options) { let from, to, pos // set from/to line if (Array.isArray(line)) { from = line[0] | 0 to = line[1] | 0 || from } else if (typeof line === 'object') { from = to = line.line | 0 pos = { line: line.line | 0, column: line.column | 0 } } else { from = to = line | 0 } // set options options = Object.assign({}, PREVIEW_OPTS, options) let color = colorer(options.cliColor) // read source by from/to let lines = readSource(source, from, to, options.offset, options.delimiter) let numberWidth = String(to).length + 4 // [] + two space if (!options.lineNumber) { numberWidth = 0 } let parts = lines.map(line => { let prefix = '' let text = '' if (options.lineNumber) { prefix = rightPad(`[${line.number}]`, numberWidth) } if (line.number >= from && line.number <= to) { text = color('red', `${prefix}${line.source}`) } else { text = color('grey', prefix) + line.source } if (pos && pos.line === line.number) { text += '\n' + ' '.repeat(numberWidth + pos.column - 1) + '^' } return text }) // add delimiter parts.unshift(color('grey', DELIMITER)) parts.push(color('grey', DELIMITER)) return parts.join('\n') }
javascript
{ "resource": "" }
q38224
readSource
train
function readSource (source, from, to, offset, delimiter) { // fix args from = from | 0 to = to | 0 || from delimiter = delimiter || PREVIEW_OPTS.delimiter if (typeof offset === 'undefined') { offset = PREVIEW_OPTS.offset } else { offset = offset | 0 } let lastIdx = -1 let currIdx = lastIdx let line = 1 let reads = [] from -= offset to += offset while (currIdx < source.length) { currIdx = source.indexOf(delimiter, lastIdx + 1) if (currIdx < 0) { currIdx = source.length } if (line > to) { break } else if (line >= from && line <= to) { reads.push({ number: line, source: source.substring(lastIdx + delimiter.length, currIdx) }) } lastIdx = currIdx line ++ } return reads }
javascript
{ "resource": "" }
q38225
getUrlParameter
train
function getUrlParameter(sPageURL) { var url = sPageURL.split('?'); var obj = {}; if (url.length == 2) { var sURLVariables = url[1].split('&'), sParameterName, i; for (i = 0; i < sURLVariables.length; i++) { sParameterName = sURLVariables[i].split('='); obj[sParameterName[0]] = sParameterName[1]; } return obj; } else { return undefined; } }
javascript
{ "resource": "" }
q38226
train
function () { var tableData = [ ['LOOP TYPE', ...config.counts] ]; var bases = []; Object.keys(results['while desc']).forEach(function (countType) { var times = results['while desc'][countType]; var sum = times.reduce(function (acc, val) { return acc + val; }, 0); bases.push(sum); }); Object.keys(results).forEach(function (loopType) { var currentResult = [loopType]; Object.keys(results[loopType]).forEach(function (countType, idx) { var times = results[loopType][countType]; var sum = times.reduce(function (acc, val) { return acc + val; }, 0); var relative = '-'; if (bases[idx] > sum) relative = '-' + String((bases[idx] / sum).toFixed(2)) + '%'; else if (bases[idx] < sum) relative = '+' + String((bases[idx] / sum).toFixed(2)) + '%'; currentResult.push(relative); }); tableData.push(currentResult); }); console.log('\n\n' + table(tableData) + '\n'); process.exit(); }
javascript
{ "resource": "" }
q38227
getAttribute
train
function getAttribute(element, name) { assertType(element, Node, false, 'Invalid element specified'); if (!element.getAttribute) return null; let value = element.getAttribute(name); if (value === '') return true; if (value === undefined || value === null) return null; try { return JSON.parse(value); } catch (err) { return value; } }
javascript
{ "resource": "" }
q38228
fileUpload
train
function fileUpload(fileURI, serverURI, fileUploadOptions) { var deferred = q.defer(); var transfer = new FileTransfer(); transfer.upload(fileURI, serverURI, function uploadSuccess(response) { deferred.resolve(response); }, function uploadFailure(error) { deferred.reject(error); }, fileUploadOptions); return deferred.promise; }
javascript
{ "resource": "" }
q38229
fileUploadRetry
train
function fileUploadRetry(fileURI, serverURI, fileUploadOptions, timeout, retries) { return fileUpload(fileURI, serverURI, fileUploadOptions) .then(function(response) { return response; }, function() { if (retries === 0) { throw new Error("Can't upload to " + JSON.stringify(serverURI)); } return q.delay(timeout) .then(function() { return fileUploadRetry(fileURI, serverURI, fileUploadOptions, timeout, retries - 1); }); }); }
javascript
{ "resource": "" }
q38230
addAllMtimes
train
function addAllMtimes(files, metalsmith, done) { var source = metalsmith.source(); // File system will be accessed for each element so iterate in parallel. each(Object.keys(files), getAddMtime, done); /** * Gets mtime of given `file` and adds it to metadata. * * @param {String} file * @param {Function} done * @api private */ function getAddMtime(file, done) { fs.stat(path.join(source, file), addMtime); /** * Adds `stats.mtime` of `file` to its metadata. * * @param {Error} err * @param {fs.Stats} stats * @api private */ function addMtime(err, stats) { if (err) { // Skip elements of `files` that don't point to existing files. // This can happen if some other Metalsmith plugin does something // strange with `files`. if (err.code === 'ENOENT') { debug('file %s not found', file); return done(); } return done(err); } debug('mtime of file %s is %s', file, stats.mtime); files[file].mtime = stats.mtime; done(); } } }
javascript
{ "resource": "" }
q38231
getAddMtime
train
function getAddMtime(file, done) { fs.stat(path.join(source, file), addMtime); /** * Adds `stats.mtime` of `file` to its metadata. * * @param {Error} err * @param {fs.Stats} stats * @api private */ function addMtime(err, stats) { if (err) { // Skip elements of `files` that don't point to existing files. // This can happen if some other Metalsmith plugin does something // strange with `files`. if (err.code === 'ENOENT') { debug('file %s not found', file); return done(); } return done(err); } debug('mtime of file %s is %s', file, stats.mtime); files[file].mtime = stats.mtime; done(); } }
javascript
{ "resource": "" }
q38232
addMtime
train
function addMtime(err, stats) { if (err) { // Skip elements of `files` that don't point to existing files. // This can happen if some other Metalsmith plugin does something // strange with `files`. if (err.code === 'ENOENT') { debug('file %s not found', file); return done(); } return done(err); } debug('mtime of file %s is %s', file, stats.mtime); files[file].mtime = stats.mtime; done(); }
javascript
{ "resource": "" }
q38233
train
function(object, type, property) { var self = this; object.__addSetter(property, this.SETTER_NAME, this.SETTER_WEIGHT, function(value, fields) { var fieldsType = type || {}; for (var i = 0, ii = fields.length; i < ii; ++i) { var params = fieldsType[1] || {}; if (!('element' in params)) { return value; } fieldsType = params.element; } return self.apply(value, fieldsType, property, fields, object); }); }
javascript
{ "resource": "" }
q38234
train
function(value, type, property, fields, object) { if (_.isUndefined(value) || _.isNull(value)) { return value; } var params = {}; if (_.isArray(type)) { params = type[1] || {}; type = type[0]; } if (!(type in this._types)) { throw new Error('Property type "' + type + '" does not exist!'); } return this._types[type].call(this, value, params, property, fields, object); }
javascript
{ "resource": "" }
q38235
train
function(delimiter) { if (!_.isString(delimiter) && !_.isRegExp(delimiter)) { throw new Error('Delimiter must be a string or a regular expression!'); } this._defaultArrayDelimiter = delimiter; return this; }
javascript
{ "resource": "" }
q38236
train
function(value, params, property) { value = +value; if ('min' in params && value < params.min) { throw new Error('Value "' + value + '" of property "' + property + '" must not be less then "' + params.min + '"!'); } if ('max' in params && value > params.max) { throw new Error('Value "' + value + '" of property "' + property + '" must not be greater then "' + params.max + '"!'); } return value; }
javascript
{ "resource": "" }
q38237
train
function(value, params, property) { value = ''+value; if ('pattern' in params && !params.pattern.test(value)) { throw new Error('Value "' + value + '" of property "' + property + '" does not match pattern "' + params.pattern + '"!'); } if ('variants' in params && -1 === params.variants.indexOf(value)) { throw new Error('Value "' + value + '" of property "' + property + '" must be one of "' + params.variants.join(', ') + '"!'); } return value; }
javascript
{ "resource": "" }
q38238
train
function(value, params, property) { if (_.isNumber(value) && !isNaN(value)) { value = new Date(value); } else if (_.isString(value)) { value = new Date(Date.parse(value)); } if (!(value instanceof Date)) { throw new Error('Value of property "' + property + '" must have datetime type!'); } return value; }
javascript
{ "resource": "" }
q38239
train
function(value, params, property, fields, object) { if (_.isString(value)) { value = value.split(params.delimiter || this._defaultArrayDelimiter); } if ('element' in params) { for (var i = 0, ii = value.length; i < ii; ++i) { value[i] = this.apply(value[i], params.element, property, fields.concat(i), object); } } return value; }
javascript
{ "resource": "" }
q38240
train
function(value, params, property, fields, object) { var that = this; if (!_.isSimpleObject(value)) { throw new Error('Value of property "' + [property].concat(fields).join('.') +'" must be a simple object!'); } if ('keys' in params) { _.each(params.keys, function(key) { if (-1 === params.keys.indexOf(key)) { throw new Error('Unsupported hash key "' + key + '" for property "' + [property].concat(fields).join('.') + '"!'); } }); } if ('element' in params) { _.each(value, function(key) { value[key] = that.apply(value[key], params.element, property, fields.concat(key), object); }) ; } return value; }
javascript
{ "resource": "" }
q38241
train
function(value, params, property, fields, object) { if (!_.isObject(value)) { throw new Error('Value of property "' + property + '" must be an object!'); } if ('instanceOf' in params) { var instanceOf = params.instanceOf; var clazzClazz = object.__isClazz ? object.__clazz : object.__clazz.__clazz; if (_.isString(instanceOf)) { instanceOf = clazzClazz.getNamespace().adjustPath(instanceOf); if (!value.__clazz) { instanceOf = clazzClazz(instanceOf); } } if (value.__clazz ? !value.__clazz.__isSubclazzOf(instanceOf) : !(value instanceof instanceOf)) { var className = instanceOf.__isClazz ? instanceOf.__name : (_.isString(instanceOf) ? instanceOf : 'another'); throw new Error('Value of property "' + property + '" must be instance of ' + className + ' clazz!'); } } return value; }
javascript
{ "resource": "" }
q38242
removeExisting
train
function removeExisting () { if (fs.existsSync("web/assets")) { var stat = fs.lstatSync("web/assets"); if (stat.isFile() || stat.isSymbolicLink()) { fs.unlinkSync("web/assets"); } else { wrench.rmdirSyncRecursive("web/assets"); } } }
javascript
{ "resource": "" }
q38243
componentsHome
train
function componentsHome(workdir) { var bowerrc = path.join(workdir, '.bowerrc'), defaultHome = path.join(workdir, 'bower_components'); return (fs.existsSync(bowerrc) && require(bowerrc).directory) || defaultHome; }
javascript
{ "resource": "" }
q38244
componentName
train
function componentName(rawname) { var name = rawname.split(':')[0], index = name.replace('\\', '/').indexOf('/'); return (index > 0) ? name.substring(0, index) : name; }
javascript
{ "resource": "" }
q38245
componentNames
train
function componentNames(workdir) { workdir = workdir || process.cwd(); try { var bowerJson = require(path.join(workdir, 'bower.json')); return _(Object.keys(bowerJson.dependencies || {})) .union(Object.keys(bowerJson.devDependencies || {})) .value(); } catch (ex) { // not found bower //console.warn(ex.message); return []; } }
javascript
{ "resource": "" }
q38246
resolve
train
function resolve(name, workdir) { workdir = workdir || process.cwd(); var compName = componentName(name), subname = name.substring(compName.length + 1), basedir = path.join(componentsHome(workdir), compName), bowerJson = require(path.join(basedir, 'bower.json')); var mainfile = Array.isArray(bowerJson.main) ? bowerJson.main.filter(function(file) { return /\.js$/.test(file); })[0] : bowerJson.main; if (subname && subname.length > 0) { var subpath = mainfile && path.join(basedir, mainfile, '..', subname); if (subpath && (fs.existsSync(subpath) || fs.existsSync(subpath + '.js'))) { return path.join(basedir, mainfile, '..', subname); } else { return path.join(basedir, subname); } } else { if (mainfile) { return path.join(basedir, mainfile); } else { if (fs.existsSync(path.join(basedir, "index.js"))) { return path.join(basedir, "index.js"); } else { return path.join(basedir, compName); } } } }
javascript
{ "resource": "" }
q38247
uglify
train
function uglify(js) { return ugli.minify(js, { fromString: true, mangle: false, compress: { warnings: false } }).code; }
javascript
{ "resource": "" }
q38248
failsafe
train
function failsafe(code, tracer, serverId, msg, opts, cb) { // eslint-disable-line const self = this; const retryTimes = opts.retryTimes || constants.DEFAULT_PARAM.FAILSAFE_RETRIES; const retryConnectTime = opts.retryConnectTime || constants.DEFAULT_PARAM.FAILSAFE_CONNECT_TIME; if (!tracer.retryTimes) { tracer.retryTimes = 1; } else { tracer.retryTimes += 1; } switch (code) { case constants.RPC_ERROR.SERVER_NOT_STARTED: case constants.RPC_ERROR.NO_TRAGET_SERVER: utils.invokeCallback(cb, new Error('rpc client is not started or cannot find remote server.')); break; case constants.RPC_ERROR.FAIL_CONNECT_SERVER: if (tracer.retryTimes <= retryTimes) { setTimeout(() => { self.connect(tracer, serverId, cb); }, retryConnectTime * tracer.retryTimes); } else { utils.invokeCallback(cb, new Error(`rpc client failed to connect to remote server: ${serverId}`)); } break; case constants.RPC_ERROR.FAIL_FIND_MAILBOX: case constants.RPC_ERROR.FAIL_SEND_MESSAGE: if (tracer.retryTimes <= retryTimes) { setTimeout(() => { self.dispatch.call(self, tracer, serverId, msg, opts, cb); }, retryConnectTime * tracer.retryTimes); } else { utils.invokeCallback(cb, new Error(`rpc client failed to send message to remote server: ${serverId}`)); } break; case constants.RPC_ERROR.FILTER_ERROR: utils.invokeCallback(cb, new Error('rpc client filter encounters error.')); break; default: utils.invokeCallback(cb, new Error('rpc client unknown error.')); } }
javascript
{ "resource": "" }
q38249
process
train
function process( ctx, obj ) { try { if ( Array.isArray( obj ) ) return processArray( ctx, obj ); switch ( typeof obj ) { case "string": return processString( ctx, obj ); case "object": return processObject( ctx, obj ); default: return obj; } } catch ( ex ) { fatal( ctx, ex ); } }
javascript
{ "resource": "" }
q38250
PubSub
train
function PubSub(stats) { // ref to statistics so they can be updated // as subscriptions change this._stats = stats; // normal channels this._channels = {}; // pattern channels this._patterns = {}; this._count = { channels: { total: 0, // total number of channels subscribers: 0, // total subscribers across all channels }, patterns: { total: 0, // total number of patterns subscribers: 0, // total subscribers across all patterns } } }
javascript
{ "resource": "" }
q38251
getChannelList
train
function getChannelList(channels) { var i , channel , list = []; for(i = 0;i < channels.length;i++) { channel = channels[i]; list.push(channel, this._channels[channel] ? this._channels[channel].length : 0); } return list; }
javascript
{ "resource": "" }
q38252
getChannels
train
function getChannels(pattern) { if(!pattern) return Object.keys(this._channels); var re = (pattern instanceof RegExp) ? pattern : Pattern.compile(pattern) , k , list = []; for(k in this._channels) { if(re.test(k)) { list.push(k); } } return list; }
javascript
{ "resource": "" }
q38253
cleanup
train
function cleanup(client) { if(client.pubsub && client.pubsub.channels && client.pubsub.patterns && !client.pubsub.channels.length && !client.pubsub.patterns.length) { client.pubsub = null; } }
javascript
{ "resource": "" }
q38254
generateHelp
train
function generateHelp(flags) { var max = 0; for (var group in flags) { for (var i = 0; i < flags[group].length; i++) { var n = 2; // ' ' if (flags[group][i].longFlag) { n += 2; // '--' n += flags[group][i].longFlag.length; } if (flags[group][i].longFlag && flags[group][i].shortFlag) { n += 2; // ', ' } if (flags[group][i].shortFlag) { n += 1; // '-' n += flags[group][i].shortFlag.length; } if (n > max) { max = n; } } } console.log('node-async-testing'); console.log(''); for (var group in flags) { console.log(group+':'); for (var i = 0; i < flags[group].length; i++) { var s = ' '; if (flags[group][i].longFlag) { s += '--' + flags[group][i].longFlag; } if (flags[group][i].longFlag && flags[group][i].shortFlag) { s += ', '; } if (flags[group][i].shortFlag) { for(var j = s.length+flags[group][i].shortFlag.length; j < max; j++) { s += ' '; } s += '-' + flags[group][i].shortFlag; } if (flags[group][i].takesValue) { s += ' <'+flags[group][i].takesValue+'>'; } console.log( s + ': ' + flags[group][i].description + (flags[group][i].options ? ' ('+flags[group][i].options.join(', ')+')' : '') ); } console.log(''); } console.log('Any other arguments are interpreted as files to run'); }
javascript
{ "resource": "" }
q38255
isPositiveFiniteInteger
train
function isPositiveFiniteInteger(value, errorMessage) { value = Number(value); if (isNaN(value) || !isFinite(value) || value < 0 || value % 1 !== 0) { throw new RangeError(errorMessage.replace('$', value)); } return value; }
javascript
{ "resource": "" }
q38256
defineObservableProperty
train
function defineObservableProperty(target, property, originalValue) { //we store the value in an non-enumerable property with generated unique name var internalPropName = '_' + (uidCounter++) + property; if (target.hasOwnProperty(property)) { Object.defineProperty(target, internalPropName, { value: originalValue, writable: true, enumerable: false, configurable: true }); } //then we create accessor method for our 'hidden' property, // that dispatch changesRecords when the value is updated Object.defineProperty(target, property, { get: function () { return this[internalPropName]; }, set: function (value) { if (!sameValue(value, this[internalPropName])) { var oldValue = this[internalPropName]; Object.defineProperty(this, internalPropName, { value: value, writable: true, enumerable: false, configurable: true }); var notifier = Object.getNotifier(this); notifier.notify({ type: 'update', name: property, oldValue: oldValue }); } }, enumerable: true, configurable: true }); }
javascript
{ "resource": "" }
q38257
createKarmaTypescriptConfig
train
function createKarmaTypescriptConfig(tsconfigJson, coverageDir) { return { tsconfig: tsconfigJson, coverageOptions: { instrumentation: !isDebug() }, reports: { 'cobertura': { directory: coverageDir, subdirectory: 'cobertura', filename: 'coverage.xml' }, 'html': { directory: coverageDir, subdirectory: '.' }, 'text-summary': null } }; }
javascript
{ "resource": "" }
q38258
Sprite
train
function Sprite( aElement, aProperties, aContent ) { aProperties = aProperties || {}; var domElement = "div"; if ( aElement && typeof aElement !== "object" ) { domElement = /** @type {string} */ ( aElement); } /* creates HTML element of requested tag type in the DOM */ if ( !aElement || typeof aElement === "string" ) { this._element = document.createElement( domElement ); } else { this._element = /** @type {Element} */ ( aElement ); } Object.keys( aProperties ).forEach( function( key ) { this._element.setAttribute( key, aProperties[ key ]); }.bind( this )); if ( aContent ) { this.setContent( aContent ); } this._children = []; Inheritance.super( this ); this._eventHandler = new EventHandler(); // separate handler for DOM Events }
javascript
{ "resource": "" }
q38259
train
function( e ) { var event = new Event( aType ); event.target = self; event.srcEvent = e; aHandler( event ); }
javascript
{ "resource": "" }
q38260
checkHeaderFromStream
train
function checkHeaderFromStream(file, ctx) { file.contents.pipe(es.wait(function (err, data) { if (err) { throw err; } var bufferFile = new File({ path: file.path, contents: data }); checkHeaderFromBuffer(bufferFile, ctx); })); }
javascript
{ "resource": "" }
q38261
checkHeaderFromBuffer
train
function checkHeaderFromBuffer(file, ctx) { if (isLicenseHeaderPresent(file)) { log(file.path, ctx); } else { error(file.path, ctx); } }
javascript
{ "resource": "" }
q38262
readLicenseHeaderFile
train
function readLicenseHeaderFile() { if (licenseFileUtf8) { return licenseFileUtf8; } if (fs.existsSync(licenseFilePath)) { return fs.readFileSync(licenseFilePath, 'utf8').split(/\r?\n/); } throw new gutil.PluginError('gulp-license-check', new Error('The license header file doesn`t exist ' + licenseFilePath)); }
javascript
{ "resource": "" }
q38263
log
train
function log(filePath, ctx) { if (isInfoLogActive) { ctx.emit('log', { msg: HEADER_PRESENT, path: filePath }); gutil.log(gutil.colors.green(HEADER_PRESENT), filePath); } }
javascript
{ "resource": "" }
q38264
error
train
function error(filePath, ctx) { if (isErrorBlocking) { throw new gutil.PluginError('gulp-license-check', new Error('The following file doesn`t contain the license header ' + filePath)); } else { logError(filePath, ctx); } }
javascript
{ "resource": "" }
q38265
logError
train
function logError(filePath, ctx) { if (isErrorLogActive) { ctx.emit('log', { msg: HEADER_NOT_PRESENT, path: filePath }); gutil.log(gutil.colors.red(HEADER_NOT_PRESENT), filePath); } }
javascript
{ "resource": "" }
q38266
isLicenseHeaderPresent
train
function isLicenseHeaderPresent(currentFile) { if (!isFileEmpty(currentFile.contents)) { var currentFileUtf8 = readCurrentFile(currentFile), licenseFileUtf8 = readLicenseHeaderFile(), skipStrict = 0; if(currentFileUtf8[0] === '"use strict";' ) { skipStrict = 1; } for (var i = skipStrict; i < licenseFileUtf8.length; i++) { if (currentFileUtf8[i + skipStrict] !== licenseFileUtf8[i]) { return false; } } } return true; }
javascript
{ "resource": "" }
q38267
getConfigFromLS
train
function getConfigFromLS() { var configStr = localStorage[getFullBSKey(browser_storage_config_1.browserStorageConfig.DB_CONFIG_KEY)]; if (typeof configStr === 'undefined') { return null; } else { return JSON.parse(configStr); } }
javascript
{ "resource": "" }
q38268
setConfigToLS
train
function setConfigToLS(configObj) { var configStr = JSON.stringify(configObj); window.localStorage[getFullBSKey(browser_storage_config_1.browserStorageConfig.DB_CONFIG_KEY)] = configStr; }
javascript
{ "resource": "" }
q38269
getInitialBrowserStorageState
train
function getInitialBrowserStorageState() { var memorizedFile = getConfigFromLS()[browser_storage_config_1.browserStorageConfig.DB_INITIAL_KEY]; return memorizedFile.map(function (memItem) { var browserStorageValue = window[memItem.storageType]['getItem'](getFullBSKey(memItem.key)); if (browserStorageValue) { return Object.assign({}, memItem, { value: browserStorageValue }); } else { return memItem; } }); }
javascript
{ "resource": "" }
q38270
initFromScratch
train
function initFromScratch(cbsConfigFromFile) { cbsConfigFromFile.initialState.forEach(function (item) { return saveItemToBrowserStorage(item); }); return _a = {}, _a[browser_storage_config_1.browserStorageConfig.DB_INITIAL_KEY] = cbsConfigFromFile.initialState, _a; var _a; }
javascript
{ "resource": "" }
q38271
initExisting
train
function initExisting(cbsConfigFromFile, cbsConfigFromLS) { // Restore items that have been manually removed by a user restoreManuallyRemovedItems(cbsConfigFromLS); var configFileDifferOptions = { fileInitialState: cbsConfigFromFile.initialState, memoryInitialState: cbsConfigFromLS[browser_storage_config_1.browserStorageConfig.DB_INITIAL_KEY] }; handleRemovedConfigItems(configFileDifferOptions); handleAddedConfigItems(configFileDifferOptions); handleUpdatedConfigItems(configFileDifferOptions); }
javascript
{ "resource": "" }
q38272
restoreManuallyRemovedItems
train
function restoreManuallyRemovedItems(cbsConfigFromLS) { cbsConfigFromLS[browser_storage_config_1.browserStorageConfig.DB_INITIAL_KEY].map(function (memoryItem) { var storageItemValue = getItemValueFromBrowserStorage(memoryItem); // the storage item has been removed, put back from memory object if (typeof storageItemValue === 'undefined') { saveItemToBrowserStorage(memoryItem); } }); }
javascript
{ "resource": "" }
q38273
percentBy
train
function percentBy(valueMapper) { var valueSetter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; return function (input) { if (input.isEmpty()) { return input; } var percents = input.map(valueMapper).update(percent()); if (!valueSetter) { return percents; } return input.map(function (item, kk, iter) { var value = percents.get(kk); return valueSetter(item, value, kk, iter); }); }; }
javascript
{ "resource": "" }
q38274
train
function(deltaTime){ var currentTime = new Date().getTime(); deltaTime = deltaTime || currentTime-this.lastUpdated; //Ignore minor updates if (deltaTime < 5){ return this; } deltaTime /= 1000; //convert to seconds //Calculate deltas based on how much time has passed since last update var data = this.attributes; if (data.isAccelerating){ var deltaVelocity = this.ACCELERATION * deltaTime; var deltaTime1 = 0; //Calculate new velocities var newVelocityX = data.velocityX + (Math.cos(data.angle) * deltaVelocity); var newVelocityY = data.velocityY + (Math.sin(data.angle) * deltaVelocity); //If velocities exceed maximums, we have to do some additional logic to calculate new positions if (newVelocityX > this.MAX_VELOCITY_X || newVelocityX < -this.MAX_VELOCITY_X){ newVelocityX = (newVelocityX > 0) ? this.MAX_VELOCITY_X : -this.MAX_VELOCITY_X; deltaTime1 = getTime(data.velocityX, newVelocityX, this.ACCELERATION); data.posX += getDistance(data.velocityX, newVelocityX, deltaTime1) + (newVelocityX*(deltaTime-deltaTime1)); } else{ data.posX += getDistance(data.velocityX, newVelocityX, deltaTime); } if (newVelocityY > this.MAX_VELOCITY_Y || newVelocityY < -this.MAX_VELOCITY_Y){ newVelocityY = (newVelocityY > 0) ? this.MAX_VELOCITY_Y : -this.MAX_VELOCITY_Y; deltaTime1 = getTime(data.velocityY, newVelocityY, this.ACCELERATION); data.posY += getDistance(data.velocityY, newVelocityY, deltaTime1) + (newVelocityY*(deltaTime-deltaTime1)); }else{ data.posY += getDistance(data.velocityY, newVelocityY, deltaTime); } data.velocityX = newVelocityX; data.velocityY = newVelocityY; } else{ data.posX += data.velocityX * deltaTime; data.posY += data.velocityY * deltaTime; } //Check to see if player has exceeded zone boundary, in which case send them to opposite side var radius = this.SIZE/2; var maxPosX = Constants.Zone.WIDTH+radius; var maxPosY = Constants.Zone.HEIGHT+radius; while (data.posX > maxPosX) data.posX -= maxPosX+radius; while (data.posX < -radius) data.posX += maxPosX+radius; while (data.posY > maxPosY) data.posY -= maxPosY+radius; while (data.posY < -radius) data.posY += maxPosY+radius; //Update last updated timestamp this.lastUpdated = currentTime; return this; }
javascript
{ "resource": "" }
q38275
train
function(posX, posY){ //Calculate the position deltas while account for zone boundaries var zoneWidth = Constants.Zone.WIDTH; var zoneHeight = Constants.Zone.HEIGHT; var deltaX = posX - this.get("posX"); if (Math.abs(deltaX) > zoneWidth/2){ (posX < zoneWidth/2) ? deltaX += zoneWidth : deltaX -= zoneWidth; } var deltaY = posY - this.get("posY"); if (Math.abs(deltaY) > zoneHeight/2){ (posY < zoneHeight/2) ? deltaY += zoneHeight : deltaY -= zoneHeight; } var data = this.attributes; //Update the velocities to move to the correct position by the next update var interval = Constants.UPDATE_INTERVAL/1000; data.velocityX += deltaX / interval; data.velocityY += deltaY / interval; //If these changes take us over the maximum velocities, update the constants to allow for it this.MAX_VELOCITY_X = Math.max(data.velocityX, Constants.Player.MAX_VELOCITY_X); this.MAX_VELOCITY_Y = Math.max(data.velocityY, Constants.Player.MAX_VELOCITY_Y); return this; }
javascript
{ "resource": "" }
q38276
readFileSync
train
function readFileSync (fileName, options) { verifyFileName (fileName); var info = getFileInfo (fileName); if (info.exists === false) { var message1 = format (cc.MSG_DOES_NOT_EXIST, fileName); throw new SafeFileError (cc.DOES_NOT_EXIST, message1); } if (info.isFile === false) { var message2 = format (cc.MSG_IS_NOT_A_FILE, fileName); throw new SafeFileError (cc.IS_NOT_A_FILE, message2); } // read data file var data = null; try { data = fs.readFileSync (fileName, options); } catch (e) { var message3 = format (cc.MSG_READ_ERROR, fileName, e.message); throw new SafeFileError (cc.READ_ERROR, message3); } // return data return (data); }
javascript
{ "resource": "" }
q38277
writeFileSync
train
function writeFileSync (fileName, data, options) { verifyFileName (fileName); var info = getFileInfo (fileName); if ((info.exists === true) && (info.isFile === false)) { var message1 = format (cc.MSG_IS_NOT_A_FILE, fileName); throw new SafeFileError (cc.IS_NOT_A_FILE, message1); } // if content undefined or null, set data to empty string if ((data === undefined) || (data === null)) { data = ""; } // write file content, throwing exception on error occurring try { fs.writeFileSync (fileName, data, options); } catch (e) { var message2 = format (cc.MSG_WRITE_ERROR, e.message); throw new SafeFileError (cc.WRITE_ERROR, message2); } }
javascript
{ "resource": "" }
q38278
safeGetState
train
function safeGetState (fileName) { if ((fileName === undefined) || (fileName === null)) { return (cc.INVALID_NAME); } // if fileName exists, verify it is a file var info = getFileInfo (fileName); if ((info.exists) && (info.isFile === false)) { return (cc.IS_NOT_A_FILE); } var state = getState (fileName); return (state.status); }
javascript
{ "resource": "" }
q38279
safeRecover
train
function safeRecover (fileName) { verifyFileName (fileName); // if fileName exists, verify it is a file var info = getFileInfo (fileName); if ((info.exists) && (info.isFile === false)) { var message1 = format (cc.MSG_IS_NOT_A_FILE, fileName); throw new SafeFileError (cc.IS_NOT_A_FILE, message1); } // get state, if doesn't exist throw error var state = getState (fileName); if (state.status === cc.DOES_NOT_EXIST) { var message2 = format (cc.MSG_DOES_NOT_EXIST, fileName); throw new SafeFileError (cc.DOES_NOT_EXIST, message2); } performRecovery (state, true); }
javascript
{ "resource": "" }
q38280
safeReadFileSync
train
function safeReadFileSync (fileName, options) { verifyFileName (fileName); // if fileName exists, verify it is a file var info = getFileInfo (fileName); if ((info.exists) && (info.isFile === false)) { var message = format (cc.MSG_IS_NOT_A_FILE, fileName); throw new SafeFileError (cc.IS_NOT_A_FILE, message); } // get state, if auto-recovery required, perform recovery var state = getState (fileName); if (state.status === cc.SAFE_RECOVERABLE) { performRecovery (state, true); } // perform read on file return (readFileSync (fileName, options)); }
javascript
{ "resource": "" }
q38281
safeWriteFileSync
train
function safeWriteFileSync (fileName, data, options) { verifyFileName (fileName); // if fileName exists, verify it is a file var info = getFileInfo (fileName); if ((info.exists) && (info.isFile === false)) { var message = format (cc.MSG_IS_NOT_A_FILE, fileName); throw new SafeFileError (cc.IS_NOT_A_FILE, message); } // get current file system state, and auto-recover if necessary var state = getState (fileName); // store data in well defined ephemeral file to allow manual recovery // If file already exists, remove it (failed prior recovery). if (state.ephemeral.exists) { fs.unlinkSync (state.ephemeral.name); } writeFileSync (state.ephemeral.name, data, options); state.ephemeral.exists = true; // if ready state file already exists, recover prior state if (state.ready.exists) { performRecovery (state, false); } fs.renameSync (state.ephemeral.name, state.ready.name); // refresh state and process recovery to set file system state state = getState (fileName); performRecovery (state, true); }
javascript
{ "resource": "" }
q38282
verifyFileName
train
function verifyFileName (fileName) { // if fileName undefined or null, throw exception if ((fileName === undefined) || (fileName === null)) { var message1 = format (cc.MSG_INVALID_NAME); throw new SafeFileError (cc.INVALID_NAME, message1); } }
javascript
{ "resource": "" }
q38283
getState
train
function getState (file) { // collect state for all possible data and recovery files var state = {}; state.ephemeral = getFileInfo (file + ".eph"); state.ready = getFileInfo (file + ".rdy"); state.base = getFileInfo (file); state.backup = getFileInfo (file + ".bak"); state.tertiary = getFileInfo (file + ".bk2"); if (state.ephemeral.exists) { state.status = cc.SAFE_INTERVENE; } else if ((state.ready.exists) || (state.tertiary.exists)) { state.status = cc.SAFE_RECOVERABLE; } else if (state.base.exists) { state.status = cc.SAFE_NORMAL; } else { if (state.backup.exists) { state.status = cc.SAFE_RECOVERABLE; } else { state.status = cc.DOES_NOT_EXIST; } } return (state); }
javascript
{ "resource": "" }
q38284
performRecovery
train
function performRecovery (state, removeEphemeral) { // if ephemeral flag true, and ephemeral file exists, remove it if ((removeEphemeral) && (state.ephemeral.exists)) { fs.unlinkSync (state.ephemeral.name); } // if only backups exist, restore from backup var baseAvailable = state.base.exists || state.ready.exists; if (baseAvailable === false) { if (state.tertiary.exists) { if (state.backup.exists) { fs.renameSync (state.backup.name, state.base.name); fs.renameSync (state.tertiary.name, state.backup.name); } else { fs.renameSync (state.tertiary.name, state.base.name); } } else if (state.backup.exists) { fs.renameSync (state.backup.name, state.base.name); } return; } // if tertiary state file exists, remove it if (state.tertiary.exists) { fs.unlinkSync (state.tertiary.name); } // if ready state file exists, update ready, base and backup files if (state.ready.exists) { var removeTertiary = false; // if base and backup exist, rename to tertiary temporarily if ((state.base.exists) && (state.backup.exists)) { fs.renameSync (state.backup.name, state.tertiary.name); removeTertiary = true; } // if base exists, rename to backup if (state.base.exists) { fs.renameSync (state.base.name, state.backup.name); } // place ready state file in base and delete temporary tertiary file fs.renameSync (state.ready.name, state.base.name); // if temporary tertiary created, remove it if (removeTertiary) { fs.unlinkSync (state.tertiary.name); } } }
javascript
{ "resource": "" }
q38285
train
function (daString) { // stop shouting daString = daString.replace(/^([A-Z]*)$/, function (match, c) { return (c ? c.toLowerCase() : '') }) // prepare camels for _ daString = daString.replace(/([A-Z])/g, function (match, c) { return (c ? '_' + c : '') }) // convert to " " daString = daString.replace(/(\-|_|\s)+(.)?/g, function (match, sep, c) { return (c ? (sep ? ' ' : '') + c.toUpperCase() : '') }) // capitalize daString = daString.replace(/(.)/, function (match, c) { return (c ? c.toUpperCase() : '') }) // clean up return daString.trim() }
javascript
{ "resource": "" }
q38286
bootModel
train
function bootModel(trinte, schema, file) { if (/\.js$/i.test(file)) { var name = file.replace(/\.js$/i, ''); var modelDir = path.resolve(__dirname, '../app/models'); trinte.models[name] = require(modelDir + '/' + name)(schema);// Include the mongoose file global[name] = trinte.models[name]; } }
javascript
{ "resource": "" }
q38287
convertUnit
train
function convertUnit (xUnit, mUnit, mVal) { if (xUnit !== mUnit) { if (mUnit === 'em') { mVal = options.px_em_ratio * mVal; } if (xUnit === 'em') { mVal = mVal/options.px_em_ratio; } } return mVal; }
javascript
{ "resource": "" }
q38288
loadModules
train
function loadModules(dir, container, args) { var files = fs.readdirSync(dir); for (var i = 0; i < files.length; i++) { var file = files[i]; var filePath = path.join(dir, file); if (fs.statSync(filePath).isDirectory()) { container[file] = {}; loadModules(filePath, container[file], args); continue; } if (/.+\.js$/.test(file)) { var name = file.replace(/\.js$/, '') container[name] = require(filePath)(args, container); } } }
javascript
{ "resource": "" }
q38289
loadPlugins
train
function loadPlugins(pluginNames) { if (pluginNames) { pluginNames.forEach(function(pluginName) { var pluginNamespace = util.getNamespace(pluginName), pluginNameWithoutNamespace = util.removeNameSpace(pluginName), pluginNameWithoutPrefix = util.removePluginPrefix(pluginNameWithoutNamespace), plugin; if (!loadedPlugins[pluginNameWithoutPrefix]) { plugin = require(pluginNamespace + util.PLUGIN_NAME_PREFIX + pluginNameWithoutPrefix); // if this plugin has rules, import them if (plugin.rules) { rules.import(plugin.rules, pluginNameWithoutPrefix); } loadedPlugins[pluginNameWithoutPrefix] = plugin; } }); } }
javascript
{ "resource": "" }
q38290
CLIEngine
train
function CLIEngine(options) { /** * Stored options for this instance * @type {Object} */ this.options = assign(Object.create(defaultOptions), options || {}); // load in additional rules if (this.options.rulePaths) { this.options.rulePaths.forEach(function(rulesdir) { rules.load(rulesdir); }); } }
javascript
{ "resource": "" }
q38291
train
function(name, pluginobject) { var pluginNameWithoutPrefix = util.removePluginPrefix(util.removeNameSpace(name)); if (pluginobject.rules) { rules.import(pluginobject.rules, pluginNameWithoutPrefix); } loadedPlugins[pluginNameWithoutPrefix] = pluginobject; }
javascript
{ "resource": "" }
q38292
train
function(directory) { if (!this.packageJSONFinder) { this.packageJSONFinder = new FileFinder(PACKAGE_FILENAME); } return this.packageJSONFinder.findInDirectoryOrParentsSync(directory || process.cwd()); }
javascript
{ "resource": "" }
q38293
train
function(moduleName, deps, callback) { //if (moduleName === "jquery/selector") { debugger; } if (!deps && !callback) { return; } // Allow deps to be optional. if (!callback && typeof deps === "function") { callback = deps; deps = undefined; } // Ensure dependencies is never falsey. deps = deps || []; // Normalize the dependencies. deps = deps.map(function(dep) { if (dep.indexOf("./") === -1) { return dep; } // Take off the last path. var normalize = moduleName.split("/").slice(0, -1).join("/"); //console.log(normalize, dep, define.join(normalize, dep)); return define.join(normalize, dep); }); // Attach to the module map. define.map[moduleName] = { moduleName: moduleName, deps: deps, callback: callback }; }
javascript
{ "resource": "" }
q38294
ShockwaveFilter
train
function ShockwaveFilter() { core.AbstractFilter.call(this, // vertex shader null, // fragment shader fs.readFileSync(__dirname + '/shockwave.frag', 'utf8'), // custom uniforms { center: { type: 'v2', value: { x: 0.5, y: 0.5 } }, params: { type: 'v3', value: { x: 10, y: 0.8, z: 0.1 } }, time: { type: '1f', value: 0 } } ); }
javascript
{ "resource": "" }
q38295
getExtensionlessFilename
train
function getExtensionlessFilename( filename ) { return filename.substr( 0, filename.length - path.extname( filename ).length); }
javascript
{ "resource": "" }
q38296
templateWithArgs
train
function templateWithArgs( apiDir, apiName, apiFuncName ) { cacheAPIs[apiName] = { reg: (RegularCacheClient .replace(/%%api.root%%/g,apiDir) .replace(/%%api.name%%/g,apiName) .replace(/%%api.funcs%%/g,JSON.stringify(apiFuncName))), service: (ServiceCacheClient .replace(/%%api.root%%/g,apiDir) .replace(/%%api.name%%/g,apiName) .replace(/%%api.funcs%%/g,JSON.stringify(apiFuncName))) } }
javascript
{ "resource": "" }
q38297
copyArgumentsArray
train
function copyArgumentsArray(args) { var copy = []; var index = 0; for (var i in args) { copy[index] = args[i]; index++; } return copy; }
javascript
{ "resource": "" }
q38298
readRawBody
train
function readRawBody(req,res,rawBodyCallback,callbackScope) { if ( typeof req._body !== 'undefined' && req._body ) { rawBodyCallback.call(callbackScope,req,res); } else { req.rawBody = ''; req.setEncoding('utf8'); req.on('data', function(chunk) { req.rawBody += chunk; }); req.on('end', function() { rawBodyCallback.call(callbackScope,req,res); }); } }
javascript
{ "resource": "" }
q38299
ConfigError
train
function ConfigError(lineno, line, file, err) { this.name = ConfigError.name; Error.call(this); var fmt = '*** FATAL CONFIG FILE ERROR ***%s'; fmt += 'Reading the configuration file, at line %s%s'; fmt += '>>> %s%s'; fmt += err && err.message && !(err instanceof TypeDefError) ? err.message : 'Bad directive or wrong number of arguments'; this.message = util.format(fmt, EOL, lineno, EOL, line, EOL); this.file = file; this.err = err; }
javascript
{ "resource": "" }