_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q55600
byday
train
function byday(rules, dt, after) { if(!rules || !rules.length) return dt; // Generate a list of candiDATES. (HA!) var candidates = rules.map(function(rule) { // Align on the correct day of the week... var days = rule[1]-wkday(dt); if(days < 0) days += 7; var newdt = add_d(new Date(dt), days); if(rule[0] > 0) { var wk = 0 | ((d(newdt) - 1) / 7) + 1; if(wk > rule[0]) return null; add_d(newdt, (rule[0] - wk) * 7); } else if(rule[0] < 0) { // Find all the matching days in the month... var dt2 = new Date(newdt); var days = []; while(m(dt2) === m(newdt)) { days.push(d(dt2)); add_d(dt2, 7); } // Then grab the nth from the end... set_d(newdt, days.reverse()[(-rule[0])-1]); } // Ignore if it's a past date... if (newdt.valueOf() <= after.valueOf()) return null; return newdt; }); // Select the date occurring next... var newdt = sort_dates(candidates).shift(); return newdt || dt; }
javascript
{ "resource": "" }
q55601
toStr
train
function toStr(next) { var stream = new Writable(); var str = ""; stream.write = function(chunk) { str += (chunk); }; stream.end = function() { next(str); }; return stream; }
javascript
{ "resource": "" }
q55602
updateYear
train
function updateYear(context) { return context.dateRange ? utils.updateYear(context.dateRange, String(utils.year())) : utils.year(); }
javascript
{ "resource": "" }
q55603
updateCopyright
train
function updateCopyright(str, context, options) { if (typeof str !== 'string') { options = context; context = str; str = null; } var opts = utils.merge({template: template, copyright: ''}, options); var pkg = opts.pkg || utils.loadPkg.sync(process.cwd()); var engine = new utils.Engine(opts); // create the template context from defaults, package.json, // context from parsing the original statement, and options. var ctx = utils.merge({}, defaults, pkg, context, opts); ctx.authors = ctx.author = author(ctx, pkg, options); ctx.years = ctx.year = updateYear(ctx); var statement = ctx.statement; // if no original statement was found, create one with the template if (typeof statement === 'undefined') { return engine.render(opts.template, ctx); } // necessary since the copyright regex doesn't match // the trailing dot. If it does later this is future-proof if (statement[statement.length - 1] !== '.') { var ch = statement + '.'; if (str.indexOf(ch) !== -1) { statement = ch; } } // create the new copyright statement var newStatement = engine.render(opts.template, ctx); if (str == null) { return newStatement; } // if the original string is no more than a copyright statement // just return the new one if (statement.trim() === str.trim() || opts.statementOnly === true) { return newStatement; } return str.replace(statement, newStatement); }
javascript
{ "resource": "" }
q55604
_exec
train
function _exec(command, args = [], options = {}) { return new Promise((fulfill, reject) => spawn(normalize(command), args, {shell: true, stdio: 'inherit', ...options}) .on('close', code => code ? reject(new Error(`${command}: ${code}`)) : fulfill()) ); }
javascript
{ "resource": "" }
q55605
create
train
function create(store, url, data, headers, options) { return exports.config.storeFetch({ data: data, method: 'POST', options: __assign({}, options, { headers: headers }), store: store, url: url, }); }
javascript
{ "resource": "" }
q55606
remove
train
function remove(store, url, headers, options) { return exports.config.storeFetch({ data: null, method: 'DELETE', options: __assign({}, options, { headers: headers }), store: store, url: url, }); }
javascript
{ "resource": "" }
q55607
fetchLink
train
function fetchLink(link, store, requestHeaders, options) { if (link) { var href = typeof link === 'object' ? link.href : link; /* istanbul ignore else */ if (href) { return read(store, href, requestHeaders, options); } } return Promise.resolve(new Response_1.Response({ data: null }, store)); }
javascript
{ "resource": "" }
q55608
mapItems
train
function mapItems(data, fn) { return data instanceof Array ? data.map(function (item) { return fn(item); }) : fn(data); }
javascript
{ "resource": "" }
q55609
flattenRecord
train
function flattenRecord(record) { var data = { __internal: { id: record.id, type: record.type, }, }; objectForEach(record.attributes, function (key) { data[key] = record.attributes[key]; }); objectForEach(record.relationships, function (key) { var rel = record.relationships[key]; if (rel.meta) { data[key + "Meta"] = rel.meta; } if (rel.links) { data.__internal.relationships = data.__internal.relationships || {}; data.__internal.relationships[key] = rel.links; } }); objectForEach(record.links, function (key) { /* istanbul ignore else */ if (record.links[key]) { data.__internal.links = data.__internal.links || {}; data.__internal.links[key] = record.links[key]; } }); objectForEach(record.meta, function (key) { /* istanbul ignore else */ if (record.meta[key] !== undefined) { data.__internal.meta = data.__internal.meta || {}; data.__internal.meta[key] = record.meta[key]; } }); return data; }
javascript
{ "resource": "" }
q55610
keys
train
function keys(obj) { var keyList = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { keyList.push(key); } } return keyList; }
javascript
{ "resource": "" }
q55611
wrap
train
function wrap(superagent, Promise) { /** * Request object similar to superagent.Request, but with end() returning * a promise. */ function PromiseRequest() { superagent.Request.apply(this, arguments); } // Inherit form superagent.Request PromiseRequest.prototype = Object.create(superagent.Request.prototype); /** Send request and get a promise that `end` was emitted */ PromiseRequest.prototype.end = function(cb) { var _end = superagent.Request.prototype.end; var self = this; return new Promise(function(accept, reject) { _end.call(self, function(err, response) { if (cb) { cb(err, response); } if (err) { err.response = response; reject(err); } else { accept(response); } }); }); }; /** Provide a more promise-y interface */ PromiseRequest.prototype.then = function(resolve, reject) { var _end = superagent.Request.prototype.end; var self = this; return new Promise(function(accept, reject) { _end.call(self, function(err, response) { if (err) { err.response = response; reject(err); } else { accept(response); } }); }).then(resolve, reject); }; /** * Request builder with same interface as superagent. * It is convenient to import this as `request` in place of superagent. */ var request = function(method, url) { return new PromiseRequest(method, url); }; /** Helper for making an options request */ request.options = function(url) { return request('OPTIONS', url); } /** Helper for making a head request */ request.head = function(url, data) { var req = request('HEAD', url); if (data) { req.send(data); } return req; }; /** Helper for making a get request */ request.get = function(url, data) { var req = request('GET', url); if (data) { req.query(data); } return req; }; /** Helper for making a post request */ request.post = function(url, data) { var req = request('POST', url); if (data) { req.send(data); } return req; }; /** Helper for making a put request */ request.put = function(url, data) { var req = request('PUT', url); if (data) { req.send(data); } return req; }; /** Helper for making a patch request */ request.patch = function(url, data) { var req = request('PATCH', url); if (data) { req.send(data); } return req; }; /** Helper for making a delete request */ request.del = function(url, data) { var req = request('DELETE', url); if (data) { req.send(data); } return req; }; // Export the request builder return request; }
javascript
{ "resource": "" }
q55612
encode
train
function encode (samples, durations, cb) { var agent = samples.length > 0 ? samples[0]._agent : null var transactions = groupTransactions(samples, durations) var traces = [].concat.apply([], samples.map(function (trans) { return trans.traces })) var groups = groupTraces(traces) var raw = rawTransactions(samples) if (agent && agent.captureTraceStackTraces) { addStackTracesToTraceGroups(groups, traces, done) } else { process.nextTick(done) } function done () { cb({ // eslint-disable-line standard/no-callback-literal transactions: transactions, traces: { groups: groups, raw: raw } }) } }
javascript
{ "resource": "" }
q55613
wrapInitPromise
train
function wrapInitPromise (original) { return function wrappedInitPromise () { var command = this var cb = this.callback if (typeof cb === 'function') { this.callback = agent._instrumentation.bindFunction(function wrappedCallback () { var trace = command.__obTrace if (trace && !trace.ended) trace.end() return cb.apply(this, arguments) }) } return original.apply(this, arguments) } }
javascript
{ "resource": "" }
q55614
promisify
train
function promisify(repl) { var _eval = repl.eval; repl.eval = function(cmd, context, filename, callback) { _eval.call(repl, cmd, context, filename, function(err, res) { if (isPromiseLike(res)) { res.then(function(ret) { callback(null, ret); }, function(err) { callback(err); }); } else { callback(err, res); } }); }; return repl; }
javascript
{ "resource": "" }
q55615
defineBuiltinVars
train
function defineBuiltinVars(context) { // define salesforce package root objects for (var key in sf) { if (sf.hasOwnProperty(key) && !global[key]) { context[key] = sf[key]; } } // expose salesforce package root as "$sf" in context. context.$sf = sf; // create default connection object var conn = new sf.Connection(); for (var prop in conn) { if (prop.indexOf('_') === 0) { // ignore private continue; } if (_.isFunction(conn[prop])) { context[prop] = _.bind(conn[prop], conn); } else if (_.isObject(conn[prop])) { defineProp(context, conn, prop); } } // expose default connection as "$conn" context.$conn = conn; }
javascript
{ "resource": "" }
q55616
train
function(conn) { this._conn = conn; this._logger = conn._logger; var delegates = [ "query", "queryMore", "create", "insert", "retrieve", "update", "upsert", "del", "delete", "destroy", "describe", "describeGlobal", "sobject" ]; delegates.forEach(function(method) { this[method] = conn.constructor.prototype[method]; }, this); this.cache = new Cache(); var cacheOptions = { key: function(type) { return type ? "describe." + type : "describe"; } }; this.describe$ = this.cache.makeCacheable(this.describe, this, cacheOptions); this.describe = this.cache.makeResponseCacheable(this.describe, this, cacheOptions); this.describeSObject$ = this.describe$; this.describeSObject = this.describe; cacheOptions = { key: 'describeGlobal' }; this.describeGlobal$ = this.cache.makeCacheable(this.describeGlobal, this, cacheOptions); this.describeGlobal = this.cache.makeResponseCacheable(this.describeGlobal, this, cacheOptions); this.initialize(); }
javascript
{ "resource": "" }
q55617
train
function() { source.removeListener('record', onRecord); dest.removeListener('drain', onDrain); source.removeListener('end', onEnd); source.removeListener('close', onClose); source.removeListener('error', onError); dest.removeListener('error', onError); source.removeListener('end', cleanup); source.removeListener('close', cleanup); dest.removeListener('end', cleanup); dest.removeListener('close', cleanup); }
javascript
{ "resource": "" }
q55618
promisedRequest
train
function promisedRequest(params, callback) { var deferred = Promise.defer(); var req; var createRequest = function() { if (!req) { req = request(params, function(err, response) { if (err) { deferred.reject(err); } else { deferred.resolve(response); } }); } return req; }; return streamify(deferred.promise, createRequest).thenCall(callback); }
javascript
{ "resource": "" }
q55619
setCulprit
train
function setCulprit (payload) { if (payload.culprit) return // skip if user provided a custom culprit var frames = payload.stacktrace.frames var filename = frames[0].filename var fnName = frames[0].function for (var n = 0; n < frames.length; n++) { if (frames[n].in_app) { filename = frames[n].filename fnName = frames[n].function break } } payload.culprit = filename ? fnName + ' (' + filename + ')' : fnName }
javascript
{ "resource": "" }
q55620
capturePayload
train
function capturePayload (endpoint, payload) { var dumpfile = path.join(os.tmpdir(), 'opbeat-' + endpoint + '-' + Date.now() + '.json') fs.writeFile(dumpfile, JSON.stringify(payload), function (err) { if (err) console.log('could not capture intake payload: %s', err.message) else console.log('intake payload captured: %s', dumpfile) }) }
javascript
{ "resource": "" }
q55621
tryRead
train
function tryRead(fd, buff, offset, length) { return new Promise((resolve, reject) => { fs.read(fd, buff, offset, length, null, (err, bytesRead, buffer) => { if (err) return reject(err); const buffLen = buffer.length; offset += bytesRead; if (offset >= buffLen) return resolve(buff); if ((offset + length) >= buffLen) length = buffLen - offset; return resolve(); }); }) .then( (fullBuffer) => { return fullBuffer ? { data: fullBuffer, fd: fd } : tryRead(fd, buff, offset, length); }, (err) => { throw err; } ); }
javascript
{ "resource": "" }
q55622
Modal
train
function Modal(config) { this.config = config; this.timers_ = []; this.scrollY = 0; this.initDom_(); var closeAttribute = 'data-' + this.config.className + '-x'; var closeClass = this.config.className + '-x'; var data = 'data-' + this.config.className + '-id'; var func = function(targetEl, e) { var modalId = targetEl.getAttribute(data); if (modalId) { e.preventDefault(); this.setActive_(true, modalId); } if (targetEl.classList.contains(closeClass) || targetEl.hasAttribute(closeAttribute)) { this.setActive_(false); } }.bind(this); events.addDelegatedListener(document, 'click', func); this.initStateFromHash_(); }
javascript
{ "resource": "" }
q55623
init
train
function init(opt_config) { if (modalInstance) { return; } var config = objects.clone(defaultConfig); if (opt_config) { objects.merge(config, opt_config); } modalInstance = new Modal(config); }
javascript
{ "resource": "" }
q55624
start
train
function start() { if (isStarted()) { return; } // Debounce the scroll event by executing the onScroll callback using a timed // interval. window.addEventListener('scroll', onScroll_, {'passive': true}); interval = window.setInterval(function() { if (scrolled) { for (var i = 0, delegate; delegate = delegates[i]; i++) { delegate.onScroll(); } scrolled = false; } }, 250); }
javascript
{ "resource": "" }
q55625
getParameterValue
train
function getParameterValue(key, opt_uri) { var uri = opt_uri || window.location.href; key = key.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]'); var regex = new RegExp('[\\?&]' + key + '=([^&#]*)'); var results = regex.exec(uri); var result = results === null ? null : results[1]; return result ? urlDecode_(result) : null; }
javascript
{ "resource": "" }
q55626
updateParamsFromUrl
train
function updateParamsFromUrl(config) { // If there is no query string in the URL, then there's nothing to do in this // function, so break early. if (!location.search) { return; } var c = objects.clone(UpdateParamsFromUrlDefaultConfig); objects.merge(c, config); var selector = c.selector; var attr = c.attr; var params = c.params; if (!params) { throw '`params` is required'; } var vals = {}; parseQueryString(location.search, function(key, value) { for (var i = 0; i < params.length; i++) { var param = params[i]; if (param instanceof RegExp) { if (key.match(param)) { vals[key] = value; } } else { if (param === key) { vals[key] = value; } } } }); var els = document.querySelectorAll(selector); for (var i = 0, el; el = els[i]; i++) { var href = el.getAttribute(attr); if (href && !href.startsWith('#')) { var url = new URL(el.getAttribute(attr), location.href); var map = parseQueryMap(url.search); // Optionally serialize the keys and values into a single key and value, // and rewrite the element's attribute with the new serialized query // string. This was built specifically to do things like pass `utm_*` // parameters into a `referrer` query string, for Google Play links, e.g. // `&referrer=utm_source%3DSOURCE`. // See https://developers.google.com/analytics/devguides/collection/android/v4/campaigns#google-play-url-builder var serializeIntoKey = el.getAttribute(c.serializeAttr); if (serializeIntoKey) { var serializedQueryString = encodeQueryMap(vals); map[serializeIntoKey] = serializedQueryString; } else { for (var key in vals) { map[key] = vals[key]; } } url.search = encodeQueryMap(map); el.setAttribute(attr, url.toString()); } } }
javascript
{ "resource": "" }
q55627
parseQueryString
train
function parseQueryString(query, callback) { // Break early for empty string. if (!query) { return; } // Remove leading `?` so that callers can pass `location.search` directly to // this function. if (query.startsWith('?')) { query = query.slice(1); } var pairs = query.split('&'); for (var i = 0; i < pairs.length; i++) { var separatorIndex = pairs[i].indexOf('='); if (separatorIndex >= 0) { var key = pairs[i].substring(0, separatorIndex); var value = pairs[i].substring(separatorIndex + 1); callback(key, urlDecode_(value)); } else { // Treat "?foo" without the "=" as having an empty value. var key = pairs[i]; callback(key, ''); } } }
javascript
{ "resource": "" }
q55628
parseQueryMap
train
function parseQueryMap(query) { var map = {}; parseQueryString(query, function(key, value) { map[key] = value; }); return map; }
javascript
{ "resource": "" }
q55629
encodeQueryMap
train
function encodeQueryMap(map) { var params = []; for (var key in map) { var value = map[key]; params.push(key + '=' + urlEncode_(value)); } return params.join('&'); }
javascript
{ "resource": "" }
q55630
initStyle
train
function initStyle(opt_config) { var config = objects.clone(defaultConfig); if (opt_config) { objects.merge(config, opt_config); } var attrName = config.attributeName; var selector = '[' + attrName + ']'; var rules = {}; rules[selector] = {'display': 'none !important'}; ui.createStyle(rules); }
javascript
{ "resource": "" }
q55631
getDelegateFunction_
train
function getDelegateFunction_(listener) { if (!delegateFunctionMap.has(listener)) { var delegateFunction = function(e) { e = e || window.event; var target = e.target || e.srcElement; target = target.nodeType === 3 ? target.parentNode : target; do { listener(target, e); if (target.parentNode) { target = target.parentNode; } } while (target.parentNode); }; delegateFunctionMap.set(listener, delegateFunction); } return delegateFunctionMap.get(listener); }
javascript
{ "resource": "" }
q55632
addDelegatedListener
train
function addDelegatedListener(el, type, listener) { incrementListenerCount(listener); return el.addEventListener(type, getDelegateFunction_(listener)); }
javascript
{ "resource": "" }
q55633
removeDelegatedListener
train
function removeDelegatedListener(el, type, listener) { var delegate = getDelegateFunction_(listener); decrementListenerCount(listener); if (getListenerCount(listener) <= 0) { delegateFunctionMap.delete(listener); } return el.removeEventListener(type, delegate); }
javascript
{ "resource": "" }
q55634
train
function(selector, opt_offset, opt_delay) { this.selector = selector; this.offset = opt_offset || null; this.delay = opt_delay || 0; // Ensure all videos are loaded. var els = document.querySelectorAll(this.selector); [].forEach.call(els, function(el) { el.load(); }); }
javascript
{ "resource": "" }
q55635
Variable
train
function Variable(name, scope) { /** * The variable name, as given in the source code. * @member {String} Variable#name */ this.name = name; /** * List of defining occurrences of this variable (like in 'var ...' * statements or as parameter), as AST nodes. * @member {esprima.Identifier[]} Variable#identifiers */ this.identifiers = []; /** * List of {@link Reference|references} of this variable (excluding parameter entries) * in its defining scope and all nested scopes. For defining * occurrences only see {@link Variable#defs}. * @member {Reference[]} Variable#references */ this.references = []; /** * List of defining occurrences of this variable (like in 'var ...' * statements or as parameter), as custom objects. * @typedef {Object} DefEntry * @property {String} DefEntry.type - the type of the occurrence (e.g. * "Parameter", "Variable", ...) * @property {esprima.Identifier} DefEntry.name - the identifier AST node of the occurrence * @property {esprima.Node} DefEntry.node - the enclosing node of the * identifier * @property {esprima.Node} [DefEntry.parent] - the enclosing statement * node of the identifier * @member {DefEntry[]} Variable#defs */ this.defs = []; this.tainted = false; /** * Whether this is a stack variable. * @member {boolean} Variable#stack */ this.stack = true; /** * Reference to the enclosing Scope. * @member {Scope} Variable#scope */ this.scope = scope; }
javascript
{ "resource": "" }
q55636
YouTubeModal
train
function YouTubeModal(config) { this.config = config; this.parentElement = document.querySelector(this.config.parentSelector); this.closeEventListener_ = this.setActive_.bind(this, false); this.popstateListener_ = this.onHistoryChange_.bind(this); this.el_ = null; this.closeEl_ = null; this.attributionEl_ = null; this.initDom_(); this.lastActiveVideoId_ = null; this.scrollY = 0; this.delegatedListener_ = function(targetEl) { var data = 'data-' + this.config.className + '-video-id'; var videoId = targetEl.getAttribute(data); var startDataAttribute = 'data-' + this.config.className + '-video-start-seconds'; var startTime = +targetEl.getAttribute(startDataAttribute); var attributionAttribute = 'data-' + this.config.className + '-attribution'; var attribution = targetEl.getAttribute(attributionAttribute); if (videoId) { this.play(videoId, true /* opt_updateState */, startTime, attribution); } }.bind(this); // Loads YouTube iframe API. events.addDelegatedListener(document, 'click', this.delegatedListener_); // Only add the script tag if it doesn't exist var scriptTag = document.querySelector('script[src="https://www.youtube.com/iframe_api"]'); if (!scriptTag) { var tag = document.createElement('script'); tag.setAttribute('src', 'https://www.youtube.com/iframe_api'); this.parentElement.appendChild(tag); } }
javascript
{ "resource": "" }
q55637
init
train
function init(opt_config) { if (singleton) { return; } var config = objects.clone(defaultConfig); if (opt_config) { objects.merge(config, opt_config); } singleton = new YouTubeModal(config); }
javascript
{ "resource": "" }
q55638
init
train
function init(opt_config) { var config = objects.clone(defaultConfig); if (opt_config) { objects.merge(config, opt_config); } initVariations(config); }
javascript
{ "resource": "" }
q55639
processStagingResp
train
function processStagingResp(resp, now, evergreen) { var keysToData = {}; for (var key in resp) { [].forEach.call(resp[key], function(datedRow) { var start = datedRow['start_date'] ? new Date(datedRow['start_date']) : null; var end = datedRow['end_date'] ? new Date(datedRow['end_date']) : null; if (evergreen) { var isEnabled = datetoggle.isEnabledNow(start, null, now); } else { var isEnabled = datetoggle.isEnabledNow(start, end, now); } if (isEnabled) { keysToData[key] = datedRow; } }); } return keysToData; }
javascript
{ "resource": "" }
q55640
compilejs
train
function compilejs(sources, outdir, outfile, opt_options) { var bundler = browserify({ entries: sources, debug: false }); return rebundle_(bundler, outdir, outfile, opt_options); }
javascript
{ "resource": "" }
q55641
watchjs
train
function watchjs(sources, outdir, outfile, opt_options) { var bundler = watchify(browserify({ entries: sources, debug: false, // Watchify options: cache: {}, packageCache: {}, fullPaths: true })); bundler.on('update', function() { gutil.log('recompiling js...'); rebundle_(bundler, outdir, outfile, opt_options); gutil.log('finished recompiling js'); }); return rebundle_(bundler, outdir, outfile, opt_options); }
javascript
{ "resource": "" }
q55642
createDom
train
function createDom(tagName, opt_className) { var element = document.createElement(tagName); if (opt_className) { element.className = opt_className; } return element; }
javascript
{ "resource": "" }
q55643
ScrollToggle
train
function ScrollToggle(el, config) { this.el_ = el; this.config_ = objects.clone(config); if (this.el_.hasAttribute('data-ak-scrolltoggle')) { var elConfig = JSON.parse(this.el_.getAttribute('data-ak-scrolltoggle')); if (elConfig && typeof elConfig === 'object') { objects.merge(this.config_, elConfig); } } // Initialize the current scroll position. this.lastScrollPos_ = 0; this.onScroll(); }
javascript
{ "resource": "" }
q55644
GoogleOAuth2Strategy
train
function GoogleOAuth2Strategy(options, verify) { var self = this; if (typeof options === 'function') { verify = options; options = {}; } if (!verify) { throw new Error('GoogleOAuth2Strategy requires a verify callback'); } requiredArgs.forEach(function (arg) { if (!options[arg.name]) { throw new Error(util.format('GoogleOAuth2Strategy requires a [%s]', arg.name)); } else if (typeof options[arg.name] !== arg.type) { throw new Error(util.format('GoogleOAuth2Strategy expects [%s] to be a [%s] but it was a [%s]', arg.name, arg.type, typeof options[arg.name])); } // If we've passed the checks, go ahead and set it in the current object. self[arg.name] = options[arg.name]; }); optionalArgs.forEach(function (arg) { if (options[arg.name] && typeof options[arg.name] !== arg.type) { throw new Error(util.format('GoogleOAuth2Strategy expects [%s] to be a [%s] but it was a [%s]', arg.name, arg.type, typeof options[arg.name])); } // If we've passed the checks, go ahead and set it in the current object. self[arg.name] = options[arg.name]; }); if (options.scope && (typeof options.scope !== 'string' && !Array.isArray(options.scope))) { throw new Error(util.format('GoogleOAuth2Strategy expects [%s] to be a [%s] but it was a [%s]', 'scope', 'array or string', typeof options.scope)); } self.scope = options.scope || 'https://www.googleapis.com/auth/userinfo.email'; passport.Strategy.call(self); self.name = 'google'; self.verify = verify; if (!self.skipUserProfile) { self.googlePlus = gapi.plus('v1'); } }
javascript
{ "resource": "" }
q55645
initVideoFallback
train
function initVideoFallback(opt_config) { var videoSelector = (opt_config && opt_config.videoSelector) || defaultConfig.fallbackVideoSelector; var imageSelector = (opt_config && opt_config.imageSelector) || defaultConfig.fallbackImageSelector; var breakpoint = (opt_config && opt_config.breakpoint) || defaultConfig.breakpoint; var hidden = {'display': 'none !important'}; var rules = {}; if (canPlayVideo()) { rules[imageSelector] = hidden; } else { rules[videoSelector] = hidden; } if (!breakpoint) { ui.createStyle(rules); } else { var minScreenQuery = '(min-width: ' + breakpoint + 'px)'; ui.createStyle(rules, minScreenQuery); var smallerBreakpoint = breakpoint - 1; var maxScreenQuery = '(max-width: ' + smallerBreakpoint + 'px)'; rules = {}; rules[videoSelector] = hidden; ui.createStyle(rules, maxScreenQuery); } }
javascript
{ "resource": "" }
q55646
adjustRect
train
function adjustRect(rect, adjustX, adjustY, ev) { // if pageX or pageY is defined we need to lock the popover to the given // x and y position. // clone the rect, so we can manipulate its properties. var localRect = { bottom: rect.bottom, height: rect.height, left: rect.left, right: rect.right, top: rect.top, width: rect.width }; if (adjustX) { localRect.left = ev.pageX; localRect.right = ev.pageX; localRect.width = 0; } if (adjustY) { localRect.top = ev.pageY; localRect.bottom = ev.pageY; localRect.height = 0; } return localRect; }
javascript
{ "resource": "" }
q55647
loadTemplate
train
function loadTemplate(template, plain) { if (!template) { return ''; } if (angular.isString(template) && plain) { return template; } return $templateCache.get(template) || $http.get(template, { cache : true }); }
javascript
{ "resource": "" }
q55648
move
train
function move(popover, placement, align, rect, triangle) { var containerRect; var popoverRect = getBoundingClientRect(popover[0]); var popoverRight; var top, left; var positionX = function() { if (align === 'center') { return Math.round(rect.left + rect.width/2 - popoverRect.width/2); } else if(align === 'right') { return rect.right - popoverRect.width; } return rect.left; }; var positionY = function() { if (align === 'center') { return Math.round(rect.top + rect.height/2 - popoverRect.height/2); } else if(align === 'bottom') { return rect.bottom - popoverRect.height; } return rect.top; }; if (placement === 'top') { top = rect.top - popoverRect.height; left = positionX(); } else if (placement === 'right') { top = positionY(); left = rect.right; } else if (placement === 'bottom') { top = rect.bottom; left = positionX(); } else if (placement === 'left') { top = positionY(); left = rect.left - popoverRect.width; } // Rescrict the popover to the bounds of the container if (true === options.restrictBounds) { containerRect = getBoundingClientRect($container[0]); // The left should be below the left of the container. left = Math.max(containerRect.left, left); // Prevent the left from causing the right to go outside // the conatiner. popoverRight = left + popoverRect.width; if (popoverRight > containerRect.width) { left = left - (popoverRight - containerRect.width); } } popover .css('top', top.toString() + 'px') .css('left', left.toString() + 'px'); if (triangle && triangle.length) { if (placement === 'top' || placement === 'bottom') { left = rect.left + rect.width / 2 - left; triangle.css('left', left.toString() + 'px'); } else { top = rect.top + rect.height / 2 - top; triangle.css('top', top.toString() + 'px'); } } }
javascript
{ "resource": "" }
q55649
train
function(delay, e) { // Disable popover if ns-popover value is false if ($parse(attrs.nsPopover)(scope) === false) { return; } $timeout.cancel(displayer_.id_); if (!isDef(delay)) { delay = 0; } // hide any popovers being displayed if (options.group) { $rootScope.$broadcast('ns:popover:hide', options.group); } displayer_.id_ = $timeout(function() { if (true === $popover.isOpen) { return; } $popover.isOpen = true; $popover.css('display', 'block'); // position the popover accordingly to the defined placement around the // |elm|. var elmRect = getBoundingClientRect(elm[0]); // If the mouse-relative options is specified we need to adjust the // element client rect to the current mouse coordinates. if (options.mouseRelative) { elmRect = adjustRect(elmRect, options.mouseRelativeX, options.mouseRelativeY, e); } move($popover, placement_, align_, elmRect, $triangle); addEventListeners(); // Hide the popover without delay on the popover click events. if (true === options.hideOnInsideClick) { $popover.on('click', insideClickHandler); } // Hide the popover without delay on outside click events. if (true === options.hideOnOutsideClick) { $document.on('click', outsideClickHandler); } // Hide the popover without delay on the button click events. if (true === options.hideOnButtonClick) { elm.on('click', buttonClickHandler); } // Call the open callback options.onOpen(scope); }, delay*1000); }
javascript
{ "resource": "" }
q55650
train
function(delay) { $timeout.cancel(hider_.id_); // do not hide if -1 is passed in. if(delay !== "-1") { // delay the hiding operation for 1.5s by default. if (!isDef(delay)) { delay = 1.5; } hider_.id_ = $timeout(function() { $popover.off('click', insideClickHandler); $document.off('click', outsideClickHandler); elm.off('click', buttonClickHandler); $popover.isOpen = false; displayer_.cancel(); $popover.css('display', 'none'); removeEventListeners(); // Call the close callback options.onClose(scope); }, delay*1000); } }
javascript
{ "resource": "" }
q55651
extract
train
function extract( pattern /* : string */, babelPlugins /* : Array<string> */ = [] ) /* : string */ { const srcPaths = glob.sync(pattern, { absolute: true }); const relativeSrcPaths = glob.sync(pattern); const contents = srcPaths.map(p => fs.readFileSync(p, 'utf-8')); const reqBabelPlugins = babelPlugins.map(b => require.resolve(`babel-plugin-${b}`) ); const messages = contents .map(content => babel.transform(content, { presets: [require.resolve('babel-preset-react-app')], plugins: [ require.resolve('babel-plugin-react-intl'), ...reqBabelPlugins, ], babelrc: false, }) ) .map(R.path(['metadata', 'react-intl', 'messages'])); const result = R.zipWith( (m, r) => m.map(R.assoc('filepath', r)), messages, relativeSrcPaths ) .filter(R.complement(R.isEmpty)) .reduce(R.concat, []); return result; }
javascript
{ "resource": "" }
q55652
trackBackgroundProc
train
function trackBackgroundProc() { runningProcs.push(proc); proc.on('close', function () { remove(runningProcs, proc); clearPid(name); grunt.log.debug('Process ' + name + ' closed.'); }); }
javascript
{ "resource": "" }
q55653
waitForReadyOutput
train
function waitForReadyOutput() { function onCloseBeforeReady(exitCode) { done(exitCode && new Error('non-zero exit code ' + exitCode)); } let outputBuffer = ''; function checkChunkForReady(chunk) { outputBuffer += chunk.toString('utf8'); // ensure the buffer doesn't grow out of control if (outputBuffer.length >= opts.readyBufferLength) { outputBuffer = outputBuffer.slice(outputBuffer.length - opts.readyBufferLength); } // don't strip ansi until we check, incase an ansi marker is split across chuncks. if (!opts.ready.test(stripAnsi(outputBuffer))) return; outputBuffer = ''; proc.removeListener('close', onCloseBeforeReady); proc.stdout.removeListener('data', checkChunkForReady); proc.stderr.removeListener('data', checkChunkForReady); done(); } proc.on('close', onCloseBeforeReady); proc.stdout.on('data', checkChunkForReady); proc.stderr.on('data', checkChunkForReady); }
javascript
{ "resource": "" }
q55654
Lexer
train
function Lexer(str, options) { options = options || {}; if (typeof str !== 'string') { throw new Error('Expected source code to be a string but got "' + (typeof str) + '"') } if (typeof options !== 'object') { throw new Error('Expected "options" to be an object but got "' + (typeof options) + '"') } //Strip any UTF-8 BOM off of the start of `str`, if it exists. str = str.replace(/^\uFEFF/, ''); this.input = str.replace(/\r\n|\r/g, '\n'); this.originalInput = this.input; this.filename = options.filename; this.interpolated = options.interpolated || false; this.lineno = options.startingLine || 1; this.colno = options.startingColumn || 1; this.plugins = options.plugins || []; this.indentStack = [0]; this.indentRe = null; // If #{} or !{} syntax is allowed when adding text this.interpolationAllowed = true; this.tokens = []; this.ended = false; }
javascript
{ "resource": "" }
q55655
train
function(type, val){ var res = {type: type, line: this.lineno, col: this.colno}; if (val !== undefined) res.val = val; return res; }
javascript
{ "resource": "" }
q55656
train
function(regexp, type){ var captures; if (captures = regexp.exec(this.input)) { var len = captures[0].length; var val = captures[1]; var diff = len - (val ? val.length : 0); var tok = this.tok(type, val); this.consume(len); this.incrementColumn(diff); return tok; } }
javascript
{ "resource": "" }
q55657
train
function() { if (this.input.length) return; if (this.interpolated) { this.error('NO_END_BRACKET', 'End of line was reached with no closing bracket for interpolation.'); } for (var i = 0; this.indentStack[i]; i++) { this.tokens.push(this.tok('outdent')); } this.tokens.push(this.tok('eos')); this.ended = true; return true; }
javascript
{ "resource": "" }
q55658
train
function() { if (/^#\{/.test(this.input)) { var match = this.bracketExpression(1); this.consume(match.end + 1); var tok = this.tok('interpolation', match.src); this.tokens.push(tok); this.incrementColumn(2); // '#{' this.assertExpression(match.src); var splitted = match.src.split('\n'); var lines = splitted.length - 1; this.incrementLine(lines); this.incrementColumn(splitted[lines].length + 1); // + 1 → '}' return true; } }
javascript
{ "resource": "" }
q55659
train
function() { var captures; if (captures = /^(?:block +)?prepend +([^\n]+)/.exec(this.input)) { var name = captures[1].trim(); var comment = ''; if (name.indexOf('//') !== -1) { comment = '//' + name.split('//').slice(1).join('//'); name = name.split('//')[0].trim(); } if (!name) return; this.consume(captures[0].length - comment.length); var tok = this.tok('block', name); tok.mode = 'prepend'; this.tokens.push(tok); return true; } }
javascript
{ "resource": "" }
q55660
train
function(){ var tok, captures, increment; if (captures = /^\+(\s*)(([-\w]+)|(#\{))/.exec(this.input)) { // try to consume simple or interpolated call if (captures[3]) { // simple call increment = captures[0].length; this.consume(increment); tok = this.tok('call', captures[3]); } else { // interpolated call var match = this.bracketExpression(2 + captures[1].length); increment = match.end + 1; this.consume(increment); this.assertExpression(match.src); tok = this.tok('call', '#{'+match.src+'}'); } this.incrementColumn(increment); tok.args = null; // Check for args (not attributes) if (captures = /^ *\(/.exec(this.input)) { var range = this.bracketExpression(captures[0].length - 1); if (!/^\s*[-\w]+ *=/.test(range.src)) { // not attributes this.incrementColumn(1); this.consume(range.end + 1); tok.args = range.src; this.assertExpression('[' + tok.args + ']'); for (var i = 0; i <= tok.args.length; i++) { if (tok.args[i] === '\n') { this.incrementLine(1); } else { this.incrementColumn(1); } } } } this.tokens.push(tok); return true; } }
javascript
{ "resource": "" }
q55661
train
function() { var tok if (tok = this.scanEndOfLine(/^-/, 'blockcode')) { this.tokens.push(tok); this.interpolationAllowed = false; this.callLexerFunction('pipelessText'); return true; } }
javascript
{ "resource": "" }
q55662
train
function() { var captures = this.scanIndentation(); if (captures) { var indents = captures[1].length; this.incrementLine(1); this.consume(indents + 1); if (' ' == this.input[0] || '\t' == this.input[0]) { this.error('INVALID_INDENTATION', 'Invalid indentation, you can use tabs or spaces but not both'); } // blank line if ('\n' == this.input[0]) { this.interpolationAllowed = true; return this.tok('newline'); } // outdent if (indents < this.indentStack[0]) { while (this.indentStack[0] > indents) { if (this.indentStack[1] < indents) { this.error('INCONSISTENT_INDENTATION', 'Inconsistent indentation. Expecting either ' + this.indentStack[1] + ' or ' + this.indentStack[0] + ' spaces/tabs.'); } this.colno = this.indentStack[1] + 1; this.tokens.push(this.tok('outdent')); this.indentStack.shift(); } // indent } else if (indents && indents != this.indentStack[0]) { this.tokens.push(this.tok('indent', indents)); this.colno = 1 + indents; this.indentStack.unshift(indents); // newline } else { this.tokens.push(this.tok('newline')); this.colno = 1 + (this.indentStack[0] || 0); } this.interpolationAllowed = true; return true; } }
javascript
{ "resource": "" }
q55663
AerospikeStore
train
function AerospikeStore (options) { if (!(this instanceof AerospikeStore)) { throw new TypeError('Cannot call AerospikeStore constructor as a function') } options = options || {} Store.call(this, options) this.as_namespace = options.namespace || 'test' this.as_set = options.set || 'express-session' this.ttl = options.ttl this.mapper = options.mapper || new DataMapper() if (options.serializer) { throw new Error('The `serializer` option is no longer supported - supply a custom data mapper instead.') } if (options.client) { this.client = options.client } else { this.client = Aerospike.client(options) this.client.connect(error => { if (error) { debug('ERROR - %s', error.message) process.nextTick(() => this._onDisconnected()) } else { process.nextTick(() => this._onConnected()) } }) } this.connected = false this.client.on('nodeAdded', () => this._onConnected()) this.client.on('disconnected', () => this._onDisconnected()) }
javascript
{ "resource": "" }
q55664
train
function(json, name, type) { if (json && json.widget) { var nodes = json.widget[type]; if (!!nodes && isArray(nodes)) { for (var i = 0; i < nodes.length; i++) { if (nameIsMatch(nodes[i], name)) { return true; } } } } return false; }
javascript
{ "resource": "" }
q55665
isCollationValid
train
function isCollationValid(collation) { let isValid = true; _.forIn(collation, function(value, key) { const itemIndex = _.findIndex(COLLATION_OPTIONS, key); if (itemIndex === -1) { debug('Collation "%s" is invalid bc of its keys', collation); isValid = false; } if (COLLATION_OPTIONS[itemIndex][key].includes(value) === false) { debug('Collation "%s" is invalid bc of its values', collation); isValid = false; } }); return isValid ? collation : false; }
javascript
{ "resource": "" }
q55666
normalizeIdentifier
train
function normalizeIdentifier(identifier) { if (identifier === ".") { // '.' might be referencing either the root or a locally scoped variable // called '.'. So try for the locally scoped variable first and then // default to the root return "(data['.'] || data)"; } return "data" + identifier.split(".").map(function(property) { return property ? "['" + property + "']" : ""; }).join(""); }
javascript
{ "resource": "" }
q55667
Compiler
train
function Compiler(tree) { this.tree = tree; this.string = ""; // Optimization pass will flatten large templates to result in faster // rendering. var nodes = this.optimize(this.tree.nodes); var compiledSource = this.process(nodes); // The compiled function body. var body = []; // If there is a function, concatenate it to the default empty value. if (compiledSource) { compiledSource = " + " + compiledSource; } // Include map and its dependencies. if (compiledSource.indexOf("map(") > -1) { body.push(createObject, type, map); } // Include encode and its dependencies. if (compiledSource.indexOf("encode(") > -1) { body.push(type, encode); } // The compiled function body. body = body.concat([ // Return the evaluated contents. "return ''" + compiledSource ]).join(";\n"); // Create the JavaScript function from the source code. this.func = new Function("data", "template", body); // toString the function to get its raw source and expose. this.source = [ "{", "_partials: {},", "_filters: {},", "getPartial: " + getPartial + ",", "getFilter: " + getFilter + ",", "registerPartial: " + registerPartial + ",", "registerFilter: " + registerFilter + ",", "render: function(data) {", "try {", "return " + this.func + "(data, this);", "} catch (ex) {", type, encode, "console.error(ex);", "return '<pre>' + encode(ex + ex.stack) + '</pre>';", "}", "}", "}" ].join("\n"); }
javascript
{ "resource": "" }
q55668
parseProperty
train
function parseProperty(value) { var retVal = { type: "Property", value: value }; if (value === "false" || value === "true") { retVal.type = "Literal"; } // Easy way to determine if the value is NaN or not. else if (Number(value) === Number(value)) { retVal.type = "Literal"; } else if (isString.test(value)) { retVal.type = "Literal"; } return retVal; }
javascript
{ "resource": "" }
q55669
Combyne
train
function Combyne(template, data) { // Allow this method to run standalone. if (!(this instanceof Combyne)) { return new Combyne(template, data); } // Expose the template for easier accessing and mutation. this.template = template; // Default the data to an empty object. this.data = data || {}; // Internal use only. Stores the partials and filters. this._partials = {}; this._filters = {}; // Ensure the template is a String. if (type(this.template) !== "string") { throw new Error("Template must be a String."); } // Normalize the delimiters with the defaults, to ensure a full object. var delimiters = defaults(Combyne.settings.delimiters, defaultDelimiters); // Create a new grammar with the delimiters. var grammar = new Grammar(delimiters).escape(); // Break down the template into a series of tokens. var stack = new Tokenizer(this.template, grammar).parse(); // Take the stack and create something resembling an AST. var tree = new Tree(stack).make(); // Expose the internal tree and stack. this.tree = tree; this.stack = stack; // Compile the template function from the tree. this.compiler = new Compiler(tree); // Update the source. this.source = this.compiler.source; }
javascript
{ "resource": "" }
q55670
getFilter
train
function getFilter(name) { if (name in this._filters) { return this._filters[name]; } else if (this._parent) { return this._parent.getFilter(name); } throw new Error("Missing filter " + name); }
javascript
{ "resource": "" }
q55671
encode
train
function encode(raw) { if (type(raw) !== "string") { return raw; } // Identifies all characters in the unicode range: 00A0-9999, ampersands, // greater & less than) with their respective html entity. return raw.replace(/["&'<>`]/g, function(match) { return "&#" + match.charCodeAt(0) + ";"; }); }
javascript
{ "resource": "" }
q55672
Grammar
train
function Grammar(delimiters) { this.delimiters = delimiters; this.internal = [ makeEntry("START_IF", "if"), makeEntry("ELSE", "else"), makeEntry("ELSIF", "elsif"), makeEntry("END_IF", "endif"), makeEntry("NOT", "not"), makeEntry("EQUALITY", "=="), makeEntry("NOT_EQUALITY", "!="), makeEntry("GREATER_THAN_EQUAL", ">="), makeEntry("GREATER_THAN", ">"), makeEntry("LESS_THAN_EQUAL", "<="), makeEntry("LESS_THAN", "<"), makeEntry("START_EACH", "each"), makeEntry("END_EACH", "endeach"), makeEntry("ASSIGN", "as"), makeEntry("PARTIAL", "partial"), makeEntry("START_EXTEND", "extend"), makeEntry("END_EXTEND", "endextend"), makeEntry("MAGIC", ".") ]; }
javascript
{ "resource": "" }
q55673
makeEntry
train
function makeEntry(name, value) { var escaped = escapeDelimiter(value); return { name: name, escaped: escaped, test: new RegExp("^" + escaped) }; }
javascript
{ "resource": "" }
q55674
getPartial
train
function getPartial(name) { if (name in this._partials) { return this._partials[name]; } else if (this._parent) { return this._parent.getPartial(name); } throw new Error("Missing partial " + name); }
javascript
{ "resource": "" }
q55675
parseNextToken
train
function parseNextToken(template, grammar, stack) { grammar.some(function(token) { var capture = token.test.exec(template); // Ignore empty captures. if (capture && capture[0]) { template = template.replace(token.test, ""); stack.push({ name: token.name, capture: capture }); return true; } }); return template; }
javascript
{ "resource": "" }
q55676
randomBytesSync
train
function randomBytesSync (size) { var err = null for (var i = 0; i < GENERATE_ATTEMPTS; i++) { try { return crypto.randomBytes(size) } catch (e) { err = e } } throw err }
javascript
{ "resource": "" }
q55677
train
function (div) { var visWidget = vis.views[vis.activeView].widgets[barsIntern.wid]; if (visWidget === undefined) { for (var view in vis.views) { if (view === '___settings') continue; if (vis.views[view].widgets[barsIntern.wid]) { visWidget = vis.views[view].widgets[barsIntern.wid]; break; } } } return visWidget; }
javascript
{ "resource": "" }
q55678
checkForIdAndData
train
function checkForIdAndData(object, callback) { var id = object[options.idProperty] , foundObject if (id === undefined || id === null) { return callback(new Error('Object has no \'' + options.idProperty + '\' property')) } foundObject = findById(id) if (foundObject === null) { return callback(new Error('No object found with \'' + options.idProperty + '\' = \'' + id + '\'')) } return callback(null, foundObject) }
javascript
{ "resource": "" }
q55679
create
train
function create(object, callback) { self.emit('create', object) callback = callback || emptyFn // clone the object var extendedObject = extend({}, object) if (!extendedObject[options.idProperty]) { idSeq += 1 extendedObject[options.idProperty] = '' + idSeq } else { if (findById(extendedObject[options.idProperty]) !== null) { return callback(new Error('Key ' + extendedObject[options.idProperty] + ' already exists')) } // if an id is provided, cast to string. extendedObject[options.idProperty] = '' + extendedObject[options.idProperty] } data.push(extend({}, extendedObject)) self.emit('afterCreate', extendedObject) callback(undefined, extendedObject) }
javascript
{ "resource": "" }
q55680
createOrUpdate
train
function createOrUpdate(object, callback) { if (typeof object[options.idProperty] === 'undefined') { // Create a new object self.create(object, callback) } else { // Try and find the object first to update var query = {} query[options.idProperty] = object[options.idProperty] self.findOne(query, function (err, foundObject) { if (foundObject) { // We found the object so update self.update(object, callback) } else { // We didn't find the object so create self.create(object, callback) } }) } }
javascript
{ "resource": "" }
q55681
read
train
function read(id, callback) { var query = {} self.emit('read', id) callback = callback || emptyFn query[options.idProperty] = '' + id findByQuery(query, {}, function (error, objects) { if (objects[0] !== undefined) { var cloned = extend({}, objects[0]) self.emit('received', cloned) callback(undefined, cloned) } else { callback(undefined, undefined) } }) }
javascript
{ "resource": "" }
q55682
update
train
function update(object, overwrite, callback) { if (typeof overwrite === 'function') { callback = overwrite overwrite = false } self.emit('update', object, overwrite) callback = callback || emptyFn var id = '' + object[options.idProperty] , updatedObject checkForIdAndData(object, function (error, foundObject) { if (error) { return callback(error) } if (overwrite) { updatedObject = extend({}, object) } else { updatedObject = extend({}, foundObject, object) } var query = {} , copy = extend({}, updatedObject) query[ options.idProperty ] = id data = Mingo.remove(data, query) data.push(updatedObject) self.emit('afterUpdate', copy, overwrite) callback(undefined, copy) }) }
javascript
{ "resource": "" }
q55683
deleteMany
train
function deleteMany(query, callback) { callback = callback || emptyFn self.emit('deleteMany', query) data = Mingo.remove(data, query) self.emit('afterDeleteMany', query) callback() }
javascript
{ "resource": "" }
q55684
del
train
function del(id, callback) { callback = callback || emptyFn if (typeof callback !== 'function') { throw new TypeError('callback must be a function or empty') } self.emit('delete', id) var query = {} query[ options.idProperty ] = id deleteMany(query, function() { self.emit('afterDelete', '' + id) callback(undefined) }) }
javascript
{ "resource": "" }
q55685
findByQuery
train
function findByQuery(query, options, callback) { if (typeof options === 'function') { callback = options options = {} } var cursor = Mingo.find(data, query, options && options.fields) if (options && options.sort) cursor = cursor.sort(options.sort) if (options && options.limit) cursor = cursor.limit(options.limit) var allData = getObjectCopies(cursor.all()) if (callback === undefined) { return es.readArray(allData).pipe(es.map(function (data, cb) { self.emit('received', data) cb(null, data) })) } else { callback(null, allData) } }
javascript
{ "resource": "" }
q55686
find
train
function find(query, options, callback) { if (typeof options === 'function') { callback = options options = {} } self.emit('find', query, options) if (callback !== undefined) { findByQuery(query, options, function(error, data) { if (error) return callback(error) self.emit('received', data) callback(null, data) }) } else { return findByQuery(query, options) } }
javascript
{ "resource": "" }
q55687
findOne
train
function findOne(query, options, callback) { if (typeof options === 'function') { callback = options options = {} } self.emit('findOne', query, options) findByQuery(query, options, function (error, objects) { self.emit('received', objects[0]) callback(undefined, objects[0]) }) }
javascript
{ "resource": "" }
q55688
count
train
function count(query, callback) { self.emit('count', query) findByQuery(query, options, function (error, objects) { self.emit('received', objects.length) callback(undefined, objects.length) }) }
javascript
{ "resource": "" }
q55689
getTeamCityOutput
train
function getTeamCityOutput(results, propNames) { const config = getUserConfig(propNames || {}); if (process.env.ESLINT_TEAMCITY_DISPLAY_CONFIG) { console.info(`Running ESLint Teamcity with config: ${JSON.stringify(config, null, 4)}`); } let outputMessages = []; switch (config.reporter.toLowerCase()) { case 'inspections': { outputMessages = formatInspections(results, config); break; } case 'errors': default: { outputMessages = formatErrors(results, config); break; } } return outputMessages.join('\n'); }
javascript
{ "resource": "" }
q55690
processNodeContentWithPosthtml
train
function processNodeContentWithPosthtml(node, options) { return function (content) { return processWithPostHtml(options.plugins, path.join(path.dirname(options.from), node.attrs.href), content, [function (tree) { // remove <content> tags and replace them with node's content return tree.match(match('content'), function () { return node.content || ''; }); }]); }; }
javascript
{ "resource": "" }
q55691
handleMouseDown
train
function handleMouseDown (e) { if(enabled){ for (var i= 0; i<excludedClasses.length; i++) { if (angular.element(e.target).hasClass(excludedClasses[i])) { return false; } } $scope.$apply(function() { onDragStart($scope); }); // Set mouse drag listeners setDragListeners(); // Set 'pushed' state pushed = true; lastClientX = startClientX = e.clientX; lastClientY = startClientY = e.clientY; clearSelection(); e.preventDefault(); e.stopPropagation(); } }
javascript
{ "resource": "" }
q55692
handleMouseUp
train
function handleMouseUp (e) { if(enabled){ var selectable = (e.target.attributes && 'drag-scroll-text' in e.target.attributes); var withinXConstraints = (e.clientX >= (startClientX - allowedClickOffset) && e.clientX <= (startClientX + allowedClickOffset)); var withinYConstraints = (e.clientY >= (startClientY - allowedClickOffset) && e.clientY <= (startClientY + allowedClickOffset)); // Set 'pushed' state pushed = false; // Check if cursor falls within X and Y axis constraints if(selectable && withinXConstraints && withinYConstraints) { // If so, select the text inside the target element selectText(e.target); } $scope.$apply(function() { onDragEnd($scope); }); removeDragListeners(); } }
javascript
{ "resource": "" }
q55693
handleMouseMove
train
function handleMouseMove (e) { if(enabled){ if (pushed) { if(!axis || axis === 'x') { $element[0].scrollLeft -= (-lastClientX + (lastClientX = e.clientX)); } if(!axis || axis === 'y') { $element[0].scrollTop -= (-lastClientY + (lastClientY = e.clientY)); } } e.preventDefault(); } }
javascript
{ "resource": "" }
q55694
destroy
train
function destroy () { $element.off('mousedown', handleMouseDown); angular.element($window).off('mouseup', handleMouseUp); angular.element($window).off('mousemove', handleMouseMove); }
javascript
{ "resource": "" }
q55695
selectText
train
function selectText (element) { var range; if ($window.document.selection) { range = $window.document.body.createTextRange(); range.moveToElementText(element); range.select(); } else if ($window.getSelection) { range = $window.document.createRange(); range.selectNode(element); $window.getSelection().addRange(range); } }
javascript
{ "resource": "" }
q55696
clearSelection
train
function clearSelection () { if ($window.getSelection) { if ($window.getSelection().empty) { // Chrome $window.getSelection().empty(); } else if ($window.getSelection().removeAllRanges) { // Firefox $window.getSelection().removeAllRanges(); } } else if ($document.selection) { // IE? $document.selection.empty(); } }
javascript
{ "resource": "" }
q55697
deepExtend
train
function deepExtend(destination) { angular.forEach(arguments, function (obj) { if (obj !== destination) { angular.forEach(obj, function (value, key) { if (destination[key] && destination[key].constructor && destination[key].constructor === Object) { deepExtend(destination[key], value); } else { destination[key] = value; } }); } }); return angular.copy(destination); }
javascript
{ "resource": "" }
q55698
checkUrl
train
function checkUrl(url, resourceName, hrefKey) { if (url == undefined || !url) { throw new Error("The provided resource name '" + resourceName + "' has no valid URL in the '" + hrefKey + "' property."); } return url }
javascript
{ "resource": "" }
q55699
getFontFeatureSettingsPrevTo
train
function getFontFeatureSettingsPrevTo(decl) { var fontFeatureSettings = null; decl.parent.walkDecls(function(decl) { if (decl.prop === "font-feature-settings") { fontFeatureSettings = decl; } }) if (fontFeatureSettings === null) { fontFeatureSettings = decl.clone() fontFeatureSettings.prop = "font-feature-settings" fontFeatureSettings.value = "" decl.parent.insertBefore(decl, fontFeatureSettings) } return fontFeatureSettings }
javascript
{ "resource": "" }