_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q10300
train
function( text2search, noSearchPhrase, noSearchResult ) { Array.call( this ); /** * Gets the text to search. * @type {string|null} */ this.text2search = text2search || null; /** * Gets a message to display when search phrase is missing. * @type {string} */ this.noSearchPhrase = noSearchPhrase; /** * Gets a message to display when search did not found the text in the contents. * @type {string} */ this.noSearchResult = noSearchResult; }
javascript
{ "resource": "" }
q10301
train
function (files, latestMigrationFile) { if (direction === 'do') { return files .sort() .filter(function () { var _mustBeApplied = (latestMigrationFile === null); return function (name) { if (latestMigrationFile === name) { _mustBeApplied = !_mustBeApplied; return false; } return _mustBeApplied; }; }() ); } else { return files.sort().reverse().filter(function (name) { return latestMigrationFile === name; }); } }
javascript
{ "resource": "" }
q10302
train
function (order, unorderedObj) { var orderedObj = []; for (var i = 0; i < order.length; i++) { orderedObj.push(unorderedObj[order[i]]); } return orderedObj; }
javascript
{ "resource": "" }
q10303
train
function (latestMigrationFile) { return function (err, files) { if (err) { throw err; } files = _getApplicableMigrations(files, latestMigrationFile); var filesRemaining = files.length; var parsedMigrations = {}; console.log('* Number of migration scripts to apply:', filesRemaining); if (filesRemaining === 0) { // me.client; // TODO : what is this ? } for (var file in files) { if (files.hasOwnProperty(file)) { var filename = files[file]; var filepath = _config.migrationFolder + '/' + filename; var parser = new migrationParser(filepath, me.client); parser.on('ready', function () { filesRemaining--; parsedMigrations[basename(this.file)] = this; if (filesRemaining === 0) { var orderedMigrations = _orderMigrations(files, parsedMigrations); // Here is where the migration really takes place me.changelog.apply(orderedMigrations, direction); } }); } } } }
javascript
{ "resource": "" }
q10304
validateFilename
train
function validateFilename(input) { let isValidCharacterString = validateCharacterString(input); if (isValidCharacterString !== true) { return isValidCharacterString; } return (input.search(/ /) === -1) ? true : 'Must be a valid POSIX.1-2013 3.170 Filename!'; }
javascript
{ "resource": "" }
q10305
makeHeaders
train
function makeHeaders(headers, params) { if (headers.length <= 0) { return params; } for (var prop in headers) { var head = headers[prop]; prop = prop.replace(/-/, '_').toUpperCase(); if (prop.indexOf('CONTENT_') < 0) { // Quick hack for PHP, might be more or less headers. prop = 'HTTP_' + prop; } params[params.length] = [prop, head] } return params; }
javascript
{ "resource": "" }
q10306
readContents
train
function readContents( contentPath, submenuFile, filingCabinet, renderer ) { var typeName = 'Content'; logger.showInfo( '*** Reading contents...' ); // Read directory items in the content store. var items = fs.readdirSync( path.join( process.cwd(), contentPath ) ); items.forEach( function ( item ) { var itemPath = path.join( contentPath, item ); // Get item info. var stats = fs.statSync( path.join( process.cwd(), itemPath ) ); if (stats.isDirectory()) { // Create new stores for the language. var contentStock = filingCabinet.contents.create( item ); var menuStock = filingCabinet.menus.create( item ); // Save the language for the menu. filingCabinet.languages.push( item ); logger.localeFound( typeName, item ); // Find and add contents for the language. processContents( itemPath, // content directory '', // content root submenuFile, // submenu filename contentStock, // content stock menuStock, // menu stock filingCabinet.references, // reference drawer item, // language renderer // markdown renderer ); } else // Unused file. logger.fileSkipped( typeName, itemPath ); } ) }
javascript
{ "resource": "" }
q10307
train
function (tmplPath) { var text = fs.readFileSync(tmplPath) .toString() .replace(/^\s*|\s*$/g, ""); return ejs.compile(text); }
javascript
{ "resource": "" }
q10308
train
function (obj, opts) { var toc = []; // Finesse comment markdown data. // Also, statefully create TOC. var sections = _.chain(obj) .map(function (data) { return new Section(data, opts); }) .filter(function (s) { return s.isPublic(); }) .map(function (s) { toc.push(s.renderToc()); // Add to TOC. return s.renderSection(); // Render section. }) .value() .join("\n"); // No Output if not sections. if (!sections) { return ""; } return "\n" + toc.join("") + "\n" + sections; }
javascript
{ "resource": "" }
q10309
train
function (text) { var inApiSection = false; return fs.createReadStream(opts.src) .pipe(es.split("\n")) .pipe(es.through(function (line) { // Hit the start marker. if (line === opts.start) { // Emit our line (it **is** included). this.emit("data", line); // Emit our the processed API data. this.emit("data", text); // Mark that we are **within** API section. inApiSection = true; } // End marker. if (line === opts.end) { // Mark that we have **exited** API section. inApiSection = false; } // Re-emit lines only if we are not within API section. if (!inApiSection) { this.emit("data", line); } })) .pipe(es.join("\n")) .pipe(es.wait()); }
javascript
{ "resource": "" }
q10310
train
function(element, options) { _.extend(this, Backbone.Events); var defaults = require('../utils/default-options')(); // set to be an object in case // it's undefined options = options || {}; // extend the defaults options = _.extend(defaults, options); this.options = options; this._currentColumns = []; this.container = element; this.innerContainer = document.createElement('div'); this.innerContainer.classList.add('inner-container'); this.innerContainer.classList.add('hide-overflow'); this.el = document.createElement('table'); this.el.classList.add('table'); this.el.classList.add('table-striped'); this.container.classList.add('table-sink-container'); this.innerContainer.appendChild(this.el); this.container.appendChild(this.innerContainer); this.innerContainer.style.maxHeight = options.height + 'px'; this.resize(); // create some scaffolding this.table = d3.select(this.el); this.thead = this.table.append('thead'); this.tbody = this.table.append('tbody'); // set if we should append to the existing table data // and not reset on batch_end this._append = options._append; this._markdownFields = this.options.markdownFields || []; this._bindScrollBlocker(); // We don't need a fully-fledged data target here, // so we just add functions as per feedback from @demmer var self = this; this.dataTarget = { _data: [], push: function(data) { // clear the table if we've done batch_end / stream_end before if (this._data.length === 0) { self.clearTable(); } // limit the data to avoid crashing the browser. If limit // is zero, then it is ignored. If the limit has been reached, // we return early and don't display the new data // check that we aren't already over the limit if (this._data.length >= self.options.limit) { // display the message and don't do anything else self._sendRowLimitReachedMessage(); return; // check that the new data won't make us go over the limit } else if ((this._data.length + data.length) > self.options.limit) { self._sendRowLimitReachedMessage(); // just add from new data until we get to the limit var i = 0; while (this._data.length < self.options.limit) { this._data.push(data[i++]); } } // we're fine. else { self._clearRowLimitReachedMessage(); this._data = this._data.concat(data); } // if you got here, draw the table self.onData(this._data); }, batch_end: function() { if (self.options.update === 'replace') { this._data = []; } }, stream_end: function() { } }; }
javascript
{ "resource": "" }
q10311
GitRepos
train
function GitRepos (path, callback) { var ev = FindIt(Abs(path)); ev.on("directory", function (dir, stat, stop) { var cDir = Path.dirname(dir) , base = Path.basename(dir) ; if (base === ".git") { callback(null, cDir, stat); stop(); } }); ev.on("error", function (err) { callback(err); }); return ev; }
javascript
{ "resource": "" }
q10312
Row
train
function Row(columnSpecs, row) { var i, col, type, val, cols = []; for (i = 0; i < columnSpecs.length; i++) { col = columnSpecs[i]; type = types.fromType(col.type); if (col.subtype) { type = type(col.subtype); } else if (col.keytype) { type = type(col.keytype, col.valuetype); } val = type.deserialize(row[i]); this[col.name] = val; cols.push(val); } Object.defineProperty(this, 'columns', { value: cols, enumerable: false }); }
javascript
{ "resource": "" }
q10313
awaitFunction
train
function awaitFunction(fn) { return (req, res, next) => { Promise.resolve(fn(req, res, next)).catch(next); }; }
javascript
{ "resource": "" }
q10314
prepareConfig
train
function prepareConfig(config) { if (!('authorizationError' in config)) { config.authorizationError = {status: 401, message: 'Unauthorized'}; } if (!('unauthorizedOnly' in config)) { config.unauthorizedOnly = false; } }
javascript
{ "resource": "" }
q10315
retrieveUserFromRedis
train
async function retrieveUserFromRedis(res, auth, tokenOrEmail, config) { if (config.redisClient) { const getFromRedis = util .promisify(config.redisClient.get) .bind(config.redisClient); const cachedUserData = await getFromRedis(`${ns}:${tokenOrEmail}`); if (cachedUserData) { const data = JSON.parse(cachedUserData); const user = auth.createAuthFromData(data); auth.currentUser = user; res.locals = res.locals || {}; res.locals.auth = auth; return user; } } }
javascript
{ "resource": "" }
q10316
saveUserInRedis
train
function saveUserInRedis(user, tokenOrEmail, config) { if (config.redisClient) { const key = `${ns}:${tokenOrEmail}`; config.redisClient.set(key, JSON.stringify(user.data_), 'EX', 10); } }
javascript
{ "resource": "" }
q10317
locationToPoint
train
function locationToPoint(loc) { var lat, lng, radius, cosLat, sinLat, cosLng, sinLng, x, y, z; lat = loc.lat * Math.PI / 180.0; lng = loc.lng * Math.PI / 180.0; radius = loc.elv + getRadius(lat); cosLng = Math.cos(lng); sinLng = Math.sin(lng); cosLat = Math.cos(lat); sinLat = Math.sin(lat); x = cosLng * cosLat * radius; y = sinLng * cosLat * radius; z = sinLat * radius; return { x: x, y: y, z: z, radius: radius }; }
javascript
{ "resource": "" }
q10318
distance
train
function distance(ap, bp) { var dx, dy, dz; dx = ap.x - bp.x; dy = ap.y - bp.y; dz = ap.z - bp.z; return Math.sqrt(dx * dx + dy * dy + dz * dz); }
javascript
{ "resource": "" }
q10319
rotateGlobe
train
function rotateGlobe(b, a, bRadius) { var br, brp, alat, acos, asin, bx, by, bz; // Get modified coordinates of 'b' by rotating the globe so // that 'a' is at lat=0, lng=0 br = { lat: b.lat, lng: (b.lng - a.lng), elv:b.elv }; brp = locationToPoint(br); // scale all the coordinates based on the original, correct geoid radius brp.x *= (bRadius / brp.radius); brp.y *= (bRadius / brp.radius); brp.z *= (bRadius / brp.radius); // restore actual geoid-based radius calculation brp.radius = bRadius; // Rotate brp cartesian coordinates around the z-axis by a.lng degrees, // then around the y-axis by a.lat degrees. // Though we are decreasing by a.lat degrees, as seen above the y-axis, // this is a positive (counterclockwise) rotation // (if B's longitude is east of A's). // However, from this point of view the x-axis is pointing left. // So we will look the other way making the x-axis pointing right, the z-axis // pointing up, and the rotation treated as negative. alat = -a.lat * Math.PI / 180.0; acos = Math.cos(alat); asin = Math.sin(alat); bx = (brp.x * acos) - (brp.z * asin); by = brp.y; bz = (brp.x * asin) + (brp.z * acos); return { x: bx, y: by, z: bz }; }
javascript
{ "resource": "" }
q10320
train
function(path, partials) { var templates = { }; grunt.file.recurse(path, function (absPath, rootDir, subDir, filename) { // ignore non-template files if (!filename.match(matcher)) { return; } // read template source and data var relPath = absPath.substr(rootDir.length + 1), tmpData = absPath.replace(matcher, '.json'), tmpSrc = grunt.file.read(absPath), // template name based on path (e.g. "index", "guide/index", etc) name = relPath.replace(matcher, ''), // set-up template specific locals locals = mustatic.merge({}, globals); // add template URL to locals locals.url = name + '.html'; // load template data and merge into locals if (grunt.file.exists(tmpData)) { locals = mustatic.merge(locals, JSON.parse(grunt.file.read(tmpData))); } // store locals data[name] = locals; templates[name] = hogan.compile(tmpSrc); }); return templates; }
javascript
{ "resource": "" }
q10321
train
function(el, options) { if (typeof options === 'undefined') { options = {}; } // apply defaults options = _.defaults(options, defaults, { orientation : 'left', labelText: '', // true to position the axis-label // when chart uses layout positioning of axis-labels is handled by layout position: true }); this._labelText = options.labelText; this._animDuration = options.duration; this._orientation = options.orientation; this._margin = options.margin; this._width = options.width; this._height = options.height; this._isPositioned = options.position; this._container = d3.select(el); this._g = null; this._text = null; }
javascript
{ "resource": "" }
q10322
eatNumber
train
function eatNumber(stream) { const start = stream.pos; const negative = stream.eat(DASH); const afterNegative = stream.pos; stream.eatWhile(isNumber); const prevPos = stream.pos; if (stream.eat(DOT) && !stream.eatWhile(isNumber)) { // Number followed by a dot, but then no number stream.pos = prevPos; } // Edge case: consumed dash only: not a number, bail-out if (stream.pos === afterNegative) { stream.pos = start; } return stream.pos !== start; }
javascript
{ "resource": "" }
q10323
Mangonel
train
function Mangonel (modules = []) { const getLaunchersByName = (modules, name) => modules.filter(m => m.name === name) const getFirstLauncher = (...args) => modules.filter(m => m.platforms.filter(p => p === args[1]).length > 0)[0] return { /** * * * @param {function} emulator launcher modules * @param {Object} [launcher={}] launcher object * @param {Object} [options={}] options object * @returns {int} processId */ launch (software, launcher = {}, settings = {}, options = {}) { const command = getFirstLauncher(modules, software.platform).buildCommand( software.file, launcher, settings ) return execute(command, options) }, modules } }
javascript
{ "resource": "" }
q10324
columnizeArray
train
function columnizeArray(array, opts) { // conditionally sort array //---------------------------------------------------------- const ar = opts && opts.sort ? typeof opts.sort === 'boolean' ? array.sort() : opts.sort(array) : array // build and freeze props //---------------------------------------------------------- const props = freeze(merge( { gap: { len: 2 , ch: ' ' } , maxRowLen: 80 } , opts , { ar , arLen: ar.length , initState: { i: 0 , strs: [] , indices: [] , widths: [] } } )) // columnize and return //---------------------------------------------------------- const columns = new Columns(props) return { strs: columns.state.strs , indices: columns.state.indices } }
javascript
{ "resource": "" }
q10325
getComponentConfiguration
train
function getComponentConfiguration(name) { var config = {}; if (typeof projectConfig[name] === 'object') { config = projectConfig[name]; } if (typeof componentConfig[name] === 'object') { if (config == null) config = {}; config = util.extend(true, config, componentConfig[name]); } if (typeof appConfig[name] === 'object') { if (config == null) config = {}; config = util.extend(true, config, appConfig[name]); } function ref(obj, str) { return str.split(".").reduce(function(o, x) { return o[x] }, obj); } if (config == null) { // if it's null, we search for inner dotted configs. try { config = ref(projectConfig, name); } catch (e) { } try { config = util.extend(true, config || {}, ref(appConfig, name)); } catch (e) { } } return config; }
javascript
{ "resource": "" }
q10326
toInboundMessage
train
function toInboundMessage(relayMessage, mail) { let inboundMessage = transport.defaultInboundMessage({ to: { email: relayMessage.rcpt_to, name: '' }, from: mail.from[0], subject: mail.subject, text: mail.text, html: mail.html, recipients: mail.to, cc: mail.cc, bcc: mail.bcc, headers: mail.headers, attachments: mail.attachments, _raw: relayMessage }); inboundMessage.id = transport.defaultMessageId(inboundMessage); return inboundMessage; }
javascript
{ "resource": "" }
q10327
handleReply
train
function handleReply(inboundMessage, data) { if (data.reply) { _.merge(data.content.headers, Transport.getReplyHeaders(inboundMessage)); data.content.subject = Transport.getReplySubject(inboundMessage); delete data.reply; } return data; }
javascript
{ "resource": "" }
q10328
throwUpError
train
function throwUpError(err) { if (err.name === 'SparkPostError') console.log(JSON.stringify(err.errors, null, 2)); setTimeout(function() { throw err; }); }
javascript
{ "resource": "" }
q10329
train
function(model) { model.can = _.extend({create: true, read: true, update: true, delete: true}, model.can, feature.can); }
javascript
{ "resource": "" }
q10330
Snippets
train
function Snippets(options) { this.options = options || {}; this.store = store(this.options); this.snippets = {}; this.presets = {}; this.cache = {}; this.cache.data = {}; var FetchFiles = lazy.FetchFiles(); this.downloader = new FetchFiles(this.options); this.presets = this.downloader.presets; if (typeof this.options.templates === 'object') { this.visit('set', this.options.templates); } }
javascript
{ "resource": "" }
q10331
train
function (name, val) { if (typeof name === 'object') { return this.visit('set', name); } utils.set(this.snippets, name, val); return this; }
javascript
{ "resource": "" }
q10332
train
function (name, preset) { if(typeof name !== 'string') { throw new TypeError('snippets#get expects `name` to be a string.'); } if (utils.startsWith(name, './')) { return this.read(name); } // ex: `http(s)://api.github.com/...` if (/^\w+:\/\//.test(name) || preset) { var snippet = this.downloader .fetch(name, preset) .download(); var parsed = url.parse(name); this.set(parsed.pathname, snippet); return new Snippet(snippet); } var res = this.snippets[name] || this.store.get(name) || utils.get(this.snippets, name); return new Snippet(res); }
javascript
{ "resource": "" }
q10333
train
function (snippets, options) { if (typeof snippets === 'string') { var glob = lazy.glob(); var files = glob.sync(snippets, options); files.forEach(function (fp) { var key = fp.split('.').join('\\.'); this.set(key, {path: fp}); }.bind(this)); } return this; }
javascript
{ "resource": "" }
q10334
train
function(options) { var userOptions = options; var series = userOptions.series; if (!series) { return userOptions; } series.forEach(function(value, index) { if (Object.keys(userOptions.yScales).length < 2 && Object.keys(userOptions.yScales).indexOf(value.yScale) === -1 && value.yScale === 'secondary') { userOptions.yScales[value.yScale] = { scaling: 'linear', minValue: 'auto', maxValue: 'auto', displayOnAxis: 'right' }; } }); return userOptions; }
javascript
{ "resource": "" }
q10335
train
function(seriesKeys) { var fieldValues = _.values(seriesKeys), matchingSeriesDef = _.find(this._attributes.series, function(seriesDef) { return _.contains(fieldValues, seriesDef.name); }); if (!matchingSeriesDef) { return _.find(this._attributes.series, function(seriesDef) { return !seriesDef.name; }); } return matchingSeriesDef; }
javascript
{ "resource": "" }
q10336
train
function() { this._setTimeRangeTo(this._jut_time_bounds, this._juttleNow); if (this._hasReceivedData && this.contextChart) { $(this.sinkBodyEl).append(this.contextChart.el); this.chart.toggleAnimations(false); } }
javascript
{ "resource": "" }
q10337
tick
train
function tick() { currentTime += 1 / 60; var p = currentTime / time; var t = easingEquations[easing](p); if (p < 1) { requestAnimationFrame(tick); window.scrollTo(0, scrollY + ((scrollTargetY - scrollY) * t)); } else { window.scrollTo(0, scrollTargetY); } }
javascript
{ "resource": "" }
q10338
chunk
train
function chunk(start, end) { // Slice, unescape and push onto result array. res.push(str.slice(start, end).replace(/\\\\/g, '\\').replace(/\\\./g, '.')); // Set starting position of next chunk. pos = end + 1; }
javascript
{ "resource": "" }
q10339
Buf
train
function Buf(buffer) { this._initialSize = 64 * 1024; this._stepSize = this._initialSize; this._pos = 0; if (typeof buffer === 'number') { this._initialSize = buffer; } if (buffer instanceof Buffer) { this._buf = buffer; } else { this._buf = new Buffer(this._initialSize); } }
javascript
{ "resource": "" }
q10340
runTheHandler
train
function runTheHandler(inboundMessage) { let handler = convo.handler; convo.handler = null; let result = handler.apply(convo, [convo, inboundMessage]); if (result === IS_WAIT_FUNCTION) { // reset the handler to wait again convo.handler = handler; } // this was a real interaction so reset the timeout and wait count else { fuse.logger.verbose('Ran handler'); resetTimeout(); convo.wait_count = 0; } }
javascript
{ "resource": "" }
q10341
addInboundMessageToConvo
train
function addInboundMessageToConvo(inboundMessage) { if (_.last(convo.inboundMessages) !== inboundMessage) { fuse.logger.debug(`Add ${inboundMessage.id} to transcript`); convo.inboundMessages.push(inboundMessage); convo.transcript.push(inboundMessage); } }
javascript
{ "resource": "" }
q10342
resetTimeout
train
function resetTimeout() { clearTimeout(convo.timeout_function); convo.timeout_function = setTimeout(function() { convo.timeout(); }, convo.timeout_after); }
javascript
{ "resource": "" }
q10343
ExpandFiles
train
function ExpandFiles(options) { if (!(this instanceof ExpandFiles)) { return new ExpandFiles(options); } Base.call(this, {}, options); this.use(utils.plugins()); this.is('Files'); this.options = options || {}; if (util.isFiles(options) || arguments.length > 1) { this.options = {}; this.expand.apply(this, arguments); return this; } }
javascript
{ "resource": "" }
q10344
expandMapping
train
function expandMapping(config, options) { var len = config.files.length, i = -1; var res = []; while (++i < len) { var raw = config.files[i]; var node = new RawNode(raw, config, this); this.emit('files', 'rawNode', node); this.emit('rawNode', node); if (node.files.length) { res.push.apply(res, node.files); } } config.files = res; return config; }
javascript
{ "resource": "" }
q10345
RawNode
train
function RawNode(raw, config, app) { utils.define(this, 'isRawNode', true); util.run(config, 'rawNode', raw); this.files = []; var paths = {}; raw.options = utils.extend({}, config.options, raw.options); var opts = resolvePaths(raw.options); var filter = filterFiles(opts); var srcFiles = utils.arrayify(raw.src); if (opts.glob !== false && utils.hasGlob(raw.src)) { srcFiles = utils.glob.sync(raw.src, opts); } srcFiles = srcFiles.filter(filter); if (config.options.mapDest) { var len = srcFiles.length, i = -1; while (++i < len) { var node = new FilesNode(srcFiles[i], raw, config); app.emit('files', 'filesNode', node); app.emit('filesNode', node); var dest = node.dest; if (!node.src && !node.path) { continue; } var src = resolveArray(node.src, opts); if (paths[dest]) { paths[dest].src = paths[dest].src.concat(src); } else { node.src = utils.arrayify(src); this.files.push(node); paths[dest] = node; } } if (!this.files.length) { node = raw; raw.src = []; this.files.push(raw); } } else { createNode(srcFiles, raw, this.files, config); } }
javascript
{ "resource": "" }
q10346
FilesNode
train
function FilesNode(src, raw, config) { utils.define(this, 'isFilesNode', true); this.options = utils.omit(raw.options, ['mapDest', 'flatten', 'rename', 'filter']); this.src = utils.arrayify(src); if (this.options.resolve) { var cwd = path.resolve(this.options.cwd || process.cwd()); this.src = this.src.map(function(fp) { return path.resolve(cwd, fp); }); } if (raw.options.mapDest) { this.dest = mapDest(raw.dest, src, raw); } else { this.dest = rewriteDest(raw.dest, src, raw.options); } // copy properties to the new node for (var key in raw) { if (key !== 'src' && key !== 'dest' && key !== 'options') { this[key] = raw[key]; } } util.run(config, 'filesNode', this); }
javascript
{ "resource": "" }
q10347
rewriteDest
train
function rewriteDest(dest, src, opts) { dest = utils.resolve(dest); if (opts.destBase) { dest = path.join(opts.destBase, dest); } if (opts.extDot || opts.hasOwnProperty('ext')) { dest = rewriteExt(dest, opts); } if (typeof opts.rename === 'function') { return opts.rename(dest, src, opts); } return dest; }
javascript
{ "resource": "" }
q10348
toNested
train
function toNested(map) { var split, first, last; utils.walkObject(map, function (val, prop1) { split = prop1.split('.'); if (!utils.validateFieldName(prop1)) { log.error('map field name "' + prop1 + '" is invalid'); } last = split[split.length - 1]; first = prop1.replace('.' + last, ''); utils.walkObject(map, function (val2, prop2) { if (prop1 !== prop2 && first === prop2) { log.error('map field name "' + prop2 + '" is invalid'); } }); }); var form = {}; var names = []; utils.walkObject(map, function (val, prop) { names.push({ keys: prop.split('.'), value: val }); }); var obj; names.forEach(function (name) { obj = form; name.keys.forEach(function (key, index) { if (index === name.keys.length - 1) { obj[key] = name.value; } else { if (!obj[key]) { obj[key] = {}; } obj = obj[key]; } }); }); return form; }
javascript
{ "resource": "" }
q10349
toPlain
train
function toPlain(map) { var split; var form = {}; var throwErr = function throwErr(key) { return log.error('map field name "' + key + '" is invalid'); }; var isInvalidKey = function isInvalidKey(str) { return str.split('.').length > 1; }; var run = function run(n, o, p) { if (o.hasOwnProperty(p)) { n += '.' + p; if (typeof o[p] === 'string' || typeof o[p] === 'number' || typeof o[p] === 'boolean' || o[p] === undefined || o[p] === null) { n = n.substring(1); form[n] = o[p]; } else { for (var k in o[p]) { if (isInvalidKey(k)) throwErr(k); run(n, o[p], k); } } } }; for (var p in map) { if (isInvalidKey(p)) throwErr(p); run('', map, p); } return form; }
javascript
{ "resource": "" }
q10350
iterateStyleRules
train
function iterateStyleRules(argument) { if (typeof argument === 'string') { checkStyleExistence(styleDefinitions, argument); collectedStyles.push(styleDefinitions[argument]); return; } if (typeof argument === 'object') { Object.keys(argument).forEach(function(styleName) { checkStyleExistence(styleDefinitions, styleName); if (argument[styleName]) { collectedStyles.push(styleDefinitions[styleName]) } }) } }
javascript
{ "resource": "" }
q10351
NativeProtocol
train
function NativeProtocol(protocolVersion) { var _protocolVersion = protocolVersion || DEFAULT_PROTOCOL_VERSION; if (!(this instanceof NativeProtocol)) return new NativeProtocol(); stream.Duplex.call(this); Object.defineProperties(this, { 'protocolVersion': { set: function(val) { if (typeof val !== 'number' || val < 1 || val > DEFAULT_PROTOCOL_VERSION) { throw new Error('Invalid protocol version is set: ' + val); } _protocolVersion = val; }, get: function() { return _protocolVersion; } } }); this._messageQueue = []; this._readBuf = new Buffer(8); // for header this.lastRead = 0; }
javascript
{ "resource": "" }
q10352
ErrorMessage
train
function ErrorMessage(errorCode, errorMessage, details) { Response.call(this, 0x00); Object.defineProperties(this, { 'errorCode': { value: errorCode || 0, enumerable: true }, 'errorMessage': { value: errorMessage || '', enumerable: true }, 'details': { value: details || {}, enumerable: true } }); }
javascript
{ "resource": "" }
q10353
AuthChallengeMessage
train
function AuthChallengeMessage(token) { var _token = token || new Buffer(0); Response.call(this, 0x0E); Object.defineProperty(this, 'token', { set: function(val) { _token = val; }, get: function() { return _token; } }); }
javascript
{ "resource": "" }
q10354
Engine
train
function Engine() { // The content manager object. var contents = null; /** * Gets the configuration object. * @param {string} configPath - The path of the configuration JSON file. * @returns {Configuration} The configuration object. */ this.getConfiguration = function( configPath ) { logger.showInfo( '>>> Getting configuration: %s', configPath ); var data = require( path.join( process.cwd(), configPath ) ); var config = new Configuration( data ); Object.freeze( config ); logger.showInfo( '>>> Configuration is ready: %j', config ); return config; }; /** * Sets up the content manager object. * @param {Configuration} config - The configuration object. */ this.getContents = function( config ) { logger.showInfo( '>>> Getting contents...' ); contents = new ContentManager( config ); logger.showInfo( '>>> Contents are ready.' ); }; /** * Sets all routes used by te application. * @param {Express.Application} app - The express.js application. * @param {object} actions - An object containing the URLs and paths of the actions. * @param {string} mode - The current Node.js environment. */ this.setRoutes = function( app, actions, mode ) { logger.showInfo( '>>> Setting routes...' ); // Set engine middlewares. contents.setMiddlewares( app ); // Set action routes. contents.setActions( app, actions || { } ); // Set engine routes. contents.setRoutes( app, mode === 'development' ); logger.showInfo( '>>> Routes are ready.' ); }; }
javascript
{ "resource": "" }
q10355
createNode
train
function createNode(name, parent, stat, parentNodeId, callback) { if(utility.hasInvalidChars(name)) { logger.info('Ignoring file \'' + name + '\' because filename contains invalid chars'); return callback(undefined); } var newNode = { directory: stat.isDirectory(), name: name, parent: parent, localActions: {create: {immediate: false, actionInitialized: new Date()}}, localParent: parentNodeId, ino: stat.ino } syncDb.create(newNode, (err, createdNode) => { callback(createdNode._id, undefined); }); }
javascript
{ "resource": "" }
q10356
deleteNode
train
function deleteNode(node, immediate, callback) { node.localActions = {delete: { remoteId: node.remoteId, actionInitialized: new Date(), immediate }}; syncDb.update(node._id, node, callback); }
javascript
{ "resource": "" }
q10357
train
function(dirPath, callback) { logger.info('getDelta start', {category: 'sync-local-delta'}); async.series([ (cb) => { logger.debug('findDeletedNodes start', {category: 'sync-local-delta'}); this.findDeletedNodes(cb) }, (cb) => { logger.debug('findChanges start', {category: 'sync-local-delta'}); this.findChanges(dirPath, undefined, null, cb); }, (cb) => { logger.debug('resolveConflicts start', {category: 'sync-local-delta'}); this.resolveConflicts(cb); } ], (err, resuls) => { logger.info('getDelta end', {category: 'sync-local-delta'}); return callback(null); }); }
javascript
{ "resource": "" }
q10358
train
function(dirPath, oldDirPath, parentNodeId, callback) { fsWrap.readdir(dirPath, (err, nodes) => { //if it is not possible to read dir abort sync if(err) { logger.warning('Error while reading dir', {category: 'sync-local-delta', dirPath, err}); throw new BlnDeltaError(err.message); } async.eachSeries(nodes, (node, cb) => { var nodePath = utility.joinPath(dirPath, node); try { var stat = fsWrap.lstatSync(nodePath); } catch(e) { logger.warning('findChanges got lstat error on node', {category: 'sync-local-delta', nodePath, code: e.code}); throw new BlnDeltaError(e.message); } if(utility.isExcludeFile(node)) { logger.info('LOCAL DELTA: ignoring file \'' + nodePath + '\' matching exclude pattern'); return cb(null); } if(utility.hasInvalidChars(node)) { logger.info('LOCAL DELTA: ignoring file \'' + name + '\' because filename contains invalid chars'); return cb(undefined); } if(stat.isSymbolicLink()) { logger.info('LOCAL DELTA: ignoring symlink \'' + nodePath + '\''); return cb(null); } syncDb.findByIno(stat.ino, (err, syncedNode) => { if(stat.isDirectory()) { let query = {path: nodePath}; if(syncedNode && syncedNode.remoteId) { query.remoteId = syncedNode.remoteId; } ignoreDb.isIgnoredNode(query, (err, isIgnored) => { if(err) return cb(err); if(isIgnored) { logger.info('ignoring directory \'' + nodePath + '\' because it is ignored by ignoredNodes', {category: 'sync-local-delta'}); return cb(null); } this.analyzeNodeForChanges(node, dirPath, oldDirPath, parentNodeId, stat, syncedNode, cb); }); } else { this.analyzeNodeForChanges(node, dirPath, oldDirPath, parentNodeId, stat, syncedNode, cb); } }); }, callback); }); }
javascript
{ "resource": "" }
q10359
train
function(callback) { //process first all directories and then all files. async.mapSeries(['getDirectories', 'getFiles'], (nodeSource, cbMap) => { syncDb[nodeSource]((err, nodes) => { async.eachSeries(nodes, (node, cb) => { // If a node has to be redownloaded do not delete it remotely // See: https://github.com/gyselroth/balloon-node-sync/issues/17 if(node.downloadOriginal) return cb(); var nodePath = utility.joinPath(node.parent, node.name); process.nextTick(() => { var nodePath = utility.joinPath(node.parent, node.name); if(fsWrap.existsSync(nodePath) === false) { //Node doesn't exist localy -> delete it remotely deleteNode(node, false, cb); } else { try { var stat = fsWrap.lstatSync(nodePath); } catch(e) { logger.warning('findDeletedNodes got lstat error on node', {category: 'sync-local-delta', nodePath, code: e.code}); throw new BlnDeltaError(e.message); } if(stat.ino === node.ino) { //node still exists at given path return cb(); } else { deleteNode(node, true, cb); } } }); }, cbMap); }); }, callback); }
javascript
{ "resource": "" }
q10360
Model
train
function Model(name, referenceModel, modellingElements, transitive) { /** @memberOf Model * @member {string} name - The name of the model */ this.__name = name _.set(this, ['__jsmf__','conformsTo'], Model) _.set(this, ['__jsmf__','uuid'], generateId()) /** @memberof Model * @member {Model} referenceModel - The referenceModel (an empty object if undefined) */ this.referenceModel = referenceModel || {} /** @memberof Model * @member {Object} modellingElements - The objects of the model, classified by their class name */ this.modellingElements = {} /** @memberOf Model * @member {Object} classes - classes and enums of the model, classified by their name */ this.classes = {} if (modellingElements !== undefined) { modellingElements = _.isArray(modellingElements) ? modellingElements : [modellingElements] if (transitive) { modellingElements = crawlElements(modellingElements) } _.forEach(modellingElements, e => this.addModellingElement(e)) } }
javascript
{ "resource": "" }
q10361
modelExport
train
function modelExport(m) { const result = _.mapValues(m.classes, _.head) result[m.__name] = m return result }
javascript
{ "resource": "" }
q10362
train
function (client, migrationFolder) { events.EventEmitter.call(this); if (client === undefined) { throw new Error('no client provided'); } _client = client; this.__defineGetter__('migrationFolder', function () { return migrationFolder; }); this.__defineSetter__('migrationFolder', function () { }); }
javascript
{ "resource": "" }
q10363
CruxLogger
train
function CruxLogger(_type, _level) { if (this instanceof CruxLogger) { Component.apply(this, arguments); this.name = 'log'; var hasColors = this.config.colors; delete this.config.colors; if (!hasColors) { for (var i = 0; i < this.config.appenders.length; i++) { this.config.appenders[i].layout = { type: 'basic' } } } log4js.configure(this.config); this.__logger = log4js.getLogger(); this.__logger.setLevel(this.config.level.toUpperCase()); global['log'] = this.__logger; } else { // In case we just called crux.Log(), we just want to return an instance of log4js this.__logger = log4js.getLogger(_type || 'default'); if (typeof _level === 'string') { this.__logger.setLevel(_level); } return this.__logger; } }
javascript
{ "resource": "" }
q10364
groupDelta
train
function groupDelta(nodes, callback) { async.eachLimit(nodes, 10, (node, cb) => { if(node.path === null) { // if node.path is null we have to skip the node logger.info('Remote Delta: Got node with path equal null', {node}); return cb(null); } const query = {remoteId: node.id, path: node.path}; ignoreDb.isIgnoredNode(query, (err, isIgnored) => { if(err) return cb(err); if(isIgnored) return cb(null); groupNode(node); cb(null); }); }, callback); }
javascript
{ "resource": "" }
q10365
groupNode
train
function groupNode(node) { node.parent = node.parent || ''; if(groupedDelta[node.id] === undefined) { groupedDelta[node.id] = { id: node.id, directory: node.directory, actions: {} }; } else if(groupedDelta[node.id].directory === undefined && node.directory !== undefined) { // Since balloon v2.1.0 action: directory is undefined for delete actions groupedDelta[node.id].directory = node.directory; } var groupedNode = groupedDelta[node.id]; if(node.deleted !==false && node.deleted !== undefined) { //in rare cases node.deleted might be a timestamp groupedNode.actions.delete = node; } else { groupedNode.actions.create = node; groupedNode.parent = node.parent; if(node.directory === false) { groupedNode.version = node.version; groupedNode.hash = node.hash; groupedNode.size = node.size; } } }
javascript
{ "resource": "" }
q10366
train
function(cursor, callback) { groupedDelta = {}; async.series([ (cb) => { logger.info('Fetching delta', {category: 'sync-remote-delta'}); fetchDelta({cursor}, (err, newCursor) => { if(err) return cb(err); cb(null, newCursor); }); }, (cb) => { logger.info('Applying collections which need to be redownloaded', {category: 'sync-remote-delta'}); syncDb.find({$and: [{directory: true}, {downloadOriginal: true}]}, (err, syncedNodes) => { if(err) return cb(err); if(!syncedNodes) return cb(null); async.map(syncedNodes, (syncedNode, mapCb) => { if(!syncedNode.remoteId) mapCb(null); fetchDelta({id: syncedNode.remoteId}, mapCb); }, cb); }); } ], (err, results) => { logger.info('getDelta ended', {category: 'sync-remote-delta'}); callback(err, results[0]); }); }
javascript
{ "resource": "" }
q10367
use
train
function use(type, fn, options) { if (typeof type === 'string' || Array.isArray(type)) { fn = wrap(type, fn); } else { options = fn; fn = type; } var val = fn.call(this, this, this.base || {}, options || {}, this.env || {}); if (typeof val === 'function') { this.fns.push(val); } if (typeof this.emit === 'function') { this.emit('use', val, this); } return this; }
javascript
{ "resource": "" }
q10368
train
function(entry, options) { if (options.isClass) return options.isClass(entry); var tags = entry.tags; for(var k = 0; k < tags.length; k++) { if(tags[k].type == 'class') return true; } return false; }
javascript
{ "resource": "" }
q10369
assertAsDefined
train
function assertAsDefined(obj, errorMsg) { if (_.isUndefined(obj) || _.isNull(obj)) { throw new Error(errorMsg); } }
javascript
{ "resource": "" }
q10370
hasDotNesting
train
function hasDotNesting(string) { const loc = string.indexOf('.'); return (loc !== -1) && (loc !== 0) && (loc !== string.length - 1); }
javascript
{ "resource": "" }
q10371
substrAtNthOccurence
train
function substrAtNthOccurence(string, start, delimiter) { const _delimiter = getValueWithDefault(delimiter, '.'); const _start = getValueWithDefault(start, 1); const tokens = string.split(_delimiter).slice(_start); return tokens.join(_delimiter); }
javascript
{ "resource": "" }
q10372
chineseRemainder_bignum
train
function chineseRemainder_bignum(a, n){ var p = bignum(1); var p1 = bignum(1); var prod = bignum(1); var i = 1; var sm = bignum(0); for(i=0; i< n.length; i++){ prod = prod.mul( n[i] ); //prod = prod * n[i]; } for(i=0; i< n.length; i++){ p = prod.div( n[i] ); //sm = sm + ( a[i] * mul_inv(p, n[i]) * p); p1 = mul_inv( p, n[i] ); p1 = p1.mul( a[i] ); p1 = p1.mul( p ); sm = sm.add( p1 ); } return sm.mod(prod); }
javascript
{ "resource": "" }
q10373
Arc
train
function Arc(start, end, height) { this.start = start; this.end = end; this.height = height; }
javascript
{ "resource": "" }
q10374
cleanStyles
train
function cleanStyles(e) { if (!e) return; // Remove any root styles, if we're able. if (typeof e.removeAttribute == 'function' && e.className != 'readability-styled') e.removeAttribute('style'); // Go until there are no more child nodes var cur = e.firstChild; while (cur) { if (cur.nodeType == 1) { // Remove style attribute(s) : if (cur.className != "readability-styled") { cur.removeAttribute("style"); } cleanStyles(cur); } cur = cur.nextSibling; } }
javascript
{ "resource": "" }
q10375
getCharCount
train
function getCharCount(e, s) { s = s || ","; return getInnerText(e).split(s).length; }
javascript
{ "resource": "" }
q10376
fixLinks
train
function fixLinks(e) { if (!e.ownerDocument.originalURL) { return; } function fixLink(link) { var fixed = url.resolve(e.ownerDocument.originalURL, link); return fixed; } var i; var imgs = e.getElementsByTagName('img'); for (i = imgs.length - 1; i >= 0; --i) { var src = imgs[i].getAttribute('src'); if (src) { imgs[i].setAttribute('src', fixLink(src)); } } var as = e.getElementsByTagName('a'); for (i = as.length - 1; i >= 0; --i) { var href = as[i].getAttribute('href'); if (href) { as[i].setAttribute('href', fixLink(href)); } } }
javascript
{ "resource": "" }
q10377
cleanSingleHeader
train
function cleanSingleHeader(e) { for (var headerIndex = 1; headerIndex < 7; headerIndex++) { var headers = e.getElementsByTagName('h' + headerIndex); for (var i = headers.length - 1; i >= 0; --i) { if (headers[i].nextSibling === null) { headers[i].parentNode.removeChild(headers[i]); } } } }
javascript
{ "resource": "" }
q10378
Snippet
train
function Snippet(file) { if (!(this instanceof Snippet)) { return new Snippet(file); } if (typeof file === 'string') { file = {path: file}; } this.history = []; if (typeof file === 'object') { this.visit('set', file); } this.cwd = this.cwd || process.cwd(); this.content = this.content || null; this.options = this.options || {}; }
javascript
{ "resource": "" }
q10379
train
function (prop, val) { if (arguments.length === 1) { if (typeof prop === 'string') { return utils.get(this.options, prop); } if (typeof prop === 'object') { return this.visit('option', prop); } } utils.set(this.options, prop, val); return this; }
javascript
{ "resource": "" }
q10380
train
function (fp) { if (this.content) return this; fp = path.resolve(this.cwd, fp || this.path); this.content = utils.tryRead(fp); return this; }
javascript
{ "resource": "" }
q10381
train
function (val, opts) { if (typeof val === 'function') { return new Snippet(val(this)); } if (typeof val === 'string') { var str = utils.tryRead(val); var res = {content: null, options: opts || {}}; if (str) { res.path = val; res.content = str.toString(); } else { res.content = val; } return new Snippet(res); } if (val instanceof Snippet) { val.option(opts); return val; } if (typeof val === 'object') { val.options = extend({}, val.options, opts); return new Snippet(val); } }
javascript
{ "resource": "" }
q10382
train
function (fp, options) { if (typeof fp === 'function') { return fp.call(this, this.path); } var opts = extend({}, this.options, options); if (typeof fp === 'object') { opts = extend({}, opts, fp); } if (typeof fp === 'string' && ~fp.indexOf(':')) { fp = fp.replace(/:(\w+)/g, function (m, prop) { return opts[prop] || this[prop] || m; }.bind(this)); } this.path = this.path || fp; var base = opts.base || this.base || path.dirname(fp); var name = opts.basename || this.relative || this.basename; var ext = opts.ext || this.extname || path.extname(fp); if (typeof fp === 'string' && fp[fp.length - 1] === '/') { base = fp; } var dest = path.join(base, utils.rewrite(name, ext)); if (dest.slice(-1) === '.') { dest = dest.slice(0, dest.length - 1) + ext; } return dest; }
javascript
{ "resource": "" }
q10383
train
function (fp, opts, cb) { if (typeof fp !== 'string') { cb = opts; opts = fp; fp = null; } if (typeof opts === 'function') { cb = opts; opts = {}; } if (typeof cb !== 'function') { throw new Error('expected a callback function.'); } var dest = this.dest(fp || this.path, opts); var file = { contents: this.content, path: dest }; opts = extend({ ask: true }, this.options, opts); utils.detect(file, opts, function (err) { if (file.contents) { utils.write(dest, file.contents, cb); } else { this.copy(dest, cb); } return this; }.bind(this)); return this; }
javascript
{ "resource": "" }
q10384
splitImportsList
train
function splitImportsList(text) { const list = []; list.push(...text .split(',') .map(s => s.trim()) .filter(s => s !== '') ); return list; }
javascript
{ "resource": "" }
q10385
goToNext
train
function goToNext() { count++; if (count === _.size(config)) { grunt.log.writeln(''); // line break grunt.log.ok('Ignored: %d', countIgnored); grunt.log.ok('Excluded: %d', countExcluded); grunt.log.ok('Processed: %d', countProcessed); done(); } }
javascript
{ "resource": "" }
q10386
train
function() { this.top = '' this.stack = [] this.caret = false this.vowels = [] this.finals = [] this.finals_found = newHashMap() this.visarga = false this.cons_str = '' this.single_cons = '' this.prefix = false this.suffix = false this.suff2 = false this.dot = false this.tokens_used = 0 this.warns = [] return this }
javascript
{ "resource": "" }
q10387
train
function(str) { var tokens = [] // size = str.length + 2 var i = 0; var maxlen = str.length; TOKEN: while (i < maxlen) { var c = str.charAt(i); var mlo = m_tokens_start.get(c); // if there are multi-char tokens starting with this char, try them if (mlo != null) { for (var len = mlo; len > 1; len--) { if (i <= maxlen - len) { var tr = str.substring(i, i + len); if (m_tokens.contains(tr)) { tokens.push(tr); i += len; continue TOKEN; } } } } // things starting with backslash are special if (c == '\\' && i <= maxlen - 2) { if (str.charAt(i + 1) == 'u' && i <= maxlen - 6) { tokens.push(str.substring(i, i + 6)); // \\uxxxx i += 6; } else if (str.charAt(i + 1) == 'U' && i <= maxlen - 10) { tokens.push(str.substring(i, i + 10)); // \\Uxxxxxxxx i += 10; } else { tokens.push(str.substring(i, i + 2)); // \\x i += 2; } continue TOKEN; } // otherwise just take one char tokens.push(c.toString()); i += 1; } return tokens; }
javascript
{ "resource": "" }
q10388
validHex
train
function validHex(t) { for (var i = 0; i < t.length; i++) { var c = t.charAt(i); if (!((c >= 'a' && c <= 'f') || (c >= '0' && c <= '9'))) return false; } return true; }
javascript
{ "resource": "" }
q10389
unicodeEscape
train
function unicodeEscape (warns, line, t) { // [], int, str var hex = t.substring(2); if (hex == '') return null; if (!validHex(hex)) { warnl(warns, line, "\"" + t + "\": invalid hex code."); return ""; } return String.fromCharCode(parseInt(hex, 16)) }
javascript
{ "resource": "" }
q10390
formatHex
train
function formatHex(t) { //char // not compatible with GWT... // return String.format("\\u%04x", (int)t); var sb = ''; sb += '\\u'; var s = t.charCodeAt(0).toString(16); for (var i = s.length; i < 4; i++) sb += '0'; sb += s; return sb; }
javascript
{ "resource": "" }
q10391
putStackTogether
train
function putStackTogether(st) { var out = ''; // put the main elements together... stacked with "+" unless it's a regular stack if (tib_stack(st.cons_str)) { out += st.stack.join(""); } else out += (st.cons_str); // caret (tsa-phru) goes here as per some (halfway broken) Unicode specs... if (st.caret) out += ("^"); // vowels... if (st.vowels.length > 0) { out += st.vowels.join("+"); } else if (!st.prefix && !st.suffix && !st.suff2 && (st.cons_str.length == 0 || st.cons_str.charAt(st.cons_str.length - 1) != 'a')) { out += "a" } // final stuff out += st.finals.join(""); if (st.dot) out += "."; return out; }
javascript
{ "resource": "" }
q10392
error
train
function error(msg) { if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.errors) { console.log('Error: ' + msg); console.log(backtrace()); } UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown); throw new Error(msg); }
javascript
{ "resource": "" }
q10393
PDFPageProxy_render
train
function PDFPageProxy_render(params) { var stats = this.stats; stats.time('Overall'); // If there was a pending destroy cancel it so no cleanup happens during // this call to render. this.pendingDestroy = false; var renderingIntent = (params.intent === 'print' ? 'print' : 'display'); if (!this.intentStates[renderingIntent]) { this.intentStates[renderingIntent] = {}; } var intentState = this.intentStates[renderingIntent]; // If there's no displayReadyCapability yet, then the operatorList // was never requested before. Make the request and create the promise. if (!intentState.displayReadyCapability) { intentState.receivingOperatorList = true; intentState.displayReadyCapability = createPromiseCapability(); intentState.operatorList = { fnArray: [], argsArray: [], lastChunk: false }; this.stats.time('Page Request'); this.transport.messageHandler.send('RenderPageRequest', { pageIndex: this.pageNumber - 1, intent: renderingIntent }); } var internalRenderTask = new InternalRenderTask(complete, params, this.objs, this.commonObjs, intentState.operatorList, this.pageNumber); internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print'; if (!intentState.renderTasks) { intentState.renderTasks = []; } intentState.renderTasks.push(internalRenderTask); var renderTask = internalRenderTask.task; // Obsolete parameter support if (params.continueCallback) { renderTask.onContinue = params.continueCallback; } var self = this; intentState.displayReadyCapability.promise.then( function pageDisplayReadyPromise(transparency) { if (self.pendingDestroy) { complete(); return; } stats.time('Rendering'); internalRenderTask.initalizeGraphics(transparency); internalRenderTask.operatorListChanged(); }, function pageDisplayReadPromiseError(reason) { complete(reason); } ); function complete(error) { var i = intentState.renderTasks.indexOf(internalRenderTask); if (i >= 0) { intentState.renderTasks.splice(i, 1); } if (self.cleanupAfterRender) { self.pendingDestroy = true; } self._tryDestroy(); if (error) { internalRenderTask.capability.reject(error); } else { internalRenderTask.capability.resolve(); } stats.timeEnd('Rendering'); stats.timeEnd('Overall'); } return renderTask; }
javascript
{ "resource": "" }
q10394
PDFPageProxy__destroy
train
function PDFPageProxy__destroy() { if (!this.pendingDestroy || Object.keys(this.intentStates).some(function(intent) { var intentState = this.intentStates[intent]; return (intentState.renderTasks.length !== 0 || intentState.receivingOperatorList); }, this)) { return; } Object.keys(this.intentStates).forEach(function(intent) { delete this.intentStates[intent]; }, this); this.objs.clear(); this.annotationsPromise = null; this.pendingDestroy = false; }
javascript
{ "resource": "" }
q10395
PDFPageProxy_renderPageChunk
train
function PDFPageProxy_renderPageChunk(operatorListChunk, intent) { var intentState = this.intentStates[intent]; var i, ii; // Add the new chunk to the current operator list. for (i = 0, ii = operatorListChunk.length; i < ii; i++) { intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]); intentState.operatorList.argsArray.push( operatorListChunk.argsArray[i]); } intentState.operatorList.lastChunk = operatorListChunk.lastChunk; // Notify all the rendering tasks there are more operators to be consumed. for (i = 0; i < intentState.renderTasks.length; i++) { intentState.renderTasks[i].operatorListChanged(); } if (operatorListChunk.lastChunk) { intentState.receivingOperatorList = false; this._tryDestroy(); } }
javascript
{ "resource": "" }
q10396
PDFObjects_getData
train
function PDFObjects_getData(objId) { var objs = this.objs; if (!objs[objId] || !objs[objId].resolved) { return null; } else { return objs[objId].data; } }
javascript
{ "resource": "" }
q10397
pf
train
function pf(value) { if (value === (value | 0)) { // integer number return value.toString(); } var s = value.toFixed(10); var i = s.length - 1; if (s[i] !== '0') { return s; } // removing trailing zeros do { i--; } while (s[i] === '0'); return s.substr(0, s[i] === '.' ? i : i + 1); }
javascript
{ "resource": "" }
q10398
pm
train
function pm(m) { if (m[4] === 0 && m[5] === 0) { if (m[1] === 0 && m[2] === 0) { if (m[0] === 1 && m[3] === 1) { return ''; } return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')'; } if (m[0] === m[3] && m[1] === -m[2]) { var a = Math.acos(m[0]) * 180 / Math.PI; return 'rotate(' + pf(a) + ')'; } } else { if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) { return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')'; } } return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' + pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')'; }
javascript
{ "resource": "" }
q10399
train
function() { // Path to apis.js file var apis_js = path.join(__dirname, '../src', 'apis.js'); // Create content // Use json-stable-stringify rather than JSON.stringify to guarantee // consistent ordering (see http://bugzil.la/1200519) var content = "/* eslint-disable */\nmodule.exports = " + stringify(apis, { space: ' ' }) + ";"; fs.writeFileSync(apis_js, content, {encoding: 'utf-8'}); }
javascript
{ "resource": "" }