_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q15600
determineAlignment
train
function determineAlignment(tooltip, size) { var model = tooltip._model; var chart = tooltip._chart; var chartArea = tooltip._chart.chartArea; var xAlign = 'center'; var yAlign = 'center'; if (model.y < size.height) { yAlign = 'top'; } else if (model.y > (chart.height - size.height)) { yAlign = 'bottom'; } var lf, rf; // functions to determine left, right alignment var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges var midX = (chartArea.left + chartArea.right) / 2; var midY = (chartArea.top + chartArea.bottom) / 2; if (yAlign === 'center') { lf = function(x) { return x <= midX; }; rf = function(x) { return x > midX; }; } else { lf = function(x) { return x <= (size.width / 2); }; rf = function(x) { return x >= (chart.width - (size.width / 2)); }; } olf = function(x) { return x + size.width + model.caretSize + model.caretPadding > chart.width; }; orf = function(x) { return x - size.width - model.caretSize - model.caretPadding < 0; }; yf = function(y) { return y <= midY ? 'top' : 'bottom'; }; if (lf(model.x)) { xAlign = 'left'; // Is tooltip too wide and goes over the right side of the chart.? if (olf(model.x)) { xAlign = 'center'; yAlign = yf(model.y); } } else if (rf(model.x)) { xAlign = 'right'; // Is tooltip too wide and goes outside left edge of canvas? if (orf(model.x)) { xAlign = 'center'; yAlign = yf(model.y); } } var opts = tooltip._options; return { xAlign: opts.xAlign ? opts.xAlign : xAlign, yAlign: opts.yAlign ? opts.yAlign : yAlign }; }
javascript
{ "resource": "" }
q15601
train
function(chart, hook, args) { var descriptors = this.descriptors(chart); var ilen = descriptors.length; var i, descriptor, plugin, params, method; for (i = 0; i < ilen; ++i) { descriptor = descriptors[i]; plugin = descriptor.plugin; method = plugin[hook]; if (typeof method === 'function') { params = [chart].concat(args || []); params.push(descriptor.options); if (method.apply(plugin, params) === false) { return false; } } } return true; }
javascript
{ "resource": "" }
q15602
train
function(chart) { var cache = chart.$plugins || (chart.$plugins = {}); if (cache.id === this._cacheId) { return cache.descriptors; } var plugins = []; var descriptors = []; var config = (chart && chart.config) || {}; var options = (config.options && config.options.plugins) || {}; this._plugins.concat(config.plugins || []).forEach(function(plugin) { var idx = plugins.indexOf(plugin); if (idx !== -1) { return; } var id = plugin.id; var opts = options[id]; if (opts === false) { return; } if (opts === true) { opts = helpers.clone(defaults.global.plugins[id]); } plugins.push(plugin); descriptors.push({ plugin: plugin, options: opts || {} }); }); cache.descriptors = descriptors; cache.id = this._cacheId; return descriptors; }
javascript
{ "resource": "" }
q15603
getBarBounds
train
function getBarBounds(vm) { var x1, x2, y1, y2, half; if (isVertical(vm)) { half = vm.width / 2; x1 = vm.x - half; x2 = vm.x + half; y1 = Math.min(vm.y, vm.base); y2 = Math.max(vm.y, vm.base); } else { half = vm.height / 2; x1 = Math.min(vm.x, vm.base); x2 = Math.max(vm.x, vm.base); y1 = vm.y - half; y2 = vm.y + half; } return { left: x1, top: y1, right: x2, bottom: y2 }; }
javascript
{ "resource": "" }
q15604
fitWithPointLabels
train
function fitWithPointLabels(scale) { // Right, this is really confusing and there is a lot of maths going on here // The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9 // // Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif // // Solution: // // We assume the radius of the polygon is half the size of the canvas at first // at each index we check if the text overlaps. // // Where it does, we store that angle and that index. // // After finding the largest index and angle we calculate how much we need to remove // from the shape radius to move the point inwards by that x. // // We average the left and right distances to get the maximum shape radius that can fit in the box // along with labels. // // Once we have that, we can find the centre point for the chart, by taking the x text protrusion // on each side, removing that from the size, halving it and adding the left x protrusion width. // // This will mean we have a shape fitted to the canvas, as large as it can be with the labels // and position it in the most space efficient manner // // https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif var plFont = helpers.options._parseFont(scale.options.pointLabels); // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width. // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points var furthestLimits = { l: 0, r: scale.width, t: 0, b: scale.height - scale.paddingTop }; var furthestAngles = {}; var i, textSize, pointPosition; scale.ctx.font = plFont.string; scale._pointLabelSizes = []; var valueCount = getValueCount(scale); for (i = 0; i < valueCount; i++) { pointPosition = scale.getPointPosition(i, scale.drawingArea + 5); textSize = measureLabelSize(scale.ctx, plFont.lineHeight, scale.pointLabels[i] || ''); scale._pointLabelSizes[i] = textSize; // Add quarter circle to make degree 0 mean top of circle var angleRadians = scale.getIndexAngle(i); var angle = helpers.toDegrees(angleRadians) % 360; var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180); var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270); if (hLimits.start < furthestLimits.l) { furthestLimits.l = hLimits.start; furthestAngles.l = angleRadians; } if (hLimits.end > furthestLimits.r) { furthestLimits.r = hLimits.end; furthestAngles.r = angleRadians; } if (vLimits.start < furthestLimits.t) { furthestLimits.t = vLimits.start; furthestAngles.t = angleRadians; } if (vLimits.end > furthestLimits.b) { furthestLimits.b = vLimits.end; furthestAngles.b = angleRadians; } } scale.setReductions(scale.drawingArea, furthestLimits, furthestAngles); }
javascript
{ "resource": "" }
q15605
train
function(largestPossibleRadius, furthestLimits, furthestAngles) { var me = this; var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l); var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r); var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t); var radiusReductionBottom = -Math.max(furthestLimits.b - (me.height - me.paddingTop), 0) / Math.cos(furthestAngles.b); radiusReductionLeft = numberOrZero(radiusReductionLeft); radiusReductionRight = numberOrZero(radiusReductionRight); radiusReductionTop = numberOrZero(radiusReductionTop); radiusReductionBottom = numberOrZero(radiusReductionBottom); me.drawingArea = Math.min( Math.floor(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2), Math.floor(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2)); me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom); }
javascript
{ "resource": "" }
q15606
train
function(datasetIndex) { var ringWeightOffset = 0; for (var i = 0; i < datasetIndex; ++i) { if (this.chart.isDatasetVisible(i)) { ringWeightOffset += this._getRingWeight(i); } } return ringWeightOffset; }
javascript
{ "resource": "" }
q15607
determineUnitForAutoTicks
train
function determineUnitForAutoTicks(minUnit, min, max, capacity) { var ilen = UNITS.length; var i, interval, factor; for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) { interval = INTERVALS[UNITS[i]]; factor = interval.steps ? interval.steps[interval.steps.length - 1] : MAX_INTEGER; if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) { return UNITS[i]; } } return UNITS[ilen - 1]; }
javascript
{ "resource": "" }
q15608
determineUnitForFormatting
train
function determineUnitForFormatting(scale, ticks, minUnit, min, max) { var ilen = UNITS.length; var i, unit; for (i = ilen - 1; i >= UNITS.indexOf(minUnit); i--) { unit = UNITS[i]; if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= ticks.length) { return unit; } } return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0]; }
javascript
{ "resource": "" }
q15609
train
function() { var me = this; if (me.margins) { me.paddingLeft = Math.max(me.paddingLeft - me.margins.left, 0); me.paddingTop = Math.max(me.paddingTop - me.margins.top, 0); me.paddingRight = Math.max(me.paddingRight - me.margins.right, 0); me.paddingBottom = Math.max(me.paddingBottom - me.margins.bottom, 0); } }
javascript
{ "resource": "" }
q15610
train
function(ticks) { var me = this; var isHorizontal = me.isHorizontal(); var optionTicks = me.options.ticks; var tickCount = ticks.length; var skipRatio = false; var maxTicks = optionTicks.maxTicksLimit; // Total space needed to display all ticks. First and last ticks are // drawn as their center at end of axis, so tickCount-1 var ticksLength = me._tickSize() * (tickCount - 1); // Axis length var axisLength = isHorizontal ? me.width - (me.paddingLeft + me.paddingRight) : me.height - (me.paddingTop + me.PaddingBottom); var result = []; var i, tick; if (ticksLength > axisLength) { skipRatio = 1 + Math.floor(ticksLength / axisLength); } // if they defined a max number of optionTicks, // increase skipRatio until that number is met if (tickCount > maxTicks) { skipRatio = Math.max(skipRatio, 1 + Math.floor(tickCount / maxTicks)); } for (i = 0; i < tickCount; i++) { tick = ticks[i]; if (skipRatio > 1 && i % skipRatio > 0) { // leave tick in place but make sure it's not displayed (#4635) delete tick.label; } result.push(tick); } return result; }
javascript
{ "resource": "" }
q15611
train
function() { var me = this; me._config = helpers.merge({}, [ me.chart.options.datasets[me._type], me.getDataset(), ], { merger: function(key, target, source) { if (key !== '_meta' && key !== 'data') { helpers._merger(key, target, source); } } }); }
javascript
{ "resource": "" }
q15612
train
function(value, index, defaultValue) { return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue); }
javascript
{ "resource": "" }
q15613
train
function(fn, args, thisArg) { if (fn && typeof fn.call === 'function') { return fn.apply(thisArg, args); } }
javascript
{ "resource": "" }
q15614
train
function(a0, a1) { var i, ilen, v0, v1; if (!a0 || !a1 || a0.length !== a1.length) { return false; } for (i = 0, ilen = a0.length; i < ilen; ++i) { v0 = a0[i]; v1 = a1[i]; if (v0 instanceof Array && v1 instanceof Array) { if (!helpers.arrayEquals(v0, v1)) { return false; } } else if (v0 !== v1) { // NOTE: two different object instances will never be equal: {x:20} != {x:20} return false; } } return true; }
javascript
{ "resource": "" }
q15615
train
function(source) { if (helpers.isArray(source)) { return source.map(helpers.clone); } if (helpers.isObject(source)) { var target = {}; var keys = Object.keys(source); var klen = keys.length; var k = 0; for (; k < klen; ++k) { target[keys[k]] = helpers.clone(source[keys[k]]); } return target; } return source; }
javascript
{ "resource": "" }
q15616
train
function() { var data = this.chart.data; return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels; }
javascript
{ "resource": "" }
q15617
train
function(e, legendItem) { var index = legendItem.datasetIndex; var ci = this.chart; var meta = ci.getDatasetMeta(index); // See controller.isDatasetVisible comment meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null; // We hid a dataset ... rerender the chart ci.update(); }
javascript
{ "resource": "" }
q15618
getBoxWidth
train
function getBoxWidth(labelOpts, fontSize) { return labelOpts.usePointStyle && labelOpts.boxWidth > fontSize ? fontSize : labelOpts.boxWidth; }
javascript
{ "resource": "" }
q15619
getNearestItems
train
function getNearestItems(chart, position, intersect, distanceMetric) { var minDistance = Number.POSITIVE_INFINITY; var nearestItems = []; parseVisibleItems(chart, function(element) { if (intersect && !element.inRange(position.x, position.y)) { return; } var center = element.getCenterPoint(); var distance = distanceMetric(position, center); if (distance < minDistance) { nearestItems = [element]; minDistance = distance; } else if (distance === minDistance) { // Can have multiple items at the same distance in which case we sort by size nearestItems.push(element); } }); return nearestItems; }
javascript
{ "resource": "" }
q15620
getDistanceMetricForAxis
train
function getDistanceMetricForAxis(axis) { var useX = axis.indexOf('x') !== -1; var useY = axis.indexOf('y') !== -1; return function(pt1, pt2) { var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0; var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0; return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2)); }; }
javascript
{ "resource": "" }
q15621
train
function(chart, e, options) { var position = getRelativePosition(e, chart); options.axis = options.axis || 'xy'; var distanceMetric = getDistanceMetricForAxis(options.axis); return getNearestItems(chart, position, options.intersect, distanceMetric); }
javascript
{ "resource": "" }
q15622
generateIjmap
train
function generateIjmap(ijmapPath) { return through2.obj((codepointsFile, encoding, callback) => { const ijmap = { icons: codepointsToIjmap(codepointsFile.contents.toString()) }; callback(null, new File({ path: ijmapPath, contents: new Buffer(JSON.stringify(ijmap), 'utf8') })); function codepointsToIjmap(codepoints) { return _(codepoints) .split('\n') // split into lines .reject(_.isEmpty) // remove empty lines .reduce((codepointMap, line) => { // build up the codepoint map let [ name, codepoint ] = line.split(' '); codepointMap[codepoint] = { name: titleize(humanize(name)) }; return codepointMap; }, {}); } }); }
javascript
{ "resource": "" }
q15623
getSvgSpriteConfig
train
function getSvgSpriteConfig(category) { return { shape: { dimension: { maxWidth: 24, maxHeight: 24 }, }, mode: { css : { bust: false, dest: './', sprite: `./svg-sprite-${ category }.svg`, example: { dest: `./svg-sprite-${ category }.html` }, render: { css: { dest: `./svg-sprite-${ category }.css` } } }, symbol : { bust: false, dest: './', sprite: `./svg-sprite-${ category }-symbol.svg`, example: { dest: `./svg-sprite-${ category }-symbol.html` } } } }; }
javascript
{ "resource": "" }
q15624
getCategoryColorPairs
train
function getCategoryColorPairs() { return _(ICON_CATEGORIES) .map((category) => _.zip(_.times(PNG_COLORS.length, () => category), PNG_COLORS)) .flatten() // flattens 1 level .value(); }
javascript
{ "resource": "" }
q15625
Server
train
function Server(srv, opts){ if (!(this instanceof Server)) return new Server(srv, opts); if ('object' == typeof srv && srv instanceof Object && !srv.listen) { opts = srv; srv = null; } opts = opts || {}; this.nsps = {}; this.parentNsps = new Map(); this.path(opts.path || '/socket.io'); this.serveClient(false !== opts.serveClient); this.parser = opts.parser || parser; this.encoder = new this.parser.Encoder(); this.adapter(opts.adapter || Adapter); this.origins(opts.origins || '*:*'); this.sockets = this.of('/'); if (srv) this.attach(srv, opts); }
javascript
{ "resource": "" }
q15626
Client
train
function Client(server, conn){ this.server = server; this.conn = conn; this.encoder = server.encoder; this.decoder = new server.parser.Decoder(); this.id = conn.id; this.request = conn.request; this.setup(); this.sockets = {}; this.nsps = {}; this.connectBuffer = []; }
javascript
{ "resource": "" }
q15627
writeToEngine
train
function writeToEngine(encodedPackets) { if (opts.volatile && !self.conn.transport.writable) return; for (var i = 0; i < encodedPackets.length; i++) { self.conn.write(encodedPackets[i], { compress: opts.compress }); } }
javascript
{ "resource": "" }
q15628
Namespace
train
function Namespace(server, name){ this.name = name; this.server = server; this.sockets = {}; this.connected = {}; this.fns = []; this.ids = 0; this.rooms = []; this.flags = {}; this.initAdapter(); }
javascript
{ "resource": "" }
q15629
throttle
train
function throttle(callback, delay) { var previousCall = new Date().getTime(); return function() { var time = new Date().getTime(); if ((time - previousCall) >= delay) { previousCall = time; callback.apply(null, arguments); } }; }
javascript
{ "resource": "" }
q15630
Socket
train
function Socket(nsp, client, query){ this.nsp = nsp; this.server = nsp.server; this.adapter = this.nsp.adapter; this.id = nsp.name !== '/' ? nsp.name + '#' + client.id : client.id; this.client = client; this.conn = client.conn; this.rooms = {}; this.acks = {}; this.connected = true; this.disconnected = false; this.handshake = this.buildHandshake(query); this.fns = []; this.flags = {}; this._rooms = []; }
javascript
{ "resource": "" }
q15631
train
function() { var corePath = __dirname + "/../src/core.js", contents = fs.readFileSync( corePath, "utf8" ); contents = contents.replace( /@VERSION/g, Release.newVersion ); fs.writeFileSync( corePath, contents, "utf8" ); }
javascript
{ "resource": "" }
q15632
train
function( callback ) { Release.exec( "grunt", "Grunt command failed" ); Release.exec( "grunt custom:-ajax,-effects --filename=jquery.slim.js && " + "grunt remove_map_comment --filename=jquery.slim.js", "Grunt custom failed" ); cdn.makeReleaseCopies( Release ); Release._setSrcVersion(); callback( files ); }
javascript
{ "resource": "" }
q15633
train
function() { // origRepo is not defined if dist was skipped Release.dir.repo = Release.dir.origRepo || Release.dir.repo; return npmTags(); }
javascript
{ "resource": "" }
q15634
clone
train
function clone() { Release.chdir( Release.dir.base ); Release.dir.dist = Release.dir.base + "/dist"; console.log( "Using distribution repo: ", distRemote ); Release.exec( "git clone " + distRemote + " " + Release.dir.dist, "Error cloning repo." ); // Distribution always works on master Release.chdir( Release.dir.dist ); Release.exec( "git checkout master", "Error checking out branch." ); console.log(); }
javascript
{ "resource": "" }
q15635
generateBower
train
function generateBower() { return JSON.stringify( { name: pkg.name, main: pkg.main, license: "MIT", ignore: [ "package.json" ], keywords: pkg.keywords }, null, 2 ); }
javascript
{ "resource": "" }
q15636
editReadme
train
function editReadme( readme ) { var rprev = new RegExp( Release.prevVersion, "g" ); return readme.replace( rprev, Release.newVersion ); }
javascript
{ "resource": "" }
q15637
commit
train
function commit() { console.log( "Adding files to dist..." ); Release.exec( "git add -A", "Error adding files." ); Release.exec( "git commit -m \"Release " + Release.newVersion + "\"", "Error committing files." ); console.log(); console.log( "Tagging release on dist..." ); Release.exec( "git tag " + Release.newVersion, "Error tagging " + Release.newVersion + " on dist repo." ); Release.tagTime = Release.exec( "git log -1 --format=\"%ad\"", "Error getting tag timestamp." ).trim(); }
javascript
{ "resource": "" }
q15638
push
train
function push() { Release.chdir( Release.dir.dist ); console.log( "Pushing release to dist repo..." ); Release.exec( "git push " + distRemote + " master --tags", "Error pushing master and tags to git repo." ); // Set repo for npm publish Release.dir.origRepo = Release.dir.repo; Release.dir.repo = Release.dir.dist; }
javascript
{ "resource": "" }
q15639
makeReleaseCopies
train
function makeReleaseCopies( Release ) { shell.mkdir( "-p", cdnFolder ); Object.keys( releaseFiles ).forEach( function( key ) { var text, builtFile = releaseFiles[ key ], unpathedFile = key.replace( /VER/g, Release.newVersion ), releaseFile = cdnFolder + "/" + unpathedFile; if ( /\.map$/.test( releaseFile ) ) { // Map files need to reference the new uncompressed name; // assume that all files reside in the same directory. // "file":"jquery.min.js" ... "sources":["jquery.js"] text = fs.readFileSync( builtFile, "utf8" ) .replace( /"file":"([^"]+)"/, "\"file\":\"" + unpathedFile.replace( /\.min\.map/, ".min.js\"" ) ) .replace( /"sources":\["([^"]+)"\]/, "\"sources\":[\"" + unpathedFile.replace( /\.min\.map/, ".js" ) + "\"]" ); fs.writeFileSync( releaseFile, text ); } else if ( builtFile !== releaseFile ) { shell.cp( "-f", builtFile, releaseFile ); } } ); }
javascript
{ "resource": "" }
q15640
finalPropName
train
function finalPropName( name ) { var final = vendorProps[ name ]; if ( final ) { return final; } if ( name in emptyStyle ) { return name; } return vendorProps[ name ] = vendorPropName( name ) || name; }
javascript
{ "resource": "" }
q15641
scan
train
function scan () { rootInstances.length = 0 let inFragment = false let currentFragment = null function processInstance (instance) { if (instance) { if (rootInstances.indexOf(instance.$root) === -1) { instance = instance.$root } if (instance._isFragment) { inFragment = true currentFragment = instance } // respect Vue.config.devtools option let baseVue = instance.constructor while (baseVue.super) { baseVue = baseVue.super } if (baseVue.config && baseVue.config.devtools) { // give a unique id to root instance so we can // 'namespace' its children if (typeof instance.__VUE_DEVTOOLS_ROOT_UID__ === 'undefined') { instance.__VUE_DEVTOOLS_ROOT_UID__ = ++rootUID } rootInstances.push(instance) } return true } } if (isBrowser) { walk(document, function (node) { if (inFragment) { if (node === currentFragment._fragmentEnd) { inFragment = false currentFragment = null } return true } let instance = node.__vue__ return processInstance(instance) }) } else { if (Array.isArray(target.__VUE_ROOT_INSTANCES__)) { target.__VUE_ROOT_INSTANCES__.map(processInstance) } } hook.emit('router:init') flush() }
javascript
{ "resource": "" }
q15642
walk
train
function walk (node, fn) { if (node.childNodes) { for (let i = 0, l = node.childNodes.length; i < l; i++) { const child = node.childNodes[i] const stop = fn(child) if (!stop) { walk(child, fn) } } } // also walk shadow DOM if (node.shadowRoot) { walk(node.shadowRoot, fn) } }
javascript
{ "resource": "" }
q15643
isQualified
train
function isQualified (instance) { const name = classify(instance.name || getInstanceName(instance)).toLowerCase() return name.indexOf(filter) > -1 }
javascript
{ "resource": "" }
q15644
mark
train
function mark (instance) { if (!instanceMap.has(instance.__VUE_DEVTOOLS_UID__)) { instanceMap.set(instance.__VUE_DEVTOOLS_UID__, instance) instance.$on('hook:beforeDestroy', function () { instanceMap.delete(instance.__VUE_DEVTOOLS_UID__) }) } }
javascript
{ "resource": "" }
q15645
getInstanceDetails
train
function getInstanceDetails (id) { const instance = instanceMap.get(id) if (!instance) { const vnode = findInstanceOrVnode(id) if (!vnode) return {} const data = { id, name: getComponentName(vnode.fnOptions), file: vnode.fnOptions.__file || null, state: processProps({ $options: vnode.fnOptions, ...(vnode.devtoolsMeta && vnode.devtoolsMeta.renderContext.props) }), functional: true } return data } else { const data = { id: id, name: getInstanceName(instance), state: getInstanceState(instance) } let i if ((i = instance.$vnode) && (i = i.componentOptions) && (i = i.Ctor) && (i = i.options)) { data.file = i.__file || null } return data } }
javascript
{ "resource": "" }
q15646
processState
train
function processState (instance) { const props = isLegacy ? instance._props : instance.$options.props const getters = instance.$options.vuex && instance.$options.vuex.getters return Object.keys(instance._data) .filter(key => ( !(props && key in props) && !(getters && key in getters) )) .map(key => ({ key, value: instance._data[key], editable: true })) }
javascript
{ "resource": "" }
q15647
processComputed
train
function processComputed (instance) { const computed = [] const defs = instance.$options.computed || {} // use for...in here because if 'computed' is not defined // on component, computed properties will be placed in prototype // and Object.keys does not include // properties from object's prototype for (const key in defs) { const def = defs[key] const type = typeof def === 'function' && def.vuex ? 'vuex bindings' : 'computed' // use try ... catch here because some computed properties may // throw error during its evaluation let computedProp = null try { computedProp = { type, key, value: instance[key] } } catch (e) { computedProp = { type, key, value: '(error during evaluation)' } } computed.push(computedProp) } return computed }
javascript
{ "resource": "" }
q15648
processFirebaseBindings
train
function processFirebaseBindings (instance) { var refs = instance.$firebaseRefs if (refs) { return Object.keys(refs).map(key => { return { type: 'firebase bindings', key, value: instance[key] } }) } else { return [] } }
javascript
{ "resource": "" }
q15649
processObservables
train
function processObservables (instance) { var obs = instance.$observables if (obs) { return Object.keys(obs).map(key => { return { type: 'observables', key, value: instance[key] } }) } else { return [] } }
javascript
{ "resource": "" }
q15650
scrollIntoView
train
function scrollIntoView (instance) { const rect = getInstanceOrVnodeRect(instance) if (rect) { // TODO: Handle this for non-browser environments. window.scrollBy(0, rect.top + (rect.height - window.innerHeight) / 2) } }
javascript
{ "resource": "" }
q15651
onContextMenu
train
function onContextMenu ({ id }) { if (id === 'vue-inspect-instance') { const src = `window.__VUE_DEVTOOLS_CONTEXT_MENU_HAS_TARGET__` chrome.devtools.inspectedWindow.eval(src, function (res, err) { if (err) { console.log(err) } if (typeof res !== 'undefined' && res) { panelAction(() => { chrome.runtime.sendMessage('vue-get-context-menu-target') }, 'Open Vue devtools to see component details') } else { pendingAction = null toast('No Vue component was found', 'warn') } }) } }
javascript
{ "resource": "" }
q15652
panelAction
train
function panelAction (cb, message = null) { if (created && panelLoaded && panelShown) { cb() } else { pendingAction = cb message && toast(message) } }
javascript
{ "resource": "" }
q15653
injectScript
train
function injectScript (scriptName, cb) { const src = ` (function() { var script = document.constructor.prototype.createElement.call(document, 'script'); script.src = "${scriptName}"; document.documentElement.appendChild(script); script.parentNode.removeChild(script); })() ` chrome.devtools.inspectedWindow.eval(src, function (res, err) { if (err) { console.log(err) } cb() }) }
javascript
{ "resource": "" }
q15654
getFragmentRect
train
function getFragmentRect ({ _fragmentStart, _fragmentEnd }) { let top, bottom, left, right util().mapNodeRange(_fragmentStart, _fragmentEnd, function (node) { let rect if (node.nodeType === 1 || node.getBoundingClientRect) { rect = node.getBoundingClientRect() } else if (node.nodeType === 3 && node.data.trim()) { rect = getTextRect(node) } if (rect) { if (!top || rect.top < top) { top = rect.top } if (!bottom || rect.bottom > bottom) { bottom = rect.bottom } if (!left || rect.left < left) { left = rect.left } if (!right || rect.right > right) { right = rect.right } } }) return { top, left, width: right - left, height: bottom - top } }
javascript
{ "resource": "" }
q15655
getTextRect
train
function getTextRect (node) { if (!isBrowser) return if (!range) range = document.createRange() range.selectNode(node) return range.getBoundingClientRect() }
javascript
{ "resource": "" }
q15656
showOverlay
train
function showOverlay ({ width = 0, height = 0, top = 0, left = 0 }, content = []) { if (!isBrowser) return overlay.style.width = ~~width + 'px' overlay.style.height = ~~height + 'px' overlay.style.top = ~~top + 'px' overlay.style.left = ~~left + 'px' overlayContent.innerHTML = '' content.forEach(child => overlayContent.appendChild(child)) document.body.appendChild(overlay) }
javascript
{ "resource": "" }
q15657
basename
train
function basename (filename, ext) { return path.basename( filename.replace(/^[a-zA-Z]:/, '').replace(/\\/g, '/'), ext ) }
javascript
{ "resource": "" }
q15658
sanitize
train
function sanitize (data) { if ( !isPrimitive(data) && !Array.isArray(data) && !isPlainObject(data) ) { // handle types that will probably cause issues in // the structured clone return Object.prototype.toString.call(data) } else { return data } }
javascript
{ "resource": "" }
q15659
internalSearchObject
train
function internalSearchObject (obj, searchTerm, seen, depth) { if (depth > SEARCH_MAX_DEPTH) { return false } let match = false const keys = Object.keys(obj) let key, value for (let i = 0; i < keys.length; i++) { key = keys[i] value = obj[key] match = internalSearchCheck(searchTerm, key, value, seen, depth + 1) if (match) { break } } return match }
javascript
{ "resource": "" }
q15660
internalSearchArray
train
function internalSearchArray (array, searchTerm, seen, depth) { if (depth > SEARCH_MAX_DEPTH) { return false } let match = false let value for (let i = 0; i < array.length; i++) { value = array[i] match = internalSearchCheck(searchTerm, null, value, seen, depth + 1) if (match) { break } } return match }
javascript
{ "resource": "" }
q15661
internalSearchCheck
train
function internalSearchCheck (searchTerm, key, value, seen, depth) { let match = false let result if (key === '_custom') { key = value.display value = value.value } (result = specialTokenToString(value)) && (value = result) if (key && compare(key, searchTerm)) { match = true seen.set(value, true) } else if (seen.has(value)) { match = seen.get(value) } else if (Array.isArray(value)) { seen.set(value, null) match = internalSearchArray(value, searchTerm, seen, depth) seen.set(value, match) } else if (isPlainObject(value)) { seen.set(value, null) match = internalSearchObject(value, searchTerm, seen, depth) seen.set(value, match) } else if (compare(value, searchTerm)) { match = true seen.set(value, true) } return match }
javascript
{ "resource": "" }
q15662
createColoredCanvas
train
function createColoredCanvas(color) { const canvas = document.createElement('canvas'); canvas.width = 6; canvas.height = 1; const context = canvas.getContext('2d'); context.fillStyle = color; context.fillRect(0, 0, 6, 1); return canvas; }
javascript
{ "resource": "" }
q15663
getPt
train
function getPt(n1, n2, perc) { const diff = n2 - n1; return n1 + (diff * perc); }
javascript
{ "resource": "" }
q15664
uploadGraphics
train
function uploadGraphics(renderer, item) { if (item instanceof Graphics) { // if the item is not dirty and already has webgl data, then it got prepared or rendered // before now and we shouldn't waste time updating it again if (item.dirty || item.clearDirty || !item._webGL[renderer.plugins.graphics.CONTEXT_UID]) { renderer.plugins.graphics.updateGraphics(item); } return true; } return false; }
javascript
{ "resource": "" }
q15665
findGraphics
train
function findGraphics(item, queue) { if (item instanceof Graphics) { queue.push(item); return true; } return false; }
javascript
{ "resource": "" }
q15666
findMultipleBaseTextures
train
function findMultipleBaseTextures(item, queue) { let result = false; // Objects with multiple textures if (item && item._textures && item._textures.length) { for (let i = 0; i < item._textures.length; i++) { if (item._textures[i] instanceof Texture) { const baseTexture = item._textures[i].baseTexture; if (queue.indexOf(baseTexture) === -1) { queue.push(baseTexture); result = true; } } } } return result; }
javascript
{ "resource": "" }
q15667
findBaseTexture
train
function findBaseTexture(item, queue) { // Objects with textures, like Sprites/Text if (item instanceof BaseTexture) { if (queue.indexOf(item) === -1) { queue.push(item); } return true; } return false; }
javascript
{ "resource": "" }
q15668
findTexture
train
function findTexture(item, queue) { if (item._texture && item._texture instanceof Texture) { const texture = item._texture.baseTexture; if (queue.indexOf(texture) === -1) { queue.push(texture); } return true; } return false; }
javascript
{ "resource": "" }
q15669
drawText
train
function drawText(helper, item) { if (item instanceof Text) { // updating text will return early if it is not dirty item.updateText(true); return true; } return false; }
javascript
{ "resource": "" }
q15670
calculateTextStyle
train
function calculateTextStyle(helper, item) { if (item instanceof TextStyle) { const font = item.toFontString(); TextMetrics.measureFont(font); return true; } return false; }
javascript
{ "resource": "" }
q15671
findText
train
function findText(item, queue) { if (item instanceof Text) { // push the text style to prepare it - this can be really expensive if (queue.indexOf(item.style) === -1) { queue.push(item.style); } // also push the text object so that we can render it (to canvas/texture) if needed if (queue.indexOf(item) === -1) { queue.push(item); } // also push the Text's texture for upload to GPU const texture = item._texture.baseTexture; if (queue.indexOf(texture) === -1) { queue.push(texture); } return true; } return false; }
javascript
{ "resource": "" }
q15672
findTextStyle
train
function findTextStyle(item, queue) { if (item instanceof TextStyle) { if (queue.indexOf(item) === -1) { queue.push(item); } return true; } return false; }
javascript
{ "resource": "" }
q15673
getSingleColor
train
function getSingleColor(color) { if (typeof color === 'number') { return hex2string(color); } else if ( typeof color === 'string' ) { if ( color.indexOf('0x') === 0 ) { color = color.replace('0x', '#'); } } return color; }
javascript
{ "resource": "" }
q15674
deepCopyProperties
train
function deepCopyProperties(target, source, propertyObj) { for (const prop in propertyObj) { if (Array.isArray(source[prop])) { target[prop] = source[prop].slice(); } else { target[prop] = source[prop]; } } }
javascript
{ "resource": "" }
q15675
mapPremultipliedBlendModes
train
function mapPremultipliedBlendModes() { const pm = []; const npm = []; for (let i = 0; i < 32; i++) { pm[i] = i; npm[i] = i; } pm[BLEND_MODES.NORMAL_NPM] = BLEND_MODES.NORMAL; pm[BLEND_MODES.ADD_NPM] = BLEND_MODES.ADD; pm[BLEND_MODES.SCREEN_NPM] = BLEND_MODES.SCREEN; npm[BLEND_MODES.NORMAL] = BLEND_MODES.NORMAL_NPM; npm[BLEND_MODES.ADD] = BLEND_MODES.ADD_NPM; npm[BLEND_MODES.SCREEN] = BLEND_MODES.SCREEN_NPM; const array = []; array.push(npm); array.push(pm); return array; }
javascript
{ "resource": "" }
q15676
sleuth_fat
train
function sleuth_fat(idx, cnt, sectors, ssz, fat_addrs) { var q = ENDOFCHAIN; if(idx === ENDOFCHAIN) { if(cnt !== 0) throw new Error("DIFAT chain shorter than expected"); } else if(idx !== -1 /*FREESECT*/) { var sector = sectors[idx], m = (ssz>>>2)-1; if(!sector) return; for(var i = 0; i < m; ++i) { if((q = __readInt32LE(sector,i*4)) === ENDOFCHAIN) break; fat_addrs.push(q); } sleuth_fat(__readInt32LE(sector,ssz-4),cnt - 1, sectors, ssz, fat_addrs); } }
javascript
{ "resource": "" }
q15677
get_sector_list
train
function get_sector_list(sectors, start, fat_addrs, ssz, chkd) { var buf = [], buf_chain = []; if(!chkd) chkd = []; var modulus = ssz - 1, j = 0, jj = 0; for(j=start; j>=0;) { chkd[j] = true; buf[buf.length] = j; buf_chain.push(sectors[j]); var addr = fat_addrs[Math.floor(j*4/ssz)]; jj = ((j*4) & modulus); if(ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j + " 4 "+ssz); if(!sectors[addr]) break; j = __readInt32LE(sectors[addr], jj); } return {nodes: buf, data:__toBuffer([buf_chain])}; }
javascript
{ "resource": "" }
q15678
make_sector_list
train
function make_sector_list(sectors, dir_start, fat_addrs, ssz) { var sl = sectors.length, sector_list = ([]); var chkd = [], buf = [], buf_chain = []; var modulus = ssz - 1, i=0, j=0, k=0, jj=0; for(i=0; i < sl; ++i) { buf = ([]); k = (i + dir_start); if(k >= sl) k-=sl; if(chkd[k]) continue; buf_chain = []; for(j=k; j>=0;) { chkd[j] = true; buf[buf.length] = j; buf_chain.push(sectors[j]); var addr = fat_addrs[Math.floor(j*4/ssz)]; jj = ((j*4) & modulus); if(ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j + " 4 "+ssz); if(!sectors[addr]) break; j = __readInt32LE(sectors[addr], jj); } sector_list[k] = ({nodes: buf, data:__toBuffer([buf_chain])}); } return sector_list; }
javascript
{ "resource": "" }
q15679
resolveSFCs
train
function resolveSFCs (dirs) { return dirs.map( layoutDir => readdirSync(layoutDir) .filter(filename => filename.endsWith('.vue')) .map(filename => { const componentName = getComponentName(filename) return { filename, componentName, isInternal: isInternal(componentName), path: resolve(layoutDir, filename) } }) ).reduce((arr, next) => { arr.push(...next) return arr }, []).reduce((map, component) => { map[component.componentName] = component return map }, {}) }
javascript
{ "resource": "" }
q15680
compile
train
function compile (config) { return new Promise((resolve, reject) => { webpack(config, (err, stats) => { if (err) { return reject(err) } if (stats.hasErrors()) { stats.toJson().errors.forEach(err => { console.error(err) }) reject(new Error(`Failed to compile with errors.`)) return } if (env.isDebug && stats.hasWarnings()) { stats.toJson().warnings.forEach(warning => { console.warn(warning) }) } resolve(stats.toJson({ modules: false })) }) }) }
javascript
{ "resource": "" }
q15681
renderHeadTag
train
function renderHeadTag (tag) { const { tagName, attributes, innerHTML, closeTag } = normalizeHeadTag(tag) return `<${tagName}${renderAttrs(attributes)}>${innerHTML}${closeTag ? `</${tagName}>` : ``}` }
javascript
{ "resource": "" }
q15682
renderAttrs
train
function renderAttrs (attrs = {}) { const keys = Object.keys(attrs) if (keys.length) { return ' ' + keys.map(name => `${name}="${escape(attrs[name])}"`).join(' ') } else { return '' } }
javascript
{ "resource": "" }
q15683
renderPageMeta
train
function renderPageMeta (meta) { if (!meta) return '' return meta.map(m => { let res = `<meta` Object.keys(m).forEach(key => { res += ` ${key}="${escape(m[key])}"` }) return res + `>` }).join('') }
javascript
{ "resource": "" }
q15684
CLI
train
async function CLI ({ beforeParse, afterParse }) { const cli = CAC() beforeParse && await beforeParse(cli) cli.parse(process.argv) afterParse && await afterParse(cli) }
javascript
{ "resource": "" }
q15685
wrapCommand
train
function wrapCommand (fn) { return (...args) => { return fn(...args).catch(err => { console.error(chalk.red(err.stack)) process.exitCode = 1 }) } }
javascript
{ "resource": "" }
q15686
resolveHost
train
function resolveHost (host) { const defaultHost = '0.0.0.0' host = host || defaultHost const displayHost = host === defaultHost ? 'localhost' : host return { displayHost, host } }
javascript
{ "resource": "" }
q15687
resolvePort
train
async function resolvePort (port) { const portfinder = require('portfinder') portfinder.basePort = parseInt(port) || 8080 port = await portfinder.getPortPromise() return port }
javascript
{ "resource": "" }
q15688
normalizeWatchFilePath
train
function normalizeWatchFilePath (filepath, baseDir) { const { isAbsolute, relative } = require('path') if (isAbsolute(filepath)) { return relative(baseDir, filepath) } return filepath }
javascript
{ "resource": "" }
q15689
routesCode
train
function routesCode (pages) { function genRoute ({ path: pagePath, key: componentName, frontmatter: { layout }, regularPath, _meta }) { let code = ` { name: ${JSON.stringify(componentName)}, path: ${JSON.stringify(pagePath)}, component: GlobalLayout, beforeEnter: (to, from, next) => { ensureAsyncComponentsLoaded(${JSON.stringify(layout || 'Layout')}, ${JSON.stringify(componentName)}).then(next) },${_meta ? `\n meta: ${JSON.stringify(_meta)}` : ''} }` const dncodedPath = decodeURIComponent(pagePath) if (dncodedPath !== pagePath) { code += `, { path: ${JSON.stringify(dncodedPath)}, redirect: ${JSON.stringify(pagePath)} }` } if (/\/$/.test(pagePath)) { code += `, { path: ${JSON.stringify(pagePath + 'index.html')}, redirect: ${JSON.stringify(pagePath)} }` } if (regularPath !== pagePath) { code += `, { path: ${JSON.stringify(regularPath)}, redirect: ${JSON.stringify(pagePath)} }` } return code } const notFoundRoute = `, { path: '*', component: GlobalLayout }` return ( `export const routes = [${pages.map(genRoute).join(',')}${notFoundRoute}\n]` ) }
javascript
{ "resource": "" }
q15690
registerUnknownCommands
train
function registerUnknownCommands (cli, options) { cli.on('command:*', async () => { const { args, options: commandoptions } = cli logger.debug('global_options', options) logger.debug('cli_options', commandoptions) logger.debug('cli_args', args) const [commandName] = args const sourceDir = args[1] ? path.resolve(args[1]) : pwd const inferredUserDocsDirectory = await inferUserDocsDirectory(pwd) logger.developer('inferredUserDocsDirectory', inferredUserDocsDirectory) logger.developer('sourceDir', sourceDir) if (inferredUserDocsDirectory && sourceDir !== inferredUserDocsDirectory) { logUnknownCommand(cli) console.log() logger.tip(`Did you miss to specify the target docs dir? e.g. ${chalk.cyan(`vuepress ${commandName} [targetDir]`)}.`) logger.tip(`A custom command registered by a plugin requires VuePress to locate your site configuration like ${chalk.cyan('vuepress dev')} or ${chalk.cyan('vuepress build')}.`) console.log() process.exit(1) } if (!inferredUserDocsDirectory) { logUnknownCommand(cli) process.exit(1) } logger.debug('Custom command', chalk.cyan(commandName)) CLI({ async beforeParse (subCli) { const app = createApp({ sourceDir: sourceDir, ...options, ...commandoptions }) await app.process() app.pluginAPI.applySyncOption('extendCli', subCli, app) console.log() }, async afterParse (subCli) { if (!subCli.matchedCommand) { logUnknownCommand(subCli) console.log() } } }) }) }
javascript
{ "resource": "" }
q15691
vBindEscape
train
function vBindEscape (strs, ...args) { return strs.reduce((prev, curr, index) => { return prev + curr + (index >= args.length ? '' : `"${JSON.stringify(args[index]) .replace(/"/g, "'") .replace(/([^\\])(\\\\)*\\'/g, (_, char) => char + '\\u0022')}"`) }, '') }
javascript
{ "resource": "" }
q15692
setTargetsValue
train
function setTargetsValue(targets, properties) { const animatables = getAnimatables(targets); animatables.forEach(animatable => { for (let property in properties) { const value = getFunctionValue(properties[property], animatable); const target = animatable.target; const valueUnit = getUnit(value); const originalValue = getOriginalTargetValue(target, property, valueUnit, animatable); const unit = valueUnit || getUnit(originalValue); const to = getRelativeValue(validateValue(value, unit), originalValue); const animType = getAnimationType(target, property); setProgressValue[animType](target, property, to, animatable.transforms, true); } }); }
javascript
{ "resource": "" }
q15693
removeTargetsFromAnimations
train
function removeTargetsFromAnimations(targetsArray, animations) { for (let a = animations.length; a--;) { if (arrayContains(targetsArray, animations[a].animatable.target)) { animations.splice(a, 1); } } }
javascript
{ "resource": "" }
q15694
onScroll
train
function onScroll(cb) { var isTicking = false; var scrollY = 0; var body = document.body; var html = document.documentElement; var scrollHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight); function scroll() { scrollY = window.scrollY; if (cb) cb(scrollY, scrollHeight); requestTick(); } function requestTick() { if (!isTicking) requestAnimationFrame(updateScroll); isTicking = true; } function updateScroll() { isTicking = false; var currentScrollY = scrollY; } scroll(); window.onscroll = scroll; }
javascript
{ "resource": "" }
q15695
scrollToElement
train
function scrollToElement(el, offset) { var off = offset || 0; var rect = el.getBoundingClientRect(); var top = rect.top + off; var animation = anime({ targets: [document.body, document.documentElement], scrollTop: '+='+top, easing: 'easeInOutSine', duration: 1500 }); // onScroll(animation.pause); }
javascript
{ "resource": "" }
q15696
isElementInViewport
train
function isElementInViewport(el, inCB, outCB, rootMargin) { var margin = rootMargin || '-10%'; function handleIntersect(entries, observer) { var entry = entries[0]; if (entry.isIntersecting) { if (inCB && typeof inCB === 'function') inCB(el, entry); } else { if (outCB && typeof outCB === 'function') outCB(el, entry); } } var observer = new IntersectionObserver(handleIntersect, {rootMargin: margin}); observer.observe(el); }
javascript
{ "resource": "" }
q15697
getThisBinding
train
function getThisBinding(thisEnvFn, inConstructor) { return getBinding(thisEnvFn, "this", thisBinding => { if (!inConstructor || !hasSuperClass(thisEnvFn)) return t.thisExpression(); const supers = new WeakSet(); thisEnvFn.traverse({ Function(child) { if (child.isArrowFunctionExpression()) return; child.skip(); }, ClassProperty(child) { child.skip(); }, CallExpression(child) { if (!child.get("callee").isSuper()) return; if (supers.has(child.node)) return; supers.add(child.node); child.replaceWithMultiple([ child.node, t.assignmentExpression( "=", t.identifier(thisBinding), t.identifier("this"), ), ]); }, }); }); }
javascript
{ "resource": "" }
q15698
getLastStatement
train
function getLastStatement(statement) { if (!t.isStatement(statement.body)) return statement; return getLastStatement(statement.body); }
javascript
{ "resource": "" }
q15699
isInLoop
train
function isInLoop(path) { const loopOrFunctionParent = path.find( path => path.isLoop() || path.isFunction(), ); return loopOrFunctionParent && loopOrFunctionParent.isLoop(); }
javascript
{ "resource": "" }