_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q48200
train
function (less) { var Keyword = less.tree.Keyword; var DetachedRuleset = less.tree.DetachedRuleset; var isa = function (n, Type) { return (n instanceof Type) ? Keyword.True : Keyword.False; }; if (!functions) { functions = { isruleset: function (n) { return isa(n, DetachedRuleset); } }; } return functions; }
javascript
{ "resource": "" }
q48201
extend
train
function extend(dest, source) { dest = dest || {}; source = source || {}; var result = clone(dest); for (var key in source) { if (source.hasOwnProperty(key)) { result[key] = source[key]; } } return result; }
javascript
{ "resource": "" }
q48202
train
function (qs) { var items = qs.split('&'); var options = {}; items = items.filter(function (item) { return item.match(/^[\w_-]+=?$|^[\w_-]+=[^=]+$/); }).forEach(function (item) { var kv = item.split('='); var value = kv[1]; if (value === undefined || value === '') { value = true; } else if (value.toLowerCase() === 'false') { value = false; } options[kv[0]] = value; }); return options; }
javascript
{ "resource": "" }
q48203
train
function(objects, user) { if (!_.isArray(objects)) { return PermissionService.isForeignObject(user.id)(objects); } return _.any(objects, PermissionService.isForeignObject(user.id)); }
javascript
{ "resource": "" }
q48204
train
function(req) { // handle add/remove routes that have :parentid as the primary key field var originalId; if (req.params.parentid) { originalId = req.params.id; req.params.id = req.params.parentid; } return new Promise(function(resolve, reject) { sails.hooks.blueprints.middleware.find(req, { ok: resolve, serverError: reject, // this isn't perfect, since it returns a 500 error instead of a 404 error // but it is better than crashing the app when a record doesn't exist notFound: reject }); }) .then(function(result) { if (originalId !== undefined) { req.params.id = originalId; } return result; }); }
javascript
{ "resource": "" }
q48205
train
function(options) { var user = options.user.email || options.user.username return [ 'User', user, 'is not permitted to', options.method, options.model.name ].join(' '); }
javascript
{ "resource": "" }
q48206
train
function(options) { var ok = Promise.resolve(); var permissions = options.permissions; if (!_.isArray(permissions)) { permissions = [permissions]; } // look up the model id based on the model name for each permission, and change it to an id ok = ok.then(function() { return Promise.all(permissions.map(function(permission) { return Model.findOne({ name: permission.model }) .then(function(model) { permission.model = model.id; return permission; }); })); }); // look up user ids based on usernames, and replace the names with ids ok = ok.then(function(permissions) { if (options.users) { return User.find({ username: options.users }) .then(function(users) { options.users = users; }); } }); ok = ok.then(function(users) { return Role.create(options); }); return ok; }
javascript
{ "resource": "" }
q48207
train
function(options) { var findRole = options.role ? Role.findOne({ name: options.role }) : null; var findUser = options.user ? User.findOne({ username: options.user }) : null; var ok = Promise.all([findRole, findUser, Model.findOne({ name: options.model })]); ok = ok.then(([ role, user, model ]) => { var query = { model: model.id, action: options.action, relation: options.relation }; if (role && role.id) { query.role = role.id; } else if (user && user.id) { query.user = user.id; } else { return Promise.reject(new Error('You must provide either a user or role to revoke the permission from')); } return Permission.destroy(query); }); return ok; }
javascript
{ "resource": "" }
q48208
train
function(user, action, model, body) { return function(obj) { return new Promise(function(resolve, reject) { Model.findOne({ identity: model }).then(function(model) { return Permission.find({ model: model.id, action: action, relation: 'user', user: user }).populate('criteria'); }).then(function(permission) { if (permission.length > 0 && PermissionService.hasPassingCriteria(obj, permission, body)) { resolve(true); } else { resolve(false); } }).catch(reject); }); }; }
javascript
{ "resource": "" }
q48209
train
function (req) { // TODO there has to be a more sails-y way to do this without including // external modules if (_.isString(req.options.alias)) { sails.log.silly('singularizing', req.options.alias, 'to use as target model'); return pluralize.singular(req.options.alias); } else if (_.isString(req.options.model)) { return req.options.model; } else { return req.model && req.model.identity; } }
javascript
{ "resource": "" }
q48210
fixInputChange
train
function fixInputChange(input) { let files; Object.defineProperty(input, 'files', { set(v) { files = v; dispatchEvent(input, 'change'); }, get(v) { return files } }); }
javascript
{ "resource": "" }
q48211
getPackageData
train
function getPackageData({ encodedPackageName, registry, auth, proxy }) { const requestHeaders = {}; if (auth) { requestHeaders.Authorization = `Bearer ${auth}`; } const options = { uri: `${registry}/${encodedPackageName}`, resolveWithFullResponse: true, // When simple is true, all non-200 status codes throw an // error. However, we want to handle status code errors in // the .then(), so we make simple false. simple: false, headers: requestHeaders }; // If any proxy setting were passed then include the http proxy agent. const requestProxy = process.env.HTTP_PROXY || process.env.http_proxy || `${proxy}`; if (requestProxy !== "undefined") { options.agent = new HttpsProxyAgent(requestProxy); } return request(options).then(response => { const { statusCode } = response; if (statusCode === 404) { throw new Error( "That package doesn't exist. Did you mean to specify a custom registry?" ); } // If the statusCode not 200 or 404, assume that something must // have gone wrong with the connection if (statusCode !== 200) { throw new Error("There was a problem connecting to the registry."); } const { body } = response; const parsedData = JSON.parse(body); return parsedData; }); }
javascript
{ "resource": "" }
q48212
spawnInstall
train
function spawnInstall(command, args) { return new Promise((resolve, reject) => { // Spawn install process const installProcess = spawn(command, args, { cwd: process.cwd(), // Something to do with this, progress bar only shows if stdio is inherit // https://github.com/yarnpkg/yarn/issues/2200 stdio: "inherit" }); installProcess.on("error", err => reject(err)); installProcess.on("close", code => { if (code !== 0) { return reject( new Error(`The install process exited with error code ${code}.`) ); } return resolve(); }); }); }
javascript
{ "resource": "" }
q48213
printPackageFormatError
train
function printPackageFormatError() { console.log( `${ C.errorText } Please specify the package to install with peerDeps in the form of \`package\` or \`package@n.n.n\`` ); console.log( `${ C.errorText } At this time you must provide the full semver version of the package.` ); console.log( `${ C.errorText } Alternatively, omit it to automatically install the latest version of the package.` ); }
javascript
{ "resource": "" }
q48214
installCb
train
function installCb(err) { if (err) { console.log(`${C.errorText} ${err.message}`); process.exit(1); } let successMessage = `${C.successText} ${packageName} and its peerDeps were installed successfully.`; if (program.onlyPeers) { successMessage = `${ C.successText } The peerDeps of ${packageName} were installed successfully.`; } console.log(successMessage); process.exit(0); }
javascript
{ "resource": "" }
q48215
projection
train
function projection(c) { var zoom = c.zoom, max = zoom < 0 ? 1 : 1 << zoom, column = c.column % max, row = c.row; if (column < 0) column += max; return { locationPoint: function(l) { var c = po.map.locationCoordinate(l), k = Math.pow(2, zoom - c.zoom); return { x: tileSize.x * (k * c.column - column), y: tileSize.y * (k * c.row - row) }; } }; }
javascript
{ "resource": "" }
q48216
cleanup
train
function cleanup(e) { if (e.tile.proxyRefs) { for (var proxyKey in e.tile.proxyRefs) { var proxyTile = e.tile.proxyRefs[proxyKey]; if ((--proxyTile.proxyCount <= 0) && cache.unload(proxyKey)) { proxyTile.element.parentNode.removeChild(proxyTile.element); } } delete e.tile.proxyRefs; } }
javascript
{ "resource": "" }
q48217
touchstart
train
function touchstart(e) { var i = -1, n = e.touches.length, t = Date.now(); // doubletap detection if ((n == 1) && (t - last < 300)) { var z = map.zoom(); map.zoomBy(1 - z + Math.floor(z), map.mouse(e.touches[0])); e.preventDefault(); } last = t; // store original zoom & touch locations zoom = map.zoom(); angle = map.angle(); while (++i < n) { t = e.touches[i]; locations[t.identifier] = map.pointLocation(map.mouse(t)); } }
javascript
{ "resource": "" }
q48218
isOptionSet
train
function isOptionSet (option) { return context.options[1] != null ? context.options[1][option] === !spaced : false }
javascript
{ "resource": "" }
q48219
isSameLine
train
function isSameLine (left, right) { return left.loc.start.line === right.loc.start.line }
javascript
{ "resource": "" }
q48220
reportNoBeginningSpace
train
function reportNoBeginningSpace (node, token) { context.report(node, token.loc.start, "There should be no space after '" + token.value + "'") }
javascript
{ "resource": "" }
q48221
validateArraySpacing
train
function validateArraySpacing (node) { if (node.elements.length === 0) { return } var first = context.getFirstToken(node) var second = context.getFirstToken(node, 1) var penultimate = context.getLastToken(node, 1) var last = context.getLastToken(node) var openingBracketMustBeSpaced = (options.objectsInArraysException && second.value === '{') || (options.arraysInArraysException && second.value === '[') || (options.singleElementException && node.elements.length === 1) ? !options.spaced : options.spaced var closingBracketMustBeSpaced = (options.objectsInArraysException && penultimate.value === '}') || (options.arraysInArraysException && penultimate.value === ']') || (options.singleElementException && node.elements.length === 1) ? !options.spaced : options.spaced // we only care about evenly spaced things if (options.either) { // newlines at any point means return if (!isSameLine(first, last)) { return } // confirm that the object expression/literal is spaced evenly if (!isEvenlySpacedAndNotTooLong(node, [first, second], [penultimate, last])) { context.report(node, 'Expected consistent spacing') } return } if (isSameLine(first, second)) { if (openingBracketMustBeSpaced && !isSpaced(first, second)) { reportRequiredBeginningSpace(node, first) } if (!openingBracketMustBeSpaced && isSpaced(first, second)) { reportNoBeginningSpace(node, first) } } if (isSameLine(penultimate, last)) { if (closingBracketMustBeSpaced && !isSpaced(penultimate, last)) { reportRequiredEndingSpace(node, last) } if (!closingBracketMustBeSpaced && isSpaced(penultimate, last)) { reportNoEndingSpace(node, last) } } }
javascript
{ "resource": "" }
q48222
checkSpacing
train
function checkSpacing (propertyName) { return function (node) { if (!node.computed) { return } var property = node[propertyName] var before = context.getTokenBefore(property) var first = context.getFirstToken(property) var last = context.getLastToken(property) var after = context.getTokenAfter(property) var startSpace, endSpace if (propertyNameMustBeEven) { if (!isSameLine(before, after)) { context.report(node, 'Expected "[" and "]" to be on the same line') return } startSpace = first.loc.start.column - before.loc.end.column endSpace = after.loc.start.column - last.loc.end.column if (startSpace !== endSpace || startSpace > 1) { context.report(node, 'Expected 1 or 0 spaces around "[" and "]"') } return } if (isSameLine(before, first)) { if (propertyNameMustBeSpaced) { if (!isSpaced(before, first) && isSameLine(before, first)) { reportRequiredBeginningSpace(node, before) } } else { if (isSpaced(before, first)) { reportNoBeginningSpace(node, before) } } } if (isSameLine(last, after)) { if (propertyNameMustBeSpaced) { if (!isSpaced(last, after) && isSameLine(last, after)) { reportRequiredEndingSpace(node, after) } } else { if (isSpaced(last, after)) { reportNoEndingSpace(node, after) } } } } }
javascript
{ "resource": "" }
q48223
validateBraceSpacing
train
function validateBraceSpacing (node, first, second, penultimate, last) { var closingCurlyBraceMustBeSpaced = (options.arraysInObjectsException && penultimate.value === ']') || (options.objectsInObjectsException && penultimate.value === '}') ? !options.spaced : options.spaced // we only care about evenly spaced things if (options.either) { // newlines at any point means return if (!isSameLine(first, last)) { return } // confirm that the object expression/literal is spaced evenly if (!isEvenlySpacedAndNotTooLong(node, [first, second], [penultimate, last])) { context.report(node, 'Expected consistent spacing') } return } // { and key are on same line if (isSameLine(first, second)) { if (options.spaced && !isSpaced(first, second)) { reportRequiredBeginningSpace(node, first) } if (!options.spaced && isSpaced(first, second)) { reportNoBeginningSpace(node, first) } } // final key and } ore on the same line if (isSameLine(penultimate, last)) { if (closingCurlyBraceMustBeSpaced && !isSpaced(penultimate, last)) { reportRequiredEndingSpace(node, last) } if (!closingCurlyBraceMustBeSpaced && isSpaced(penultimate, last)) { reportNoEndingSpace(node, last) } } }
javascript
{ "resource": "" }
q48224
train
function() { var cmd = `networksetup -setairportnetwork ${net_interface} "${ssid}"`; run_as_user(cmd, [], function(err, out) { return cb(err, out); }); }
javascript
{ "resource": "" }
q48225
train
function(key, cb) { // ensure the plugin is loaded if registration succeeds var success = function() { shared.plugin_manager.force_enable('control-panel', function(err) { cb(); }); } // set API key and clear Device key shared.keys.set_api_key(key, function(err) { if (err) return cb(err); log('Linking device...'); shared.panel.link(function(err) { if (!err) return success(); // ok, we got an error. clear the API key before returning. // call back the original error as well. shared.keys.set_api_key('', function(e) { cb(err); }); }); }) }
javascript
{ "resource": "" }
q48226
train
function(error, method) { queued++; if (typeof wipe[method] == 'function') { wipe[method](function(err, removed) { if (err) last_err = err; removed += removed; --queued || finished(last_err); }) } else return finished(error); }
javascript
{ "resource": "" }
q48227
train
function(file, cb) { var error, hash = createHash('sha1'), stream = fs.ReadStream(file); stream.on('data', function(chunk) { hash.update(chunk); }); stream.on('error', function(e) { if (!error) cb(e); error = e; }) stream.on('end', function() { if (!error) cb(null, hash.digest('hex')); }); }
javascript
{ "resource": "" }
q48228
like_a_boss
train
function like_a_boss(attempt) { fs.rename(from, to, function(err) { if (err) log('Error when moving directory: ' + err.message); // if no error, or err is not EPERM/EACCES, we're done if (!err || (err.code != 'EPERM' && err.code != 'EACCES')) cb(); else if (attempt >= 30) // max attempts reached, so give up. cb(err); else setTimeout(function() { like_a_boss(attempt + 1) }, 1000); }) }
javascript
{ "resource": "" }
q48229
train
function(hostname, callback) { get_nodes(function(err,nodes) { if (err) return callback(err); var n = nodes.filter(function(node) { return node.name === hostname; }); callback(null,(n.length === 1) ? n[0].ip_address : null); }); }
javascript
{ "resource": "" }
q48230
train
function(version, cb) { var version_path = join(paths.versions, version), opts = { env: process.env, cwd: version_path }, args = ['config', 'activate']; opts.env.UPGRADING_FROM = common.version; if (process.platform == 'win32') { var bin = join(version_path, 'bin', 'node.exe'); args = [join('lib', 'conf', 'cli.js')].concat(args); } else { var bin = join(version_path, 'bin', paths.bin); } run_synced(bin, args, opts, function(err, code) { if (!err && code === 0) return cb(); shared.log('Failed. Rolling back!'); // something went wrong while upgrading. // remove new package & undo pre_uninstall shared.version_manager.remove(version, function(er) { cb(er || err); }); }); }
javascript
{ "resource": "" }
q48231
train
function(type, action, name, opts, emitter) { logger.info('Running: ' + name) running[name] = action; emitter.once('end', function(err, out) { if (err) hooks.trigger('error', err); logger.info('Stopped: ' + name); action_stopped(name); setTimeout(function() { hooks.trigger(type, 'stopped', name, opts, err, out); }, 1000); if (action.events) emitter.removeAllListeners(); }) if (!action.events) return; watch_action_events(action.events, emitter); }
javascript
{ "resource": "" }
q48232
store
train
function store(err, resp, data) { if (err && (err.code == 'EADDRINFO' || err.code == 'ENOTFOUND')) failed.push(data); }
javascript
{ "resource": "" }
q48233
warn
train
function warn(str, code) { if (process.stdout.writable) process.stdout.write(str + '\n'); if (typeof code != 'undefined') process.exit(code); }
javascript
{ "resource": "" }
q48234
visible
train
function visible(plugin_name) { var obj = get_base_object(); obj.config = scoped_config(plugin_name); obj.logger = scoped_logger(plugin_name); return obj; }
javascript
{ "resource": "" }
q48235
train
function(type, name, opts) { if (!watching) return; var storable = ['start', 'watch', 'report']; if (type == 'cancel') // report cancelled remove('report', name); else if (storable.indexOf(type) !== -1) // ok for launch store(type, name, opts); }
javascript
{ "resource": "" }
q48236
train
function() { if (!watching) return; hooks.on('action', function(event, name) { if (event == 'stopped' || event == 'failed') remove('start', name); }); hooks.on('trigger', function(event, name) { if (event == 'stopped') remove('watch', name); }); }
javascript
{ "resource": "" }
q48237
prettify
train
function prettify(data) { let json = JSON.stringify(data); json = json.replace(/{/g, "{\n\n\t"); json = json.replace(/,/g, ",\n\t"); json = json.replace(/}/g, ",\n\n}"); return json; }
javascript
{ "resource": "" }
q48238
setOptions
train
function setOptions(options) { exports.options = options; home.options = options; renderMarkdown.options = options; renderGithubMarkdown.options = options; }
javascript
{ "resource": "" }
q48239
RenderMarkdown
train
function RenderMarkdown() { this.options = {}; // Default value only. this.routeMe = function(req, res) { var md = new Markdown(); var debug = req.param('debug', false); md.debug = debug; md.bufmax = 2048; var fileName = path.join(viewsDir, req.params.filename); if (debug) console.error('>>>renderMarkdown: fileName="' + fileName + '"'); res.write(jade.renderFile( path.join(viewsDir, 'mdheader.jade'), {title: this.options.title, subtitle: 'Markdown', pretty: true})); md.once('end', function() { res.write(jade.renderFile(path.join(viewsDir, 'mdtrailer.jade'), {pretty: true})); res.end(); }); md.render(fileName, mdOpts, function(err) { if (debug) console.error('>>>renderMarkdown: err=' + err); if (err) { res.write('>>>' + err); res.end(); return; } else md.pipe(res); }); }; }
javascript
{ "resource": "" }
q48240
fromListPush
train
function fromListPush(toPush, nodes) { var h = toPush.height; // Maybe the node on this height does not exist. if (nodes.length === h) { var node = { ctor: '_Array', height: h + 1, table: [], lengths: [] }; nodes.push(node); } nodes[h].table.push(toPush); var len = length(toPush); if (nodes[h].lengths.length > 0) { len += nodes[h].lengths[nodes[h].lengths.length - 1]; } nodes[h].lengths.push(len); if (nodes[h].table.length === M) { fromListPush(nodes[h], nodes); nodes[h] = { ctor: '_Array', height: h + 1, table: [], lengths: [] }; } }
javascript
{ "resource": "" }
q48241
push
train
function push(item, a) { var pushed = push_(item, a); if (pushed !== null) { return pushed; } var newTree = create(item, a.height); return siblise(a, newTree); }
javascript
{ "resource": "" }
q48242
push_
train
function push_(item, a) { // Handle resursion stop at leaf level. if (a.height === 0) { if (a.table.length < M) { var newA = { ctor: '_Array', height: 0, table: a.table.slice() }; newA.table.push(item); return newA; } else { return null; } } // Recursively push var pushed = push_(item, botRight(a)); // There was space in the bottom right tree, so the slot will // be updated. if (pushed !== null) { var newA = nodeCopy(a); newA.table[newA.table.length - 1] = pushed; newA.lengths[newA.lengths.length - 1]++; return newA; } // When there was no space left, check if there is space left // for a new slot with a tree which contains only the item // at the bottom. if (a.table.length < M) { var newSlot = create(item, a.height - 1); var newA = nodeCopy(a); newA.table.push(newSlot); newA.lengths.push(newA.lengths[newA.lengths.length - 1] + length(newSlot)); return newA; } else { return null; } }
javascript
{ "resource": "" }
q48243
map
train
function map(f, a) { var newA = { ctor: '_Array', height: a.height, table: new Array(a.table.length) }; if (a.height > 0) { newA.lengths = a.lengths; } for (var i = 0; i < a.table.length; i++) { newA.table[i] = a.height === 0 ? f(a.table[i]) : map(f, a.table[i]); } return newA; }
javascript
{ "resource": "" }
q48244
append
train
function append(a,b) { if (a.table.length === 0) { return b; } if (b.table.length === 0) { return a; } var c = append_(a, b); // Check if both nodes can be crunshed together. if (c[0].table.length + c[1].table.length <= M) { if (c[0].table.length === 0) { return c[1]; } if (c[1].table.length === 0) { return c[0]; } // Adjust .table and .lengths c[0].table = c[0].table.concat(c[1].table); if (c[0].height > 0) { var len = length(c[0]); for (var i = 0; i < c[1].lengths.length; i++) { c[1].lengths[i] += len; } c[0].lengths = c[0].lengths.concat(c[1].lengths); } return c[0]; } if (c[0].height > 0) { var toRemove = calcToRemove(a, b); if (toRemove > E) { c = shuffle(c[0], c[1], toRemove); } } return siblise(c[0], c[1]); }
javascript
{ "resource": "" }
q48245
insertRight
train
function insertRight(parent, node) { var index = parent.table.length - 1; parent.table[index] = node; parent.lengths[index] = length(node); parent.lengths[index] += index > 0 ? parent.lengths[index - 1] : 0; }
javascript
{ "resource": "" }
q48246
get2
train
function get2(a, b, index) { return index < a.length ? a[index] : b[index - a.length]; }
javascript
{ "resource": "" }
q48247
createNode
train
function createNode(h, length) { if (length < 0) { length = 0; } var a = { ctor: '_Array', height: h, table: new Array(length) }; if (h > 0) { a.lengths = new Array(length); } return a; }
javascript
{ "resource": "" }
q48248
nodeCopy
train
function nodeCopy(a) { var newA = { ctor: '_Array', height: a.height, table: a.table.slice() }; if (a.height > 0) { newA.lengths = a.lengths.slice(); } return newA; }
javascript
{ "resource": "" }
q48249
length
train
function length(array) { if (array.height === 0) { return array.table.length; } else { return array.lengths[array.lengths.length - 1]; } }
javascript
{ "resource": "" }
q48250
getSlot
train
function getSlot(i, a) { var slot = i >> (5 * a.height); while (a.lengths[slot] <= i) { slot++; } return slot; }
javascript
{ "resource": "" }
q48251
create
train
function create(item, h) { if (h === 0) { return { ctor: '_Array', height: 0, table: [item] }; } return { ctor: '_Array', height: h, table: [create(item, h - 1)], lengths: [1] }; }
javascript
{ "resource": "" }
q48252
mainToProgram
train
function mainToProgram(moduleName, wrappedMain) { var main = wrappedMain.main; if (typeof main.init === 'undefined') { var emptyBag = batch(_elm_lang$core$Native_List.Nil); var noChange = _elm_lang$core$Native_Utils.Tuple2( _elm_lang$core$Native_Utils.Tuple0, emptyBag ); return _elm_lang$virtual_dom$VirtualDom$programWithFlags({ init: function() { return noChange; }, view: function() { return main; }, update: F2(function() { return noChange; }), subscriptions: function () { return emptyBag; } }); } var flags = wrappedMain.flags; var init = flags ? initWithFlags(moduleName, main.init, flags) : initWithoutFlags(moduleName, main.init); return _elm_lang$virtual_dom$VirtualDom$programWithFlags({ init: init, view: main.view, update: main.update, subscriptions: main.subscriptions, }); }
javascript
{ "resource": "" }
q48253
makeEmbedHelp
train
function makeEmbedHelp(moduleName, program, rootDomNode, flags) { var init = program.init; var update = program.update; var subscriptions = program.subscriptions; var view = program.view; var makeRenderer = program.renderer; // ambient state var managers = {}; var renderer; // init and update state in main process var initApp = _elm_lang$core$Native_Scheduler.nativeBinding(function(callback) { var results = init(flags); var model = results._0; renderer = makeRenderer(rootDomNode, enqueue, view(model)); var cmds = results._1; var subs = subscriptions(model); dispatchEffects(managers, cmds, subs); callback(_elm_lang$core$Native_Scheduler.succeed(model)); }); function onMessage(msg, model) { return _elm_lang$core$Native_Scheduler.nativeBinding(function(callback) { var results = A2(update, msg, model); model = results._0; renderer.update(view(model)); var cmds = results._1; var subs = subscriptions(model); dispatchEffects(managers, cmds, subs); callback(_elm_lang$core$Native_Scheduler.succeed(model)); }); } var mainProcess = spawnLoop(initApp, onMessage); function enqueue(msg) { _elm_lang$core$Native_Scheduler.rawSend(mainProcess, msg); } var ports = setupEffects(managers, enqueue); return ports ? { ports: ports } : {}; }
javascript
{ "resource": "" }
q48254
fireEvent
train
function fireEvent(element, name, data) { if (data === void 0) { data = {}; } var event = new CustomEvent(name, { detail: data, bubbles: true }); element.dispatchEvent(event); return event; }
javascript
{ "resource": "" }
q48255
fireMaterializeEvent
train
function fireMaterializeEvent(element, name, data) { if (data === void 0) { data = {}; } return fireEvent(element, "" + constants_1.constants.eventPrefix + name, data); }
javascript
{ "resource": "" }
q48256
cleanOptions
train
function cleanOptions(options) { Object.keys(options).filter(function (key) { return options[key] === undefined; }).forEach(function (key) { return delete options[key]; }); }
javascript
{ "resource": "" }
q48257
makeRe
train
function makeRe(pattern, options) { if (pattern instanceof RegExp) { return pattern; } if (typeof pattern !== 'string') { throw new TypeError('expected a string'); } if (pattern.length > MAX_LENGTH) { throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); } var key = pattern; // do this before shallow cloning options, it's a lot faster if (!options || (options && options.cache !== false)) { key = createKey(pattern, options); if (cache.hasOwnProperty(key)) { return cache[key]; } } var opts = extend({}, options); if (opts.contains === true) { if (opts.negate === true) { opts.strictNegate = false; } else { opts.strict = false; } } if (opts.strict === false) { opts.strictOpen = false; opts.strictClose = false; } var open = opts.strictOpen !== false ? '^' : ''; var close = opts.strictClose !== false ? '$' : ''; var flags = opts.flags || ''; var regex; if (opts.nocase === true && !/i/.test(flags)) { flags += 'i'; } try { if (opts.negate || typeof opts.strictNegate === 'boolean') { pattern = not.create(pattern, opts); } var str = open + '(?:' + pattern + ')' + close; regex = new RegExp(str, flags); if (opts.safe === true && safe(regex) === false) { throw new Error('potentially unsafe regular expression: ' + regex.source); } } catch (err) { if (opts.strictErrors === true || opts.safe === true) { err.key = key; err.pattern = pattern; err.originalOptions = options; err.createdOptions = opts; throw err; } try { regex = new RegExp('^' + pattern.replace(/(\W)/g, '\\$1') + '$'); } catch (err) { regex = /.^/; //<= match nothing } } if (opts.cache !== false) { memoize(regex, key, pattern, opts); } return regex; }
javascript
{ "resource": "" }
q48258
memoize
train
function memoize(regex, key, pattern, options) { define(regex, 'cached', true); define(regex, 'pattern', pattern); define(regex, 'options', options); define(regex, 'key', key); cache[key] = regex; }
javascript
{ "resource": "" }
q48259
Link
train
function Link({ to, children }) { function click(e) { e.preventDefault() navigate(to) } return <a href={to} onClick={click}> {children} </a> }
javascript
{ "resource": "" }
q48260
clamp
train
function clamp(value, min, max) { if (value < min) return min if (value > max) return max return value }
javascript
{ "resource": "" }
q48261
convertHexToRGB
train
function convertHexToRGB(color) { if (color.length === 4) { let extendedColor = '#' for (let i = 1; i < color.length; i++) extendedColor += color.charAt(i) + color.charAt(i) color = extendedColor } const values = { r: parseInt(color.substr(1, 2), 16), g: parseInt(color.substr(3, 2), 16), b: parseInt(color.substr(5, 2), 16) } return `rgb(${values.r}, ${values.g}, ${values.b})` }
javascript
{ "resource": "" }
q48262
decomposeColor
train
function decomposeColor(color) { if (color.charAt(0) === '#') return decomposeColor(convertHexToRGB(color)) color = color.replace(/\s/g, '') const marker = color.indexOf('(') if (marker === -1) throw new Error(`Rambler UI: The ${color} color was not parsed correctly, because it has an unsupported format (color name or RGB %). This may cause issues in component rendering.`) const type = color.substring(0, marker) let values = color.substring(marker + 1, color.length - 1).split(',') values = values.map(value => parseFloat(value)) return {type, values} }
javascript
{ "resource": "" }
q48263
getLuminance
train
function getLuminance(color) { color = decomposeColor(color) if (color.type.indexOf('rgb') > -1) { const rgb = color.values.map(val => { val /= 255 // normalized return val <= 0.03928 ? val / 12.92 : Math.pow((val + 0.055) / 1.055, 2.4) }) return Number( (0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]).toFixed(3) ) // Truncate at 3 digits } else if (color.type.indexOf('hsl') > -1) { return color.values[2] / 100 } }
javascript
{ "resource": "" }
q48264
convertColorToString
train
function convertColorToString(color) { const {type, values} = color // Only convert the first 3 values to int (i.e. not alpha) if (type.indexOf('rgb') > -1) for (let i = 0; i < 3; i++) values[i] = parseInt(values[i]) let colorString if (type.indexOf('hsl') > -1) colorString = `${color.type}(${values[0]}, ${values[1]}%, ${values[2]}%` else colorString = `${color.type}(${values[0]}, ${values[1]}, ${values[2]}` if (values.length === 4) colorString += `, ${color.values[3].toFixed(2)})` else colorString += ')' return colorString }
javascript
{ "resource": "" }
q48265
inflect
train
function inflect(gender, name, gcase, nametype) { var nametype_rulesets = rules[nametype], parts = name.split('-'), result = []; for (var i = 0; i < parts.length; i++) { var part = parts[i], first_word = i === 0 && parts.size > 1, rule = find_rule_global(gender, part, nametype_rulesets, {first_word: first_word}); if (rule) result.push(apply_rule(part, gcase, rule)); else result.push(part); } return result.join('-'); }
javascript
{ "resource": "" }
q48266
find_rule_global
train
function find_rule_global(gender, name, nametype_rulesets, features) { if (!features) features = {}; var tags = []; for (var key in features) { if (features.hasOwnProperty(key)) tags.push(key); } if (nametype_rulesets.exceptions) { var rule = find_rule_local( gender, name, nametype_rulesets.exceptions, true, tags); if (rule) return rule; } return find_rule_local( gender, name, nametype_rulesets.suffixes, false, tags); }
javascript
{ "resource": "" }
q48267
find_rule_local
train
function find_rule_local(gender, name, ruleset, match_whole_word, tags) { for (var i = 0; i < ruleset.length; i++) { var rule = ruleset[i]; if (rule.tags) { var common_tags = []; for (var j = 0; j < rule.tags.length; j++) { var tag = rule.tags[j]; if (!contains(tags, tag)) common_tags.push(tag); } if (!common_tags.length) continue; } if (rule.gender !== 'androgynous' && gender !== rule.gender) continue; name = name.toLowerCase(); for (var j = 0; j < rule.test.length; j++) { var sample = rule.test[j]; var test = match_whole_word ? name : name.substr(name.length - sample.length); if (test === sample) return rule; } } return false; }
javascript
{ "resource": "" }
q48268
apply_rule
train
function apply_rule(name, gcase, rule) { var mod; if (gcase === 'nominative') mod = '.'; else { for (var i = 0; i < predef.cases.length; i++) { if (gcase === predef.cases[i]) { mod = rule.mods[i - 1]; break; } } } for (var i = 0; i < mod.length; i++) { var chr = mod[i]; switch (chr) { case '.': break; case '-': name = name.substr(0, name.length - 1); break; default: name += chr; } } return name; }
javascript
{ "resource": "" }
q48269
train
function (metadata) { var result = createResult(metadata) var parentResult = current() if (parentResult) { parentResult.children.push(result) } currentNesting.push(result) }
javascript
{ "resource": "" }
q48270
createFunction
train
function createFunction(name, args, fn) { if (isFunction(args)) { fn = args; args = []; } return new Function('body', 'return function ' + name + '(' + args.join(', ') + ') { return body.apply(this, arguments); };' )(fn); }
javascript
{ "resource": "" }
q48271
promisifyRequest
train
function promisifyRequest(requestMethod) { return function(apiPath, params, callback) { const promise = new Promise(function(resolve, reject) { requestMethod.call(this, apiPath, params, function(err, resp) { if (err) { reject(err); } else { resolve(resp); } }); }.bind(this)); if (callback) { promise .then(function(body) { callback(null, body); }) .catch(function(err) { callback(err, null); }); } return promise; }; }
javascript
{ "resource": "" }
q48272
getRequest
train
function getRequest(requestGet, credentials, baseUrl, apiPath, requestOptions, params, callback) { params = params || {}; if (credentials.consumer_key) { params.api_key = credentials.consumer_key; } return requestGet(extend({ url: baseUrl + apiPath + '?' + qs.stringify(params), oauth: credentials, json: true, }, requestOptions), requestCallback(callback)); }
javascript
{ "resource": "" }
q48273
postRequest
train
function postRequest(requestPost, credentials, baseUrl, apiPath, requestOptions, params, callback) { params = params || {}; // Sign without multipart data const currentRequest = requestPost(extend({ url: baseUrl + apiPath, oauth: credentials, }, requestOptions), function(err, response, body) { try { body = JSON.parse(body); } catch (e) { body = { error: 'Malformed Response: ' + body, }; } requestCallback(callback)(err, response, body); }); // Sign it with the non-data parameters const dataKeys = ['data']; currentRequest.form(omit(params, dataKeys)); currentRequest.oauth(credentials); // Clear the side effects from form(param) delete currentRequest.headers['content-type']; delete currentRequest.body; // if 'data' is an array, rename it with indices if ('data' in params && Array.isArray(params.data)) { for (let i = 0; i < params.data.length; ++i) { params['data[' + i + ']'] = params.data[i]; } delete params.data; } // And then add the full body const form = currentRequest.form(); for (const key in params) { form.append(key, params[key]); } // Add the form header back extend(currentRequest.headers, form.getHeaders()); return currentRequest; }
javascript
{ "resource": "" }
q48274
addMethod
train
function addMethod(client, methodName, apiPath, paramNames, requestType) { const apiPathSplit = apiPath.split('/'); const apiPathParamsCount = apiPath.split(/\/:[^\/]+/).length - 1; const buildApiPath = function(args) { let pathParamIndex = 0; return reduce(apiPathSplit, function(apiPath, apiPathChunk, i) { // Parse arguments in the path if (apiPathChunk === ':blogIdentifier') { // Blog URLs are special apiPathChunk = forceFullBlogUrl(args[pathParamIndex++]); } else if (apiPathChunk[0] === ':') { apiPathChunk = args[pathParamIndex++]; } if (apiPathChunk) { return apiPath + '/' + apiPathChunk; } else { return apiPath; } }, ''); }; const namedParams = (apiPath.match(/\/:[^\/]+/g) || []).map(function(param) { return param.substr(2); }).concat(paramNames, 'params', 'callback'); const methodBody = function() { const argsLength = arguments.length; const args = new Array(argsLength); for (let i = 0; i < argsLength; i++) { args[i] = arguments[i]; } const requiredParamsStart = apiPathParamsCount; const requiredParamsEnd = requiredParamsStart + paramNames.length; const requiredParamArgs = args.slice(requiredParamsStart, requiredParamsEnd); // Callback is at the end const callback = isFunction(args[args.length - 1]) ? args.pop() : null; // Required Parmas const params = zipObject(paramNames, requiredParamArgs); extend(params, isPlainObject(args[args.length - 1]) ? args.pop() : {}); // Path arguments are determined after required parameters const apiPathArgs = args.slice(0, apiPathParamsCount); let request = requestType; if (isString(requestType)) { request = requestType.toUpperCase() === 'POST' ? client.postRequest : client.getRequest; } else if (!isFunction(requestType)) { request = client.getRequest; } return request.call(client, buildApiPath(apiPathArgs), params, callback); }; set(client, methodName, createFunction(methodName, namedParams, methodBody)); }
javascript
{ "resource": "" }
q48275
addMethods
train
function addMethods(client, methods, requestType) { let apiPath, paramNames; for (const methodName in methods) { apiPath = methods[methodName]; if (isString(apiPath)) { paramNames = []; } else if (isPlainObject(apiPath)) { paramNames = apiPath.paramNames || []; apiPath = apiPath.path; } else { paramNames = apiPath[1] || []; apiPath = apiPath[0]; } addMethod(client, methodName, apiPath, paramNames, requestType || 'GET'); } }
javascript
{ "resource": "" }
q48276
wrapCreatePost
train
function wrapCreatePost(type, validate) { return function(blogIdentifier, params, callback) { params = extend({type: type}, params); if (isArray(validate)) { validate = partial(function(params, requireKeys) { if (requireKeys.length) { const keyIntersection = intersection(keys(params), requireKeys); if (requireKeys.length === 1 && !keyIntersection.length) { throw new Error('Missing required field: ' + requireKeys[0]); } else if (!keyIntersection.length) { throw new Error('Missing one of: ' + requireKeys.join(', ')); } else if (keyIntersection.length > 1) { throw new Error('Can only use one of: ' + requireKeys.join(', ')); } } return true; }, params, validate); } if (isFunction(validate)) { if (!validate(params)) { throw new Error('Error validating parameters'); } } if (arguments.length > 2) { return this.createPost(blogIdentifier, params, callback); } else { return this.createPost(blogIdentifier, params); } }; }
javascript
{ "resource": "" }
q48277
TumblrClient
train
function TumblrClient(options) { // Support for `TumblrClient(credentials, baseUrl, requestLibrary)` if (arguments.length > 1) { options = { credentials: arguments[0], baseUrl: arguments[1], request: arguments[2], returnPromises: false, }; } options = options || {}; this.version = CLIENT_VERSION; this.credentials = get(options, 'credentials', omit(options, 'baseUrl', 'request')); this.baseUrl = get(options, 'baseUrl', API_BASE_URL); this.request = get(options, 'request', request); this.requestOptions = { followRedirect: false, headers: { 'User-Agent': 'tumblr.js/' + CLIENT_VERSION, }, }; this.addGetMethods(API_METHODS.GET); this.addPostMethods(API_METHODS.POST); /** * Creates a text post on the given blog * * @see {@link https://www.tumblr.com/docs/api/v2#ptext-posts|API docs} * * @method createTextPost * * @param {string} blogIdentifier - blog name or URL * @param {Object} params - parameters sent with the request * @param {string} [params.title] - post title text * @param {string} params.body - post body text * @param {TumblrClient~callback} [callback] - invoked when the request completes * * @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used * * @memberof TumblrClient */ this.createTextPost = wrapCreatePost('text', ['body']); /** * Creates a photo post on the given blog * * @see {@link https://www.tumblr.com/docs/api/v2#pphoto-posts|API docs} * * @method createPhotoPost * * @param {string} blogIdentifier - blog name or URL * @param {Object} params - parameters sent with the request * @param {string} params.source - image source URL * @param {Stream|Array} params.data - an image or array of images * @param {string} params.data64 - base64-encoded image data * @param {string} [params.caption] - post caption text * @param {TumblrClient~callback} [callback] - invoked when the request completes * * @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used * * @memberof TumblrClient */ this.createPhotoPost = wrapCreatePost('photo', ['data', 'data64', 'source']); /** * Creates a quote post on the given blog * * @see {@link https://www.tumblr.com/docs/api/v2#pquote-posts|API docs} * * @method createQuotePost * * @param {string} blogIdentifier - blog name or URL * @param {Object} params - parameters sent with the request * @param {string} params.quote - quote text * @param {string} [params.source] - quote source * @param {TumblrClient~callback} [callback] - invoked when the request completes * * @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used * * @memberof TumblrClient */ this.createQuotePost = wrapCreatePost('quote', ['quote']); /** * Creates a link post on the given blog * * @see {@link https://www.tumblr.com/docs/api/v2#plink-posts|API docs} * * @method createLinkPost * * @param {string} blogIdentifier - blog name or URL * @param {Object} params - parameters sent with the request * @param {string} [params.title] - post title text * @param {string} params.url - the link URL * @param {string} [params.thumbnail] - the URL of an image to use as the thumbnail * @param {string} [params.excerpt] - an excerpt from the page the link points to * @param {string} [params.author] - the name of the author of the page the link points to * @param {string} [params.description] - post caption text * @param {TumblrClient~callback} [callback] - invoked when the request completes * * @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used * * @memberof TumblrClient */ this.createLinkPost = wrapCreatePost('link', ['url']); /** * Creates a chat post on the given blog * * @see {@link https://www.tumblr.com/docs/api/v2#pchat-posts|API docs} * * @method createChatPost * * @param {string} blogIdentifier - blog name or URL * @param {Object} params - parameters sent with the request * @param {string} [params.title] - post title text * @param {string} params.conversation - chat text * @param {TumblrClient~callback} [callback] - invoked when the request completes * * @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used * * @memberof TumblrClient */ this.createChatPost = wrapCreatePost('chat', ['conversation']); /** * Creates an audio post on the given blog * * @see {@link https://www.tumblr.com/docs/api/v2#paudio-posts|API docs} * * @method createAudioPost * * @param {string} blogIdentifier - blog name or URL * @param {Object} params - parameters sent with the request * @param {string} params.external_url - image source URL * @param {Stream} params.data - an audio file * @param {string} [params.caption] - post caption text * @param {TumblrClient~callback} [callback] - invoked when the request completes * * @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used * * @memberof TumblrClient */ this.createAudioPost = wrapCreatePost('audio', ['data', 'data64', 'external_url']); /** * Creates a video post on the given blog * * @see {@link https://www.tumblr.com/docs/api/v2#pvideo-posts|API docs} * * @method createVideoPost * * @param {string} blogIdentifier - blog name or URL * @param {Object} params - parameters sent with the request * @param {string} params.embed - embed code or a video URL * @param {Stream} params.data - a video file * @param {string} [params.caption] - post caption text * @param {TumblrClient~callback} [callback] - invoked when the request completes * * @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used * * @memberof TumblrClient */ this.createVideoPost = wrapCreatePost('video', ['data', 'data64', 'embed']); // Enable Promise mode if (get(options, 'returnPromises', false)) { this.returnPromises(); } }
javascript
{ "resource": "" }
q48278
train
function(options) { // Support for `TumblrClient(credentials, baseUrl, requestLibrary)` if (arguments.length > 1) { options = { credentials: arguments[0], baseUrl: arguments[1], request: arguments[2], returnPromises: false, }; } // Create the Tumblr Client const client = new TumblrClient(options); return client; }
javascript
{ "resource": "" }
q48279
Email
train
function Email (options) { this.action = options.action || SEND_EMAIL_ACTION; this.key = options.key; this.secret = options.secret; this.amazon = options.amazon; this.from = options.from; this.subject = options.subject; this.message = options.message; this.altText = options.altText; this.rawMessage = options.rawMessage; this.configurationSet = options.configurationSet; this.messageTags = options.messageTags; this.extractRecipient(options, 'to'); this.extractRecipient(options, 'cc'); this.extractRecipient(options, 'bcc'); this.extractRecipient(options, 'replyTo'); }
javascript
{ "resource": "" }
q48280
moveToMostRecentLru
train
function moveToMostRecentLru(lru, lruPath) { var lruLen = lru.length, lruPathLen = lruPath.length, isMatch, i, ii; for (i = 0; i < lruLen; i++) { isMatch = true; for (ii = 0; ii < lruPathLen; ii++) { if (!isEqual(lru[i][ii].arg, lruPath[ii].arg)) { isMatch = false; break; } } if (isMatch) { break; } } lru.push(lru.splice(i, 1)[0]); }
javascript
{ "resource": "" }
q48281
removeCachedResult
train
function removeCachedResult(removedLru) { var removedLruLen = removedLru.length, currentLru = removedLru[removedLruLen - 1], tmp, i; currentLru.cacheItem.delete(currentLru.arg); // walk down the tree removing dead branches (size 0) along the way for (i = removedLruLen - 2; i >= 0; i--) { currentLru = removedLru[i]; tmp = currentLru.cacheItem.get(currentLru.arg); if (!tmp || !tmp.size) { currentLru.cacheItem.delete(currentLru.arg); } else { break; } } }
javascript
{ "resource": "" }
q48282
rebuild
train
function rebuild (dir, _callback) { var cwd = process.cwd() , gypInst = gyp() var callback = function (err) { _callback(err) } gypInst.parseArgv([ null, null, 'rebuild', '--loglevel', 'silent' ]) process.chdir(dir) gypInst.commands.clean([], function (err) { if (err) return callback(new Error('node-gyp clean: ' + err.message)) gypInst.commands.configure([], function (err) { if (err) return callback(new Error('node-gyp configure: ' + err.message)) gypInst.commands.build([], function (err) { if (err) return callback(new Error('node-gyp build: ' + err.message)) process.chdir(cwd) return callback() }) }) }) }
javascript
{ "resource": "" }
q48283
checkBinding
train
function checkBinding (mode, callback) { var exercise = this function fail (msg) { exercise.emit('fail', msg) return callback(null, false) } fs.readFile(path.join(exercise.submission, 'binding.gyp'), 'utf8', function (err, data) { if (err) return fail('Read binding.gyp (' + err.message + ')') var doc try { doc = yaml.safeLoad(data) } catch (e) { return fail('Parse binding.gyp (' + e.message + ')') } if (!is.isObject(doc)) return fail('binding.gyp does not contain a parent object ({ ... })') if (!is.isArray(doc.targets)) return fail('binding.gyp does not contain a targets array ({ targets: [ ... ] })') if (!is.isString(doc.targets[0].target_name)) return fail('binding.gyp does not contain a target_name for the first target') if (doc.targets[0].target_name != 'myaddon') return fail('binding.gyp does not name the first target "myaddon"') exercise.emit('pass', 'binding.gyp includes a "myaddon" target') if (!is.isArray(doc.targets[0].sources)) return fail('binding.gyp does not contain a sources array for the first target (sources: [ ... ])') if (!doc.targets[0].sources.some(function (s) { return s == 'myaddon.cc' })) return fail('binding.gyp does not list "myaddon.cc" in the sources array for the first target') exercise.emit('pass', 'binding.gyp includes "myaddon.cc" as a source file') if (!is.isArray(doc.targets[0].include_dirs)) return fail('binding.gyp does not contain a include_dirs array for the first target (include_dirs: [ ... ])') var nanConstruct = '<!(node -e "require(\'nan\')")' //TODO: grep the source for this string to make sure it's got `"` style quotes if (!doc.targets[0].include_dirs.some(function (s) { return s == nanConstruct })) return fail('binding.gyp does not list NAN properly in the include_dirs array for the first target') exercise.emit('pass', 'binding.gyp includes a correct NAN include statement') callback(null, true) }) }
javascript
{ "resource": "" }
q48284
checkSubmissionDir
train
function checkSubmissionDir (mode, callback) { var exercise = this exercise.submission = this.args[0] // submission first arg obviously function failBadPath () { exercise.emit('fail', 'Submitted a readable directory path (please supply a path to your solution)') callback(null, false) } if (!exercise.submission) return failBadPath() fs.stat(exercise.submission, function (err, stat) { if (err) return failBadPath() if (!stat.isDirectory()) return failBadPath() callback(null, true) }) }
javascript
{ "resource": "" }
q48285
checkCompile
train
function checkCompile (dir) { return function (mode, callback) { var exercise = this if (!exercise.passed) return callback(null, true) // shortcut if we've already had a failure gyp.rebuild(dir, function (err) { if (err) { exercise.emit('fail', err.message) return callback(null, false) } callback(null, true) }) } }
javascript
{ "resource": "" }
q48286
cleanup
train
function cleanup (dirs) { return function (mode, pass, callback) { var done = after(dirs.length, callback) dirs.forEach(function (dir) { rimraf(dir, done) }) } }
javascript
{ "resource": "" }
q48287
setup
train
function setup (mode, callback) { copy(testPackageSrc, testPackageRnd, { overwrite: true }, function (err) { if (err) return callback(err) copy.copyDeps(testPackageRnd, callback) }) }
javascript
{ "resource": "" }
q48288
train
function(eventName, eventHandler) { var stack = this.actual.data("events")[eventName]; var i; for (i = 0; i < stack.length; i++) { if (stack[i].handler == eventHandler) { return true; } } return false; }
javascript
{ "resource": "" }
q48289
train
function ( options ) { var defaults = { excludeFields: [], customKeySuffix: "", locationBased: false, timeout: 0, autoRelease: true, onBeforeSave: function() {}, onSave: function() {}, onBeforeRestore: function() {}, onRestore: function() {}, onRelease: function() {} }; this.options = this.options || $.extend( defaults, options ); this.browserStorage = browserStorage; }
javascript
{ "resource": "" }
q48290
train
function( targets, options ) { this.setOptions( options ); targets = targets || {}; var self = this; this.targets = this.targets || []; if ( self.options.name ) { this.href = self.options.name; } else { this.href = location.hostname + location.pathname + location.search + location.hash; } this.targets = $.merge( this.targets, targets ); this.targets = $.unique( this.targets ); this.targets = $( this.targets ); if ( ! this.browserStorage.isAvailable() ) { return false; } var callback_result = self.options.onBeforeRestore.call( self ); if ( callback_result === undefined || callback_result ) { self.restoreAllData(); } if ( this.options.autoRelease ) { self.bindReleaseData(); } if ( ! params.started[ this.getInstanceIdentifier() ] ) { if ( self.isCKEditorPresent() ) { var intervalId = setInterval( function() { if (CKEDITOR.isLoaded) { clearInterval(intervalId); self.bindSaveData(); params.started[ self.getInstanceIdentifier() ] = true; } }, 100); } else { self.bindSaveData(); params.started[ self.getInstanceIdentifier() ] = true; } } }
javascript
{ "resource": "" }
q48291
train
function() { var self = this; if ( self.options.timeout ) { self.saveDataByTimeout(); } self.targets.each( function() { var targetFormIdAndName = getElementIdentifier( $( this ) ); self.findFieldsToProtect( $( this ) ).each( function() { if ( $.inArray( this, self.options.excludeFields ) !== -1 ) { // Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration. return true; } var field = $( this ); var prefix = (self.options.locationBased ? self.href : "") + targetFormIdAndName + getElementIdentifier( field ) + self.options.customKeySuffix; if ( field.is( ":text" ) || field.is( "textarea" ) ) { if ( ! self.options.timeout ) { self.bindSaveDataImmediately( field, prefix ); } } self.bindSaveDataOnChange( field ); } ); } ); }
javascript
{ "resource": "" }
q48292
train
function() { var self = this; var restored = false; self.targets.each( function() { var target = $( this ); var targetFormIdAndName = getElementIdentifier( $( this ) ); self.findFieldsToProtect( target ).each( function() { if ( $.inArray( this, self.options.excludeFields ) !== -1 ) { // Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration. return true; } var field = $( this ); var prefix = (self.options.locationBased ? self.href : "") + targetFormIdAndName + getElementIdentifier( field ) + self.options.customKeySuffix; var resque = self.browserStorage.get( prefix ); if ( resque !== null ) { self.restoreFieldsData( field, resque ); restored = true; } } ); } ); if ( restored ) { self.options.onRestore.call( self ); } }
javascript
{ "resource": "" }
q48293
train
function( field, resque ) { if ( field.attr( "name" ) === undefined && field.attr( "id" ) === undefined ) { return false; } var name = field.attr( "name" ); if ( field.is( ":checkbox" ) && resque !== "false" && ( name === undefined || name.indexOf( "[" ) === -1 ) ) { // If we aren't named by name (e.g. id) or we aren't in a multiple element field field.prop( "checked", true ); } else if( field.is( ":checkbox" ) && resque === "false" && ( name === undefined || name.indexOf( "[" ) === -1 ) ) { // If we aren't named by name (e.g. id) or we aren't in a multiple element field field.prop( "checked", false ); } else if ( field.is( ":radio" ) ) { if ( field.val() === resque ) { field.prop( "checked", true ); } } else if ( name === undefined || name.indexOf( "[" ) === -1 ) { // If we aren't named by name (e.g. id) or we aren't in a multiple element field field.val( resque ); } else { resque = resque.split( "," ); field.val( resque ); } }
javascript
{ "resource": "" }
q48294
train
function( key, value, fireCallback ) { var self = this; var callback_result = self.options.onBeforeSave.call( self ); if ( callback_result !== undefined && callback_result === false ) { return; } // if fireCallback is undefined it should be true fireCallback = fireCallback === undefined ? true : fireCallback; this.browserStorage.set( key, value ); if ( fireCallback && value !== "" ) { this.options.onSave.call( this ); } }
javascript
{ "resource": "" }
q48295
train
function() { var self = this; self.targets.each( function() { var target = $( this ); var formIdAndName = getElementIdentifier( target ); self.releaseData( formIdAndName, self.findFieldsToProtect( target ) ); } ); }
javascript
{ "resource": "" }
q48296
statusValid
train
function statusValid (xhr) { try { var status = xhr.status return (status !== null && status !== 0) } catch (e) { return false } }
javascript
{ "resource": "" }
q48297
handleVinylStream
train
function handleVinylStream(sources, opt) { var collected = streamToArray(sources); return through2.obj(function (target, enc, cb) { if (target.isStream()) { return cb(error('Streams not supported for target templates!')); } collected.then(function (collection) { target.contents = getNewContent(target, collection, opt); this.push(target); cb(); }.bind(this)) .catch(function (error) { cb(error); }); }); }
javascript
{ "resource": "" }
q48298
getNewContent
train
function getNewContent(target, collection, opt) { var logger = opt.quiet ? noop : function (filesCount) { if (filesCount) { var pluralState = filesCount > 1 ? 's' : ''; log(cyan(filesCount) + ' file' + pluralState + ' into ' + magenta(target.relative) + '.'); } else { log('Nothing to inject into ' + magenta(target.relative) + '.'); } }; var content = String(target.contents); var targetExt = extname(target.path); var files = prepareFiles(collection, targetExt, opt, target); var filesPerTags = groupArray(files, 'tagKey'); var startAndEndTags = Object.keys(filesPerTags); var matches = []; var injectedFilesCount = 0; startAndEndTags.forEach(function (tagKey) { var files = filesPerTags[tagKey]; var startTag = files[0].startTag; var endTag = files[0].endTag; var tagsToInject = getTagsToInject(files, target, opt); content = inject(content, { startTag: startTag, endTag: endTag, tagsToInject: tagsToInject, removeTags: opt.removeTags, empty: opt.empty, willInject: function (filesToInject) { injectedFilesCount += filesToInject.length; }, onMatch: function (match) { matches.push(match[0]); } }); }); logger(injectedFilesCount); if (opt.empty) { var ext = '{{ANY}}'; var startTag = getTagRegExp(opt.tags.start(targetExt, ext, opt.starttag), ext, opt); var endTag = getTagRegExp(opt.tags.end(targetExt, ext, opt.endtag), ext, opt); content = inject(content, { startTag: startTag, endTag: endTag, tagsToInject: [], removeTags: opt.removeTags, empty: opt.empty, shouldAbort: function (match) { return matches.indexOf(match[0]) !== -1; } }); } return Buffer.from(content); }
javascript
{ "resource": "" }
q48299
inject
train
function inject(content, opt) { var startTag = opt.startTag; var endTag = opt.endTag; var startMatch; var endMatch; /** * The content consists of: * * <everything before startMatch> * <startMatch> * <previousInnerContent> * <endMatch> * <everything after endMatch> */ while ((startMatch = startTag.exec(content)) !== null) { if (typeof opt.onMatch === 'function') { opt.onMatch(startMatch); } if (typeof opt.shouldAbort === 'function' && opt.shouldAbort(startMatch)) { continue; } // Take care of content length change: endTag.lastIndex = startTag.lastIndex; endMatch = endTag.exec(content); if (!endMatch) { throw error('Missing end tag for start tag: ' + startMatch[0]); } var toInject = opt.tagsToInject.slice(); if (typeof opt.willInject === 'function') { opt.willInject(toInject); } // <everything before startMatch>: var newContents = content.slice(0, startMatch.index); if (opt.removeTags) { if (opt.empty) { // Take care of content length change: startTag.lastIndex -= startMatch[0].length; } } else { // <startMatch> + <endMatch> toInject.unshift(startMatch[0]); toInject.push(endMatch[0]); } var previousInnerContent = content.substring(startTag.lastIndex, endMatch.index); var indent = getLeadingWhitespace(previousInnerContent); // <new inner content>: newContents += toInject.join(indent); // <everything after endMatch>: newContents += content.slice(endTag.lastIndex); // Replace old content with new: content = newContents; } return content; }
javascript
{ "resource": "" }