_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q3600
train
function (prefix, preout, messages) { if (prefix && this.LEVELS[prefix] < this.level) { return; } var msg = ""; for (var i = 0; i < messages.length; i++) { 0 < i ? msg += ' ' + messages[i]: msg += messages[i]; } var out = msg; if (prefix) { out = preout + ' ' + msg; } console.log(out); }
javascript
{ "resource": "" }
q3601
hyphenateText
train
function hyphenateText(dom, forceHyphenateAllChildren) { if (dom.childNodes !== undefined) { dom.childNodes.forEach(function(node) { if (node.nodeName === '#text' && !isSkippable(node) && (forceHyphenateAllChildren || isPresent(options.elements, dom.tagName))) { node.value = hypher.hyphenateText(node.value); } else { hyphenateText(node, isPresent(options.elements, dom.tagName)); } }); } return dom; }
javascript
{ "resource": "" }
q3602
isSkippable
train
function isSkippable(node) { var result = false; if (node && node.parentNode && node.parentNode.attrs && Array.isArray(node.parentNode.attrs)) { node.parentNode.attrs.forEach(function(attr) { if (attr.name && attr.value && attr.name === HYPHENATE_DATA_ATTR && attr.value === 'false') { result = true; } }); } return result; }
javascript
{ "resource": "" }
q3603
isIgnoredFile
train
function isIgnoredFile(file) { if (options.ignore !== undefined) { var result = false; options.ignore.forEach(function(pattern) { if (minimatch(file, pattern)) { result = true; return false; } }); return result; } return false; }
javascript
{ "resource": "" }
q3604
filter
train
function filter(tree, query, options) { var compiledQuery = _.isFunction(query) ? query : _.matches(query); var settings = _.defaults(options, { childNode: ['children'] }); settings.childNode = _.castArray(settings.childNode); var seekDown = function seekDown(tree) { return tree.filter(function (branch, index) { return compiledQuery(branch, index); }).map(function (branch) { settings.childNode.some(function (key) { if (_.has(branch, key)) { if (_.isArray(branch[key])) { branch[key] = seekDown(branch[key]); } else { delete branch[key]; } } }); return branch; }); }; if (_.isArray(tree)) { return seekDown(tree, []) || []; } else { return seekDown([tree], [])[0] || {}; } }
javascript
{ "resource": "" }
q3605
hasChildren
train
function hasChildren(branch, options) { var settings = _.defaults(options, { childNode: ['children'] }); return settings.childNode.some(function (key) { return branch[key] && _.isArray(branch[key]) && branch[key].length; }); }
javascript
{ "resource": "" }
q3606
attemptNext
train
function attemptNext() { if (--settings.attempts > 0 && dirty) { dirty = false; // Mark sweep as clean - will get dirty if resolver sees a function return resolver(base, []).then(attemptNext); } else { resolve(); } }
javascript
{ "resource": "" }
q3607
sortBy
train
function sortBy(tree, propertyName) { var _this = this; // It is needed an array structure to sort. if (!_.isArray(tree)) tree = [tree]; tree.forEach(function (item) { return _(item).keys().forEach(function (key) { if (_.isArray(item[key])) item[key] = _this.sortBy(item[key], propertyName); }); }); return _.sortBy(tree, propertyName); }
javascript
{ "resource": "" }
q3608
train
function() { this.jsonInit({ "message0": "%1", "args0": [ { "type": "field_variable", "name": "CLONE_NAME_OPTION", "variableTypes": [Blockly.CLONE_NAME_VARIABLE_TYPE], "variable": Blockly.Msg.DEFAULT_CLONE_NAME } ], "colour": Blockly.Colours.control.secondary, "colourSecondary": Blockly.Colours.control.secondary, "colourTertiary": Blockly.Colours.control.tertiary, "extensions": ["output_string"] }); }
javascript
{ "resource": "" }
q3609
defaultTheme
train
function defaultTheme(theme) { if (theme == null) return Form.defaultProps.theme if (typeof theme !== 'object') { throw new Error('Invalid Frig theme. Expected an object') } Form.defaultProps.theme = theme UnboundInput.defaultProps.theme = theme return true }
javascript
{ "resource": "" }
q3610
Argument
train
function Argument(handler, options, desc) { if (!options.hasOwnProperty('scope')) { options.scope = 'global'; } this._parent = null; this._name = null; this._options = options; this._desc = desc; this._handler = handler; return this; }
javascript
{ "resource": "" }
q3611
train
function(model, at){ model = new this._Model(model, this.options.Model.options); if (!this.hasModel(model)) { // Attach events to the model that will signal collection events this.attachModelEvents(model); // If _models is empty, then we make sure to push instead of splice. at = this.length == 0 ? void 0 : at; if (at != void 0) { this._models.splice(at, 0, model); } else { this._models.push(model); } this.length = this._models.length; this._changed = true; // if at is undefined, then it would be at the end of the array, thus this.length-1 this.signalAdd(model, at != void 0 ? at : this.length - 1); } return this; }
javascript
{ "resource": "" }
q3612
train
function(index){ var len = arguments.length, i = 0, results; if (len > 1) { results = []; while(len--){ results.push(this.get(arguments[i++])); } return results; } return this._models[index]; }
javascript
{ "resource": "" }
q3613
train
function(model){ if (this.hasModel(model)) { // Clean up when removing so that it doesn't try removing itself from the collection this.detachModelEvents(model); this._models.erase(model); this.length = this._models.length; this._changed = true; this.signalRemove(model); } return this; }
javascript
{ "resource": "" }
q3614
train
function(oldModel, newModel){ var index; if (oldModel && newModel && this.hasModel(oldModel) && !this.hasModel(newModel)) { index = this.indexOf(oldModel); if (index > -1) { this.act(function(){ this.add(newModel, index); this.remove(oldModel); }); !this.isActive() && this.signalChange() && this.resetChange(); } } return this; }
javascript
{ "resource": "" }
q3615
fireRequest
train
function fireRequest(urlStr, callback) { var start = Date.now(); request({ url: urlStr, method: 'GET', maxRedirects: 8, timeout: 10 * 1000 //headers: { 'User-Agent': 'woobot/2.0' } }, function (error, response) { callback(error, response, Date.now() - start); }); }
javascript
{ "resource": "" }
q3616
validate
train
function validate(options) { const schema = joi.object().keys({ actionName: joi.string().required(), authKey: joi.string().required(), modelName: joi.string().required(), acl: joi.object(), aclContextName: joi.string().required() }); const errorMsg = 'Invalid rule options: '; const aclContext = options.acl[options.aclContextName]; joi.assert(options, schema, errorMsg); joi.assert(aclContext, joi.func().required(), errorMsg); return true; }
javascript
{ "resource": "" }
q3617
makeme
train
function makeme (dir,mode,cb){ var callback = function(err,parent){ //console.log('makeme: ',dir) if(err) throw new Error(err) if(parent){ // replace root of dir with parent dir = path.join(parent,path.basename(dir)); } fs.mkdir(dir,mode,function(err){ if(err !== null){ if( err.code === 'EEXIST' && err.path === dir){ // make sure the directory really does exist fs.stat(dir,function(staterr,stat){ // as mkdirP guys say, this is very strange if(staterr || !stat.isDirectory()){ if(cb) cb(err); } if(cb) cb(null,dir); return null; // if the stat is good, do nothing. some other processed did it }); }else{ console.log(err); throw new Error(err); } }else{ if(cb) cb(null,dir); } return 1; }); }; return callback; }
javascript
{ "resource": "" }
q3618
handleStatforPath
train
function handleStatforPath(p, mode, parent,next){ return function(exists){ if(!exists){ //console.log('no path ' + p + ' so recurse'); return makedir(parent, mode, makeme(p,mode,next)); }else{ // console.log('have path, recursing ends at ',p); next(); } return 1; }; }
javascript
{ "resource": "" }
q3619
makedir
train
function makedir(p,mode,next){ if (typeof mode === 'function' || mode === undefined) { next = mode; mode = 0777 & (~process.umask()); } if (typeof mode === 'string') mode = parseInt(mode, 8); p = path.resolve(p); // recursively make sure that directory exists. // var parent = path.dirname(p); if(parent){ fs.exists(p,handleStatforPath(p,mode,parent,next)); }else{ // following convention, if the path is actually a dot at this // point, prepend the current process root dir and carry on // back up the stack. // if(p === '.'){ // replace . with rootdir p = rootdir; // recurse back up with that value return next(null,p) } // // not sure what is up. path.dirname should create '.' for // parent of relative path names // console.log('in make parent dir, no parents left for : '+p+' try prepending the process root dir'); throw new Error('parent failure ' + p); } return null; }
javascript
{ "resource": "" }
q3620
process
train
function process(segments, parent) { var last = segments.pop(); if (last) { parent[last] = parent[last] || {}; process(segments, parent[last]); } else { parent[true] = true; } }
javascript
{ "resource": "" }
q3621
isExtendOf
train
function isExtendOf(name, variable) { var offset = typeof variable === 'object' && variable ? Object.getPrototypeOf(variable) : null, pattern = offset ? new RegExp('^' + name + '$') : null; // It is not quite feasible to compare the inheritance using `instanceof` (all constructors would have to // be registered somehow then) we simply compare the constructor function names. // As a side effect, this enables polymorphic to compare against the exact type (unless a developer has // altered the constructor name, which is not protected from overwriting) while (offset && offset.constructor) { if (pattern.test(offset.constructor.name)) { return true; } offset = Object.getPrototypeOf(offset); } return false; }
javascript
{ "resource": "" }
q3622
parameterize
train
function parameterize(candidate) { candidate.param = candidate.param.map(function(param) { var value; if ('value' in param) { value = param.value; } else if ('reference' in param) { value = candidate.param.reduce(function(p, c) { return c !== param && !p && param.reference === c.name && 'value' in c ? c.value : p; }, null); } return value; }); return candidate; }
javascript
{ "resource": "" }
q3623
matchSignature
train
function matchSignature(list, arg) { var types = arg.map(function(variable) { return new RegExp('^(' + type(variable) + ')'); }); return list.filter(function(config) { var variadic = false, result; // result is true if no more arguments are provided than the signature allows OR the last // argument in the signature is variadic result = arg.length <= config.arguments.length || (config.arguments[config.arguments.length - 1] && config.arguments[config.arguments.length - 1].type === '...'); // test each given argument agains the configured signatures if (result) { arg.forEach(function(value, index) { var expect = config.arguments[index] ? config.arguments[index].type : null; // look at ourself and ahead - if there is a following item, and it is variadic, it may be // left out entirely (zero or more) if (isTypeAtIndex('...', config.arguments, index)) { variadic = true; } // the result remains valid as long as the values match the given signature // (type matches or it is variadic) result = result && (variadic || types[index].test(expect) || (expect[expect.length - 1] !== '!' && isExtendOf(expect, value))); }); } return result; }); }
javascript
{ "resource": "" }
q3624
prepare
train
function prepare(list, arg) { return list.map(function(config) { var item = { // the function to call call: config.call, // all configured arguments arguments: config.arguments, // the calculated specificity specificity: config.arguments.map(function(argument, index) { var value = 'value' in argument, specificity = 0; // if a argument not a variadic one and the value is specified if (argument.type !== '...' && index < arg.length) { ++specificity; // bonus points if the exact type matches (explicit by type) // OR there is no default value (explicitly provided) if (Number(argument.type === type(arg[index], true) || isExtendOf(argument.type, arg[index]) || !value)) { ++specificity; } // extra bonus points if the type is explicity the same (in case of inheritance) if (new RegExp('^' + type(arg[index], true) + '!$').test(argument.type)){ ++specificity; } } return specificity; }).join(''), // the parameters with which the `call` may be executed param: config.arguments.map(function(argument, index) { var result = {}; result.name = argument.name; // if a variadic type is encountered, the remainder of the given arguments becomes the value if (argument.type === '...') { result.value = arg.slice(index); } else if (index < arg.length && typeof arg[index] !== 'undefined' && arg[index] !== null) { result.value = arg[index]; } else if ('value' in argument) { result.value = argument.value; } else if ('reference' in argument) { result.reference = argument.reference; } return result; }) }; return item; }); }
javascript
{ "resource": "" }
q3625
prioritize
train
function prioritize(list, arg) { return list.sort(function(a, b) { var typing = function(item, index) { return +(item.type === type(arg[index], true)); }; // if the calculated specificity is not equal it has precedence if (a.specificity !== b.specificity) { // the shortest specificity OR ELSE the highest specificity wins return a.specificity.length - b.specificity.length || b.specificity - a.specificity; } // if the specificity is equal, we want to prioritize on the more explicit types return b.arguments.map(typing).join('') - a.arguments.map(typing).join(''); }); }
javascript
{ "resource": "" }
q3626
isTypeAtIndex
train
function isTypeAtIndex(type, list, index) { return list.length > index && 'type' in list[index] ? list[index].type === type : false; }
javascript
{ "resource": "" }
q3627
delegate
train
function delegate(arg) { // create a list of possible candidates based on the given arguments var candidate = matchSignature(registry, arg); // prepare the configured signatures/arguments based on the arguments actually recieved candidate = prepare(candidate, arg); // prioritize the candidates candidate = prioritize(candidate, arg); // and finally, filter any candidate which does not fully comply with the signature based on the - now - parameters candidate = candidate.filter(function(item) { var variadic = false, min = item.arguments.map(function(argument, index) { variadic = isTypeAtIndex('...', item.arguments, index) || isTypeAtIndex('...', item.arguments, index + 1); return +(!(variadic || 'value' in argument || 'reference' in argument)); }).join('').match(/^1+/); return arg.length >= (min ? min[0].length : 0); }); return candidate.length ? parameterize(candidate[0]) : false; }
javascript
{ "resource": "" }
q3628
cast
train
function cast(type, variable) { var result = variable; switch (type) { case 'number': result = +result; break; case 'int': result = parseInt(result, 10); break; case 'float': result = parseFloat(result); break; case 'bool': case 'boolean': result = ['true', '1', 1].indexOf(result) >= 0; break; } return result; }
javascript
{ "resource": "" }
q3629
numberType
train
function numberType(type, variable, explicit) { // if the integer value is identical to the float value, it is an integer return (parseInt(variable, 10) === parseFloat(variable) ? 'int' : 'float') + (explicit ? '' : '|' + type); }
javascript
{ "resource": "" }
q3630
type
train
function type(variable, explicit) { var result = typeof variable; switch (result) { case 'number': result = numberType(result, variable, explicit); break; case 'object': result = objectType(result, variable, explicit); break; case 'boolean': result = booleanType(result, explicit); break; case 'undefined': result = undefinedType(result, explicit); break; } return result; }
javascript
{ "resource": "" }
q3631
prepareArgument
train
function prepareArgument(match, name) { var result = { type: match ? match[1] : false, name: match ? match[2] : name }; if (match) { if (match[4] === '@') { result.reference = match[5]; } else if (match[3] === '=') { result.value = cast(result.type, match[5]); } } return result; }
javascript
{ "resource": "" }
q3632
parse
train
function parse(signature) { var pattern = /^(?:void|([a-zA-Z]+!?|\.{3})(?:[:\s]+([a-zA-Z]+)(?:(=)(@)?(.*))?)?)?$/; return signature.split(/\s*,\s*/).map(function(argument, index, all) { var result = prepareArgument(argument.match(pattern), 'var' + (index + 1)); if (result.type === false) { throw new Error('polymorphic: invalid argument "' + argument + '" in signature "' + signature + '"'); } else if (result.type === '...' && index < all.length - 1) { throw new Error('polymorphic: variadic argument must be at end of signature "' + signature + '"'); } return result; }).filter(function(argument) { // a type is undefined if it was declared as 'void' or '' (an empty string) return argument.type !== undefined; }); }
javascript
{ "resource": "" }
q3633
polymorph
train
function polymorph() { var arg = Array.prototype.slice.call(arguments), candidate = delegate(arg); if (!candidate) { throw new Error('polymorph: signature not found "' + arg.map(function(variable) { return type(variable); }).join(', ') + '"'); } return candidate.call.apply(this, candidate.param); }
javascript
{ "resource": "" }
q3634
getRouteFiles
train
function getRouteFiles (pathName) { var items = fs.readdirSync(pathName); var files = []; items.forEach(function(itemName) { var fullName = path.join(pathName, itemName); var fsStat = fs.statSync(fullName); // If directory, then scan for "routes.js" if (fsStat.isDirectory()) { getRouteFiles(fullName).forEach(function(a) { files.push(a); }); } else if (fsStat.isFile() && itemName === 'routes.js') { // routes.js found, append to list files.push(fullName); } }); return files; }
javascript
{ "resource": "" }
q3635
applyRules
train
function applyRules(rules, model, user) { const rulePromises = _.map(rules, (rule) => rule.applyTo(model, user)); return Promise.all(rulePromises) //TODO validate rule results to handle optional vs. required auth... .catch(function catchAuthError(error) { return Promise.reject(error); }); }
javascript
{ "resource": "" }
q3636
readSecure
train
function readSecure(user, options) { // jscs:disable // jshint -W040 const self = this; // jshint +W040 // jscs:enable const shield = self.constructor.shield; const action = 'read'; const rules = shield.getApplicableRules(action); return shield._fetch.call(self, options) .then(function runShieldRules(result) { // TODO: investigate what happens if fetch returns nothing (err?) return applyRules(rules, self, user) .then(function resolveResult() { return result; }); }); }
javascript
{ "resource": "" }
q3637
readAllSecure
train
function readAllSecure(user, options) { // jscs:disable // jshint -W040 const self = this; // jshint +W040 // jscs:enable const shield = self.constructor.shield; const action = 'read'; const rules = shield.getApplicableRules(action); return shield._fetchAll.call(self, options) .then(function runShieldRules(collection) { // TODO: investigate what happens if fetch returns nothing (err?) return collection.mapThen((mdl) => applyRules(rules, mdl, user)) .then(function resolveResult() { return collection; }); }); }
javascript
{ "resource": "" }
q3638
deleteSecure
train
function deleteSecure(user, options) { // jscs:disable // jshint -W040 const self = this; // jshint +W040 // jscs:enable const Model = self.constructor; const shield = Model.shield; const action = 'delete'; const rules = shield.getApplicableRules(action); const primaryKey = Model.idAttribute; const query = {}; const tmpModel = Model.forge(query); query[primaryKey] = self.get(primaryKey); return tmpModel.read(user) .then(function validateUpdatePrivs(originalModel) { // TODO: investigate what happens if fetch returns nothing (err?) return applyRules(rules, originalModel, user); }).then(function executeUpdate() { return shield._destroy.call(self, options); }); }
javascript
{ "resource": "" }
q3639
updateSecure
train
function updateSecure(user, options) { // jscs:disable // jshint -W040 const self = this; // jshint +W040 // jscs:enable const Model = self.constructor; const shield = Model.shield; const action = 'update'; const rules = shield.getApplicableRules(action); const primaryKey = Model.idAttribute; const query = {}; const tmpModel = Model.forge(query); // validate that the model isNew if (self.isNew()) { return Promise.reject( new AuthError('attempt to update a new record') ); } query[primaryKey] = self.get(primaryKey); return tmpModel.read(user) .then(function validateUpdatePrivs(originalModel) { // TODO: investigate what happens if fetch returns nothing (err?) return applyRules(rules, originalModel, user); }).then(function executeUpdate() { return shield._save.call(self, options); }); }
javascript
{ "resource": "" }
q3640
createSecure
train
function createSecure(user, options) { // jscs:disable // jshint -W040 const self = this; // jshint +W040 // jscs:enable let shield; let action; let rules; // validate that the model isNew if (!self.isNew()) { return Promise.reject( new AuthError('attempt to create a record that exists') ); } // assign vars shield = self.constructor.shield; action = 'create'; rules = shield.getApplicableRules(action); // run authorization, then perform save return applyRules(rules, self, user) .then(function executeSave() { return shield._save.call(self, options); }); }
javascript
{ "resource": "" }
q3641
bypass
train
function bypass(method, options) { // jscs:disable // jshint -W040 const self = this; // jshint +W040 // jscs:enable const shield = self.constructor.shield; if (!_.includes(shield.protectedMethods, method)) { return Promise.reject(new Error('no such protected method')); } const protectedMethod = `_${method}`; return shield[protectedMethod].call(self, options); }
javascript
{ "resource": "" }
q3642
addError
train
function addError(data, error) { if (!data.error) { data.error = []; } error.lineNumber = data.lineNumber; data.error.push(error); }
javascript
{ "resource": "" }
q3643
createTmpHashAction
train
function createTmpHashAction(contentHashFields, multiRowFields) { let tmpHashFields = []; // where there fields from the contentHashFields in the multiRowFields? let fieldClash = false; // add the original content hash fields to an new array // but check that there are not in the multiRowFields. for (let i = 0; i < contentHashFields.length; i++) { let found = false; for (let j = 0; j < multiRowFields.length; j++) { if (contentHashFields[i] === multiRowFields[j]) { found = true; continue; } } if (found) { fieldClash = true; } else { tmpHashFields.push(contentHashFields[i]); } } // now we have a new array if (fieldClash) { // only in this case we need a separate hash return createHashFunction(tmpHashFields, TMP_HASH_FIELD_NAME); } else { // In this case we could use the normal content hash as the muti row fields where not included return; } }
javascript
{ "resource": "" }
q3644
RenderManager
train
function RenderManager(view) { this.running = false; this._frame = 0; this.view = view; this.skipFrames = 0; this.skipFramesCounter = 0; this.onEnterFrame = new signals.Signal(); this.onExitFrame = new signals.Signal(); this.render = this.render.bind(this); this.renderLoop = this.renderLoop.bind(this); }
javascript
{ "resource": "" }
q3645
mergeMap
train
function mergeMap(instance, data) { // for each key in canReflect.eachKey(instance, function(value, prop) { if(!canReflect.hasKey(data, prop)) { canReflect.deleteKeyValue(instance, prop); return; } var newValue = canReflect.getKeyValue(data, prop); canReflect.deleteKeyValue(data, prop); // cases: // a. list // b. map // c. primitive // if the data is typed, we would just replace it if (canReflect.isPrimitive(value)) { canReflect.setKeyValue(instance, prop, newValue); return; } var newValueIsList = Array.isArray(newValue), currentValueIsList = canReflect.isMoreListLikeThanMapLike(value); if (currentValueIsList && newValueIsList) { mergeList(value, newValue); } else if (!newValueIsList && !currentValueIsList && canReflect.isMapLike(value) && canReflect.isPlainObject(newValue)) { // TODO: the `TYPE` should probably be infered from the `_define` property definition. var schema = canReflect.getSchema(value); if (schema && schema.identity && schema.identity.length) { var id = canReflect.getIdentity(value, schema); if (id != null && id === canReflect.getIdentity(newValue, schema)) { mergeMap(value, newValue); return; } } canReflect.setKeyValue(instance, prop, canReflect.new(value.constructor, newValue)); } else { canReflect.setKeyValue(instance, prop, newValue); } }); canReflect.eachKey(data, function(value, prop) { canReflect.setKeyValue(instance, prop, value); }); }
javascript
{ "resource": "" }
q3646
Command
train
function Command(handler, options, desc) { Command.super_.apply(this, [handler, options, desc]); }
javascript
{ "resource": "" }
q3647
loadJSON
train
function loadJSON (file, callback) { loadText(file, function (err, data) { if (err) { callback(err, null) } else { var json = null try { json = JSON.parse(data) } catch (e) { return callback(e, null) } callback(null, json) } }) }
javascript
{ "resource": "" }
q3648
train
function(req, res, next) { async.parallel({ applications: (fn) => { const spy = { stash: {} }; applications.get(req, spy, () => { if(spy.stash.code !== 200) { return fn(new Error('Error getting applications.')); } return fn(null, spy.stash.body); }); }, hosts: (fn) => { const spy = { stash: {} }; hosts.get(req, spy, () => { if(spy.stash.code !== 200) { return fn(new Error('Error getting hosts.')); } return fn(null, spy.stash.body); }); } }, (err, results) => { if(err) { res.stash.code = 500; return next(); } res.stash.body = { applications: results.applications, hosts: results.hosts }; res.stash.code = 200; return next(); }); }
javascript
{ "resource": "" }
q3649
HTTPError
train
function HTTPError(statusCode, message) { if (!(this instanceof HTTPError)) { return new HTTPError(statusCode, message); } assert(statusCode >= 400, 'Not a valid HTTP error code'); this.statusCode = statusCode; this.code = statusCode; this.message = message || defaultMessage; }
javascript
{ "resource": "" }
q3650
map
train
function map(schema, valueSchema) { if (!objtools.isPlainObject(schema)) { valueSchema = schema; schema = {}; } schema.type = 'map'; schema.values = valueSchema; return schema; }
javascript
{ "resource": "" }
q3651
train
function() { this.jsonInit({ "message0": "%1", "args0": [ { "type": "field_dropdown", "name": "ON", "options": [ [Blockly.Msg.MOTION_IFON_EDGE, '_edge_'], [Blockly.Msg.MOTION_IFON_POINTER, '_mouse_'], ] } ], "colour": Blockly.Colours.motion.secondary, "colourSecondary": Blockly.Colours.motion.secondary, "colourTertiary": Blockly.Colours.motion.tertiary, "extensions": ["output_string"] }); }
javascript
{ "resource": "" }
q3652
train
function (src, dst, config, headers, callback) { if (_.isFunction(headers)) { callback = headers; headers = undefined; } var options = config.options; if (!fsys.isFileSync(src)) { return callback(new Error('source file not found. path:', src)); } _.defaults(options || (options = {}), DEFAULT_OPTIONS); var encode = options.encode; var compress = options.compress; var firebug = options.firebug; var linenos = options.linenos; var urlopt = options.url; var raw = fs.readFileSync(src, encode); var styl = stylus(raw) .set('filename', dst) .set('compress', compress) .set('firebug', firebug) .set('linenos', linenos) .define('b64', stylus.url(urlopt)) ; if (options.nib) { // use nib library styl.use(nib()); } // extend options if (config.hasOwnProperty('extend') && headers && common.isUAOverride(config, headers) && config.extend.hasOwnProperty('content')) { options = obj.copy(config.extend.content, config).options; logger.debug('Override stylus options:', options); } // define functions and constant values if (options.fn && Object.keys(options.fn).length) { styl.use(function (styl) { _.each(options.fn, function (fn, name) { if (_.isFunction(fn)) { styl.define(name, function (data) { return fn(data && data.val); }); } else { styl.define(name, function () { return fn; }); } }); }); } styl.render(function (err, css) { err && callback(err, css); fs.writeFileSync(dst, css, encode); callback(null, css); }); }
javascript
{ "resource": "" }
q3653
incrementalProp
train
function incrementalProp(state1, state2, propName, compare) { const values1 = state1[propName]; const values2 = state2[propName]; let result; // Note: Values may be undefined if no data was read. if (((values1 && values1.length !== 0) || state1.ended) && ((values2 && values2.length !== 0) || state2.ended)) { const minLen = Math.min( values1 ? values1.length : 0, values2 ? values2.length : 0 ); if ((values1 && values1.length > minLen) && !state2.ended) { result = compare(values1.slice(0, minLen), values2); } else if ((values2 && values2.length > minLen) && !state1.ended) { result = compare(values1, values2.slice(0, minLen)); } else { result = compare(values1, values2); } if (minLen > 0 && (result === null || result === undefined)) { state1[propName] = values1.slice(minLen); state2[propName] = values2.slice(minLen); } } return result; }
javascript
{ "resource": "" }
q3654
train
function (context) { context.setCookie = function (name, value, options) { var cookieStr = cookie.serialize(name, value, options); if (res) { var header = res.getHeader('Set-Cookie') || []; if (!Array.isArray(header)) { header = [header]; } header.push(cookieStr); res.setHeader('Set-Cookie', header); } else { document.cookie = cookieStr; } cookies[name] = value; }; context.clearCookie = function (name, options) { context.setCookie(name, "", merge({ expires: new Date(1), path: '/' }, options)); delete cookies[name]; }; context.getCookie = function (name) { return cookies[name]; }; }
javascript
{ "resource": "" }
q3655
onList
train
function onList(newList) { var current = this.currentList || []; newList = newList || []; if (current[offPatchesSymbol]) { current[offPatchesSymbol](this.onPatchesNotify, "notify"); } var patches = diff(current, newList); this.currentList = newList; this.onPatchesNotify(patches); if (newList[onPatchesSymbol]) { // If observable, set up bindings on list changes newList[onPatchesSymbol](this.onPatchesNotify, "notify"); } }
javascript
{ "resource": "" }
q3656
onPatchesNotify
train
function onPatchesNotify(patches) { // we are going to collect all patches this.patches.push.apply(this.patches, patches); // TODO: share priority queues.deriveQueue.enqueue(this.onPatchesDerive, this, [], { priority: this.priority }); }
javascript
{ "resource": "" }
q3657
clean
train
function clean(object, follow = false) { // check if object is an object if (is(object) && !empty(object)) { // clone the object to use as the result and // so it is immutable let result = clone(object); // if follow is true flatten the object keys so // its easy to get the path to delete and so // it's easy to check if values are null/undefined // if follow is false it will just be the base // object therefore it will only check the base keys const keysObject = follow ? deflate(object) : object; // loop over the keys of the object Object.keys(keysObject).forEach((key) => { // get the value of the current key const value = keysObject[key]; // if the value is undefined or null if (value === undefined || value === null) { // delete the key/value from the object result = del(result, key); } }); // return the result return result; } // if the object isn't an object or is empty return // an empty object this will keep the return immutable return {}; }
javascript
{ "resource": "" }
q3658
train
function(id) { var canvasContainer = document.createElement("div"); canvasContainer.id = id; canvasContainer.width = window.innerWidth; canvasContainer.height = window.innerHeight; this.addCanvasContainerToDOMBody(canvasContainer); this.setDOMMode(canvasContainer, this.domMode); return canvasContainer; }
javascript
{ "resource": "" }
q3659
train
function(element, mode) { var style = element.style; switch(mode) { case DOMMode.FULLSCREEN: style.position = "fixed"; style.left = "0px"; style.top = "0px"; style.width = '100%'; style.height = '100%'; break; case DOMMode.CONTAINER: style.position = "absolute"; style.left = "0px"; style.top = "0px"; style.width = this.canvasContainer.clientWidth + 'px'; style.height = this.canvasContainer.clientHeight + 'px'; break; default: } }
javascript
{ "resource": "" }
q3660
del
train
function del(object, path) { // check if the object is an object and isn't empty if (is(object) && !empty(object)) { // clone the object let cloned = clone(object); // set the new value for the cloned object so we // can manipulate it const result = cloned; // get the path parts const pathParts = getPathParts(path); // loop over all the path parts for (let index = 0; index < pathParts.length; index += 1) { // get the current key const key = pathParts[index]; // check if the current path is the last key if (index === pathParts.length - 1) { // if it is the last key delete the value from the object delete cloned[key]; } // set the modified values to the object cloned = cloned[key]; } // return the result return result; } // if the object isn't an object or is empty return // an empty object this will keep the return immutable return {}; }
javascript
{ "resource": "" }
q3661
train
function(e, ui) { var dst = $(this), targets = $.grep(ui.helper.data('files')||[], function(h) { return h? true : false; }), result = [], dups = [], faults = [], isCopy = ui.helper.hasClass('elfinder-drag-helper-plus'), c = 'class', cnt, hash, i, h; if (typeof e.button === 'undefined' || ui.helper.data('namespace') !== namespace || ! self.insideWorkzone(e.pageX, e.pageY)) { return false; } if (dst.hasClass(self.res(c, 'cwdfile'))) { hash = self.cwdId2Hash(dst.attr('id')); } else if (dst.hasClass(self.res(c, 'navdir'))) { hash = self.navId2Hash(dst.attr('id')); } else { hash = cwd; } cnt = targets.length; while (cnt--) { h = targets[cnt]; // ignore drop into itself or in own location if (h != hash && files[h].phash != hash) { result.push(h); } else { ((isCopy && h !== hash && files[hash].write)? dups : faults).push(h); } } if (faults.length) { return false; } ui.helper.data('droped', true); if (dups.length) { ui.helper.hide(); self.exec('duplicate', dups, {_userAction: true}); } if (result.length) { ui.helper.hide(); self.clipboard(result, !isCopy); self.exec('paste', hash, {_userAction: true}, hash).always(function(){ self.clipboard([]); self.trigger('unlockfiles', {files : targets}); }); self.trigger('drop', {files : targets}); } }
javascript
{ "resource": "" }
q3662
train
function() { var full; if (node.hasClass(cls)) { return node.get(0); } else { full = node.find('.' + cls); if (full.length) { return full.get(0); } } return null; }
javascript
{ "resource": "" }
q3663
train
function(type, order, stickFolders, alsoTreeview) { this.storage('sortType', (this.sortType = this.sortRules[type] ? type : 'name')); this.storage('sortOrder', (this.sortOrder = /asc|desc/.test(order) ? order : 'asc')); this.storage('sortStickFolders', (this.sortStickFolders = !!stickFolders) ? 1 : ''); this.storage('sortAlsoTreeview', (this.sortAlsoTreeview = !!alsoTreeview) ? 1 : ''); this.trigger('sortchange'); }
javascript
{ "resource": "" }
q3664
train
function(a, b) { var self = elFinder.prototype.naturalCompare; if (typeof self.loc == 'undefined') { self.loc = (navigator.userLanguage || navigator.browserLanguage || navigator.language || 'en-US'); } if (typeof self.sort == 'undefined') { if ('11'.localeCompare('2', self.loc, {numeric: true}) > 0) { // Native support if (window.Intl && window.Intl.Collator) { self.sort = new Intl.Collator(self.loc, {numeric: true}).compare; } else { self.sort = function(a, b) { return a.localeCompare(b, self.loc, {numeric: true}); }; } } else { /* * Edited for elFinder (emulates localeCompare() by numeric) by Naoki Sawada aka nao-pon */ /* * Huddle/javascript-natural-sort (https://github.com/Huddle/javascript-natural-sort) */ /* * Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license * Author: Jim Palmer (based on chunking idea from Dave Koelle) * http://opensource.org/licenses/mit-license.php */ self.sort = function(a, b) { var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi, sre = /(^[ ]*|[ ]*$)/g, dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/, hre = /^0x[0-9a-f]+$/i, ore = /^0/, syre = /^[\x01\x21-\x2f\x3a-\x40\x5b-\x60\x7b-\x7e]/, // symbol first - (Naoki Sawada) i = function(s) { return self.sort.insensitive && (''+s).toLowerCase() || ''+s; }, // convert all to strings strip whitespace // first character is "_", it's smallest - (Naoki Sawada) x = i(a).replace(sre, '').replace(/^_/, "\x01") || '', y = i(b).replace(sre, '').replace(/^_/, "\x01") || '', // chunk/tokenize xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'), yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'), // numeric, hex or date detection xD = parseInt(x.match(hre)) || (xN.length != 1 && x.match(dre) && Date.parse(x)), yD = parseInt(y.match(hre)) || xD && y.match(dre) && Date.parse(y) || null, oFxNcL, oFyNcL, locRes = 0; // first try and sort Hex codes or Dates if (yD) { if ( xD < yD ) return -1; else if ( xD > yD ) return 1; } // natural sorting through split numeric strings and default strings for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) { // find floats not starting with '0', string or 0 if not defined (Clint Priest) oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0; oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0; // handle numeric vs string comparison - number < string - (Kyle Adams) // but symbol first < number - (Naoki Sawada) if (isNaN(oFxNcL) !== isNaN(oFyNcL)) { if (isNaN(oFxNcL) && (typeof oFxNcL !== 'string' || ! oFxNcL.match(syre))) { return 1; } else if (typeof oFyNcL !== 'string' || ! oFyNcL.match(syre)) { return -1; } } // use decimal number comparison if either value is string zero if (parseInt(oFxNcL, 10) === 0) oFxNcL = 0; if (parseInt(oFyNcL, 10) === 0) oFyNcL = 0; // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2' if (typeof oFxNcL !== typeof oFyNcL) { oFxNcL += ''; oFyNcL += ''; } // use locale sensitive sort for strings when case insensitive // note: localeCompare interleaves uppercase with lowercase (e.g. A,a,B,b) if (self.sort.insensitive && typeof oFxNcL === 'string' && typeof oFyNcL === 'string') { locRes = oFxNcL.localeCompare(oFyNcL, self.loc); if (locRes !== 0) return locRes; } if (oFxNcL < oFyNcL) return -1; if (oFxNcL > oFyNcL) return 1; } return 0; }; self.sort.insensitive = true; } } return self.sort(a, b); }
javascript
{ "resource": "" }
q3665
train
function(file1, file2) { var self = this, type = self.sortType, asc = self.sortOrder == 'asc', stick = self.sortStickFolders, rules = self.sortRules, sort = rules[type], d1 = file1.mime == 'directory', d2 = file2.mime == 'directory', res; if (stick) { if (d1 && !d2) { return -1; } else if (!d1 && d2) { return 1; } } res = asc ? sort(file1, file2) : sort(file2, file1); return type !== 'name' && res === 0 ? res = asc ? rules.name(file1, file2) : rules.name(file2, file1) : res; }
javascript
{ "resource": "" }
q3666
train
function(prefix, phash, glue) { var i = 0, ext = '', p, name; prefix = this.i18n(false, prefix); phash = phash || this.cwd().hash; glue = (typeof glue === 'undefined')? ' ' : glue; if (p = prefix.match(/^(.+)(\.[^.]+)$/)) { ext = p[2]; prefix = p[1]; } name = prefix+ext; if (!this.fileByName(name, phash)) { return name; } while (i < 10000) { name = prefix + glue + (++i) + ext; if (!this.fileByName(name, phash)) { return name; } } return prefix + Math.random() + ext; }
javascript
{ "resource": "" }
q3667
train
function(file, asObject) { var self = this, template = { 'background' : 'url(\'{url}\') 0 0 no-repeat', 'background-size' : 'contain' }, style = '', cssObj = {}, i = 0; if (file.icon) { style = 'style="'; $.each(template, function(k, v) { if (i++ === 0) { v = v.replace('{url}', self.escape(file.icon)); } if (asObject) { cssObj[k] = v; } else { style += k+':'+v+';'; } }); style += '"'; } return asObject? cssObj : style; }
javascript
{ "resource": "" }
q3668
train
function(mimeType) { var prefix = 'elfinder-cwd-icon-', mime = mimeType.toLowerCase(), isText = this.textMimes[mime]; mime = mime.split('/'); if (isText) { mime[0] += ' ' + prefix + 'text'; } return prefix + mime[0] + (mime[1] ? ' ' + prefix + mime[1].replace(/(\.|\+)/g, '-') : ''); }
javascript
{ "resource": "" }
q3669
train
function(f) { var isObj = typeof(f) == 'object' ? true : false, mime = isObj ? f.mime : f, kind; if (isObj && f.alias && mime != 'symlink-broken') { kind = 'Alias'; } else if (this.kinds[mime]) { if (isObj && mime === 'directory' && (! f.phash || f.isroot)) { kind = 'Root'; } else { kind = this.kinds[mime]; } } if (! kind) { if (mime.indexOf('text') === 0) { kind = 'Text'; } else if (mime.indexOf('image') === 0) { kind = 'Image'; } else if (mime.indexOf('audio') === 0) { kind = 'Audio'; } else if (mime.indexOf('video') === 0) { kind = 'Video'; } else if (mime.indexOf('application') === 0) { kind = 'App'; } else { kind = mime; } } return this.messages['kind'+kind] ? this.i18n('kind'+kind) : mime; }
javascript
{ "resource": "" }
q3670
train
function(format, date) { var self = this, output, d, dw, m, y, h, g, i, s; if (! date) { date = new Date(); } h = date[self.getHours](); g = h > 12 ? h - 12 : h; i = date[self.getMinutes](); s = date[self.getSeconds](); d = date[self.getDate](); dw = date[self.getDay](); m = date[self.getMonth]() + 1; y = date[self.getFullYear](); output = format.replace(/[a-z]/gi, function(val) { switch (val) { case 'd': return d > 9 ? d : '0'+d; case 'j': return d; case 'D': return self.i18n(self.i18.daysShort[dw]); case 'l': return self.i18n(self.i18.days[dw]); case 'm': return m > 9 ? m : '0'+m; case 'n': return m; case 'M': return self.i18n(self.i18.monthsShort[m-1]); case 'F': return self.i18n(self.i18.months[m-1]); case 'Y': return y; case 'y': return (''+y).substr(2); case 'H': return h > 9 ? h : '0'+h; case 'G': return h; case 'g': return g; case 'h': return g > 9 ? g : '0'+g; case 'a': return h >= 12 ? 'pm' : 'am'; case 'A': return h >= 12 ? 'PM' : 'AM'; case 'i': return i > 9 ? i : '0'+i; case 's': return s > 9 ? s : '0'+s; } return val; }); return output; }
javascript
{ "resource": "" }
q3671
train
function(file, t) { var self = this, ts = t || file.ts, i18 = self.i18, date, format, output, d, dw, m, y, h, g, i, s; if (self.options.clientFormatDate && ts > 0) { date = new Date(ts*1000); format = ts >= this.yesterday ? this.fancyFormat : this.dateFormat; output = self.date(format, date); return ts >= this.yesterday ? output.replace('$1', this.i18n(ts >= this.today ? 'Today' : 'Yesterday')) : output; } else if (file.date) { return file.date.replace(/([a-z]+)\s/i, function(a1, a2) { return self.i18n(a2)+' '; }); } return self.i18n('dateUnknown'); }
javascript
{ "resource": "" }
q3672
train
function(num) { var v = new Number(num); if (v) { if (v.toLocaleString) { return v.toLocaleString(); } else { return String(num).replace( /(\d)(?=(\d\d\d)+(?!\d))/g, '$1,'); } } return num; }
javascript
{ "resource": "" }
q3673
train
function(o) { var c = ''; if (!o.read && !o.write) { c = 'elfinder-na'; } else if (!o.read) { c = 'elfinder-wo'; } else if (!o.write) { c = 'elfinder-ro'; } if (o.type) { c += ' elfinder-' + this.escape(o.type); } return c; }
javascript
{ "resource": "" }
q3674
train
function(f) { var p = []; f.read && p.push(this.i18n('read')); f.write && p.push(this.i18n('write')); return p.length ? p.join(' '+this.i18n('and')+' ') : this.i18n('noaccess'); }
javascript
{ "resource": "" }
q3675
train
function(s) { var n = 1, u = 'b'; if (s == 'unknown') { return this.i18n('unknown'); } if (s > 1073741824) { n = 1073741824; u = 'GB'; } else if (s > 1048576) { n = 1048576; u = 'MB'; } else if (s > 1024) { n = 1024; u = 'KB'; } s = s/n; return (s > 0 ? n >= 1048576 ? s.toFixed(2) : Math.round(s) : 0) +' '+u; }
javascript
{ "resource": "" }
q3676
train
function(mime, target) { target = target || this.cwd().hash; var res = true, // default is allow mimeChecker = this.option('uploadMime', target), allow, deny, check = function(checker) { var ret = false; if (typeof checker === 'string' && checker.toLowerCase() === 'all') { ret = true; } else if (Array.isArray(checker) && checker.length) { $.each(checker, function(i, v) { v = v.toLowerCase(); if (v === 'all' || mime.indexOf(v) === 0) { ret = true; return false; } }); } return ret; }; if (mime && $.isPlainObject(mimeChecker)) { mime = mime.toLowerCase(); allow = check(mimeChecker.allow); deny = check(mimeChecker.deny); if (mimeChecker.firstOrder === 'allow') { res = false; // default is deny if (! deny && allow === true) { // match only allow res = true; } } else { res = true; // default is allow if (deny === true && ! allow) { // match only deny res = false; } } } return res; }
javascript
{ "resource": "" }
q3677
train
function(tasks) { var l = tasks.length, chain = function(task, idx) { ++idx; if (tasks[idx]) { return chain(task.then(tasks[idx]), idx); } else { return task; } }; if (l > 1) { return chain(tasks[0](), 0); } else { return tasks[0](); } }
javascript
{ "resource": "" }
q3678
train
function(url) { var dfd = $.Deferred(), ifm; try { ifm = $('<iframe width="1" height="1" scrolling="no" frameborder="no" style="position:absolute; top:-1px; left:-1px" crossorigin="use-credentials">') .attr('src', url) .one('load', function() { var ifm = $(this); try { this.contentDocument.location.reload(true); ifm.one('load', function() { ifm.remove(); dfd.resolve(); }); } catch(e) { ifm.attr('src', '').attr('src', url).one('load', function() { ifm.remove(); dfd.resolve(); }); } }) .appendTo('body'); } catch(e) { ifm && ifm.remove(); dfd.reject(); } return dfd; }
javascript
{ "resource": "" }
q3679
train
function(files, opts) { var self = this, cwd = this.getUI('cwd'), cwdHash = this.cwd().hash, newItem = $(); opts = opts || {}; $.each(files, function(i, f) { if (f.phash === cwdHash || self.searchStatus.state > 1) { newItem = newItem.add(cwd.find('#'+self.cwdHash2Id(f.hash))); if (opts.firstOnly) { return false; } } }); return newItem; }
javascript
{ "resource": "" }
q3680
train
function(url) { if (url.match(/^http/i)) { return url; } if (url.substr(0,2) === '//') { return window.location.protocol + url; } var root = window.location.protocol + '//' + window.location.host, reg = /[^\/]+\/\.\.\//, ret; if (url.substr(0, 1) === '/') { ret = root + url; } else { ret = root + window.location.pathname.replace(/\/[^\/]+$/, '/') + url; } ret = ret.replace('/./', '/'); while(reg.test(ret)) { ret = ret.replace(reg, ''); } return ret; }
javascript
{ "resource": "" }
q3681
train
function (checkUrl) { var url; checkUrl = this.convAbsUrl(checkUrl); if (location.origin && window.URL) { try { url = new URL(checkUrl); return location.origin === url.origin; } catch(e) {} } url = document.createElement('a'); url.href = checkUrl; return location.protocol === url.protocol && location.host === url.host && location.port && url.port; }
javascript
{ "resource": "" }
q3682
train
function() { var self = this, node = this.getUI(), ni = node.css('z-index'); if (ni && ni !== 'auto' && ni !== 'inherit') { self.zIndex = ni; } else { node.parents().each(function(i, n) { var z = $(n).css('z-index'); if (z !== 'auto' && z !== 'inherit' && (z = parseInt(z))) { self.zIndex = z; return false; } }); } }
javascript
{ "resource": "" }
q3683
train
function(urls) { var self = this; if (typeof urls === 'string') { urls = [ urls ]; } $.each(urls, function(i, url) { url = self.convAbsUrl(url).replace(/^https?:/i, ''); if (! $("head > link[href='+url+']").length) { $('head').append('<link rel="stylesheet" type="text/css" href="' + url + '" />'); } }); return this; }
javascript
{ "resource": "" }
q3684
train
function(func, arr, opts) { var dfrd = $.Deferred(), abortFlg = false, parms = Object.assign({ interval : 0, numPerOnce : 1 }, opts || {}), resArr = [], vars =[], curVars = [], exec, tm; dfrd._abort = function(resolve) { tm && clearTimeout(tm); vars = []; abortFlg = true; if (dfrd.state() === 'pending') { dfrd[resolve? 'resolve' : 'reject'](resArr); } }; dfrd.fail(function() { dfrd._abort(); }).always(function() { dfrd._abort = function() {}; }); if (typeof func === 'function' && Array.isArray(arr)) { vars = arr.concat(); exec = function() { var i, len, res; if (abortFlg) { return; } curVars = vars.splice(0, parms.numPerOnce); len = curVars.length; for (i = 0; i < len; i++) { if (abortFlg) { break; } res = func(curVars[i]); (res !== null) && resArr.push(res); } if (abortFlg) { return; } if (vars.length) { tm = setTimeout(exec, parms.interval); } else { dfrd.resolve(resArr); } }; if (vars.length) { tm = setTimeout(exec, 0); } else { dfrd.resolve(resArr); } } else { dfrd.reject(); } return dfrd; }
javascript
{ "resource": "" }
q3685
train
function(dir, update) { var self = this, prev = update? dir : (self.file(dir.hash) || dir), prevTs = prev.ts, change = false; // backup original stats if (update || !dir._realStats) { dir._realStats = { locked: dir.locked || 0, dirs: dir.dirs || 0, ts: dir.ts }; } // set lock dir.locked = 1; if (!prev.locked) { change = true; } // has leaf root to `dirs: 1` dir.dirs = 1; if (!prev.dirs) { change = true; } // set ts $.each(self.leafRoots[dir.hash], function() { var f = self.file(this); if (f && f.ts && (dir.ts || 0) < f.ts) { dir.ts = f.ts; } }); if (prevTs !== dir.ts) { change = true; } return change; }
javascript
{ "resource": "" }
q3686
train
function(xhr, o) { var opts = o || {}; if (xhr) { opts.quiet && (xhr.quiet = true); if (opts.abort && xhr._requestId) { this.request({ data: { cmd: 'abort', id: xhr._requestId }, preventDefault: true }); } xhr.abort(); xhr = void 0; } }
javascript
{ "resource": "" }
q3687
train
function (trans, val) { var key, tmpArr = {}, isArr = $.isArray(trans); for (key in trans) { if (isArr || trans.hasOwnProperty(key)) { tmpArr[trans[key]] = val || key; } } return tmpArr; }
javascript
{ "resource": "" }
q3688
train
function(arrayBuffer, sliceSize) { var segments= [], fi = 0; while(fi * sliceSize < arrayBuffer.byteLength){ segments.push(arrayBuffer.slice(fi * sliceSize, (fi + 1) * sliceSize)); fi++; } return segments; }
javascript
{ "resource": "" }
q3689
train
function(e, ui) { var dst = $(this), helper = ui.helper, cl = hover+' '+dropover, hash, status; e.stopPropagation(); helper.data('dropover', helper.data('dropover') + 1); dst.data('dropover', true); if (ui.helper.data('namespace') !== fm.namespace || ! insideNavbar(e.clientX) || ! fm.insideWorkzone(e.pageX, e.pageY)) { dst.removeClass(cl); helper.removeClass('elfinder-drag-helper-move elfinder-drag-helper-plus'); return; } dst.addClass(hover); if (dst.is('.'+collapsed+':not(.'+expanded+')')) { dst.data('expandTimer', setTimeout(function() { dst.is('.'+collapsed+'.'+hover) && dst.children('.'+arrow).trigger('click'); }, 500)); } if (dst.is('.elfinder-ro,.elfinder-na')) { dst.removeClass(dropover); helper.removeClass('elfinder-drag-helper-move elfinder-drag-helper-plus'); return; } hash = fm.navId2Hash(dst.attr('id')); dst.data('dropover', hash); $.each(ui.helper.data('files'), function(i, h) { if (h === hash || (fm.file(h).phash === hash && !ui.helper.hasClass('elfinder-drag-helper-plus'))) { dst.removeClass(cl); return false; // break $.each } }); if (helper.data('locked')) { status = 'elfinder-drag-helper-plus'; } else { status = 'elfinder-drag-helper-move'; if (e.shiftKey || e.ctrlKey || e.metaKey) { status += ' elfinder-drag-helper-plus'; } } dst.hasClass(dropover) && helper.addClass(status); requestAnimationFrame(function(){ dst.hasClass(dropover) && helper.addClass(status); }); }
javascript
{ "resource": "" }
q3690
train
function(e, d) { selectTm && cancelAnimationFrame(selectTm); if (! e.data || ! e.data.selected || ! e.data.selected.length) { selectTm = requestAnimationFrame(function() { self.opened() && updateOnSel(); }); } else { self.opened() && updateOnSel(); } }
javascript
{ "resource": "" }
q3691
train
function(ql) { var fm = ql.fm, mimes = fm.arrayFlip(['text/html', 'application/xhtml+xml']), preview = ql.preview; preview.on(ql.evUpdate, function(e) { var file = e.file, jqxhr, loading; if (mimes[file.mime] && ql.dispInlineRegex.test(file.mime) && (!ql.options.getSizeMax || file.size <= ql.options.getSizeMax)) { e.stopImmediatePropagation(); loading = $('<div class="elfinder-quicklook-info-data"> '+fm.i18n('nowLoading')+'<span class="elfinder-info-spinner"></div>').appendTo(ql.info.find('.elfinder-quicklook-info')); // stop loading on change file if not loaded yet preview.one('change', function() { jqxhr.state() == 'pending' && jqxhr.reject(); }).addClass('elfinder-overflow-auto'); jqxhr = fm.request({ data : {cmd : 'get', target : file.hash, conv : 1, _t : file.ts}, options : {type: 'get', cache : true}, preventDefault : true }) .done(function(data) { ql.hideinfo(); var doc = $('<iframe class="elfinder-quicklook-preview-html"/>').appendTo(preview)[0].contentWindow.document; doc.open(); doc.write(data.content); doc.close(); }) .always(function() { loading.remove(); }); } }); }
javascript
{ "resource": "" }
q3692
train
function(ql) { var fm = ql.fm, mimes = fm.arrayFlip(['text/x-markdown']), preview = ql.preview, marked = null, show = function(data, loading) { ql.hideinfo(); var doc = $('<iframe class="elfinder-quicklook-preview-html"/>').appendTo(preview)[0].contentWindow.document; doc.open(); doc.write(marked(data.content)); doc.close(); loading.remove(); }, error = function(loading) { marked = false; loading.remove(); }; preview.on(ql.evUpdate, function(e) { var file = e.file, jqxhr, loading; if (mimes[file.mime] && fm.options.cdns.marked && marked !== false && ql.dispInlineRegex.test(file.mime) && (!ql.options.getSizeMax || file.size <= ql.options.getSizeMax)) { e.stopImmediatePropagation(); loading = $('<div class="elfinder-quicklook-info-data"> '+fm.i18n('nowLoading')+'<span class="elfinder-info-spinner"></div>').appendTo(ql.info.find('.elfinder-quicklook-info')); // stop loading on change file if not loaded yet preview.one('change', function() { jqxhr.state() == 'pending' && jqxhr.reject(); }).addClass('elfinder-overflow-auto'); jqxhr = fm.request({ data : {cmd : 'get', target : file.hash, conv : 1, _t : file.ts}, options : {type: 'get', cache : true}, preventDefault : true }) .done(function(data) { if (marked || window.marked) { if (!marked) { marked = window.marked; } show(data, loading); } else { fm.loadScript([fm.options.cdns.marked], function(res) { marked = res || window.marked || false; delete window.marked; if (marked) { show(data, loading); } else { error(loading); } }, { tryRequire: true, error: function() { error(loading); } } ); } }) .fail(function() { error(loading); }); } }); }
javascript
{ "resource": "" }
q3693
train
function(ql) { var fm = ql.fm, mime = 'application/pdf', preview = ql.preview, active = false; if ((fm.UA.Safari && fm.OS === 'mac' && !fm.UA.iOS) || fm.UA.IE) { active = true; } else { $.each(navigator.plugins, function(i, plugins) { $.each(plugins, function(i, plugin) { if (plugin.type === mime) { return !(active = true); } }); }); } active && preview.on(ql.evUpdate, function(e) { var file = e.file, node; if (file.mime === mime && ql.dispInlineRegex.test(file.mime)) { e.stopImmediatePropagation(); ql.hideinfo(); ql.cover.addClass('elfinder-quicklook-coverbg'); node = $('<object class="elfinder-quicklook-preview-pdf" data="'+fm.openUrl(file.hash)+'" type="application/pdf" />') .appendTo(preview); } }); }
javascript
{ "resource": "" }
q3694
train
function(ql) { var fm = ql.fm, mime = 'application/x-shockwave-flash', preview = ql.preview, active = false; $.each(navigator.plugins, function(i, plugins) { $.each(plugins, function(i, plugin) { if (plugin.type === mime) { return !(active = true); } }); }); active && preview.on(ql.evUpdate, function(e) { var file = e.file, node; if (file.mime === mime && ql.dispInlineRegex.test(file.mime)) { e.stopImmediatePropagation(); ql.hideinfo(); node = $('<embed class="elfinder-quicklook-preview-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" src="'+fm.openUrl(file.hash)+'" quality="high" type="application/x-shockwave-flash" wmode="transparent" />') .appendTo(preview); } }); }
javascript
{ "resource": "" }
q3695
train
function(element) { var pnode = element; var x = pnode.offsetLeft; var y = pnode.offsetTop; while ( pnode.offsetParent ) { pnode = pnode.offsetParent; if (pnode != document.body && pnode.currentStyle['position'] != 'static') { break; } if (pnode != document.body && pnode != document.documentElement) { x -= pnode.scrollLeft; y -= pnode.scrollTop; } x += pnode.offsetLeft; y += pnode.offsetTop; } return { x: x, y: y }; }
javascript
{ "resource": "" }
q3696
catchClientError
train
function catchClientError(req, res, next) { const { end } = res; res.end = function() { // console.log(`Catch client response : ${req.url} ${res.statusCode}`); const errorRoute = Route .routes('err') .filter((obj) => { return obj.extra.status === res.statusCode && obj.route !== req.url; }); if(errorRoute.length > 0 && !isRedirect) { return redirect(errorRoute[0], req, res, next); } isRedirect = false; end.apply(res, arguments); }; next(); }
javascript
{ "resource": "" }
q3697
loadQuote
train
async function loadQuote(store, quoteId) { const quote = await fetchQuote(quoteId) await store.update(state => { if (!state.quotes) { state.quotes = {} } state.quotes[quoteId] = quote }) return { quoteId } }
javascript
{ "resource": "" }
q3698
nextQuote
train
async function nextQuote(store) { await store.update(state => { state.quoteId = state.quoteId + 1 if (state.quoteId >= MAX_QUOTE_ID) { state.quoteId = 1 } }) }
javascript
{ "resource": "" }
q3699
prevQuote
train
async function prevQuote(store) { await store.update(state => { state.quoteId = state.quoteId - 1 if (state.quoteId <= 0) { state.quoteId = MAX_QUOTE_ID } }) }
javascript
{ "resource": "" }