_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q47500
|
traverseTopDown
|
train
|
function traverseTopDown(fn) {
var result, i;
result = fn.call(this);
if(result)
return result;
if (this instanceof tree.ConsNode || this instanceof tree.ListNode) {
for (i = 0; i < this.length; i++) {
traverseTopDown.call(this[i], fn);
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q47501
|
ConsNode
|
train
|
function ConsNode(cons, children) {
this.cons = cons;
for(var i = 0; i < children.length; i++) {
this[i] = children[i];
}
this.length = children.length;
}
|
javascript
|
{
"resource": ""
}
|
q47502
|
findNodeAround
|
train
|
function findNodeAround(node, pos, test, base, state) {
test = makeTest(test);
if (!base) base = exports.base;
try {
;(function c(node, st, override) {
var type = override || node.type;
if (node.start > pos || node.end < pos) return;
base[type](node, st, c);
if (test(type, node)) throw new Found(node, st);
})(node, state);
} catch (e) {
if (e instanceof Found) return e;
throw e;
}
}
|
javascript
|
{
"resource": ""
}
|
q47503
|
isIdentifierChar
|
train
|
function isIdentifierChar(code, astral) {
if (code < 48) return code === 36;
if (code < 58) return true;
if (code < 65) return false;
if (code < 91) return true;
if (code < 97) return code === 95;
if (code < 123) return true;
return code >= 0xaa;
}
|
javascript
|
{
"resource": ""
}
|
q47504
|
parseExpressionAt
|
train
|
function parseExpressionAt(input, pos, options) {
var p = new _state.Parser(options, input, pos);
p.nextToken();
return p.parseExpression();
}
|
javascript
|
{
"resource": ""
}
|
q47505
|
finishNodeAt
|
train
|
function finishNodeAt(node, type, pos, loc) {
node.type = type;
node.end = pos;
if (this.options.locations) node.loc.end = loc;
if (this.options.ranges) node.range[1] = pos;
return node;
}
|
javascript
|
{
"resource": ""
}
|
q47506
|
getOptions
|
train
|
function getOptions(opts) {
var options = {};
for (var opt in defaultOptions) {
options[opt] = opts && _util.has(opts, opt) ? opts[opt] : defaultOptions[opt];
}if (options.allowReserved == null) options.allowReserved = options.ecmaVersion < 5;
if (_util.isArray(options.onToken)) {
(function () {
var tokens = options.onToken;
options.onToken = function (token) {
return tokens.push(token);
};
})();
}
if (_util.isArray(options.onComment)) options.onComment = pushComment(options, options.onComment);
return options;
}
|
javascript
|
{
"resource": ""
}
|
q47507
|
Token
|
train
|
function Token(p) {
this.type = p.type;
this.value = p.value;
this.start = p.start;
this.end = p.end;
if (p.options.locations) this.loc = new _locutil.SourceLocation(p, p.startLoc, p.endLoc);
if (p.options.ranges) this.range = [p.start, p.end];
}
|
javascript
|
{
"resource": ""
}
|
q47508
|
_minWidth
|
train
|
function _minWidth (col) {
var padding = col.padding || []
var minWidth = 1 + (padding[left] || 0) + (padding[right] || 0)
if (col.border) minWidth += 4
return minWidth
}
|
javascript
|
{
"resource": ""
}
|
q47509
|
measure
|
train
|
function measure(test, done) {
var start = now();
test(function (error, results) {
var stop = now();
done(error, results, stop - start);
});
}
|
javascript
|
{
"resource": ""
}
|
q47510
|
sample
|
train
|
function sample(test, asap, minDuration, sampleSize, done) {
var count = 0;
var totalDuration = 0;
var sampleDurations = [];
next();
function next() {
measure(function (done) {
test(asap, done);
}, function (error, results, duration) {
if (error) {
done(error);
}
if (sampleDurations.length < sampleSize) {
sampleDurations.push(duration);
} else if (Math.random() < 1 / count) {
sampleDurations.splice(Math.floor(Math.random() * sampleDurations.length), 1);
sampleDurations.push(duration);
}
totalDuration += duration;
count++;
if (totalDuration >= minDuration) {
done(null, {
name: test.name,
subjectName: asap.name,
count: count,
totalDuration: totalDuration,
averageFrequency: count / totalDuration,
averageDuration: totalDuration / count,
averageOpsHz: count / totalDuration,
sampleDurations: sampleDurations
});
} else {
next();
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
q47511
|
assertOut
|
train
|
function assertOut(key, expected, result) {
var actual = result[key];
var statement = expected instanceof RegExp
? expected.test(actual)
: expected === actual;
if (statement !== true) {
var message = 'Expected ' + key +' to match "' + expected + '". Actual: "' + actual + '"';
return error(result, message, expected, actual);
}
}
|
javascript
|
{
"resource": ""
}
|
q47512
|
error
|
train
|
function error(result, message, expected, actual) {
var err = new AssertionError('`' + result.cmd + '`: ' + message);
err.result = result;
if (expected) err.expected = expected;
if (actual) err.actual = actual;
return err;
}
|
javascript
|
{
"resource": ""
}
|
q47513
|
Result
|
train
|
function Result(cmd, code, options) {
options = options || {};
this.options = options;
this.code = code;
this.cmd = cmd;
}
|
javascript
|
{
"resource": ""
}
|
q47514
|
Runner
|
train
|
function Runner(options) {
if (!(this instanceof Runner)) return new Runner(options);
options = options || {};
this.options = options;
this.batch = new Batch;
this.world = new World;
this.expectations = [];
this.prompts = [];
this.responses = [];
this.baseCmd = '';
this.standardInput = null;
}
|
javascript
|
{
"resource": ""
}
|
q47515
|
World
|
train
|
function World(env, cwd) {
this.env = env || clone(process.env);
this.cwd = cwd;
this.timeout = null;
}
|
javascript
|
{
"resource": ""
}
|
q47516
|
cloneCounterValues
|
train
|
function cloneCounterValues(counters) {
const result = {};
Object.keys(counters).forEach(name => {
result[name] = Array.from(counters[name]);
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q47517
|
flattenTree
|
train
|
function flattenTree(root) {
let newChildren = [];
root.children.forEach(child => {
const commonParent = getDeepMoreThenOneChild(child);
if (commonParent.children.length === 0) {
newChildren.push(commonParent);
} else {
newChildren = newChildren.concat(commonParent.children);
}
});
root.children = newChildren;
}
|
javascript
|
{
"resource": ""
}
|
q47518
|
normaliseDeps
|
train
|
function normaliseDeps (deps) {
if (Array.isArray(deps)) {
deps = deps.reduce(function (d, depName) {
d[depName] = '*'
return d
}, {})
}
return deps
}
|
javascript
|
{
"resource": ""
}
|
q47519
|
printWarnings
|
train
|
function printWarnings (deps, type) {
if (!Object.keys(deps).length) return
var warnings = {
E404: {title: 'Unregistered', list: []},
ESCM: {title: 'SCM', list: []},
EDEPTYPE: {title: 'Non-string dependency', list: []}
}
for (var name in deps) {
var dep = deps[name]
if (dep.warn) {
warnings[dep.warn.code].list.push([clc.magenta(name), clc.red(dep.warn.toString())])
}
}
Object.keys(warnings).forEach(function (warnType) {
var warnList = warnings[warnType].list
if (!warnList.length) return
var table = new Table({head: ['Name', 'Message'], style: {head: ['reset']}})
console.log(clc.underline(warnings[warnType].title + ' ' + (type ? type + 'D' : 'd') + 'ependencies') + '\n')
warnList.forEach(function (row) { table.push(row) })
console.log(table.toString() + '\n')
})
}
|
javascript
|
{
"resource": ""
}
|
q47520
|
getUpdatedDeps
|
train
|
function getUpdatedDeps (pkg, cb) {
var opts = {
stable: !argv.unstable,
loose: true,
error: {
E404: argv.error404,
ESCM: argv.errorSCM,
EDEPTYPE: argv.errorDepType
},
ignore: argv.ignore || argv.i
}
if (argv.registry) {
opts.npm = {registry: argv.registry}
}
david.getUpdatedDependencies(pkg, opts, function (err, deps) {
if (err) return cb(err)
david.getUpdatedDependencies(pkg, xtend(opts, {dev: true}), function (err, devDeps) {
if (err) return cb(err)
david.getUpdatedDependencies(pkg, xtend(opts, {optional: true}), function (err, optionalDeps) {
cb(err, filterDeps(deps), filterDeps(devDeps), filterDeps(optionalDeps))
})
})
})
}
|
javascript
|
{
"resource": ""
}
|
q47521
|
installDeps
|
train
|
function installDeps (deps, opts, cb) {
opts = opts || {}
var depNames = Object.keys(deps)
// Nothing to install!
if (!depNames.length) {
return cb(null)
}
depNames = depNames.filter(function (depName) {
return !deps[depName].warn
})
var npmOpts = {global: opts.global}
// Avoid warning message from npm for invalid registry url
if (opts.registry) {
npmOpts.registry = opts.registry
}
npm.load(npmOpts, function (err) {
if (err) return cb(err)
if (opts.save) {
npm.config.set('save' + (opts.dev ? '-dev' : opts.optional ? '-optional' : ''), true)
}
var installArgs = [depNames.map(function (depName) {
return depName + '@' + deps[depName][argv.unstable ? 'latest' : 'stable']
}), function (err) {
npm.config.set('save' + (opts.dev ? '-dev' : opts.optional ? '-optional' : ''), false)
cb(err)
}]
if (opts.path) { installArgs.unshift(opts.path) }
npm.commands.install.apply(npm.commands, installArgs)
})
}
|
javascript
|
{
"resource": ""
}
|
q47522
|
isScm
|
train
|
function isScm (version) {
var scmPrefixes = ['git:', 'git+ssh:', 'https:', 'git+https:']
var blacklisted = scmPrefixes.filter(function (prefix) {
return version.indexOf(prefix) === 0
})
return !!blacklisted.length
}
|
javascript
|
{
"resource": ""
}
|
q47523
|
train
|
function() {
if (!started) {
// Since the application doesn't start running immediately, track
// whether this function was called and use that to keep it from
// starting the main loop multiple times.
started = true;
// In the main loop, draw() is called after update(), so if we
// entered the main loop immediately, we would never render the
// initial state before any updates occur. Instead, we run one
// frame where all we do is draw, and then start the main loop with
// the next frame.
rafHandle = requestAnimationFrame(function(timestamp) {
// Render the initial state before any updates occur.
draw(1);
// The application isn't considered "running" until the
// application starts drawing.
running = true;
// Reset variables that are used for tracking time so that we
// don't simulate time passed while the application was paused.
lastFrameTimeMs = timestamp;
lastFpsUpdate = timestamp;
framesSinceLastFpsUpdate = 0;
// Start the main loop.
rafHandle = requestAnimationFrame(animate);
});
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q47524
|
animate
|
train
|
function animate(timestamp) {
// Run the loop again the next time the browser is ready to render.
// We set rafHandle immediately so that the next frame can be canceled
// during the current frame.
rafHandle = requestAnimationFrame(animate);
// Throttle the frame rate (if minFrameDelay is set to a non-zero value by
// `MainLoop.setMaxAllowedFPS()`).
if (timestamp < lastFrameTimeMs + minFrameDelay) {
return;
}
// frameDelta is the cumulative amount of in-app time that hasn't been
// simulated yet. Add the time since the last frame. We need to track total
// not-yet-simulated time (as opposed to just the time elapsed since the
// last frame) because not all actually elapsed time is guaranteed to be
// simulated each frame. See the comments below for details.
frameDelta += timestamp - lastFrameTimeMs;
lastFrameTimeMs = timestamp;
// Run any updates that are not dependent on time in the simulation. See
// `MainLoop.setBegin()` for additional details on how to use this.
begin(timestamp, frameDelta);
// Update the estimate of the frame rate, `fps`. Approximately every
// second, the number of frames that occurred in that second are included
// in an exponential moving average of all frames per second. This means
// that more recent seconds affect the estimated frame rate more than older
// seconds.
if (timestamp > lastFpsUpdate + fpsUpdateInterval) {
// Compute the new exponential moving average.
fps =
// Divide the number of frames since the last FPS update by the
// amount of time that has passed to get the mean frames per second
// over that period. This is necessary because slightly more than a
// second has likely passed since the last update.
fpsAlpha * framesSinceLastFpsUpdate * 1000 / (timestamp - lastFpsUpdate) +
(1 - fpsAlpha) * fps;
// Reset the frame counter and last-updated timestamp since their
// latest values have now been incorporated into the FPS estimate.
lastFpsUpdate = timestamp;
framesSinceLastFpsUpdate = 0;
}
// Count the current frame in the next frames-per-second update. This
// happens after the previous section because the previous section
// calculates the frames that occur up until `timestamp`, and `timestamp`
// refers to a time just before the current frame was delivered.
framesSinceLastFpsUpdate++;
/*
* A naive way to move an object along its X-axis might be to write a main
* loop containing the statement `obj.x += 10;` which would move the object
* 10 units per frame. This approach suffers from the issue that it is
* dependent on the frame rate. In other words, if your application is
* running slowly (that is, fewer frames per second), your object will also
* appear to move slowly, whereas if your application is running quickly
* (that is, more frames per second), your object will appear to move
* quickly. This is undesirable, especially in multiplayer/multi-user
* applications.
*
* One solution is to multiply the speed by the amount of time that has
* passed between rendering frames. For example, if you want your object to
* move 600 units per second, you might write `obj.x += 600 * delta`, where
* `delta` is the time passed since the last frame. (For convenience, let's
* move this statement to an update() function that takes `delta` as a
* parameter.) This way, your object will move a constant distance over
* time. However, at low frame rates and high speeds, your object will move
* large distances every frame, which can cause it to do strange things
* such as move through walls. Additionally, we would like our program to
* be deterministic. That is, every time we run the application with the
* same input, we would like exactly the same output. If the time between
* frames (the `delta`) varies, our output will diverge the longer the
* program runs due to accumulated rounding errors, even at normal frame
* rates.
*
* A better solution is to separate the amount of time simulated in each
* update() from the amount of time between frames. Our update() function
* doesn't need to change; we just need to change the delta we pass to it
* so that each update() simulates a fixed amount of time (that is, `delta`
* should have the same value each time update() is called). The update()
* function can be run multiple times per frame if needed to simulate the
* total amount of time passed since the last frame. (If the time that has
* passed since the last frame is less than the fixed simulation time, we
* just won't run an update() until the the next frame. If there is
* unsimulated time left over that is less than our timestep, we'll just
* leave it to be simulated during the next frame.) This approach avoids
* inconsistent rounding errors and ensures that there are no giant leaps
* through walls between frames.
*
* That is what is done below. It introduces a new problem, but it is a
* manageable one: if the amount of time spent simulating is consistently
* longer than the amount of time between frames, the application could
* freeze and crash in a spiral of death. This won't happen as long as the
* fixed simulation time is set to a value that is high enough that
* update() calls usually take less time than the amount of time they're
* simulating. If it does start to happen anyway, see `MainLoop.setEnd()`
* for a discussion of ways to stop it.
*
* Additionally, see `MainLoop.setUpdate()` for a discussion of performance
* considerations.
*
* Further reading for those interested:
*
* - http://gameprogrammingpatterns.com/game-loop.html
* - http://gafferongames.com/game-physics/fix-your-timestep/
* - https://gamealchemist.wordpress.com/2013/03/16/thoughts-on-the-javascript-game-loop/
* - https://developer.mozilla.org/en-US/docs/Games/Anatomy
*/
numUpdateSteps = 0;
while (frameDelta >= simulationTimestep) {
update(simulationTimestep);
frameDelta -= simulationTimestep;
/*
* Sanity check: bail if we run the loop too many times.
*
* One way this could happen is if update() takes longer to run than
* the time it simulates, thereby causing a spiral of death. For ways
* to avoid this, see `MainLoop.setEnd()`. Another way this could
* happen is if the browser throttles serving frames, which typically
* occurs when the tab is in the background or the device battery is
* low. An event outside of the main loop such as audio processing or
* synchronous resource reads could also cause the application to hang
* temporarily and accumulate not-yet-simulated time as a result.
*
* 240 is chosen because, for any sane value of simulationTimestep, 240
* updates will simulate at least one second, and it will simulate four
* seconds with the default value of simulationTimestep. (Safari
* notifies users that the script is taking too long to run if it takes
* more than five seconds.)
*
* If there are more updates to run in a frame than this, the
* application will appear to slow down to the user until it catches
* back up. In networked applications this will usually cause the user
* to get out of sync with their peers, but if the updates are taking
* this long already, they're probably already out of sync.
*/
if (++numUpdateSteps >= 240) {
panic = true;
break;
}
}
/*
* Render the screen. We do this regardless of whether update() has run
* during this frame because it is possible to interpolate between updates
* to make the frame rate appear faster than updates are actually
* happening. See `MainLoop.setDraw()` for an explanation of how to do
* that.
*
* We draw after updating because we want the screen to reflect a state of
* the application that is as up-to-date as possible. (`MainLoop.start()`
* draws the very first frame in the application's initial state, before
* any updates have occurred.) Some sources speculate that rendering
* earlier in the requestAnimationFrame callback can get the screen painted
* faster; this is mostly not true, and even when it is, it's usually just
* a trade-off between rendering the current frame sooner and rendering the
* next frame later.
*
* See `MainLoop.setDraw()` for details about draw() itself.
*/
draw(frameDelta / simulationTimestep);
// Run any updates that are not dependent on time in the simulation. See
// `MainLoop.setEnd()` for additional details on how to use this.
end(fps, panic);
panic = false;
}
|
javascript
|
{
"resource": ""
}
|
q47525
|
build
|
train
|
function build (obj, opts) {
var XMLHDR = {
version: '1.0',
encoding: 'UTF-8'
};
var XMLDTD = {
pubid: '-//Apple//DTD PLIST 1.0//EN',
sysid: 'http://www.apple.com/DTDs/PropertyList-1.0.dtd'
};
var doc = xmlbuilder.create('plist');
doc.dec(XMLHDR.version, XMLHDR.encoding, XMLHDR.standalone);
doc.dtd(XMLDTD.pubid, XMLDTD.sysid);
doc.att('version', '1.0');
walk_obj(obj, doc);
if (!opts) opts = {};
// default `pretty` to `true`
opts.pretty = opts.pretty !== false;
return doc.end(opts);
}
|
javascript
|
{
"resource": ""
}
|
q47526
|
walk_obj
|
train
|
function walk_obj(next, next_child) {
var tag_type, i, prop;
var name = type(next);
if ('Undefined' == name) {
return;
} else if (Array.isArray(next)) {
next_child = next_child.ele('array');
for (i = 0; i < next.length; i++) {
walk_obj(next[i], next_child);
}
} else if (Buffer.isBuffer(next)) {
next_child.ele('data').raw(next.toString('base64'));
} else if ('Object' == name) {
next_child = next_child.ele('dict');
for (prop in next) {
if (next.hasOwnProperty(prop)) {
next_child.ele('key').txt(prop);
walk_obj(next[prop], next_child);
}
}
} else if ('Number' == name) {
// detect if this is an integer or real
// TODO: add an ability to force one way or another via a "cast"
tag_type = (next % 1 === 0) ? 'integer' : 'real';
next_child.ele(tag_type).txt(next.toString());
} else if ('Date' == name) {
next_child.ele('date').txt(ISODateString(new Date(next)));
} else if ('Boolean' == name) {
next_child.ele(next ? 'true' : 'false');
} else if ('String' == name) {
next_child.ele('string').txt(next);
} else if ('ArrayBuffer' == name) {
next_child.ele('data').raw(base64.fromByteArray(next));
} else if (next && next.buffer && 'ArrayBuffer' == type(next.buffer)) {
// a typed array
next_child.ele('data').raw(base64.fromByteArray(new Uint8Array(next.buffer), next_child));
}
}
|
javascript
|
{
"resource": ""
}
|
q47527
|
disableAll
|
train
|
function disableAll(win) {
debug(`Disabling all shortcuts on window ${title(win)}`);
const wc = win.webContents;
const shortcutsOfWindow = windowsWithShortcuts.get(wc);
for (const shortcut of shortcutsOfWindow) {
shortcut.enabled = false;
}
}
|
javascript
|
{
"resource": ""
}
|
q47528
|
enableAll
|
train
|
function enableAll(win) {
debug(`Enabling all shortcuts on window ${title(win)}`);
const wc = win.webContents;
const shortcutsOfWindow = windowsWithShortcuts.get(wc);
for (const shortcut of shortcutsOfWindow) {
shortcut.enabled = true;
}
}
|
javascript
|
{
"resource": ""
}
|
q47529
|
unregisterAll
|
train
|
function unregisterAll(win) {
debug(`Unregistering all shortcuts on window ${title(win)}`);
const wc = win.webContents;
const shortcutsOfWindow = windowsWithShortcuts.get(wc);
// Remove listener from window
shortcutsOfWindow.removeListener();
windowsWithShortcuts.delete(wc);
}
|
javascript
|
{
"resource": ""
}
|
q47530
|
register
|
train
|
function register(win, accelerator, callback) {
let wc;
if (typeof callback === 'undefined') {
wc = ANY_WINDOW;
callback = accelerator;
accelerator = win;
} else {
wc = win.webContents;
}
if (Array.isArray(accelerator) === true) {
accelerator.forEach(accelerator => {
if (typeof accelerator === 'string') {
register(win, accelerator, callback);
}
});
return;
}
debug(`Registering callback for ${accelerator} on window ${title(win)}`);
_checkAccelerator(accelerator);
debug(`${accelerator} seems a valid shortcut sequence.`);
let shortcutsOfWindow;
if (windowsWithShortcuts.has(wc)) {
debug(`Window has others shortcuts registered.`);
shortcutsOfWindow = windowsWithShortcuts.get(wc);
} else {
debug(`This is the first shortcut of the window.`);
shortcutsOfWindow = [];
windowsWithShortcuts.set(wc, shortcutsOfWindow);
if (wc === ANY_WINDOW) {
const keyHandler = _onBeforeInput(shortcutsOfWindow);
const enableAppShortcuts = (e, win) => {
const wc = win.webContents;
wc.on('before-input-event', keyHandler);
wc.once('closed', () =>
wc.removeListener('before-input-event', keyHandler)
);
};
// Enable shortcut on current windows
const windows = BrowserWindow.getAllWindows();
windows.forEach(win => enableAppShortcuts(null, win));
// Enable shortcut on future windows
app.on('browser-window-created', enableAppShortcuts);
shortcutsOfWindow.removeListener = () => {
const windows = BrowserWindow.getAllWindows();
windows.forEach(win =>
win.webContents.removeListener('before-input-event', keyHandler)
);
app.removeListener('browser-window-created', enableAppShortcuts);
};
} else {
const keyHandler = _onBeforeInput(shortcutsOfWindow);
wc.on('before-input-event', keyHandler);
// Save a reference to allow remove of listener from elsewhere
shortcutsOfWindow.removeListener = () =>
wc.removeListener('before-input-event', keyHandler);
wc.once('closed', shortcutsOfWindow.removeListener);
}
}
debug(`Adding shortcut to window set.`);
const eventStamp = toKeyEvent(accelerator);
shortcutsOfWindow.push({
eventStamp,
callback,
enabled: true
});
debug(`Shortcut registered.`);
}
|
javascript
|
{
"resource": ""
}
|
q47531
|
unregister
|
train
|
function unregister(win, accelerator) {
let wc;
if (typeof accelerator === 'undefined') {
wc = ANY_WINDOW;
accelerator = win;
} else {
if (win.isDestroyed()) {
debug(`Early return because window is destroyed.`);
return;
}
wc = win.webContents;
}
if (Array.isArray(accelerator) === true) {
accelerator.forEach(accelerator => {
if (typeof accelerator === 'string') {
unregister(win, accelerator);
}
});
return;
}
debug(`Unregistering callback for ${accelerator} on window ${title(win)}`);
_checkAccelerator(accelerator);
debug(`${accelerator} seems a valid shortcut sequence.`);
if (!windowsWithShortcuts.has(wc)) {
debug(`Early return because window has never had shortcuts registered.`);
return;
}
const shortcutsOfWindow = windowsWithShortcuts.get(wc);
const eventStamp = toKeyEvent(accelerator);
const shortcutIdx = _findShortcut(eventStamp, shortcutsOfWindow);
if (shortcutIdx === -1) {
return;
}
shortcutsOfWindow.splice(shortcutIdx, 1);
// If the window has no more shortcuts,
// we remove it early from the WeakMap
// and unregistering the event listener
if (shortcutsOfWindow.length === 0) {
// Remove listener from window
shortcutsOfWindow.removeListener();
// Remove window from shortcuts catalog
windowsWithShortcuts.delete(wc);
}
}
|
javascript
|
{
"resource": ""
}
|
q47532
|
watchAppearForScrollables
|
train
|
function watchAppearForScrollables (tagName, context) {
// when this is a scroller/list/waterfall
if (scrollableTypes.indexOf(tagName) > -1) {
const sd = context.scrollDirection
if (!sd || sd !== 'horizontal') {
appearWatched = context
watchAppear(context, true)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47533
|
bindEvents
|
train
|
function bindEvents (ctx, evts, attrs, tag, appearAttached) {
for (const key in evts) {
const appearEvtName = appearEventsMap[key]
if (appearEvtName) {
attrs[`data-evt-${appearEvtName}`] = ''
if (!appearAttached.value) {
appearAttached.value = true
attrs['weex-appear'] = ''
}
}
else {
attrs[`data-evt-${key}`] = ''
if (key !== 'click') {
// should stop propagation by default.
// TODO: should test inBubble first.
const handler = evts[key]
if (isArray(evts[key])) {
handler.unshift(ctx.$stopPropagation)
}
else {
evts[key] = [ctx.$stopPropagation, handler]
}
}
}
}
if (evts.click) {
evts.weex$tap = evts.click
evts.click = ctx.$stopOuterA
}
if (evts.scroll) {
evts.weex$scroll = evts.scroll
delete evts.scroll
}
}
|
javascript
|
{
"resource": ""
}
|
q47534
|
setRootFont
|
train
|
function setRootFont (width, viewportWidth, force) {
const doc = window.document
const rem = width * 750 / viewportWidth / 10
if (!doc.documentElement) { return }
const rootFontSize = doc.documentElement.style.fontSize
if (!rootFontSize || force) {
doc.documentElement.style.fontSize = rem + 'px'
}
info.rem = rem
info.rootValue = viewportWidth / 10
}
|
javascript
|
{
"resource": ""
}
|
q47535
|
getCommonAncestor
|
train
|
function getCommonAncestor(el1, el2) {
var el = el1
while (el) {
if (el.contains(el2) || el == el2) {
return el
}
el = el.parentNode
}
return null
}
|
javascript
|
{
"resource": ""
}
|
q47536
|
fireEvent
|
train
|
function fireEvent(element, type, extra) {
var event = doc.createEvent('HTMLEvents')
event.initEvent(type, true, true)
if (typeof extra === 'object') {
for (var p in extra) {
event[p] = extra[p]
}
}
/**
* A flag to distinguish with other events with the same name generated
* by another library in the same page.
*/
event._for = 'weex'
element.dispatchEvent(event)
}
|
javascript
|
{
"resource": ""
}
|
q47537
|
train
|
function (key, value, callbackId) {
const sender = this.sender
if (!supportLocalStorage) {
return callNotSupportFail(sender, callbackId)
}
if (!key || (!value && value !== 0)) {
sender.performCallback(callbackId, {
result: 'failed',
data: INVALID_PARAM
})
return
}
try {
localStorage.setItem(key, value)
sender.performCallback(callbackId, {
result: SUCCESS,
data: UNDEFINED
})
}
catch (e) {
// accept any exception thrown during a storage attempt as a quota error
callFail(sender, callbackId)
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47538
|
train
|
function (key, callbackId) {
const sender = this.sender
if (!supportLocalStorage) {
return callNotSupportFail(sender, callbackId)
}
if (!key) {
sender.performCallback(callbackId, {
result: FAILED,
data: INVALID_PARAM
})
return
}
try {
const val = localStorage.getItem(key)
sender.performCallback(callbackId, {
result: val ? SUCCESS : FAILED,
data: val || UNDEFINED
})
}
catch (e) {
// accept any exception thrown during a storage attempt as a quota error
callFail(sender, callbackId)
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47539
|
train
|
function (callbackId) {
const sender = this.sender
if (!supportLocalStorage) {
return callNotSupportFail(sender, callbackId)
}
try {
const len = localStorage.length
sender.performCallback(callbackId, {
result: SUCCESS,
data: len
})
}
catch (e) {
// accept any exception thrown during a storage attempt as a quota error
callFail(sender, callbackId)
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47540
|
train
|
function (callbackId) {
const sender = this.sender
if (!supportLocalStorage) {
return callNotSupportFail(sender, callbackId)
}
try {
const _arr = []
for (let i = 0; i < localStorage.length; i++) {
_arr.push(localStorage.key(i))
}
sender.performCallback(callbackId, {
result: SUCCESS,
data: _arr
})
}
catch (e) {
// accept any exception thrown during a storage attempt as a quota error
callFail(sender, callbackId)
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47541
|
createMouseEvent
|
train
|
function createMouseEvent(eventName, originalEvent, finger) {
var e = document.createEvent('MouseEvent');
e.initMouseEvent(eventName, true, true,
originalEvent.view, originalEvent.detail,
finger.x || originalEvent.screenX, finger.y || originalEvent.screenY,
finger.x || originalEvent.clientX, finger.y || originalEvent.clientY,
originalEvent.ctrlKey, originalEvent.shiftKey,
originalEvent.altKey, originalEvent.metaKey,
originalEvent.button, finger.target || originalEvent.relatedTarget
);
e.synthetic = true;
// Set this so we can match shared targets later.
e._finger = finger;
return e;
}
|
javascript
|
{
"resource": ""
}
|
q47542
|
phantomTouchStart
|
train
|
function phantomTouchStart(e) {
if (e.synthetic) return;
mouseIsDown = true;
e.preventDefault();
e.stopPropagation();
fireTouchEvents('touchstart', e);
}
|
javascript
|
{
"resource": ""
}
|
q47543
|
moveFingers
|
train
|
function moveFingers(e) {
// We'll use this if the second is locked with the first.
var changeX = e.clientX - fingers[0].x || 0;
var changeY = e.clientY - fingers[0].y || 0;
// The first finger just follows the mouse.
fingers[0].move(e.clientX, e.clientY);
// TODO: Determine modifier keys independent of mouse movement.
if (e.altKey) {
// Reset the center.
if (!centerX && !centerY) {
centerX = innerWidth / 2;
centerY = innerHeight / 2;
}
// Lock the center with the first finger.
if (e.shiftKey) {
centerX += changeX;
centerY += changeY;
}
var secondX = centerX + (centerX - e.clientX);
var secondY = centerY + (centerY - e.clientY);
fingers[1].move(secondX, secondY);
} else {
// Disengage the second finger.
fingers[1].move(NaN, NaN);
// Reset the center next time the alt key is held.
centerX = NaN;
centerY = NaN;
}
}
|
javascript
|
{
"resource": ""
}
|
q47544
|
phantomTouchEnd
|
train
|
function phantomTouchEnd(e) {
if (e.synthetic) return;
mouseIsDown = false;
e.preventDefault();
e.stopPropagation();
fireTouchEvents('touchend', e);
fingers.forEach(function(finger) {
if (!finger.target) return;
// Mobile Safari moves all the mouse event to fire after the touchend event.
finger.target.dispatchEvent(createMouseEvent('mouseover', e, finger));
finger.target.dispatchEvent(createMouseEvent('mousemove', e, finger));
finger.target.dispatchEvent(createMouseEvent('mousedown', e, finger));
// TODO: These two only fire if content didn't change. How can we tell?
finger.target.dispatchEvent(createMouseEvent('mouseup', e, finger));
finger.target.dispatchEvent(createMouseEvent('click', e, finger));
});
}
|
javascript
|
{
"resource": ""
}
|
q47545
|
phantomKeyUp
|
train
|
function phantomKeyUp(e) {
if (e.keyCode === 27) {
if (document.documentElement.classList.contains('_phantom-limb')) {
stop();
} else {
start();
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47546
|
inlineAllStyles
|
train
|
function inlineAllStyles(element) {
let styles = getComputedStyle(element);
for(let key in styles) {
if(styles.hasOwnProperty(key)) {
element.style[key] = styles[key];
}
}
for(let i = 0; i < element.childNodes.length; i++) {
let node = element.childNodes[i];
if(node.nodeType === 1) {
inlineAllStyles(node);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47547
|
cut
|
train
|
function cut(buffer, size) {
var chunks = [];
var cursor = 0;
do {
var chunkSize = Math.min(size, buffer.length - cursor);
chunks.push(buffer.slice(cursor, cursor + chunkSize));
cursor += chunkSize;
} while(cursor < buffer.length);
return chunks;
}
|
javascript
|
{
"resource": ""
}
|
q47548
|
onRequest
|
train
|
function onRequest(request, response) {
var filename = path.join(__dirname, request.url);
// Serving server.js from cache. Useful for microbenchmarks.
if (request.url === cachedUrl) {
if (response.push) {
// Also push down the client js, since it's possible if the requester wants
// one, they want both.
var push = response.push('/client.js');
push.writeHead(200);
fs.createReadStream(path.join(__dirname, '/client.js')).pipe(push);
}
response.end(cachedFile);
}
// Reading file from disk if it exists and is safe.
else if ((filename.indexOf(__dirname) === 0) && fs.existsSync(filename) && fs.statSync(filename).isFile()) {
response.writeHead(200);
var fileStream = fs.createReadStream(filename);
fileStream.pipe(response);
fileStream.on('finish',response.end);
}
// Example for testing large (boundary-sized) frames.
else if (request.url === "/largeframe") {
response.writeHead(200);
var body = 'a';
for (var i = 0; i < 14; i++) {
body += body;
}
body = body + 'a';
response.end(body);
}
// Otherwise responding with 404.
else {
response.writeHead(404);
response.end();
}
}
|
javascript
|
{
"resource": ""
}
|
q47549
|
favicon
|
train
|
function favicon (path, options) {
var opts = options || {}
var icon // favicon cache
var maxAge = calcMaxAge(opts.maxAge)
if (!path) {
throw new TypeError('path to favicon.ico is required')
}
if (Buffer.isBuffer(path)) {
icon = createIcon(Buffer.from(path), maxAge)
} else if (typeof path === 'string') {
path = resolveSync(path)
} else {
throw new TypeError('path to favicon.ico must be string or buffer')
}
return function favicon (req, res, next) {
if (getPathname(req) !== '/favicon.ico') {
next()
return
}
if (req.method !== 'GET' && req.method !== 'HEAD') {
res.statusCode = req.method === 'OPTIONS' ? 200 : 405
res.setHeader('Allow', 'GET, HEAD, OPTIONS')
res.setHeader('Content-Length', '0')
res.end()
return
}
if (icon) {
send(req, res, icon)
return
}
fs.readFile(path, function (err, buf) {
if (err) return next(err)
icon = createIcon(buf, maxAge)
send(req, res, icon)
})
}
}
|
javascript
|
{
"resource": ""
}
|
q47550
|
calcMaxAge
|
train
|
function calcMaxAge (val) {
var num = typeof val === 'string'
? ms(val)
: val
return num != null
? Math.min(Math.max(0, num), ONE_YEAR_MS)
: ONE_YEAR_MS
}
|
javascript
|
{
"resource": ""
}
|
q47551
|
createIcon
|
train
|
function createIcon (buf, maxAge) {
return {
body: buf,
headers: {
'Cache-Control': 'public, max-age=' + Math.floor(maxAge / 1000),
'ETag': etag(buf)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47552
|
createIsDirError
|
train
|
function createIsDirError (path) {
var error = new Error('EISDIR, illegal operation on directory \'' + path + '\'')
error.code = 'EISDIR'
error.errno = 28
error.path = path
error.syscall = 'open'
return error
}
|
javascript
|
{
"resource": ""
}
|
q47553
|
isFresh
|
train
|
function isFresh (req, res) {
return fresh(req.headers, {
'etag': res.getHeader('ETag'),
'last-modified': res.getHeader('Last-Modified')
})
}
|
javascript
|
{
"resource": ""
}
|
q47554
|
resolveSync
|
train
|
function resolveSync (iconPath) {
var path = resolve(iconPath)
var stat = fs.statSync(path)
if (stat.isDirectory()) {
throw createIsDirError(path)
}
return path
}
|
javascript
|
{
"resource": ""
}
|
q47555
|
metadataMiddleware
|
train
|
function metadataMiddleware (options) {
//claimTypes, issuer, pem, endpointPath
options = options || {};
if(!options.issuer) {
throw new Error('options.issuer is required');
}
if(!options.cert) {
throw new Error('options.cert is required');
}
var claimTypes = (options.profileMapper || PassportProfileMapper).prototype.metadata;
var issuer = options.issuer;
var pem = encoders.removeHeaders(options.cert);
return function (req, res) {
var endpoint = getEndpointAddress(req, options.endpointPath);
var mexEndpoint = options.mexEndpoint ? getEndpointAddress(req, options.mexEndpoint) : '';
res.set('Content-Type', 'application/xml');
res.send(templates.metadata({
claimTypes: claimTypes,
pem: pem,
issuer: issuer,
endpoint: endpoint,
mexEndpoint: mexEndpoint
}).replace(/\n/g, ''));
};
}
|
javascript
|
{
"resource": ""
}
|
q47556
|
leftZeroFill
|
train
|
function leftZeroFill(number, targetLength) {
var output = number + "";
while (output.length < targetLength){
output = "0" + output;
}
return output;
}
|
javascript
|
{
"resource": ""
}
|
q47557
|
toJalaliFormat
|
train
|
function toJalaliFormat(format) {
for (var i = 0; i < format.length; i++) {
if(!i || (format[i-1] !== "j" && format[i-1] !== format[i])) {
if (format[i] === "Y" || format[i] === "M" || format[i] === "D" || format[i] === "g") {
format = format.slice(0, i) + "j" + format.slice(i);
}
}
}
return format;
}
|
javascript
|
{
"resource": ""
}
|
q47558
|
normalizeUnits
|
train
|
function normalizeUnits(units, momentObj) {
if (isJalali(momentObj)) {
units = toJalaliUnit(units);
}
if (units) {
var lowered = units.toLowerCase();
units = unitAliases[lowered] || lowered;
}
// TODO : add unit test
if (units === "jday") units = "day";
else if (units === "jd") units = "d";
return units;
}
|
javascript
|
{
"resource": ""
}
|
q47559
|
setDate
|
train
|
function setDate(momentInstance, year, month, day) {
var d = momentInstance._d;
if (momentInstance._isUTC) {
/*eslint-disable new-cap*/
momentInstance._d = new Date(Date.UTC(year, month, day,
d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds()));
/*eslint-enable new-cap*/
} else {
momentInstance._d = new Date(year, month, day,
d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds());
}
}
|
javascript
|
{
"resource": ""
}
|
q47560
|
findImportedPath
|
train
|
function findImportedPath(url, prev, includedFilesMap, includedPaths) {
let candidateFromPaths;
if(prev !== 'stdin') {
const prevPath = path.posix.dirname(prev);
candidateFromPaths = [prevPath, ...includedPaths];
} else {
candidateFromPaths = [...includedPaths];
}
for(let i = 0; i < candidateFromPaths.length; i++) {
let candidatePath;
let candidateFromPath = normalizePath(makeAbsolute(candidateFromPaths[i]));
if (path.isAbsolute(url)) {
candidatePath = normalizePath(url);
} else {
// Get normalize absolute candidate from path
candidatePath = path.posix.join(candidateFromPath, url);
}
if(includedFilesMap[candidatePath]) {
return candidatePath;
} else {
let urlBasename = path.posix.basename(url);
let indexOfBasename = url.lastIndexOf(urlBasename);
let partialUrl = `${url.substring(0, indexOfBasename)}_${urlBasename}`;
if (path.isAbsolute(partialUrl)) {
candidatePath = normalizePath(partialUrl);
} else {
candidatePath = path.posix.join(candidateFromPath, partialUrl);
}
if(includedFilesMap[candidatePath]) {
return candidatePath;
}
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q47561
|
getImportAbsolutePath
|
train
|
function getImportAbsolutePath(url, prev, includedFilesMap, includedPaths = []) {
// Ensure that both @import 'file' and @import 'file.scss' is mapped correctly
let extension = path.posix.extname(prev);
if(path.posix.extname(url) !== extension) {
url += extension;
}
const absolutePath = findImportedPath(url, prev, includedFilesMap, includedPaths);
if(!absolutePath) {
throw new Error(`Can not determine imported file for url '${url}' imported in ${prev}`);
}
return absolutePath;
}
|
javascript
|
{
"resource": ""
}
|
q47562
|
getImportResult
|
train
|
function getImportResult(extractions, url, prev, includedFilesMap, includedPaths) {
const absolutePath = getImportAbsolutePath(url, prev, includedFilesMap, includedPaths);
const contents = extractions[absolutePath].injectedData;
return { file: absolutePath, contents };
}
|
javascript
|
{
"resource": ""
}
|
q47563
|
getDeclarationDeps
|
train
|
function getDeclarationDeps($ast, declaration, scope) {
if(scope !== SCOPE_EXPLICIT) {
return {};
}
const depParentNodes = $ast(declaration).parents(node => {
if(node.node.type === 'mixin') {
return true;
} else if(node.node.type === 'atrule') {
const atruleIdentNode = $ast(node).children('atkeyword').children('ident');
return atruleIdentNode.length() > 0 && atruleIdentNode.first().value() === 'function'
} else {
return false;
}
});
if(depParentNodes.length() === 0) {
return {};
}
const depParentNode = depParentNodes.last();
const depKeywordNode = depParentNode.children('atkeyword').children('ident');
if(depKeywordNode.length() === 0) {
return {};
}
const atKeyword = depKeywordNode.first().value();
if(!DEP_HOST[atKeyword]) {
return {};
}
const depHostNode = DEP_HOST[atKeyword](depParentNode);
const atKeywordIdentifierNode = depHostNode.children('ident');
if(atKeywordIdentifierNode.length() === 0) {
return {};
}
const atIdentifier = atKeywordIdentifierNode.first().value();
const argumentsNode = depHostNode.children('arguments');
// Count arguments to mixin/function @atrule
const requiredArgsCount = argumentsNode.children('variable').length();
const optionalArgsCount = argumentsNode.children('declaration').length();
const totalArgsCount = requiredArgsCount + optionalArgsCount;
if(!DEP_KEYWORDS[atKeyword]) {
return {};
}
return {
[DEP_KEYWORDS[atKeyword]]: {
name: atIdentifier,
argsCount: {
total: totalArgsCount,
required: requiredArgsCount,
optional: optionalArgsCount,
},
},
};
}
|
javascript
|
{
"resource": ""
}
|
q47564
|
parseDeclaration
|
train
|
function parseDeclaration($ast, declaration, scope) {
const variable = {};
const propertyNode = $ast(declaration)
.children('property');
variable.declarationClean = propertyNode.value();
variable.position = propertyNode.get(0).start;
variable.declaration = `$${variable.declarationClean}`;
variable.expression = parseExpression($ast, declaration);
variable.flags = {
default: isDefaultDeclaration($ast, declaration),
global: isExplicitGlobalDeclaration($ast, declaration),
};
variable.deps = getDeclarationDeps($ast, declaration, scope);
return variable;
}
|
javascript
|
{
"resource": ""
}
|
q47565
|
processFile
|
train
|
function processFile(idx, count, filename, data, parsedDeclarations, pluggable) {
const declarations = parsedDeclarations.files[filename];
// Inject dependent declaration extraction to last file
const dependentDeclarations = idx === count - 1 ? parsedDeclarations.dependentDeclarations : [];
const variables = { global: {} };
const globalDeclarationResultHandler = (declaration, value, sassValue) => {
if(!variables.global[declaration.declaration]) {
variables.global[declaration.declaration] = [];
}
const variableValue = pluggable.run(Pluggable.POST_VALUE, { value, sassValue }).value;
variables.global[declaration.declaration].push({ declaration, value: variableValue });
}
const fileId = getFileId(filename);
const injection = injectExtractionFunctions(fileId, declarations, dependentDeclarations, { globalDeclarationResultHandler });
const injectedData = `${data}\n\n${injection.injectedData}`;
const injectedFunctions = injection.injectedFunctions;
return {
fileId,
declarations,
variables,
injectedData,
injectedFunctions,
};
}
|
javascript
|
{
"resource": ""
}
|
q47566
|
getRenderedStats
|
train
|
function getRenderedStats(rendered, compileOptions) {
return {
entryFilename: normalizePath(rendered.stats.entry),
includedFiles: rendered.stats.includedFiles.map(f => normalizePath(makeAbsolute(f))),
includedPaths: (compileOptions.includePaths || []).map(normalizePath),
};
}
|
javascript
|
{
"resource": ""
}
|
q47567
|
makeExtractionCompileOptions
|
train
|
function makeExtractionCompileOptions(compileOptions, entryFilename, extractions, importer) {
const extractionCompileOptions = Object.assign({}, compileOptions);
const extractionFunctions = {};
// Copy all extraction function for each file into one object for compilation
Object.keys(extractions).forEach(extractionKey => {
Object.assign(extractionFunctions, extractions[extractionKey].injectedFunctions);
});
extractionCompileOptions.functions = Object.assign(extractionFunctions, compileOptions.functions);
extractionCompileOptions.data = extractions[entryFilename].injectedData;
if(!makeExtractionCompileOptions.imported) {
extractionCompileOptions.importer = importer;
}
return extractionCompileOptions;
}
|
javascript
|
{
"resource": ""
}
|
q47568
|
compileExtractionResult
|
train
|
function compileExtractionResult(orderedFiles, extractions) {
const extractedVariables = { global: {} };
orderedFiles.map(filename => {
const globalFileVariables = extractions[filename].variables.global;
Object.keys(globalFileVariables).map(variableKey => {
globalFileVariables[variableKey].forEach(extractedVariable => {
let variable = extractedVariables.global[variableKey];
let currentVariableSources = [];
let currentVariableDeclarations = [];
if(variable) {
currentVariableSources = variable.sources;
currentVariableDeclarations = variable.declarations;
}
const hasOnlyDefaults = currentVariableDeclarations.every(declaration => declaration.flags.default);
const currentIsDefault = extractedVariable.declaration.flags.default;
if(currentVariableDeclarations.length === 0 || !currentIsDefault || hasOnlyDefaults) {
variable = extractedVariables.global[variableKey] = Object.assign({}, extractedVariable.value);
}
variable.sources = currentVariableSources.indexOf(filename) < 0 ? [...currentVariableSources, filename] : currentVariableSources;
variable.declarations = [...currentVariableDeclarations, {
expression: extractedVariable.declaration.expression,
flags: extractedVariable.declaration.flags,
in: filename,
position: extractedVariable.declaration.position,
}];
});
});
});
return extractedVariables;
}
|
javascript
|
{
"resource": ""
}
|
q47569
|
isColor
|
train
|
function isColor(value) {
return value.r != null
&& value.g != null
&& value.b != null
&& value.a != null
&& value.hex != null;
}
|
javascript
|
{
"resource": ""
}
|
q47570
|
serializeValue
|
train
|
function serializeValue(sassValue, isInList) {
switch(sassValue.constructor) {
case sass.types.String:
case sass.types.Boolean:
return `${sassValue.getValue()}`;
case sass.types.Number:
return `${sassValue.getValue()}${sassValue.getUnit()}`;
case sass.types.Color:
return serializeColor(sassValue);
case sass.types.Null:
return `null`;
case sass.types.List:
const listLength = sassValue.getLength();
const listElement = [];
const hasSeparator = sassValue.getSeparator();
for(let i = 0; i < listLength; i++) {
listElement.push(serialize(sassValue.getValue(i), true));
}
// Make sure nested lists are serialized with surrounding parenthesis
if(isInList) {
return `(${listElement.join(hasSeparator ? ',' : ' ')})`;
} else {
return `${listElement.join(hasSeparator ? ',' : ' ')}`;
}
case sass.types.Map:
const mapLength = sassValue.getLength();
const mapValue = {};
for(let i = 0; i < mapLength; i++) {
const key = serialize(sassValue.getKey(i));
const value = serialize(sassValue.getValue(i));
mapValue[key] = value;
}
const serializedMapValues = Object.keys(mapValue).map(key => `${key}: ${mapValue[key]}`);
return `(${serializedMapValues})`;
default:
throw new Error(`Unsupported sass variable type '${sassValue.constructor.name}'`)
};
}
|
javascript
|
{
"resource": ""
}
|
q47571
|
createInjection
|
train
|
function createInjection(fileId, categoryPrefix, declaration, idx, declarationResultHandler) {
const fnName = `${FN_PREFIX}_${fileId}_${categoryPrefix}_${declaration.declarationClean}_${idx}`;
const injectedFunction = function(sassValue) {
const value = createStructuredValue(sassValue);
declarationResultHandler(declaration, value, sassValue);
return sassValue;
};
let injectedCode = `@if global_variable_exists('${declaration.declarationClean}') {
$${fnName}: ${fnName}(${declaration.declaration});
}\n`
return { fnName, injectedFunction, injectedCode };
}
|
javascript
|
{
"resource": ""
}
|
q47572
|
includeRawDataFile
|
train
|
function includeRawDataFile(includedFiles, files, entryFilename, data) {
let orderedFiles = includedFiles;
if(entryFilename === RAW_DATA_FILE && data) {
files[RAW_DATA_FILE] = data;
orderedFiles = [...orderedFiles, RAW_DATA_FILE];
} else if(orderedFiles.length > 0) {
orderedFiles = [...orderedFiles.slice(1), orderedFiles[0]];
}
return {
compiledFiles: files,
orderedFiles,
};
}
|
javascript
|
{
"resource": ""
}
|
q47573
|
makeValue
|
train
|
function makeValue(sassValue) {
switch(sassValue.constructor) {
case sass.types.String:
case sass.types.Boolean:
return { value: sassValue.getValue() };
case sass.types.Number:
return { value: sassValue.getValue(), unit: sassValue.getUnit() };
case sass.types.Color:
const r = Math.round(sassValue.getR());
const g = Math.round(sassValue.getG());
const b = Math.round(sassValue.getB());
return {
value: {
r, g, b,
a: sassValue.getA(),
hex: `#${toColorHex(r)}${toColorHex(g)}${toColorHex(b)}`
},
};
case sass.types.Null:
return { value: null };
case sass.types.List:
const listLength = sassValue.getLength();
const listValue = [];
for(let i = 0; i < listLength; i++) {
listValue.push(createStructuredValue(sassValue.getValue(i)));
}
return { value: listValue, separator: sassValue.getSeparator() ? ',' : ' ' };
case sass.types.Map:
const mapLength = sassValue.getLength();
const mapValue = {};
for(let i = 0; i < mapLength; i++) {
// Serialize map keys of arbitrary type for extracted struct
const serializedKey = serialize(sassValue.getKey(i));
mapValue[serializedKey] = createStructuredValue(sassValue.getValue(i));
}
return { value: mapValue };
default:
throw new Error(`Unsupported sass variable type '${sassValue.constructor.name}'`)
};
}
|
javascript
|
{
"resource": ""
}
|
q47574
|
AssetManager
|
train
|
function AssetManager(generator, config, logger, document, renderManager) {
events.EventEmitter.call(this);
this._generator = generator;
this._config = config;
this._logger = logger;
this._document = document;
this._metaDataRoot = config["meta-data-root"] || META_PLUGIN_ID;
this._renderManager = renderManager;
this._fileManager = new FileManager(generator, config, logger);
this._errorManager = new ErrorManager(generator, config, logger, this._fileManager);
this._handleChange = this._handleChange.bind(this);
this._handleCompsChange = this._handleCompsChange.bind(this);
}
|
javascript
|
{
"resource": ""
}
|
q47575
|
RenderManager
|
train
|
function RenderManager(generator, config, logger) {
events.EventEmitter.call(this);
this._generator = generator;
this._config = config;
this._logger = logger;
this._svgRenderers = {};
this._pixmapRenderers = {};
this._componentsByDocument = {};
this._pending = {};
this._working = {};
this._renderedAssetCount = 0;
}
|
javascript
|
{
"resource": ""
}
|
q47576
|
_pauseAssetGeneration
|
train
|
function _pauseAssetGeneration(id) {
if (_waitingDocuments.hasOwnProperty(id)) {
_canceledDocuments[id] = true;
} else if (_assetManagers.hasOwnProperty(id)) {
_assetManagers[id].stop();
}
}
|
javascript
|
{
"resource": ""
}
|
q47577
|
_handleFileChange
|
train
|
function _handleFileChange(id, change) {
// If the filename changed but the saved state didn't change, then the file must have been renamed
if (change.previous && !change.hasOwnProperty("previousSaved")) {
_stopAssetGeneration(id);
_stateManager.deactivate(id);
}
}
|
javascript
|
{
"resource": ""
}
|
q47578
|
_getChangedSettings
|
train
|
function _getChangedSettings(settings) {
if (settings && typeof(settings) === "object") {
return _generator.extractDocumentSettings({generatorSettings: settings}, PLUGIN_ID);
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q47579
|
_handleDocGeneratorSettingsChange
|
train
|
function _handleDocGeneratorSettingsChange(id, change) {
var curSettings = _getChangedSettings(change.current),
prevSettings = _getChangedSettings(change.previous),
curEnabled = !!(curSettings && curSettings.enabled),
prevEnabled = !!(prevSettings && prevSettings.enabled);
if (prevEnabled !== curEnabled) {
if (curEnabled) {
_stateManager.activate(id);
} else {
_stateManager.deactivate(id);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47580
|
_handleOpenDocumentsChanged
|
train
|
function _handleOpenDocumentsChanged(all, opened) {
var open = opened || all;
open.forEach(function (id) {
_documentManager.getDocument(id).done(function (document) {
document.on("generatorSettings", _handleDocGeneratorSettingsChange.bind(undefined, id));
}, function (error) {
_logger.warning("Error getting document during a document changed event, " +
"document was likely closed.", error);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q47581
|
_startAssetGeneration
|
train
|
function _startAssetGeneration(id) {
if (_waitingDocuments.hasOwnProperty(id)) {
return;
}
var documentPromise = _documentManager.getDocument(id);
_waitingDocuments[id] = documentPromise;
documentPromise.done(function (document) {
delete _waitingDocuments[id];
if (_canceledDocuments.hasOwnProperty(id)) {
delete _canceledDocuments[id];
} else {
if (!_assetManagers.hasOwnProperty(id)) {
_assetManagers[id] = new AssetManager(_generator, _config, _logger, document, _renderManager);
document.on("closed", _stopAssetGeneration.bind(undefined, id));
document.on("end", _restartAssetGeneration.bind(undefined, id));
document.on("file", _handleFileChange.bind(undefined, id));
}
_assetManagers[id].start();
}
});
}
|
javascript
|
{
"resource": ""
}
|
q47582
|
_getConfig
|
train
|
function _getConfig() {
var copy = {},
property;
for (property in _config) {
if (_config.hasOwnProperty(property)) {
copy[property] = _config[property];
}
}
return copy;
}
|
javascript
|
{
"resource": ""
}
|
q47583
|
_setConfig
|
train
|
function _setConfig(config, keepExisting) {
var property;
// optionally clean out the existing properties first
if (!keepExisting) {
for (property in _config) {
if (_config.hasOwnProperty(property)) {
delete _config[property];
}
}
}
// add in the new properties
for (property in config) {
if (config.hasOwnProperty(property)) {
_config[property] = config[property];
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47584
|
init
|
train
|
function init(generator, config, logger) {
_generator = generator;
_config = config;
_logger = logger;
_documentManager = new DocumentManager(generator, config, logger);
_stateManager = new StateManager(generator, config, logger, _documentManager);
_renderManager = new RenderManager(generator, config, logger);
if (!!_config["css-enabled"]) {
var SONToCSS = require("./lib/css/sontocss.js");
_SONToCSSConverter = new SONToCSS(generator, config, logger, _documentManager);
}
// For automated tests
exports._renderManager = _renderManager;
exports._stateManager = _stateManager;
exports._assetManagers = _assetManagers;
exports._layerNameParse = require("./lib/parser").parse;
_stateManager.on("enabled", _startAssetGeneration);
_stateManager.on("disabled", _pauseAssetGeneration);
_documentManager.on("openDocumentsChanged", _handleOpenDocumentsChanged);
Headlights.init(generator, logger, _stateManager, _renderManager);
}
|
javascript
|
{
"resource": ""
}
|
q47585
|
BaseRenderer
|
train
|
function BaseRenderer(generator, config, logger, document) {
this._generator = generator;
this._document = document;
this._logger = logger;
if (config.hasOwnProperty("use-jpg-encoding")) {
this._useJPGEncoding = config["use-jpg-encoding"];
}
if (config.hasOwnProperty("use-smart-scaling")) {
this._useSmartScaling = !!config["use-smart-scaling"];
}
if (config.hasOwnProperty("include-ancestor-masks")) {
this._includeAncestorMasks = !!config["include-ancestor-masks"];
}
if (config.hasOwnProperty("convert-color-space")) {
this._convertColorSpace = !!config["convert-color-space"];
}
if (config.hasOwnProperty("icc-profile")) {
this._useICCProfile = config["icc-profile"];
}
if (config.hasOwnProperty("embed-icc-profile")) {
this._embedICCProfile = config["embed-icc-profile"];
}
if (config.hasOwnProperty("allow-dither")) {
this._allowDither = !!config["allow-dither"];
}
if (config.hasOwnProperty("use-psd-smart-object-pixel-scaling")) {
this._forceSmartPSDPixelScaling = !!config["use-psd-smart-object-pixel-scaling"];
}
if (config.hasOwnProperty("use-pngquant")) {
this._usePngquant = !!config["use-pngquant"];
}
if (config.hasOwnProperty("use-flite")) {
this._useFlite = !!config["use-flite"];
}
if (config.hasOwnProperty("webp-lossless")) {
this._webpLossless = !!config["webp-lossless"];
}
if (config.hasOwnProperty("clip-all-images-to-document-bounds")) {
this._clipAllImagesToDocumentBounds = !!config["clip-all-images-to-document-bounds"];
}
if (config.hasOwnProperty("clip-all-images-to-artboard-bounds")) {
this._clipAllImagesToArtboardBounds = !!config["clip-all-images-to-artboard-bounds"];
}
if (config.hasOwnProperty("mask-adds-padding")) {
this._masksAddPadding = !!config["mask-adds-padding"];
}
if (config.hasOwnProperty("expand-max-dimensions")) {
this._expandMaxDimensions = !!config["expand-max-dimensions"];
}
}
|
javascript
|
{
"resource": ""
}
|
q47586
|
SVGRenderer
|
train
|
function SVGRenderer(generator, config, logger, document) {
BaseRenderer.call(this, generator, config, logger, document);
if (config.hasOwnProperty("svgomg-enabled")) {
this._useSVGOMG = !!config["svgomg-enabled"];
}
}
|
javascript
|
{
"resource": ""
}
|
q47587
|
createSVGRenderer
|
train
|
function createSVGRenderer(generator, config, logger, document) {
return new SVGRenderer(generator, config, logger, document);
}
|
javascript
|
{
"resource": ""
}
|
q47588
|
PixmapRenderer
|
train
|
function PixmapRenderer(generator, config, logger, document) {
BaseRenderer.call(this, generator, config, logger, document);
if (config.hasOwnProperty("interpolation-type")) {
this._interpolationType = config["interpolation-type"];
}
}
|
javascript
|
{
"resource": ""
}
|
q47589
|
createPixmapRenderer
|
train
|
function createPixmapRenderer(generator, config, logger, document) {
return new PixmapRenderer(generator, config, logger, document);
}
|
javascript
|
{
"resource": ""
}
|
q47590
|
_shallowCopy
|
train
|
function _shallowCopy(component) {
var clone = {},
property;
for (property in component) {
if (component.hasOwnProperty(property)) {
clone[property] = component[property];
}
}
return clone;
}
|
javascript
|
{
"resource": ""
}
|
q47591
|
_deriveComponent
|
train
|
function _deriveComponent(def, basic) {
var derived = _shallowCopy(basic);
if (def.hasOwnProperty("folder")) {
if (derived.hasOwnProperty("folder")) {
var folder = def.folder.concat(basic.folder);
derived.folder = folder;
} else {
derived.folder = def.folder;
}
}
if (def.hasOwnProperty("suffix")) {
var index = basic.file.lastIndexOf("."),
filename = basic.file.substring(0, index),
extension = basic.file.substring(index);
derived.file = filename + def.suffix + extension;
}
if (def.hasOwnProperty("scale") ||
def.hasOwnProperty("width") ||
def.hasOwnProperty("height")) {
if (!derived.hasOwnProperty("scale") &&
!derived.hasOwnProperty("width") &&
!derived.hasOwnProperty("height")) {
if (def.hasOwnProperty("scale")) {
derived.scale = def.scale;
}
if (def.hasOwnProperty("width")) {
derived.width = def.width;
}
if (def.hasOwnProperty("height")) {
derived.height = def.height;
}
}
}
if (def.hasOwnProperty("canvasWidth") ||
def.hasOwnProperty("canvasHeight") ||
def.hasOwnProperty("canvasOffsetX") ||
def.hasOwnProperty("canvasOffsetY")) {
if (!derived.hasOwnProperty("canvasWidth") &&
!derived.hasOwnProperty("canvasHeight") &&
!derived.hasOwnProperty("canvasOffsetX") &&
!derived.hasOwnProperty("canvasOffsetY")) {
if (def.hasOwnProperty("canvasWidth")) {
derived.canvasWidth = def.canvasWidth;
}
if (def.hasOwnProperty("canvasHeight")) {
derived.canvasHeight = def.canvasHeight;
}
if (def.hasOwnProperty("canvasOffsetX")) {
derived.canvasOffsetX = def.canvasOffsetX;
}
if (def.hasOwnProperty("canvasOffsetY")) {
derived.canvasOffsetY = def.canvasOffsetY;
}
}
}
if (def.hasOwnProperty("quality")) {
if (!derived.hasOwnProperty("quality")) {
derived.quality = def.quality;
}
}
derived.id = def.id + ":" + basic.id;
derived.assetPath = _getAssetPath(derived);
derived.default = def;
return derived;
}
|
javascript
|
{
"resource": ""
}
|
q47592
|
ComponentManager
|
train
|
function ComponentManager(generator, config) {
this._parserManager = new ParserManager(config);
this._config = config || {};
this._allComponents = {};
this._componentsForLayer = {};
this._componentsForComp = {};
this._componentsForDocument = {};
this._paths = {};
this._defaultLayerId = null;
this._metaDefaultComponents = [];
this._metaDataRoot = config["meta-data-root"] || META_PLUGIN_ID;
}
|
javascript
|
{
"resource": ""
}
|
q47593
|
ParserManager
|
train
|
function ParserManager(config) {
this._config = config || {};
this._supportedUnits = {
"in": true,
"cm": true,
"px": true,
"mm": true
};
this._supportedExtensions = {
"jpg": true,
"png": true,
"gif": true,
"svg": this._config.hasOwnProperty("svg-enabled") ? !!this._config["svg-enabled"] : true,
"webp": !!this._config["webp-enabled"]
};
}
|
javascript
|
{
"resource": ""
}
|
q47594
|
FileManager
|
train
|
function FileManager(generator, config, logger) {
this._generator = generator;
this._config = config;
this._logger = logger;
this._queue = new AsyncQueue();
this._queue.pause();
this._queue.on("error", function (err) {
this._logger.error(err);
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q47595
|
DocumentManager
|
train
|
function DocumentManager(generator, config, logger, options) {
EventEmitter.call(this);
this._generator = generator;
this._config = config;
this._logger = logger;
options = options || {};
this._getDocumentInfoFlags = options.getDocumentInfoFlags;
this._clearCacheOnChange = options.clearCacheOnChange;
this._documents = {};
this._documentDeferreds = {};
this._documentChanges = {};
this._openDocumentIds = {};
this._newOpenDocumentIds = {};
this._newClosedDocumentIds = {};
this._initActiveDocumentID();
this._resetOpenDocumentIDs()
.then(function () {
// make sure that openDocumentsChanged fires once on startup, even
// if there are no open documents
this._handleOpenDocumentsChange();
}.bind(this))
.done();
generator.onPhotoshopEvent("imageChanged", this._handleImageChanged.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q47596
|
Document
|
train
|
function Document(generator, config, logger, raw) {
if (DEBUG_TO_RAW_CONVERSION) {
debugLogObject("raw", raw);
}
events.EventEmitter.call(this);
this._generator = generator;
this._config = config;
this._logger = logger;
var property;
for (property in raw) {
if (raw.hasOwnProperty(property)) {
switch (property) {
case "id":
this._id = raw.id;
break;
case "count":
this._count = raw.count;
break;
case "timeStamp":
this._timeStamp = raw.timeStamp;
break;
case "version":
this._version = raw.version;
break;
case "file":
this._setFile(raw.file);
break;
case "bounds":
this._setBounds(raw.bounds);
break;
case "selection":
// Resolving the selection depends on the layers; set it in a later pass
break;
case "resolution":
this._setResolution(raw.resolution);
break;
case "globalLight":
this._setGlobalLight(raw.globalLight);
break;
case "generatorSettings":
this._setGeneratorSettings(raw.generatorSettings);
break;
case "layers":
this._setLayers(raw.layers);
break;
case "comps":
this._setComps(raw.comps);
break;
case "placed":
this._setPlaced(raw.placed);
break;
case "mode":
this._setMode(raw.mode);
break;
case "profile":
case "depth":
// Do nothing for these properties
// TODO could profile be helpful for embedding color profile?
break;
default:
this._logger.warn("Unhandled property in raw constructor:", property, raw[property]);
}
}
}
if (raw.hasOwnProperty("selection")) {
this._setSelection(raw.selection);
}
if (DEBUG_TO_RAW_CONVERSION) {
debugLogObject("document.toRaw", this.toRaw());
}
}
|
javascript
|
{
"resource": ""
}
|
q47597
|
BaseLayer
|
train
|
function BaseLayer(document, group, raw) {
this._document = document;
this._logger = document._logger;
if (group) {
this._setGroup(group);
}
var handledProperties = this._handledProperties || {},
property;
for (property in raw) {
if (raw.hasOwnProperty(property) && !handledProperties.hasOwnProperty(property)) {
switch (property) {
case "id":
this._id = raw.id;
break;
case "name":
this._setName(raw.name);
break;
case "bounds":
this._setBounds(raw.bounds);
break;
case "artboard":
this._setArtboard(raw.artboard);
break;
case "boundsWithFX":
this._setBoundsWithFX(raw.boundsWithFX);
break;
case "visible":
this._setVisible(raw.visible);
break;
case "clipped":
this._setClipped(raw.clipped);
break;
case "mask":
this._setMask(raw.mask);
break;
case "layerEffects":
this._setLayerEffects(raw.layerEffects);
break;
case "generatorSettings":
this._setGeneratorSettings(raw.generatorSettings);
break;
case "blendOptions":
this._setBlendOptions(raw.blendOptions);
break;
case "protection":
this._setProtection(raw.protection);
break;
case "path":
this._setPath(raw.path);
break;
case "type":
this._setType(raw.type);
break;
case "index":
case "added":
// ignore these properties
break;
default:
this._logger.warn("Unhandled property in raw constructor:", property, raw[property]);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47598
|
createLayer
|
train
|
function createLayer(document, parent, rawLayer) {
if (!parent && !rawLayer.hasOwnProperty("type")) {
return new LayerGroup(document, null, rawLayer);
}
switch (rawLayer.type) {
case "layerSection":
case "artboardSection":
case "framedGroupSection":
return new LayerGroup(document, parent, rawLayer);
case "layer":
return new Layer(document, parent, rawLayer);
case "shapeLayer":
return new ShapeLayer(document, parent, rawLayer);
case "textLayer":
return new TextLayer(document, parent, rawLayer);
case "adjustmentLayer":
return new AdjustmentLayer(document, parent, rawLayer);
case "smartObjectLayer":
return new SmartObjectLayer(document, parent, rawLayer);
case "backgroundLayer":
return new BackgroundLayer(document, parent, rawLayer);
default:
throw new Error("Unknown layer type:", rawLayer.type);
}
}
|
javascript
|
{
"resource": ""
}
|
q47599
|
getAframeElementsFromSceneStructure
|
train
|
function getAframeElementsFromSceneStructure(sceneStructure, parent) {
var collection = parent ? null : [] // use collection or parent
sceneStructure.forEach(function(element3d) {
// check if type is supported in aframe
if (validTypes.indexOf(element3d.type) > -1) {
// get html attributes from element3d objects
var el = addEntity({
attributes: getAttributes(element3d),
parent: parent
})
// the level scene might be baked
if (element3d.type === 'level') {
createBakedElement(el, element3d)
}
// recursively proceed through sceneStructure
if (element3d.children && element3d.children.length) getAframeElementsFromSceneStructure(element3d.children, el)
if (collection) collection.push(el)
}
})
return collection
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.