_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q10800
equipFromInventory
train
function equipFromInventory (attributes, index, slotName) { if (index >= attributes.inventory.length) { throw new InventoryIndexError(index); } var item = attributes.inventory[index]; if (!slotName) { slotName = item.slot; } if (!slotName) { throw new UnequippableItemError(item.name); } if (!(slotName in attributes.equipped)) { throw new SlotNameError(slotName); } if (item.slot !== slotName) { throw new InvalidSlotError(item.slot, slotName); } if (!requirements.met(attributes, item.requirements)) { throw new RequirementsNotMetError(); } if (attributes.equipped[slotName]) { unEquip(attributes, slotName); } attributes.inventory.splice(index, 1); attributes.equipped[slotName] = item; return attributes; }
javascript
{ "resource": "" }
q10801
isWearable
train
function isWearable (attributes, index) { if (index >= attributes.inventory.length) { throw new InventoryIndexError(index); } var item = attributes.inventory[index]; if (!requirements.met(attributes, item.requirements)) { throw new RequirementsNotMetError(); } var slotName = item.slot; if (!slotName) { throw new UnequippableItemError(item.name); } return slotName; }
javascript
{ "resource": "" }
q10802
train
function (database, callback) { var s = this, querier = s._querier; querier.connect(); async.waterfall([ function (callback) { querier.showTables(database, function (err, tables) { callback(err, tables); }); }, function (tables, callback) { var tableNames = s._parseTableNames(tables); async.map(tableNames, function (table, callback) { querier.descTable(database, table, function (err, data1) { querier.selectKeyColumnUsage(database, table, function (err, data2) { callback(err, { name: table, columns: s._parseTableData(data1), relations: s._getRelations(data2, table) }); }); }); }, callback); }, function (data, callback) { var database = {}; data.forEach(function (data) { database[data.name] = data; }); callback(null, database); } ], function (err, result) { querier.disconnect(); callback(err, result); }); return s; }
javascript
{ "resource": "" }
q10803
train
function (database, table, callback) { var s = this, querier = s._querier; querier.connect(); querier.descTable(database, table, function (err, data) { querier.disconnect(); callback(err, s._parseTableData(data || {})); }); return s; }
javascript
{ "resource": "" }
q10804
train
function (database, callback) { var s = this, querier = s._querier; querier.connect(); async.waterfall([ function (callback) { querier.showTables(database, function (err, tables) { callback(err, tables); }); }, function (tables, callback) { var tableNames = s._parseTableNames(tables); async.map(tableNames, function (table, callback) { querier.selectKeyColumnUsage(database, table, function (err, data) { callback(err, { name: table, keyColumnUsage: s._parseTableKeyColumnUsageData(data) }); }); }, callback); }, function (data, callback) { var database = {}; data.forEach(function (data) { database[data.name] = data.keyColumnUsage; }); callback(null, database); } ], function (err, result) { querier.disconnect(); callback(err, result); }); return s; }
javascript
{ "resource": "" }
q10805
train
function (database, table, callback) { var s = this, querier = s._querier; querier.connect(); querier.selectKeyColumnUsage(database, table, function (err, data) { querier.disconnect(); callback(err, s._parseTableKeyColumnUsageData(data)); }); return s; }
javascript
{ "resource": "" }
q10806
train
function() { var block_tpl_content = fs.readFileSync( path.join(this.opts.templatePath, 'doc-block.hbs')); this.tpl_block = this.hbs.compile(block_tpl_content.toString()); includeHelper.register(this.hbs, this); this._postProcessDocFiles(); return this; }
javascript
{ "resource": "" }
q10807
Image
train
function Image() { if (!this) return new Image(); this.url = null; EventEmitter.call(this); setTimeout(function timeout() { if (this.onerror) this.on('error', this.onerror); if (this.onload) this.on('load', this.onload); }.bind(this)); }
javascript
{ "resource": "" }
q10808
train
function (zaproxy, statusFn, callback) { var wait = function () { statusFn(function (err, body) { if (err) { callback(err); return; } if (body.status < 100) { grunt.log.write('.'); setTimeout(function () { wait(callback); }, 1000); } else { callback(null, body); } }); }; wait(); }
javascript
{ "resource": "" }
q10809
numberType
train
function numberType(mname, tpe, options) { const doubles = options.themeDoubles.split(',') if (doubles && doubles.includes(mname)) { return 'Double' } else { return 'Int' } }
javascript
{ "resource": "" }
q10810
getCurrentConfigs
train
function getCurrentConfigs(bundle) { dbgHWTest('getCurrentConfigs', bundle.calibrationInfoValid); var defered = q.defer(); bundle.device.sReadMany(bundle.infoToCache) .then(function(results) { // bundle.currentDeviceConfigs results.forEach(function(result) { bundle.currentDeviceConfigs[result.name] = result; }); defered.resolve(bundle); }, function(err) { bundle.overallResult = false; bundle.overallMessage = 'Failed to read current device configs.'; bundle.shortMessage = 'Failed'; defered.resolve(bundle); }); return defered.promise; }
javascript
{ "resource": "" }
q10811
train
function(bundle_deps) { var patterns = [ '**', '!dist/**', '!plato/**', '!cov-*/**', '!test*/**', '!config/**', '!output/**', '!coverage/**', '!node_modules/**', '!package.json', // this will be processed '!Gruntfile.js', '!Makefile', '!makefile', '!npm-debug.log', '!*.sublime-project', '!sonar-project.properties', '!**/*.tar.gz' ]; if (bundle_deps) { var nodeModulePatterns = _.uniq(getProductionNodeModules().map(formatDirectory)); patterns = patterns.concat(nodeModulePatterns); } var fhignore = grunt.config.get('fhignore'); var extras = []; if (fhignore && _.isArray(fhignore)) { extras = fhignore.map(function(elem) { return '!' + elem; }); } Array.prototype.push.apply(patterns, extras); var fhinclude = grunt.config.get('fhinclude'); extras = []; if(fhinclude && _.isArray(fhinclude)) { extras = fhinclude; } Array.prototype.push.apply(patterns, extras); grunt.log.debug("Patterns: " + patterns); return patterns; }
javascript
{ "resource": "" }
q10812
reset
train
function reset(schemas) { var resolver = new Resolver(schemas); // Reduce force sequential execution. return Promise.reduce(resolver.resolve().reverse(), resetSchema.bind(this), []); }
javascript
{ "resource": "" }
q10813
resetSchema
train
function resetSchema(result, schema) { var knex = this.knex; return knex.schema.hasTable(schema.tableName) .then(function (exists) { if (! exists) return result; return knex(schema.tableName).del() .then(function () { return result.concat([schema]); }); }); }
javascript
{ "resource": "" }
q10814
train
function () { var heights = this.s.heights; var max = 1000000; heights.virtual = heights.row * this.s.dt.fnRecordsDisplay(); heights.scroll = heights.virtual; if ( heights.scroll > max ) { heights.scroll = max; } this.dom.force.style.height = heights.scroll+"px"; }
javascript
{ "resource": "" }
q10815
train
function () { var dt = this.s.dt; var origTable = dt.nTable; var nTable = origTable.cloneNode( false ); var tbody = $('<tbody/>').appendTo( nTable ); var container = $( '<div class="'+dt.oClasses.sWrapper+' DTS">'+ '<div class="'+dt.oClasses.sScrollWrapper+'">'+ '<div class="'+dt.oClasses.sScrollBody+'"></div>'+ '</div>'+ '</div>' ); // Want 3 rows in the sizing table so :first-child and :last-child // CSS styles don't come into play - take the size of the middle row $('tbody tr:lt(4)', origTable).clone().appendTo( tbody ); while( $('tr', tbody).length < 3 ) { tbody.append( '<tr><td>&nbsp;</td></tr>' ); } $('div.'+dt.oClasses.sScrollBody, container).append( nTable ); var appendTo; if (dt._bInitComplete) { appendTo = origTable.parentNode; } else { if (!this.s.dt.nHolding) { this.s.dt.nHolding = $( '<div></div>' ).insertBefore( this.s.dt.nTable ); } appendTo = this.s.dt.nHolding; } container.appendTo( appendTo ); this.s.heights.row = $('tr', tbody).eq(1).outerHeight(); container.remove(); }
javascript
{ "resource": "" }
q10816
train
function () { if ( !this.s.dt.oFeatures.bInfo ) { return; } var dt = this.s.dt, language = dt.oLanguage, iScrollTop = this.dom.scroller.scrollTop, iStart = Math.floor( this.fnPixelsToRow(iScrollTop, false, this.s.ani)+1 ), iMax = dt.fnRecordsTotal(), iTotal = dt.fnRecordsDisplay(), iPossibleEnd = Math.ceil( this.fnPixelsToRow(iScrollTop+this.s.heights.viewport, false, this.s.ani) ), iEnd = iTotal < iPossibleEnd ? iTotal : iPossibleEnd, sStart = dt.fnFormatNumber( iStart ), sEnd = dt.fnFormatNumber( iEnd ), sMax = dt.fnFormatNumber( iMax ), sTotal = dt.fnFormatNumber( iTotal ), sOut; if ( dt.fnRecordsDisplay() === 0 && dt.fnRecordsDisplay() == dt.fnRecordsTotal() ) { /* Empty record set */ sOut = language.sInfoEmpty+ language.sInfoPostFix; } else if ( dt.fnRecordsDisplay() === 0 ) { /* Empty record set after filtering */ sOut = language.sInfoEmpty +' '+ language.sInfoFiltered.replace('_MAX_', sMax)+ language.sInfoPostFix; } else if ( dt.fnRecordsDisplay() == dt.fnRecordsTotal() ) { /* Normal record set */ sOut = language.sInfo. replace('_START_', sStart). replace('_END_', sEnd). replace('_MAX_', sMax). replace('_TOTAL_', sTotal)+ language.sInfoPostFix; } else { /* Record set after filtering */ sOut = language.sInfo. replace('_START_', sStart). replace('_END_', sEnd). replace('_MAX_', sMax). replace('_TOTAL_', sTotal) +' '+ language.sInfoFiltered.replace( '_MAX_', dt.fnFormatNumber(dt.fnRecordsTotal()) )+ language.sInfoPostFix; } var callback = language.fnInfoCallback; if ( callback ) { sOut = callback.call( dt.oInstance, dt, iStart, iEnd, iMax, iTotal, sOut ); } var n = dt.aanFeatures.i; if ( typeof n != 'undefined' ) { for ( var i=0, iLen=n.length ; i<iLen ; i++ ) { $(n[i]).html( sOut ); } } }
javascript
{ "resource": "" }
q10817
forEachChildren
train
function forEachChildren(proc, iterator) { for (let id in proc.children) { iterator(proc.children[id]); } }
javascript
{ "resource": "" }
q10818
bindChild
train
function bindChild(proc, model, key, childCmd) { const { logicClass, updateMsg, createArgs } = childCmd; const originalModel = model[key]; let actualModel = originalModel || {}; let currProc = procOf(actualModel); // Protect update of the model of the same type if (updateMsg && (!currProc || !(currProc.logic instanceof logicClass))) { proc.logger.onCatchError(new Error('Child model does not exists or have incorrect type'), proc); return; } // Re-run prepare with new config args if proc already running // with the same logic class, otherwise destroy the logic if (currProc) { if (!updateMsg) { currProc.destroy(); currProc = null; actualModel = {}; } else { runLogicUpdate(currProc, updateMsg); } } // Run new process for given child definition if no proc was // binded to the model or if it was destroyed if (!currProc) { const shouldRehydrate = actualModel && actualModel === originalModel; currProc = new proc.constructor({ createArgs, logicClass, parent: proc, logger: proc.logger, contexts: proc.contexts, internalContext: proc.internalContext }); model[key] = actualModel; currProc.bind(actualModel); currProc.run(shouldRehydrate); proc.children[currProc.id] = currProc; } return currProc; }
javascript
{ "resource": "" }
q10819
bindComputedFieldCmd
train
function bindComputedFieldCmd(proc, model, key, computeVal) { const { logger } = proc; // Create getter function const isMemoized = computeVal instanceof MemoizedFieldCmd; const computeFn = isMemoized ? computeVal.computeFn : computeVal; const safeComputeValue = () => safeExecFunction(logger, computeFn) const getter = isMemoized ? memoize(safeComputeValue) : safeComputeValue; // Register memoized field in the process to be able to reset // when the model changed if (isMemoized) { proc.computedFields[key] = getter; } // Set the getter in the model Object.defineProperty(model, key, { enumerable: true, configurable: true, set: noop, get: getter }); }
javascript
{ "resource": "" }
q10820
runLogicCreate
train
function runLogicCreate(proc, rehydrate) { const { exec, logic, createArgs, model } = proc; if (logic.create) { const commandFactory = () => { logic.model = !rehydrate ? undefined : model; const res = logic.create.apply(logic, createArgs); logic.model = model; return res; }; exec(commandFactory); } }
javascript
{ "resource": "" }
q10821
runModelObservers
train
function runModelObservers(proc) { const observersIterator = (obs) => obs(); maybeForEach(proc.observers, observersIterator); if (proc.parent) { maybeForEach(proc.childrenObservers, observersIterator); } }
javascript
{ "resource": "" }
q10822
execTask
train
function execTask(proc, taskObj) { const { tasks, logger, model, sharedModel, config, logic } = proc; const { task, executor, notifyCmd, successCmd, failCmd, customArgs, execEvery, customExecId, id: taskId } = taskObj; // If not in multi-thread mode or just need to cancel a tak – // cancel all running task with same identifier (command id) if (taskObj.cancelTask || !execEvery) { cancelTask(proc, taskId); if (taskObj.cancelTask) return; } // Define next execution id const execId = customExecId || nextId(); const executions = tasks[taskId] = tasks[taskId] || {}; const cleanup = () => delete executions[execId]; // Do not create any new task if the task with given exec id // already exists. Usefull for throttle/debounce tasks if (executions[execId]) { executions[execId].exec(taskObj); } else { const taskCall = executor(proc, taskObj); executions[execId] = taskCall; taskCall.exec(taskObj).then(cleanup, cleanup); } }
javascript
{ "resource": "" }
q10823
train
function(template, map, fallback) { if (!map) return template; return template.replace(/\$\{.+?}/g, (match) => { const path = match.substr(2, match.length - 3).trim(); return get(path, map, fallback); }); }
javascript
{ "resource": "" }
q10824
train
function(address, innerSize, writeValues) { return function (lastResults) { var innerDeferred = q.defer(); var addresses = []; var values = []; var directions = []; var numFrames; var numValues; // Flash memory pointer directions.push(driver_const.LJM_WRITE); // Key if (key === undefined) { numFrames = 2; numValues = [1]; } else { // Write for key directions.push(driver_const.LJM_WRITE); addresses.push(driver_const.T7_MA_EXF_KEY); values.push(key); numFrames = 3; numValues = [1, 1]; } if (isReadOp) directions.push(driver_const.LJM_READ); else directions.push(driver_const.LJM_WRITE); addresses.push(ptrAddress); values.push(address); addresses.push(flashAddress); if (isReadOp) { for (var i=0; i<innerSize; i++) { values.push(null); } } else { values.push.apply(values, writeValues); } numValues.push(innerSize); device.rwMany( addresses, directions, numValues, values, // createSafeReject(innerDeferred), function(err) { // console.log('tseries_upgrade: calling rwMany', isReadOp, addresses, directions, numValues, values); // console.log('tseries_upgrade: rwMany Error', err); // console.log('Throwing Upgrade Error', err); if(!isReadOp) { // console.log('Failed to write flash data', addresses, numValues, values, err); } var callFunc = createSafeReject(innerDeferred); callFunc(err); }, function (newResults) { if(!isReadOp) { // console.log('Successfully wrote flash data', addresses, numValues, values); } lastResults.push.apply(lastResults, newResults); innerDeferred.resolve(lastResults); } ); return innerDeferred.promise; }; }
javascript
{ "resource": "" }
q10825
train
function (name, pkgDir) { if (!isString(name) || !isString(pkgDir) || S(name).isEmpty() || S(pkgDir).isEmpty() || !isDirectory.sync(pkgDir)) { return 1 } var scope = utils(name, pkgDir) try { scope.validateIsUnityRoot() scope.createModulesDirectoryInAssets() scope.createModuleDirectory() scope.copyModuleResources() } catch (err) { scope.cleanupOnPostInstallError() scope.printError(err) return 1 } return 0 }
javascript
{ "resource": "" }
q10826
train
function (name, pkgDir) { if (!isString(name) || !isString(pkgDir) || S(name).isEmpty() || S(pkgDir).isEmpty() || !isDirectory.sync(pkgDir)) { return 1 } var scope = utils(name, pkgDir) try { scope.removeModuleDirectory() } catch (err) { scope.printError(err) return 1 } return 0 }
javascript
{ "resource": "" }
q10827
train
function(grunt) { var me = this; this.hookChild( grunt.util, 'spawn', function(original, spawnArgs) { var options = spawnArgs[0]; var callback = spawnArgs[1]; if (options.cmd === process.argv[0]) { var module; for (var i = 0; i < options.args.length; i++) { if (options.args[i].lastIndexOf('--') != 0) { module = options.args[i]; break; } } me.addDebugArg(options.args, module); } return original.call(this, options, callback); } ); }
javascript
{ "resource": "" }
q10828
train
function(year, monthIndex) { if (year.year) { year = year.year(); monthIndex = year.month(); } var intercalaryMonth = this.intercalaryMonth(year); return !!intercalaryMonth && intercalaryMonth === monthIndex; }
javascript
{ "resource": "" }
q10829
train
function(dateString) { var match = dateString.match(DATE_REGEXP); var year = this._validateYear(+match[1]); var month = +match[2]; var isIntercalary = !!match[3]; var monthIndex = this.toMonthIndex(year, month, isIntercalary); var day = +match[4]; return this.newDate(year, monthIndex, day); }
javascript
{ "resource": "" }
q10830
cleanMarks
train
function cleanMarks( o ) { delete o[randKey]; for ( prop in o ) { if ( p.hasOwnProperty( prop ) && get_type( p[prop] ) == 'object' && randKey in p[prop]) { cleanMarks( p[prop] ); } } }
javascript
{ "resource": "" }
q10831
match_objects_teardown
train
function match_objects_teardown( o, p, result ) { if ( get_type( o ) == 'object' ) { cleanMarks( o ); } if ( get_type( p ) == 'object' ) { cleanMarks( p ); } return result; }
javascript
{ "resource": "" }
q10832
query
train
function query( q, limit, offset ) { var i, _l, res, strict = true, reverse = false; if ( this.length === 0 || arguments.length === 0 ) { return []; } if ( typeof q === 'object' && q != null && 'query' in q && arguments.length === 1 ) { limit = +q.limit; offset = +q.offset; strict = !!q.strict; reverse = !!q.reverse; q = q.query; } if ( isNaN( limit ) ) { limit = Infinity; } offset = offset || 0; if ( typeof Array.prototype.filter === 'function' ) { return this.filter(function( o ) { return match( o, q, strict ) === !reverse; }).slice( offset, offset + limit ); } res = []; _l = Math.min( this.length, limit + offset ); i = 0; for ( ; i<_l; i++ ) { if ( match( this[ i ], q, strict ) === !reverse ) { if ( offset-- > 0 ) { continue; } res.push( this[ i ] ); } } return res; }
javascript
{ "resource": "" }
q10833
wma
train
function wma(close, n = 5) { let result = [] let len = close.length if (len === 0 || n <= 0) { return result } let avg = close[0] result.push(avg) let T_m = close[0] let div = n * (n + 1) / 2 for (let i = 1; i < len; i++) { if (i < n) { T_m += close[i] let sum = 0 let d = 0 for (let j = 0; j <= i; j++) { sum += close[i - j] * (n - j) d += (n - j) } avg = sum / d } else { avg += (n * close[i] - T_m) / div T_m += close[i] - close[i - n] } result.push(avg) } return result }
javascript
{ "resource": "" }
q10834
ema
train
function ema(close, n = 5) { let len = close.length let result = [] if (len === 0 || n <= 0) { return result } let alpha = 2 / (n + 1) let avg = close[0] result.push(avg) for (let i = 1; i < len; i++) { avg = alpha * close[i] + (1 - alpha) * avg result.push(avg) } return result }
javascript
{ "resource": "" }
q10835
kdj
train
function kdj(close, high, low, n = 5) { let len = close.length let k = [] let d = [] let j = [] if (len === 0 || n <= 0) { return {k, d, j} } let ik = 50 let id = 50 let ij = 50 let rsv = (close[0] - low[0]) * 100 / (high[0] - low[0]) ik = 2 * ik / 3 + rsv / 3 id = 2 * id / 3 + ik / 3 ij = 3 * ik - 2 * id k.push(ik) d.push(id) j.push(ij) let ln = low[0] let hn = high[0] for (let i = 1; i < len; i++) { if (i < n) { if (ln > low[i]) { ln = low[i] } if (hn < high[i]) { hn = high[i] } } else { if (ln === low[i - n]) { ln = low[i] for (let j = 1; j < n; j++) { if (low[i - j] < ln) { ln = low[i - j] } } } else { if (ln > low[i]) { ln = low[i] } } if (hn === high[i - n]) { hn = high[i] for (let j = 1; j < n; j++) { if (high[i - j] > hn) { hn = high[i - j] } } } else { if (hn < high[i]) { hn = high[i] } } } rsv = (close[i] - ln) * 100 / (hn - ln) ik = 2 * ik / 3 + rsv / 3 id = 2 * id / 3 + ik / 3 ij = 3 * ik - 2 * id k.push(ik) d.push(id) j.push(ij) } return {k, d, j} }
javascript
{ "resource": "" }
q10836
train
function(location, name) { this.location = location; this.name = name; if (typeof localStorage === 'undefined' || localStorage === null) { if (this.name) { this.name = require('sanitize-filename')(this.name, {replacement: '_'}); require('mkdirp').sync(this.location); } } else { this.localStorage = localStorage; } this.path = this.location; if (this.name) this.path += '/' + this.name; }
javascript
{ "resource": "" }
q10837
flatten
train
function flatten(matrix) { const res = []; // If the given matrix is not a matrix but a scalar. if (!Array.isArray(matrix)) { matrix = [ [matrix] ]; } matrix.forEach((row) => { // If the given matrix is a vector. if (!Array.isArray(row)) { row = [row]; } row.forEach((elem) => { res.push(elem.real); res.push(elem.imag); }); }); return res; }
javascript
{ "resource": "" }
q10838
matrix
train
function matrix(rows, columns, values) { // console.log(values); const res = []; let row = []; let real; values.forEach((v, i) => { if (i % 2 == 0) { real = v; } else { row.push({ real: real, imag: v }); if ((i + 1) / 2 % columns == 0) { res.push(row); row = []; } } }); return res; }
javascript
{ "resource": "" }
q10839
Client
train
function Client(config) { RED.nodes.createNode(this, config); const port = String(Math.floor(Math.random() * (40000 - 30000 + 1)) + 30000); // Start a DLPA-Node server. // Options: // --listen LISTEN Listening port. // --host HOST Address of the DLPA server to be connected. // --port PORT Port number of the DLPA server to be connected. // --id CLIENT_ID Client ID // --epsilon EPSILON Epsilon used in the Laplace distribution to add noises. const proc = spawn("python3", [ "-m", "dlpanode.server", "--listen", port, "--host", config.host, "--port", config.port, "--id", config.client_id, "--epsilon", config.epsilon ], { "cwd": __dirname, stdio: ["pipe", process.stdout, "pipe"] }); let exited = false; proc.on("exit", (code, signal) => { this.log(`DLPA-Node server is closed: ${signal}`); exited = true; }) const logger = readline.createInterface({ input: proc.stderr, }); logger.on("line", (line) => { this.log(line) }) const client = new dlpanode.DLPAClient( `localhost:${port}`, grpc.credentials.createInsecure()); this.on("input", (msg) => { // Send a message to the server. client.encryptNoisySum({ values: flatten(msg.payload).map(v => Math.round((v + MAG) * MAG)) }, (err, response) => { if (err) { this.error(err); } }); }); // Stop the server. this.on("close", (done) => { if (exited) { done(); return; } // Wait the server is closed. proc.on("exit", () => { done(); }); // Send a signal. this.log("DLPA-Node server is closing"); proc.stdin.close(); proc.stdout.close(); logger.close(); proc.kill(); }); }
javascript
{ "resource": "" }
q10840
Server
train
function Server(config) { RED.nodes.createNode(this, config); // Start a DLPA server. // Options: // --port PORT Listening port number. // --clients CLIENTS The number of clicents. // --max-workers MAX_WORKERS // The maximum number of workiers (default: 10). const proc = spawn("python3", [ "-m", "dlpa.server", "--port", config.port, "--clients", config.nclient, "--key-length", "128", "--time-span", config.span ? config.span : "300" ], { cwd: __dirname, }); let exited = false; proc.on("exit", (code, signal) => { this.log(`DLPA server is closed: ${signal}`); exited = true; }) const logger = readline.createInterface({ input: proc.stderr }); logger.on("line", (line) => { this.log(line); }) // Wait results which should be outputted into stderr; and then // post a message based on each output. const rl = readline.createInterface({ input: proc.stdout }); rl.on("line", (line) => { const payload = JSON.parse(line); this.send({ "topic": config.topic, "payload": matrix( parseInt(config.rows, 10), parseInt(config.columns, 10), payload.value.map(v => (v / MAG) - MAG)) }); }); // Stop the server. this.on("close", (done) => { if (exited) { done(); return; } // Wait the server is closed. proc.on("exit", () => { done(); }); // Send a signal. this.log("DLPA server is closing"); proc.stdin.close(); rl.close(); logger.close(); proc.kill(); }); }
javascript
{ "resource": "" }
q10841
updateAllDeps
train
function updateAllDeps (pPackageObject, pOutdatedPackages = {}, pOptions = {}) { return Object.assign( {}, pPackageObject, Object.keys(pPackageObject) .filter(pPkgKey => pPkgKey.includes('ependencies')) .reduce( (pAll, pDepKey) => { pAll[pDepKey] = updateDeps(pPackageObject[pDepKey], pOutdatedPackages, pOptions) return pAll }, {} ) ) }
javascript
{ "resource": "" }
q10842
train
function(index) { //Check the index value if(index >= nutty._middlewares.length){ return; } //Call the middleware nutty._middlewares[index](args, function(error) { //Check for undefined error if(typeof error === 'undefined'){ var error = null; } //Check for error if(error && error instanceof Error) { //Throw the error throw error; } //Next middleware on the list return middlewares_recursive(index + 1); }); }
javascript
{ "resource": "" }
q10843
getEntityExtensions
train
function getEntityExtensions(entity) { // Check if entity passed as instance or class if (entity instanceof _entt2.default) { // Return property configuration from instance return _cache.ConfigurationCache.get(entity).extensions; } else if (_lodash2.default.isFunction(entity) && entity.prototype instanceof _entt2.default) { // Return property configuration from class return _cache.ConfigurationCache.get(new entity()).extensions; } }
javascript
{ "resource": "" }
q10844
AerospikeStore
train
function AerospikeStore(options){ var self = this; options = options || {}; Store.call(self,options); self.prefix = null == options.prefix ? _default_prefix : options.prefix; self.ns = null == options.ns ? _default_ns : options.ns; self.st = null == options.st ? _default_set : options.st; self.ttl = null == options.ttl ? _default_ttl : options.ttl; if(!options.hosts || options.hosts.length<=0){ options.hosts = [_default_host]; } if(options.hosts){ var hosts = options.hosts.map(function(host){ var _val = host.split(':'); var _host = _val[0]; var _port = ~~_val[1] || _default_port; return { addr:_host,port:_port}; }); var timeout = (typeof options.timeout === 'number' ? options.timeout : _default_timeout); aerospike.client({ hosts:hosts, log:{ level: _default_log_level }, policies:{ timeout: timeout } }).connect(function(err,client){ if(err && err.code !== aerospike.status.AEROSPIKE_OK){ console.error('Aerospike server connection Error : %j',err); }else{ self.client = client; } }); } }
javascript
{ "resource": "" }
q10845
train
function($menu) { // position to the lower middle of the trigger element if ($.ui && $.ui.position) { // .position() is provided as a jQuery UI utility // (...and it won't work on hidden elements) $menu.css('display', 'block').position({ my: "center top", at: "center bottom", of: this, offset: "0 5", collision: "fit" }).css('display', 'none'); } else { // determine contextMenu position var offset = this.offset(); offset.top += this.outerHeight(); offset.left += this.outerWidth() / 2 - $menu.outerWidth() / 2; $menu.css(offset); } }
javascript
{ "resource": "" }
q10846
train
function(e) { e.preventDefault(); e.stopImmediatePropagation(); $(this).trigger($.Event("contextmenu", { data: e.data, pageX: e.pageX, pageY: e.pageY })); }
javascript
{ "resource": "" }
q10847
train
function(e) { // show menu var $this = $(this); if ($this.data('contextMenuActive') && $currentTrigger && $currentTrigger.length && $currentTrigger.is($this) && !$this.hasClass('context-menu-disabled')) { e.preventDefault(); e.stopImmediatePropagation(); $currentTrigger = $this; $this.trigger($.Event("contextmenu", { data: e.data, pageX: e.pageX, pageY: e.pageY })); } $this.removeData('contextMenuActive'); }
javascript
{ "resource": "" }
q10848
train
function(e) { e.stopPropagation(); var opt = $(this).data('contextMenu') || {}; // obtain currently selected menu if (opt.$selected) { var $s = opt.$selected; opt = opt.$selected.parent().data('contextMenu') || {}; opt.$selected = $s; } var $children = opt.$menu.children(), $prev = !opt.$selected || !opt.$selected.prev().length ? $children.last() : opt.$selected.prev(), $round = $prev; // skip disabled while ($prev.hasClass('disabled') || $prev.hasClass('not-selectable')) { if ($prev.prev().length) { $prev = $prev.prev(); } else { $prev = $children.last(); } if ($prev.is($round)) { // break endless loop return; } } // leave current if (opt.$selected) { handle.itemMouseleave.call(opt.$selected.get(0), e); } // activate next handle.itemMouseenter.call($prev.get(0), e); // focus input var $input = $prev.find('input, textarea, select'); if ($input.length) { $input.focus(); } }
javascript
{ "resource": "" }
q10849
train
function(e) { var $this = $(this).closest('.context-menu-item'), data = $this.data(), opt = data.contextMenu, root = data.contextMenuRoot; root.$selected = opt.$selected = $this; root.isInput = opt.isInput = true; }
javascript
{ "resource": "" }
q10850
train
function(e) { var $this = $(this), data = $this.data(), opt = data.contextMenu, root = data.contextMenuRoot, key = data.contextMenuKey, callback; // abort if the key is unknown or disabled or is a menu if (!opt.items[key] || $this.is('.disabled, .context-menu-submenu, .context-menu-separator, .not-selectable')) { return; } e.preventDefault(); e.stopImmediatePropagation(); if ($.isFunction(root.callbacks[key]) && Object.prototype.hasOwnProperty.call(root.callbacks, key)) { // item-specific callback callback = root.callbacks[key]; } else if ($.isFunction(root.callback)) { // default callback callback = root.callback; } else { // no callback, no action return; } // hide menu if callback doesn't stop that if (callback.call(root.$trigger, key, root) !== false) { root.$menu.trigger('contextmenu:hide'); } else if (root.$menu.parent().length) { op.update.call(root.$trigger, root); } }
javascript
{ "resource": "" }
q10851
gulpResourceHints
train
function gulpResourceHints (opt) { var options = helpers.options(opt) helpers.reset() return new Transform({ objectMode: true, transform: function (file, enc, cb) { if (file.isNull()) { helpers.logger(PLUGIN_NAME, 'no file', true) cb(null, file) return } var fileContents = String(file.contents) // Gather assets, keep unique values // Using https://www.npmjs.com/package/list-assets var assets = new Set(listAssets.html( fileContents, { absolute: true, protocolRelative: true } ).map(ob => ob.url)) if (assets.size < 0) { // Skip file: no static assets cb(null, file) return } if (!helpers.hasInsertionPoint(file)) { helpers.logger(PLUGIN_NAME, 'Skipping file: no <head> or token found', true) cb(null, file) return } // Future feature! Gotta do more stream madness // if (options.getCSSAssets) { // for (var k = 0, cssLen = assets.length; k < cssLen; k++) { // if (assets[k].endsWith('.css') || assets[k].endsWith('.CSS')) { // assets.push(listAssets.css( // fileContents // )) // } // } // } // Build resource hints based on user-selected assets var data = [''] assets.forEach((aVal, aKey, set) => { Object.keys(options.paths).forEach((key) => { if (options.paths[key] === '') { return } data.push(helpers.buildResourceHint(key, aVal, options.paths[key])) }) }) data = data.reduce((a, b) => a + b) var newFile = helpers.writeDataToFile(file, data, options.pageToken) if (!newFile) { helpers.logger(PLUGIN_NAME + ': Could not write data to file. ' + file.relative) cb(null, file) return } else { file.contents = new Buffer(newFile) } cb(null, file) } }) }
javascript
{ "resource": "" }
q10852
train
function(key, data, callback) { 'use strict'; /** * Read scores by values. * * @param {Array} values * @param {Function} callback */ var ReadScores = function(values, callback) { var result = []; /** * Get scores recursive. */ var GetRecursive = function() { if (!values.length) { callback(null, result); return; } var value = values.pop(); this.getClient().zscore(key, value, function(err, score) { if (err) { callback(err); return; } result.push(score); GetRecursive(); }); }.bind(this); GetRecursive(); }.bind(this); /** * Read key. * * @param {String} key * @param {String} type * @param {Function} rkCallback */ var ReadKey = function(key, type, rkCallback) { var params = [ key ], command = { set: 'smembers', zset: 'zrange', list: 'lrange', hash: 'hgetall' }[ type ] || 'get'; if (command.indexOf('range') !== -1) { params.push(0); params.push(-1); } params.push(function(err, values) { if (err) { rkCallback(err); return; } switch (type) { case 'zset': ReadScores(_.clone(values).reverse(), function(err, scores) { rkCallback(null, _.zip(scores, values)); }); break; default: rkCallback(null, values); break; } }); this.getClient()[ command ].apply(this.getClient(), params); }.bind(this); switch (this.getExportParams().type) { // Export as redis type. case 'redis': return function(err, type) { var type2PrintSetCommand = { string: 'SET', set: 'SADD', zset: 'ZADD', list: 'RPUSH', hash: 'HSET' }; if (!data) { data = ''; } ReadKey(key, type, function(err, value) { if (err) { callback(err); return; } var command = type2PrintSetCommand[ type ]; key = key.trim(); switch (type) { case 'set': _.each(value, function(item) { data += command + ' "' + key + '" "' + item + "\"\n"; }); break; case 'zset': _.each(value, function(item) { data += command + ' "' + key + '" ' + item[0] + ' "' + item[1] + "\"\n"; }); break; case 'hash': _.each(_.pairs(value), function(item) { data += command + ' "' + key + '" "' + item[0] + '" "' + item[1] + "\"\n"; }); break; default: data += command + ' "' + key + '" "' + value + "\"\n"; break; } callback(null, data); }); }; // Export as json type. case 'json': return function(err, type) { if (!data) { data = {}; } ReadKey(key, type, function(err, value) { if (err) { callback(err); return; } switch (type) { case 'zset': var withoutScores = []; _.each(value, function(item) { withoutScores.push(item[1]); }); value = withoutScores; break; } data[ key.trim() ] = value; callback(null, data); }); }; } }
javascript
{ "resource": "" }
q10853
train
function(err, status) { if (err) { callback(err); return; } if (status || status === 'OK') { report.inserted += _.isNumber(status) ? status : 1; } else { // Hm... report.errors += 1; } AddRecursive(); }
javascript
{ "resource": "" }
q10854
mustUnzip
train
function mustUnzip(file, mode){ if (mode){ return mode === 'tgz'; } var extension = path.extname(file); return contains(['.tgz', '.gz'], extension); }
javascript
{ "resource": "" }
q10855
isDynamicProperty
train
function isDynamicProperty (propertyConfiguration) { return propertyConfiguration // Is defined as dynamic && propertyConfiguration.dynamic // Dynamic option value is a function && _.isFunction(propertyConfiguration.dynamic) // Dynamic option value is not a EnTT class && (propertyConfiguration.dynamic !== EnTT); }
javascript
{ "resource": "" }
q10856
train
function(name, language) { name = (name || 'gregorian').toLowerCase(); language = language || ''; var cal = this._localCals[name + '-' + language]; if (!cal && this.calendars[name]) { cal = new this.calendars[name](language); this._localCals[name + '-' + language] = cal; } if (!cal) { throw (this.local.invalidCalendar || this.regionalOptions[''].invalidCalendar). replace(/\{0\}/, name); } return cal; }
javascript
{ "resource": "" }
q10857
train
function(year, month, day, calendar, language) { calendar = (year != null && year.year ? year.calendar() : (typeof calendar === 'string' ? this.instance(calendar, language) : calendar)) || this.instance(); return calendar.newDate(year, month, day); }
javascript
{ "resource": "" }
q10858
train
function(digits, powers) { return function(value) { var localNumber = ''; var power = 0; while (value > 0) { var units = value % 10; localNumber = (units === 0 ? '' : digits[units] + powers[power]) + localNumber; power++; value = Math.floor(value / 10); } if (localNumber.indexOf(digits[1] + powers[1]) === 0) { localNumber = localNumber.substr(1); } return localNumber || digits[0]; } }
javascript
{ "resource": "" }
q10859
CDate
train
function CDate(calendar, year, month, day) { this._calendar = calendar; this._year = year; this._month = month; this._day = day; if (this._calendar._validateLevel === 0 && !this._calendar.isValid(this._year, this._month, this._day)) { throw ($.calendars.local.invalidDate || $.calendars.regionalOptions[''].invalidDate). replace(/\{0\}/, this._calendar.local.name); } }
javascript
{ "resource": "" }
q10860
pad
train
function pad(value, length) { value = '' + value; return '000000'.substring(0, length - value.length) + value; }
javascript
{ "resource": "" }
q10861
train
function(year, month, day) { return this._calendar.newDate((year == null ? this : year), month, day); }
javascript
{ "resource": "" }
q10862
train
function(year, month, day) { if (!this._calendar.isValid(year, month, day)) { throw ($.calendars.local.invalidDate || $.calendars.regionalOptions[''].invalidDate). replace(/\{0\}/, this._calendar.local.name); } this._year = year; this._month = month; this._day = day; return this; }
javascript
{ "resource": "" }
q10863
train
function(year) { var date = this._validate(year, this.minMonth, this.minDay, $.calendars.local.invalidYear || $.calendars.regionalOptions[''].invalidYear); return (date.year() < 0 ? this.local.epochs[0] : this.local.epochs[1]); }
javascript
{ "resource": "" }
q10864
train
function(year, month) { var date = this._validate(year, month, this.minDay, $.calendars.local.invalidMonth || $.calendars.regionalOptions[''].invalidMonth); return (date.month() + this.monthsInYear(date) - this.firstMonth) % this.monthsInYear(date) + this.minMonth; }
javascript
{ "resource": "" }
q10865
apply_write
train
function apply_write (key, value, err) { var _reading = reading[key] reading[key] = null while(_reading && _reading.length) _reading.shift()(err, value) _write() }
javascript
{ "resource": "" }
q10866
train
function (key, value) { store[key] = value //not urgent, but save this if we are not doing anything. dirty[key] = true apply_write(key, value) }
javascript
{ "resource": "" }
q10867
send_commands
train
function send_commands(cmds, cb) { function callback(value) { if (cb) cb(value) this.locked = false } function run() { if (this.locked = cmds.length > 0) send_command(cmds.shift(), (success) => { if (success) setTimeout(run, 200); else callback(false); }); else callback(true); }; if(!this.locked) run(); }
javascript
{ "resource": "" }
q10868
getDefPath
train
function getDefPath(defPath) { // if path passed... if(defPath) { // if not url and not absolute... if(!/^https?:/.test(defPath) && !path.isAbsolute(defPath)) { // normalize path as relative to folder containing node_modules return path.normalize(path.join(__dirname, '/../../../', defPath)); } // else, return unchanged... else { return defPath; } } // else, return defualt path... else { return path.normalize(path.join(__dirname, _swaggerDef)); } }
javascript
{ "resource": "" }
q10869
truncateSamples
train
function truncateSamples(samples) { /** @type {number} */ let len = samples.length; for (let i=0; i<len; i++) { if (samples[i] > 1) { samples[i] = 1; } else if (samples[i] < -1) { samples[i] = -1; } } }
javascript
{ "resource": "" }
q10870
Response
train
function Response(statusCode, headers, body) { this.statusCode = statusCode; this.headers = {}; for (var key in headers) { this.headers[key.toLowerCase()] = headers[key]; } this.body = body; }
javascript
{ "resource": "" }
q10871
train
function (menu, cmenu) { var className = cmenu.className; $.each(cmenu.theme.split(","), function (i, n) { className += ' ' + cmenu.themePrefix + n; }); // var $t = $('<div style="background-color:#ffff00; xwidth:200px; height:200px"><table style="" cellspacing=0 cellpadding=0></table></div>').click(function(){cmenu.hide(); return false;}); // We wrap a table around it so width can be flexible var $t = $('<table style="" cellspacing="0" cellpadding="0"></table>').click(function () { cmenu.hide(); return false; }); // We wrap a table around it so width can be flexible var $tr = $('<tr></tr>'); var $td = $('<td></td>'); var $div = cmenu._div = $('<div class="' + className + '"></div>'); cmenu._div.hover( function () { if (cmenu.closeTimer) { clearTimeout(cmenu.closeTimer); cmenu.closeTimer = null; } }, function () { var myClass = cmenu; function timerRelay() { myClass.hide(); } myClass.closeTimer = setTimeout(timerRelay, 500); } ); // Each menu item is specified as either: // title:function // or title: { property:value ... } /* for (var i=0; i<menu.length; i++) { var m = menu[i]; if (m==$.contextMenu.separator) { $div.append(cmenu.createSeparator()); } else { for (var opt in menu[i]) { $div.append(cmenu.createMenuItem(opt,menu[i][opt])); // Extracted to method for extensibility } } } */ for (var i = 0; i < menu.length; i++) { var m = menu[i]; if (m === $.contextMenu.separator) { $div.append(cmenu.createSeparator()); } else { $div.append(cmenu.createMenuItem(m)); // Extracted to method for extensibility } } if (cmenu.useIframe) { $td.append(cmenu.createIframe()); } $t.append($tr.append($td.append($div))); return $t; }
javascript
{ "resource": "" }
q10872
train
function (obj) { var cmenu = this; var label = obj.label; if (typeof obj === "function") { obj = {onclick: obj}; } // If passed a simple function, turn it into a property of an object // Default properties, extended in case properties are passed var o = $.extend({ onclick: function () { }, className: '', hoverClassName: cmenu.itemHoverClassName, icon: '', disabled: false, title: '', hoverItem: cmenu.hoverItem, hoverItemOut: cmenu.hoverItemOut }, obj); // If an icon is specified, hard-code the background-image style. Themes that don't show images should take this into account in their CSS var iconStyle = (o.icon) ? 'background-image:url(' + o.icon + ');' : ''; var $div = $('<div class="' + cmenu.itemClassName + ' ' + o.className + ((o.disabled) ? ' ' + cmenu.disabledItemClassName : '') + '" title="' + o.title + '"></div>') // If the item is disabled, don't do anything when it is clicked .click( function (e) { if (cmenu.isItemDisabled(this)) { return false; } else { return o.onclick.call(cmenu.target, this, cmenu, e, label); } } ) // Change the class of the item when hovered over .hover( function () { o.hoverItem.call(this, (cmenu.isItemDisabled(this)) ? cmenu.disabledItemHoverClassName : o.hoverClassName); } , function () { o.hoverItemOut.call(this, (cmenu.isItemDisabled(this)) ? cmenu.disabledItemHoverClassName : o.hoverClassName); } ); var $idiv = $('<div class="' + cmenu.innerDivClassName + '" style="' + iconStyle + '">' + label + '</div>'); $div.append($idiv); return $div; }
javascript
{ "resource": "" }
q10873
train
function (cmenu) { cmenu.shadowObj = $('<div class="' + cmenu.shadowClass + '"></div>').css({ display: 'none', position: "absolute", zIndex: 9998, opacity: cmenu.shadowOpacity, backgroundColor: cmenu.shadowColor }); $(cmenu.appendTo).append(cmenu.shadowObj); }
javascript
{ "resource": "" }
q10874
train
function (x, y, e) { var cmenu = this; if (cmenu.shadow) { cmenu.shadowObj.css({ width: (cmenu.menu.width() + cmenu.shadowWidthAdjust) + "px", height: (cmenu.menu.height() + cmenu.shadowHeightAdjust) + "px", top: (y + cmenu.shadowOffsetY) + "px", left: (x + cmenu.shadowOffsetX) + "px" }).addClass(cmenu.shadowClass)[cmenu.showTransition](cmenu.showSpeed); } }
javascript
{ "resource": "" }
q10875
train
function (clickX, clickY, cmenu, e) { var x = clickX + cmenu.offsetX; var y = clickY + cmenu.offsetY; var h = $(cmenu.menu).height(); var w = $(cmenu.menu).width(); var dir = cmenu.direction; if (cmenu.constrainToScreen) { var $w = $(window); var wh = $w.height(); var ww = $w.width(); var st = $w.scrollTop(); var maxTop = y - st - 5; var maxBottom = wh + st - y - 5; if (h > maxBottom) { if (h > maxTop) { if (maxTop > maxBottom) { // scrollable en haut h = maxTop; cmenu._div.css('height', h + 'px').css('overflow-y', 'scroll'); y -= h; } else { // scrollable en bas h = maxBottom; cmenu._div.css('height', h + 'px').css('overflow-y', 'scroll'); } } else { // menu ok en haut y -= h; } } else { // menu ok en bas } var maxRight = x + w - $w.scrollLeft(); if (maxRight > ww) { x -= (maxRight - ww); } } return {'x': x, 'y': y}; }
javascript
{ "resource": "" }
q10876
train
function () { var cmenu = this; if (cmenu.shown) { if (cmenu.iframe) { $(cmenu.iframe).hide(); } if (cmenu.menu) { cmenu.menu[cmenu.hideTransition](cmenu.hideSpeed, ((cmenu.hideCallback) ? function () { cmenu.hideCallback.call(cmenu); } : null)); } if (cmenu.shadow) { cmenu.shadowObj[cmenu.hideTransition](cmenu.hideSpeed); } } cmenu.shown = false; }
javascript
{ "resource": "" }
q10877
fnArraySwitch
train
function fnArraySwitch( aArray, iFrom, iTo ) { var mStore = aArray.splice( iFrom, 1 )[0]; aArray.splice( iTo, 0, mStore ); }
javascript
{ "resource": "" }
q10878
train
function( dt, opts ) { var oDTSettings; if ( $.fn.dataTable.Api ) { oDTSettings = new $.fn.dataTable.Api( dt ).settings()[0]; } // 1.9 compatibility else if ( dt.fnSettings ) { // DataTables object, convert to the settings object oDTSettings = dt.fnSettings(); } else if ( typeof dt === 'string' ) { // jQuery selector if ( $.fn.dataTable.fnIsDataTable( $(dt)[0] ) ) { oDTSettings = $(dt).eq(0).dataTable().fnSettings(); } } else if ( dt.nodeName && dt.nodeName.toLowerCase() === 'table' ) { // Table node if ( $.fn.dataTable.fnIsDataTable( dt.nodeName ) ) { oDTSettings = $(dt.nodeName).dataTable().fnSettings(); } } else if ( dt instanceof jQuery ) { // jQuery object if ( $.fn.dataTable.fnIsDataTable( dt[0] ) ) { oDTSettings = dt.eq(0).dataTable().fnSettings(); } } else { // DataTables settings object oDTSettings = dt; } // Ensure that we can't initialise on the same table twice if ( oDTSettings._colReorder ) { throw "ColReorder already initialised on table #"+oDTSettings.nTable.id; } // Convert from camelCase to Hungarian, just as DataTables does var camelToHungarian = $.fn.dataTable.camelToHungarian; if ( camelToHungarian ) { camelToHungarian( ColReorder.defaults, ColReorder.defaults, true ); camelToHungarian( ColReorder.defaults, opts || {} ); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * @namespace Settings object which contains customisable information for ColReorder instance */ this.s = { /** * DataTables settings object * @property dt * @type Object * @default null */ "dt": null, /** * Initialisation object used for this instance * @property init * @type object * @default {} */ "init": $.extend( true, {}, ColReorder.defaults, opts ), /** * Number of columns to fix (not allow to be reordered) * @property fixed * @type int * @default 0 */ "fixed": 0, /** * Number of columns to fix counting from right (not allow to be reordered) * @property fixedRight * @type int * @default 0 */ "fixedRight": 0, /** * Callback function for once the reorder has been done * @property reorderCallback * @type function * @default null */ "reorderCallback": null, /** * @namespace Information used for the mouse drag */ "mouse": { "startX": -1, "startY": -1, "offsetX": -1, "offsetY": -1, "target": -1, "targetIndex": -1, "fromIndex": -1 }, /** * Information which is used for positioning the insert cusor and knowing where to do the * insert. Array of objects with the properties: * x: x-axis position * to: insert point * @property aoTargets * @type array * @default [] */ "aoTargets": [] }; /** * @namespace Common and useful DOM elements for the class instance */ this.dom = { /** * Dragging element (the one the mouse is moving) * @property drag * @type element * @default null */ "drag": null, /** * The insert cursor * @property pointer * @type element * @default null */ "pointer": null }; /* Constructor logic */ this.s.dt = oDTSettings; this.s.dt._colReorder = this; this._fnConstruct(); /* Add destroy callback */ oDTSettings.oApi._fnCallbackReg(oDTSettings, 'aoDestroyCallback', $.proxy(this._fnDestroy, this), 'ColReorder'); return this; }
javascript
{ "resource": "" }
q10879
train
function ( a ) { if ( a.length != this.s.dt.aoColumns.length ) { this.s.dt.oInstance.oApi._fnLog( this.s.dt, 1, "ColReorder - array reorder does not "+ "match known number of columns. Skipping." ); return; } for ( var i=0, iLen=a.length ; i<iLen ; i++ ) { var currIndex = $.inArray( i, a ); if ( i != currIndex ) { /* Reorder our switching array */ fnArraySwitch( a, currIndex, i ); /* Do the column reorder in the table */ this.s.dt.oInstance.fnColReorder( currIndex, i ); } } /* When scrolling we need to recalculate the column sizes to allow for the shift */ if ( this.s.dt.oScroll.sX !== "" || this.s.dt.oScroll.sY !== "" ) { this.s.dt.oInstance.fnAdjustColumnSizing( false ); } /* Save the state */ this.s.dt.oInstance.oApi._fnSaveState( this.s.dt ); this._fnSetColumnIndexes(); if ( this.s.reorderCallback !== null ) { this.s.reorderCallback.call( this ); } }
javascript
{ "resource": "" }
q10880
train
function ( oState ) { var i, iLen, aCopy, iOrigColumn; var oSettings = this.s.dt; var columns = oSettings.aoColumns; oState.ColReorder = []; /* Sorting */ if ( oState.aaSorting ) { // 1.10.0- for ( i=0 ; i<oState.aaSorting.length ; i++ ) { oState.aaSorting[i][0] = columns[ oState.aaSorting[i][0] ]._ColReorder_iOrigCol; } var aSearchCopy = $.extend( true, [], oState.aoSearchCols ); for ( i=0, iLen=columns.length ; i<iLen ; i++ ) { iOrigColumn = columns[i]._ColReorder_iOrigCol; /* Column filter */ oState.aoSearchCols[ iOrigColumn ] = aSearchCopy[i]; /* Visibility */ oState.abVisCols[ iOrigColumn ] = columns[i].bVisible; /* Column reordering */ oState.ColReorder.push( iOrigColumn ); } } else if ( oState.order ) { // 1.10.1+ for ( i=0 ; i<oState.order.length ; i++ ) { oState.order[i][0] = columns[ oState.order[i][0] ]._ColReorder_iOrigCol; } var stateColumnsCopy = $.extend( true, [], oState.columns ); for ( i=0, iLen=columns.length ; i<iLen ; i++ ) { iOrigColumn = columns[i]._ColReorder_iOrigCol; /* Columns */ oState.columns[ iOrigColumn ] = stateColumnsCopy[i]; /* Column reordering */ oState.ColReorder.push( iOrigColumn ); } } }
javascript
{ "resource": "" }
q10881
train
function ( e, nTh ) { var that = this; /* Store information about the mouse position */ var target = $(e.target).closest('th, td'); var offset = target.offset(); var idx = parseInt( $(nTh).attr('data-column-index'), 10 ); if ( idx === undefined ) { return; } this.s.mouse.startX = e.pageX; this.s.mouse.startY = e.pageY; this.s.mouse.offsetX = e.pageX - offset.left; this.s.mouse.offsetY = e.pageY - offset.top; this.s.mouse.target = this.s.dt.aoColumns[ idx ].nTh;//target[0]; this.s.mouse.targetIndex = idx; this.s.mouse.fromIndex = idx; this._fnRegions(); /* Add event handlers to the document */ $(document) .on( 'mousemove.ColReorder', function (e) { that._fnMouseMove.call( that, e ); } ) .on( 'mouseup.ColReorder', function (e) { that._fnMouseUp.call( that, e ); } ); }
javascript
{ "resource": "" }
q10882
train
function ( e ) { var that = this; if ( this.dom.drag === null ) { /* Only create the drag element if the mouse has moved a specific distance from the start * point - this allows the user to make small mouse movements when sorting and not have a * possibly confusing drag element showing up */ if ( Math.pow( Math.pow(e.pageX - this.s.mouse.startX, 2) + Math.pow(e.pageY - this.s.mouse.startY, 2), 0.5 ) < 5 ) { return; } this._fnCreateDragNode(); } /* Position the element - we respect where in the element the click occured */ this.dom.drag.css( { left: e.pageX - this.s.mouse.offsetX, top: e.pageY - this.s.mouse.offsetY } ); /* Based on the current mouse position, calculate where the insert should go */ var bSet = false; var lastToIndex = this.s.mouse.toIndex; for ( var i=1, iLen=this.s.aoTargets.length ; i<iLen ; i++ ) { if ( e.pageX < this.s.aoTargets[i-1].x + ((this.s.aoTargets[i].x-this.s.aoTargets[i-1].x)/2) ) { this.dom.pointer.css( 'left', this.s.aoTargets[i-1].x ); this.s.mouse.toIndex = this.s.aoTargets[i-1].to; bSet = true; break; } } // The insert element wasn't positioned in the array (less than // operator), so we put it at the end if ( !bSet ) { this.dom.pointer.css( 'left', this.s.aoTargets[this.s.aoTargets.length-1].x ); this.s.mouse.toIndex = this.s.aoTargets[this.s.aoTargets.length-1].to; } // Perform reordering if realtime updating is on and the column has moved if ( this.s.init.bRealtime && lastToIndex !== this.s.mouse.toIndex ) { this.s.dt.oInstance.fnColReorder( this.s.mouse.fromIndex, this.s.mouse.toIndex ); this.s.mouse.fromIndex = this.s.mouse.toIndex; this._fnRegions(); } }
javascript
{ "resource": "" }
q10883
train
function ( e ) { var that = this; $(document).off( 'mousemove.ColReorder mouseup.ColReorder' ); if ( this.dom.drag !== null ) { /* Remove the guide elements */ this.dom.drag.remove(); this.dom.pointer.remove(); this.dom.drag = null; this.dom.pointer = null; /* Actually do the reorder */ this.s.dt.oInstance.fnColReorder( this.s.mouse.fromIndex, this.s.mouse.toIndex ); this._fnSetColumnIndexes(); /* When scrolling we need to recalculate the column sizes to allow for the shift */ if ( this.s.dt.oScroll.sX !== "" || this.s.dt.oScroll.sY !== "" ) { this.s.dt.oInstance.fnAdjustColumnSizing( false ); } /* Save the state */ this.s.dt.oInstance.oApi._fnSaveState( this.s.dt ); if ( this.s.reorderCallback !== null ) { this.s.reorderCallback.call( this ); } } }
javascript
{ "resource": "" }
q10884
train
function () { var aoColumns = this.s.dt.aoColumns; this.s.aoTargets.splice( 0, this.s.aoTargets.length ); this.s.aoTargets.push( { "x": $(this.s.dt.nTable).offset().left, "to": 0 } ); var iToPoint = 0; for ( var i=0, iLen=aoColumns.length ; i<iLen ; i++ ) { /* For the column / header in question, we want it's position to remain the same if the * position is just to it's immediate left or right, so we only incremement the counter for * other columns */ if ( i != this.s.mouse.fromIndex ) { iToPoint++; } if ( aoColumns[i].bVisible ) { this.s.aoTargets.push( { "x": $(aoColumns[i].nTh).offset().left + $(aoColumns[i].nTh).outerWidth(), "to": iToPoint } ); } } /* Disallow columns for being reordered by drag and drop, counting right to left */ if ( this.s.fixedRight !== 0 ) { this.s.aoTargets.splice( this.s.aoTargets.length - this.s.fixedRight ); } /* Disallow columns for being reordered by drag and drop, counting left to right */ if ( this.s.fixed !== 0 ) { this.s.aoTargets.splice( 0, this.s.fixed ); } }
javascript
{ "resource": "" }
q10885
train
function () { var scrolling = this.s.dt.oScroll.sX !== "" || this.s.dt.oScroll.sY !== ""; var origCell = this.s.dt.aoColumns[ this.s.mouse.targetIndex ].nTh; var origTr = origCell.parentNode; var origThead = origTr.parentNode; var origTable = origThead.parentNode; var cloneCell = $(origCell).clone(); // This is a slightly odd combination of jQuery and DOM, but it is the // fastest and least resource intensive way I could think of cloning // the table with just a single header cell in it. this.dom.drag = $(origTable.cloneNode(false)) .addClass( 'DTCR_clonedTable' ) .append( $(origThead.cloneNode(false)).append( $(origTr.cloneNode(false)).append( cloneCell[0] ) ) ) .css( { position: 'absolute', top: 0, left: 0, width: $(origCell).outerWidth(), height: $(origCell).outerHeight() } ) .appendTo( 'body' ); this.dom.pointer = $('<div></div>') .addClass( 'DTCR_pointer' ) .css( { position: 'absolute', top: scrolling ? $('div.dataTables_scroll', this.s.dt.nTableWrapper).offset().top : $(this.s.dt.nTable).offset().top, height : scrolling ? $('div.dataTables_scroll', this.s.dt.nTableWrapper).height() : $(this.s.dt.nTable).height() } ) .appendTo( 'body' ); }
javascript
{ "resource": "" }
q10886
train
function () { var i, iLen; for ( i=0, iLen=this.s.dt.aoDrawCallback.length ; i<iLen ; i++ ) { if ( this.s.dt.aoDrawCallback[i].sName === 'ColReorder_Pre' ) { this.s.dt.aoDrawCallback.splice( i, 1 ); break; } } $(this.s.dt.nTHead).find( '*' ).off( '.ColReorder' ); $.each( this.s.dt.aoColumns, function (i, column) { $(column.nTh).removeAttr('data-column-index'); } ); this.s.dt._colReorder = null; this.s = null; }
javascript
{ "resource": "" }
q10887
train
function () { $.each( this.s.dt.aoColumns, function (i, column) { $(column.nTh).attr('data-column-index', i); } ); }
javascript
{ "resource": "" }
q10888
train
function() { return appdev.getMetadata(['./assets/functions.json']).then(function() { if (!appdev.client.context['user-claims']) { grunt.fail.fatal('failed to authenticate to Mozu'); done(); return false; } return false; }).catch( function(err) { grunt.fail.fatal('failed to authenticate to Mozu'); done(); return true; }); }
javascript
{ "resource": "" }
q10889
arrDel
train
function arrDel(arr, indexArr) { // check params if (arr == null) { return []; }else if(Object.prototype.toString.call(arr) !== "[object Array]"){ throw new TypeError('PARAM MUST BE ARRAY'); } if(indexArr == null){ return arr }else if(Object.prototype.toString.call(indexArr) !== "[object Array]"){ throw new TypeError('PARAM MUST BE ARRAY'); } var arrLen = arr.length; for(var i=0, len=indexArr.length; i < len; i++){ if(typeof indexArr[i] !== "number"){ throw new TypeError('PARAM MUST BE NUMBER ARRAY'); } if(Math.abs(indexArr[i]) > arrLen){ indexArr[i] = arrLen + 1; } if(indexArr[i] >= -arrLen && indexArr[i] < 0){ indexArr[i] = indexArr[i] + arrLen; } } // first sort indexArr, then remove redupliction indexArr.sort(function(a, b){ return a - b }) var tmpArr = []; for(var i=0, len=indexArr.length; i < len; i++){ if(tmpArr.indexOf(indexArr[i]) == -1){ tmpArr.push(indexArr[i]) } } // should not change the value of input arr var outArr = JSON.parse(JSON.stringify(arr)); if (arr.length === 0) { return []; } for (var i = 0, len = tmpArr.length; i < len; i++) { outArr.splice(tmpArr[i] - i, 1); } return outArr }
javascript
{ "resource": "" }
q10890
getGesture
train
function getGesture(gestures, type) { if (!gestures.length) return; var types = _.pluck(gestures, 'type'); var index = types.indexOf(type); if (index > -1) return gestures[index]; }
javascript
{ "resource": "" }
q10891
timestampsPlugin
train
function timestampsPlugin(schema, options) { // Add the fields to the schema schema.add({ createdAt: { type: Date, 'default': Date.now }, updatedAt: { type: Date, 'default': Date.now }, deletedAt: { type: Date, sparse: true } }); // Define the pre save hook schema.pre('save', function (next) { this.updatedAt = new Date(); next(); }); // Create an index on all the paths schema.path('createdAt').index(true); schema.path('updatedAt').index(true); schema.path('deletedAt').index(true); }
javascript
{ "resource": "" }
q10892
train
function(date) { if (this._calendar.name !== date._calendar.name) { throw (_exports.local.differentCalendars || _exports.regionalOptions[''].differentCalendars). replace(/\{0\}/, this._calendar.local.name).replace(/\{1\}/, date._calendar.local.name); } var c = (this._year !== date._year ? this._year - date._year : this._month !== date._month ? this.monthOfYear() - date.monthOfYear() : this._day - date._day); return (c === 0 ? 0 : (c < 0 ? -1 : +1)); }
javascript
{ "resource": "" }
q10893
train
function(year) { var date = this._validate(year, this.minMonth, this.minDay, _exports.local.invalidYear || _exports.regionalOptions[''].invalidYear); return (date.year() < 0 ? '-' : '') + pad(Math.abs(date.year()), 4) }
javascript
{ "resource": "" }
q10894
train
function(year, ord) { var m = (ord + this.firstMonth - 2 * this.minMonth) % this.monthsInYear(year) + this.minMonth; this._validate(year, m, this.minDay, _exports.local.invalidMonth || _exports.regionalOptions[''].invalidMonth); return m; }
javascript
{ "resource": "" }
q10895
train
function(year, month, day) { var date = this._validate(year, month, day, _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate); return date.toJD() - this.newDate(date.year(), this.fromMonthOfYear(date.year(), this.minMonth), this.minDay).toJD() + 1; }
javascript
{ "resource": "" }
q10896
train
function(year, month, day) { var date = this._validate(year, month, day, _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate); return (Math.floor(this.toJD(date)) + 2) % this.daysInWeek(); }
javascript
{ "resource": "" }
q10897
train
function(year, month, day) { this._validate(year, month, day, _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate); return {}; }
javascript
{ "resource": "" }
q10898
train
function(date, value, period) { this._validate(date, this.minMonth, this.minDay, _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate); var y = (period === 'y' ? value : date.year()); var m = (period === 'm' ? value : date.month()); var d = (period === 'd' ? value : date.day()); if (period === 'y' || period === 'm') { d = Math.min(d, this.daysInMonth(y, m)); } return date.date(y, m, d); }
javascript
{ "resource": "" }
q10899
train
function () { //Get the object var _this = this; //Update options var o = $.AdminLTE.options.controlSidebarOptions; //Get the sidebar var sidebar = $(o.selector); //The toggle button var btn = $(o.toggleBtnSelector); //Listen to the click event btn.on('click', function (e) { e.preventDefault(); //If the sidebar is not open if (!sidebar.hasClass('control-sidebar-open') && !$('body').hasClass('control-sidebar-open')) { //Open the sidebar _this.open(sidebar, o.slide); } else { _this.close(sidebar, o.slide); } }); //If the body has a boxed layout, fix the sidebar bg position var bg = $(".control-sidebar-bg"); _this._fix(bg); //If the body has a fixed layout, make the control sidebar fixed if ($('body').hasClass('fixed')) { _this._fixForFixed(sidebar); } else { //If the content height is less than the sidebar's height, force max height if ($('.content-wrapper, .right-side').height() < sidebar.height()) { _this._fixForContent(sidebar); } } }
javascript
{ "resource": "" }