_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q44300
drawChart
train
function drawChart(chart) { var streaming = chart.streaming; var frameRate = chart.options.plugins.streaming.frameRate; var frameDuration = 1000 / (Math.max(frameRate, 0) || 30); var next = streaming.lastDrawn + frameDuration || 0; var now = Date.now(); var lastMouseEvent = streaming.lastMouseEvent; if (next <= now) { // Draw only when animation is inactive if (!chart.animating && !chart.tooltip._start) { chart.draw(); } if (lastMouseEvent) { chart.eventHandler(lastMouseEvent); } streaming.lastDrawn = (next + frameDuration > now) ? next : now; } }
javascript
{ "resource": "" }
q44301
train
function (minimumInterval, callback) { var timeout = null; return function () { var that = this, args = arguments; if(timeout === null) { timeout = setTimeout(function () { timeout = null; }, minimumInterval); callback.apply(that, args); } }; }
javascript
{ "resource": "" }
q44302
blank
train
function blank(v) { if (typeof v === 'undefined') return true; if (v instanceof Array && v.length === 0) return true; if (v === null) return true; if (typeof v === 'string' && v === '') return true; return false; }
javascript
{ "resource": "" }
q44303
Schema
train
function Schema(name, settings) { var schema = this; name = name ? name.toLowerCase() : ''; switch (name) { case 'sqlite': name = 'sqlite3'; break; case 'mysqldb': case 'mariadb': name = 'mysql'; break; case 'mongo': name = 'mongodb'; break; case 'couchdb': case 'couch': name = 'nano'; break; case 'rethinkdb': case 'rethink': name = 'rethinkdb'; break; } // just save everything we get schema.name = name; schema.settings = settings; // Disconnected by default schema.connected = false; // create blank models pool schema.models = {}; schema.definitions = {}; // define schema types schema.Text = function Text() { }; schema.JSON = schema.Json = function JSON() { }; schema.Float = function Float() { }; schema.Real = schema.Double = function Real() { }; schema.Int = schema.Integer = function Integer() { }; schema.UUID = schema.Uuid = function UUID() { }; schema.TimeUUID = schema.TimeUuid = function TimeUUID() { }; schema.CounterColumn = function CounterColumn() { }; schema.Blob = schema.Bytes = function Blob() { }; schema.Date = schema.Timestamp = Date; schema.Boolean = schema.Tinyint = Boolean; schema.Number = Number; schema.String = schema.Varchar = String; // and initialize schema using adapter // this is only one initialization entry point of adapter // this module should define `adapter` member of `this` (schema) var adapter; if (typeof name === 'object') { adapter = name; schema.name = adapter.name; } else if (name.match(/^\//)) { // try absolute path adapter = require(name); } else if (existsSync(__dirname + '/adapters/' + name + '.js')) { // try built-in adapter adapter = require('./adapters/' + name); } else { try { adapter = require('caminte-' + name); } catch (e) { throw new Error('Adapter ' + name + ' is not defined, try\n npm install ' + name); } } adapter.initialize(schema, function () { // we have an adaper now? if (!schema.adapter) { throw new Error('Adapter is not defined correctly: it should create `adapter` member of schema'); } schema.adapter.log = function (query, start) { schema.log(query, start); }; schema.adapter.logger = function (query) { 'use strict'; var t1 = Date.now(); var log = schema.log; return function (q) { log(q || query, t1); }; }; var res = getState(schema); if (util.isError(res)) { schema.emit('error', res); } else { schema.connected = true; schema.emit('connected'); } }.bind(schema)); }
javascript
{ "resource": "" }
q44304
train
function(time) { grunt.log.writeln(String( 'Completed in ' + time.toFixed(3) + 's at ' + (new Date()).toString() ).cyan + ' - ' + waiting); }
javascript
{ "resource": "" }
q44305
TaskRun
train
function TaskRun(target) { this.name = target.name || 0; this.files = target.files || []; this._getConfig = target._getConfig; this.options = target.options; this.startedAt = false; this.spawned = null; this.changedFiles = Object.create(null); this.spawnTaskFailure = false; this.livereloadOnError = true; if (typeof this.options.livereloadOnError !== 'undefined') { this.livereloadOnError = this.options.livereloadOnError; } }
javascript
{ "resource": "" }
q44306
AmazonMwsResource
train
function AmazonMwsResource(AmazonMws, urlData) { this._AmazonMws = AmazonMws; this._urlData = urlData || {}; this.basePath = utils.makeURLInterpolator(AmazonMws.getApiField('basePath')); this.path = utils.makeURLInterpolator(this.path); if (this.includeBasic) { this.includeBasic.forEach(function (methodName) { this[methodName] = AmazonMwsResource.BASIC_METHODS[methodName]; }, this); } this.initialize.apply(this, arguments); }
javascript
{ "resource": "" }
q44307
amazonMwsMethod
train
function amazonMwsMethod(spec) { var commandPath = typeof spec.path === 'function' ? spec.path : utils.makeURLInterpolator(spec.path || ''); var requestMethod = (spec.method || 'GET').toUpperCase(); var urlParams = spec.urlParams || []; var encode = spec.encode || function (data) { return data; }; return function () { var self = this; var args = [].slice.call(arguments); var callback = typeof args[args.length - 1] === 'function' && args.pop(); var urlData = this.createUrlData(); return this.wrapTimeout(new Promise((function (resolve, reject) { for (var i = 0, l = urlParams.length; i < l; ++i) { // Note that we shift the args array after every iteration so this just // grabs the "next" argument for use as a URL parameter. var arg = args[0]; var param = urlParams[i]; var isOptional = OPTIONAL_REGEX.test(param); param = param.replace(OPTIONAL_REGEX, ''); if (!arg) { if (isOptional) { urlData[param] = ''; continue; } return reject(new Error( 'AmazonMws: Argument "' + urlParams[i] + '" required, but got: ' + arg + ' (on API request to ' + requestMethod + ' ' + commandPath + ')' )); } urlData[param] = args.shift(); } var data = encode(utils.getDataFromArgs(args)); var opts = utils.getOptionsFromArgs(args); if (args.length) { var err = new Error('AmazonMws: Unknown arguments (' + args + ').'); return reject(err); } var requestPath = this.createFullPath(commandPath, urlData); function requestCallback(err, response) { if (err) { reject(err); } else { resolve( spec.transformResponseData ? spec.transformResponseData(response) : response ); } } var options = {headers: objectAssign(opts.headers, spec.headers)}; options.useBody = spec.useBody || false; self._request(requestMethod, requestPath, data, opts.auth, options, requestCallback); }).bind(this)), callback); }; }
javascript
{ "resource": "" }
q44308
_Error
train
function _Error() { this.populate.apply(this, arguments); var stack = (new Error(this.message)).stack; debug('stack ', stack); }
javascript
{ "resource": "" }
q44309
train
function (cb) { if (AmazonMws.USER_AGENT_SERIALIZED) { return cb(AmazonMws.USER_AGENT_SERIALIZED); } this.getClientUserAgentSeeded(AmazonMws.USER_AGENT, function (cua) { AmazonMws.USER_AGENT_SERIALIZED = cua; cb(AmazonMws.USER_AGENT_SERIALIZED); }); }
javascript
{ "resource": "" }
q44310
train
function (seed, cb) { exec('uname -a', function (err, uname) { var userAgent = {}; for (var field in seed) { userAgent[field] = encodeURIComponent(seed[field]); } // URI-encode in case there are unusual characters in the system's uname. userAgent.uname = encodeURIComponent(uname) || 'UNKNOWN'; cb(JSON.stringify(userAgent)); }); }
javascript
{ "resource": "" }
q44311
collectMessage
train
function collectMessage(message, processingQueue, cb) { const threshold = message.getRetryThreshold(); const messageRetryThreshold = typeof threshold === 'number' ? threshold : dispatcher.getMessageRetryThreshold(); const delay = message.getRetryDelay(); const messageRetryDelay = typeof delay === 'number' ? delay : dispatcher.getMessageRetryDelay(); let destQueueName = null; let delayed = false; let requeued = false; const multi = client.multi(); /** * Only exceptions from non periodic messages are handled. * Periodic messages are ignored once they are delivered to a consumer. */ if (!dispatcher.isPeriodic(message)) { const uuid = message.getId(); /** * Attempts */ const attempts = increaseAttempts(message); /** * */ if (attempts < messageRetryThreshold) { debug(`Trying to consume message ID [${uuid}] again (attempts: [${attempts}]) ...`); if (messageRetryDelay) { debug(`Scheduling message ID [${uuid}] (delay: [${messageRetryDelay}])...`); message.setScheduledDelay(messageRetryDelay); dispatcher.schedule(message, multi); delayed = true; } else { debug(`Message ID [${uuid}] is going to be enqueued immediately...`); destQueueName = keyQueueName; requeued = true; } } else { debug(`Message ID [${uuid}] has exceeded max retry threshold...`); destQueueName = keyQueueNameDead; } /** * */ if (destQueueName) { debug(`Moving message [${uuid}] to queue [${destQueueName}]...`); multi.lpush(destQueueName, message.toString()); } multi.rpop(processingQueue); multi.exec((err) => { if (err) cb(err); else { if (dispatcher.isTest()) { if (requeued) dispatcher.emit(events.MESSAGE_REQUEUED, message); else if (delayed) dispatcher.emit(events.MESSAGE_DELAYED, message); else dispatcher.emit(events.MESSAGE_DEAD_LETTER, message); } cb(); } }); } else { client.rpop(processingQueue, cb); } }
javascript
{ "resource": "" }
q44312
isPaddedArgument
train
function isPaddedArgument (node) { var parentArray = node.parent().arguments ? node.parent().arguments : node.parent().elements var idx = parentArray.indexOf(node) if (idx === 0) { // first arg if (prePreChar === '(' && preChar === '(' && postChar === ')') { // already padded return true } } else if (idx === parentArray.length - 1) { // last arg if (preChar === '(' && postChar === ')' && postPostChar === ')') { // already padded return true } } else { // middle arg if (preChar === '(' && postChar === ')') { // already padded return true } } return false }
javascript
{ "resource": "" }
q44313
isArgumentToFunctionCall
train
function isArgumentToFunctionCall (node) { return isCallExpression(node.parent()) && node.parent().arguments.length && node.parent().arguments.indexOf(node) !== -1 }
javascript
{ "resource": "" }
q44314
isIIFECall
train
function isIIFECall (node) { return node && isCallExpression(node) && node.callee && node.callee.type === 'FunctionExpression' }
javascript
{ "resource": "" }
q44315
isProbablyWebpackModule
train
function isProbablyWebpackModule (node) { return isElementOfArray(node) && isArgumentToFunctionCall(node.parent()) && isIIFECall(node.parent().parent()) }
javascript
{ "resource": "" }
q44316
arrayToMatrix
train
function arrayToMatrix (a) { return { a: a[0], b: a[1], c: a[2], d: a[3], e: a[4], f: a[5] } }
javascript
{ "resource": "" }
q44317
tempRedirect
train
function tempRedirect(req, res) { var params = { Bucket: S3_BUCKET, Key: checkTrailingSlash(getFileKeyDir(req)) + req.params[0] }; var s3 = getS3(); s3.getSignedUrl('getObject', params, function(err, url) { res.redirect(url); }); }
javascript
{ "resource": "" }
q44318
createQueryMetadata
train
function createQueryMetadata (pageSize, bookmark) { const metadata = new _serviceProto.QueryMetadata(); metadata.setPageSize(pageSize); metadata.setBookmark(bookmark); return metadata.toBuffer(); }
javascript
{ "resource": "" }
q44319
train
function (cwd = process.cwd()) { const promise = new Promise((resolve, reject) => { const _name = this.toString(); // eslint-disable-next-line no-console console.log(`spawning:: ${_name}`); const call = spawn(this.cmd, this.args, {env: process.env, shell: true, stdio: 'inherit', cwd}); this.args = []; call.on('exit', (code) => { // eslint-disable-next-line no-console console.log(`spawning:: ${_name} code::${code}`); if (code === 0) { resolve(0); } else { reject(code); } }); return call; }); return promise; }
javascript
{ "resource": "" }
q44320
parseCoordinates
train
function parseCoordinates(coord) { if (Array.isArray(coord) && coord.length === 2) { return { lng: coord[0], lat: coord[1], }; } if (coord instanceof Object && coord !== null) { return { lng: coord.lng || coord.lon, lat: coord.lat, }; } return {}; }
javascript
{ "resource": "" }
q44321
train
function (object) { var listeners = this.listeners; for (var i = 0, iMax = this.listeners.length; i < iMax; i++) { var listener = listeners[i]; if (listener && listener.object == object) { return i; } } return -1; }
javascript
{ "resource": "" }
q44322
train
function (object, event, properties) { var index = this.indexOf(object); var listener = this.listeners[index]; if (listener) { var callbacks = listener.events[event]; if (callbacks) { for (var i = 0, iMax = callbacks.length; i < iMax; i++) { callbacks[i](properties); } } } }
javascript
{ "resource": "" }
q44323
isLoaded
train
function isLoaded (url) { if (urls[url] == true) { return true; } var image = new Image(); image.src = url; if (image.complete) { return true; } return false; }
javascript
{ "resource": "" }
q44324
load
train
function load (url, callback, sendCallbackWhenAlreadyLoaded) { if (sendCallbackWhenAlreadyLoaded == undefined) { sendCallbackWhenAlreadyLoaded = true; } if (isLoaded(url)) { if (sendCallbackWhenAlreadyLoaded) { callback(url); } return; } if (isLoading(url) && !sendCallbackWhenAlreadyLoaded) { return; } var c = callbacks[url]; if (!c) { var image = new Image(); image.src = url; c = []; callbacks[url] = c; image.onload = function (event) { urls[url] = true; delete callbacks[url]; for (var i = 0; i < c.length; i++) { c[i](url); } } } if (c.indexOf(callback) == -1) { c.push(callback); } }
javascript
{ "resource": "" }
q44325
loadAll
train
function loadAll (urls, callback, sendCallbackWhenAlreadyLoaded) { // list all urls which are not yet loaded var urlsLeft = []; urls.forEach(function (url) { if (!isLoaded(url)) { urlsLeft.push(url); } }); if (urlsLeft.length) { // there are unloaded images var countLeft = urlsLeft.length; urlsLeft.forEach(function (url) { load(url, function () { countLeft--; if (countLeft == 0) { // done! callback(); } }, sendCallbackWhenAlreadyLoaded); }); } else { // we are already done! if (sendCallbackWhenAlreadyLoaded) { callback(); } } }
javascript
{ "resource": "" }
q44326
filterImageUrls
train
function filterImageUrls (elem, urls) { var child = elem.firstChild; while (child) { if (child.tagName == 'IMG') { var url = child.src; if (urls.indexOf(url) == -1) { urls.push(url); } } filterImageUrls(child, urls); child = child.nextSibling; } }
javascript
{ "resource": "" }
q44327
cloudCollide
train
function cloudCollide(tag, board, sw) { sw >>= 5; var sprite = tag.sprite, w = tag.width >> 5, lx = tag.x - (w << 4), sx = lx & 0x7f, msx = 32 - sx, h = tag.y1 - tag.y0, x = (tag.y + tag.y0) * sw + (lx >> 5), last; for (var j = 0; j < h; j++) { last = 0; for (var i = 0; i <= w; i++) { if (((last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0)) & board[x + i]) return true; } x += sw; } return false; }
javascript
{ "resource": "" }
q44328
train
function (properties, featureCollection, mergeKey) { var features = featureCollection.features; var featureIndex = L.GeometryUtils.indexFeatureCollection(features, mergeKey); var property; var mergeValue; var newFeatureCollection = { type: 'FeatureCollection', features: [] }; for (var key in properties) { if (properties.hasOwnProperty(key)) { property = properties[key]; mergeValue = property[mergeKey]; if (mergeValue) { var feature = featureIndex[mergeValue]; for (var prop in property) { feature.properties[prop] = property[prop]; } newFeatureCollection.features.push(feature); } } } return newFeatureCollection; }
javascript
{ "resource": "" }
q44329
train
function (featureCollection, indexKey) { var features = featureCollection.features; var feature; var properties; var featureIndex = {}; var value; for (var index = 0; index < features.length; ++index) { feature = features[index]; properties = feature.properties; value = properties[indexKey]; // If the value already exists in the index, then either create a GeometryCollection or append the // feature's geometry to the existing GeometryCollection if (value in featureIndex) { var existingFeature = featureIndex[value]; if (existingFeature.geometry.type !== 'GeometryCollection') { featureIndex[value] = { type: 'Feature', geometry: { type: 'GeometryCollection', geometries: [feature.geometry, existingFeature.geometry] } }; } else { existingFeature.geometry.geometries.push(feature.geometry); } } else { featureIndex[value] = feature; } } return featureIndex; }
javascript
{ "resource": "" }
q44330
train
function (element, style) { var styleString = ''; for (var key in style) { styleString += key + ': ' + style[key] + ';'; } element.setAttribute('style', styleString); return element; }
javascript
{ "resource": "" }
q44331
train
function (element, attr) { for (var key in attr) { element.setAttribute(key, attr[key]); } return element; }
javascript
{ "resource": "" }
q44332
train
function (location, options, record) { var marker; if (location) { if (options.numberOfSides >= 30 && !(options.innerRadius || (options.innerRadiusX && options.innerRadiusY))) { marker = new L.CircleMarker(location, options); } else { marker = new L.RegularPolygonMarker(location, options); } } return marker; }
javascript
{ "resource": "" }
q44333
train
function (data) { // Initialize framework linear functions for mapping earthquake data properties to Leaflet style properties // Color scale - green to red using the basic HSLHueFunction var magnitudeColorFunction = new L.HSLHueFunction(new L.Point(0,90), new L.Point(10,0), {outputSaturation: '100%', outputLuminosity: '25%'}); var magnitudeFillColorFunction = new L.HSLHueFunction(new L.Point(0,90), new L.Point(10,0), {outputSaturation: '100%', outputLuminosity: '50%'}); var magnitudeRadiusFunction = new L.LinearFunction(new L.Point(0,10), new L.Point(10,30)); // Color scale - white to orange to red using a PiecewiseFunction // NOTE: Uncomment these lines to see the difference /* var magnitudeColorFunction = new L.PiecewiseFunction([ new L.HSLLuminosityFunction(new L.Point(0,0.8), new L.Point(4,0.3), {outputSaturation: '100%', outputHue: 30}), new L.HSLHueFunction(new L.Point(4,30), new L.Point(10,0), {outputLuminosity: '30%'}) ]); var magnitudeFillColorFunction = new L.PiecewiseFunction([ new L.HSLLuminosityFunction(new L.Point(0,1), new L.Point(4,0.5), {outputSaturation: '100%', outputHue: 30}), new L.HSLHueFunction(new L.Point(4,30), new L.Point(10,0)) ]); */ var now = Math.round((new Date()).getTime()); var start = now - 86400000; // Initialize a linear function to map earthquake time to opacity var timeOpacityFunction = new L.LinearFunction(new L.Point(start,0.3), new L.Point(now,1)); var fontSizeFunction = new L.LinearFunction(new L.Point(0,8), new L.Point(10,24)); var textFunction = function (value) { return { text: value, style: { 'font-size': fontSizeFunction.evaluate(value) } }; }; // Setup a new data layer var dataLayer = new L.DataLayer(data,{ recordsField: 'features', latitudeField: 'geometry.coordinates.1', longitudeField: 'geometry.coordinates.0', locationMode: L.LocationModes.LATLNG, displayOptions: { 'properties.mag': { displayName: 'Magnitude', color: magnitudeColorFunction, fillColor: magnitudeFillColorFunction, radius: magnitudeRadiusFunction, text: textFunction }, 'properties.time': { displayName: 'Time', opacity: timeOpacityFunction, fillOpacity: timeOpacityFunction, displayText: function (value) { return moment.unix(value/1000).format('MM/DD/YY HH:mm'); } } }, layerOptions: { numberOfSides: 4, radius: 10, weight: 1, color: '#000', opacity: 0.2, stroke: true, fillOpacity: 0.7, dropShadow: true, gradient: true }, tooltipOptions: { iconSize: new L.Point(90,76), iconAnchor: new L.Point(-4,76) }, onEachRecord: function (layer, record, location) { var $html = $(L.HTMLUtils.buildTable(record)); layer.bindPopup($html.wrap('<div/>').parent().html(),{ minWidth: 400, maxWidth: 400 }); } }); // Add the data layer to the map map.addLayer(dataLayer); lastLayer = dataLayer; }
javascript
{ "resource": "" }
q44334
train
function () { if (lastLayer) { map.removeLayer(lastLayer); } $.ajax({ //url: 'http://earthquake.usgs.gov/earthquakes/feed/geojsonp/all/day', url: 'http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojsonp', type: 'GET', dataType: 'jsonp', jsonp: false }); }
javascript
{ "resource": "" }
q44335
train
function () { var selected = timeline.getSelection(); if (selected.length > 0) { var row = selected[0].row; var item = timeline.getItem(row); var id = $(item.content).attr('data-id'); var layer = layers[id]; if (lastLayer && lastLayer.viewedImage) { lastLayer.viewedImage.fire('click'); } layer._map.panTo(layer.getLatLng()); layer.fire('click'); lastLayer = layer; } }
javascript
{ "resource": "" }
q44336
parseUrlsOption
train
async function parseUrlsOption (state, urls) { if (!urls || urls.length === 0) { // get URLs for all sections across all pages const pages = await getDocPages(state) return (await pages.reduce(toSectionUrls.bind(null, state), [])).map(normalizeUrl) } const normalizedUrls = urls.map(normalizeUrl) const invalidUrls = normalizedUrls.filter(isntV3DocumentationUrl) if (invalidUrls.length) { throw new Error(`Invalid URLs: ${invalidUrls.join(', ')}`) } const pageUrls = normalizedUrls.filter(isPageUrl) const sectionUrls = normalizedUrls.filter(isSectionUrl) return _.uniq((await pageUrls.reduce(toSectionUrls.bind(null, state), [])).concat(sectionUrls)) }
javascript
{ "resource": "" }
q44337
replaceTimeNowDefault
train
function replaceTimeNowDefault (state) { state.results.forEach(output => { output.params.forEach(result => { if (result.default === 'Time.now') { result.default = '<current date/time>' } }) }) }
javascript
{ "resource": "" }
q44338
_parseScenarios
train
function _parseScenarios(feature) { feature.elements.forEach(scenario => { scenario.passed = 0; scenario.failed = 0; scenario.notDefined = 0; scenario.skipped = 0; scenario.pending = 0; scenario.ambiguous = 0; scenario.duration = 0; scenario.time = '00:00:00.000'; scenario = _parseSteps(scenario); if (scenario.duration > 0) { feature.duration += scenario.duration; scenario.time = formatDuration(scenario.duration) } if (scenario.hasOwnProperty('description') && scenario.description) { scenario.description = scenario.description.replace(new RegExp('\r?\n', 'g'), "<br />"); } if (scenario.failed > 0) { suite.scenarios.total++; suite.scenarios.failed++; feature.scenarios.total++; feature.isFailed = true; return feature.scenarios.failed++; } if (scenario.ambiguous > 0) { suite.scenarios.total++; suite.scenarios.ambiguous++; feature.scenarios.total++; feature.isAmbiguous = true; return feature.scenarios.ambiguous++; } if (scenario.notDefined > 0) { suite.scenarios.total++; suite.scenarios.notDefined++; feature.scenarios.total++; feature.isNotdefined = true; return feature.scenarios.notDefined++; } if (scenario.pending > 0) { suite.scenarios.total++; suite.scenarios.pending++; feature.scenarios.total++; feature.isPending = true; return feature.scenarios.pending++; } if (scenario.skipped > 0) { suite.scenarios.total++; suite.scenarios.skipped++; feature.scenarios.total++; return feature.scenarios.skipped++; } /* istanbul ignore else */ if (scenario.passed > 0) { suite.scenarios.total++; suite.scenarios.passed++; feature.scenarios.total++; return feature.scenarios.passed++; } }); feature.isSkipped = feature.scenarios.total === feature.scenarios.skipped; return feature; }
javascript
{ "resource": "" }
q44339
_readTemplateFile
train
function _readTemplateFile(fileName) { if (fileName) { try { fs.accessSync(fileName, fs.constants.R_OK); return fs.readFileSync(fileName, 'utf-8'); } catch (err) { return fs.readFileSync(path.join(__dirname, '..', 'templates', fileName), 'utf-8'); } } else { return ""; } }
javascript
{ "resource": "" }
q44340
_isBase64
train
function _isBase64(string) { const notBase64 = /[^A-Z0-9+\/=]/i; const stringLength = string.length; if (!stringLength || stringLength % 4 !== 0 || notBase64.test(string)) { return false; } const firstPaddingChar = string.indexOf('='); return firstPaddingChar === -1 || firstPaddingChar === stringLength - 1 || (firstPaddingChar === stringLength - 2 && string[stringLength - 1] === '='); }
javascript
{ "resource": "" }
q44341
_createFeaturesOverviewIndexPage
train
function _createFeaturesOverviewIndexPage(suite) { const featuresOverviewIndex = path.resolve(reportPath, INDEX_HTML); FEATURES_OVERVIEW_TEMPLATE = suite.customMetadata ? FEATURES_OVERVIEW_CUSTOM_METADATA_TEMPLATE : FEATURES_OVERVIEW_TEMPLATE; fs.writeFileSync( featuresOverviewIndex, _.template(_readTemplateFile(FEATURES_OVERVIEW_INDEX_TEMPLATE))({ suite: suite, featuresOverview: _.template(_readTemplateFile(FEATURES_OVERVIEW_TEMPLATE))({ suite: suite, _: _ }), featuresScenariosOverviewChart: _.template(_readTemplateFile(SCENARIOS_OVERVIEW_CHART_TEMPLATE))({ overviewPage: true, scenarios: suite.scenarios, _: _ }), customDataOverview: _.template(_readTemplateFile(CUSTOMDATA_TEMPLATE))({ suite: suite, _: _ }), featuresOverviewChart: _.template(_readTemplateFile(FEATURES_OVERVIEW_CHART_TEMPLATE))({ suite: suite, _: _ }), customStyle: _readTemplateFile(suite.customStyle), styles: _readTemplateFile(suite.style), genericScript: _readTemplateFile(GENERIC_JS), pageTitle: pageTitle, reportName: reportName, pageFooter: pageFooter }) ); }
javascript
{ "resource": "" }
q44342
_createFeatureIndexPages
train
function _createFeatureIndexPages(suite) { // Set custom metadata overview for the feature FEATURE_METADATA_OVERVIEW_TEMPLATE = suite.customMetadata ? FEATURE_CUSTOM_METADATA_OVERVIEW_TEMPLATE : FEATURE_METADATA_OVERVIEW_TEMPLATE; suite.features.forEach(feature => { const featurePage = path.resolve(reportPath, `${FEATURE_FOLDER}/${feature.id}.html`); fs.writeFileSync( featurePage, _.template(_readTemplateFile(FEATURE_OVERVIEW_INDEX_TEMPLATE))({ feature: feature, featureScenariosOverviewChart: _.template(_readTemplateFile(SCENARIOS_OVERVIEW_CHART_TEMPLATE))({ overviewPage: false, feature: feature, suite: suite, scenarios: feature.scenarios, _: _ }), featureMetadataOverview: _.template(_readTemplateFile(FEATURE_METADATA_OVERVIEW_TEMPLATE))({ metadata: feature.metadata, _: _ }), scenarioTemplate: _.template(_readTemplateFile(SCENARIOS_TEMPLATE))({ suite: suite, scenarios: feature.elements, _: _ }), customStyle: _readTemplateFile(suite.customStyle), styles: _readTemplateFile(suite.style), genericScript: _readTemplateFile(GENERIC_JS), pageTitle: pageTitle, reportName: reportName, pageFooter: pageFooter, }) ); // Copy the assets fs.copySync( path.resolve(path.dirname(require.resolve("../package.json")),'templates/assets'), path.resolve(reportPath, 'assets') ); }); }
javascript
{ "resource": "" }
q44343
parseAndValidateArgs
train
function parseAndValidateArgs (options) { // parse and validate args var args = nopt({ 'archs': [String], 'appx': String, 'phone': Boolean, 'win': Boolean, 'bundle': Boolean, 'packageCertificateKeyFile': String, 'packageThumbprint': String, 'publisherId': String, 'buildConfig': String, 'buildFlag': [String, Array] }, {}, options.argv, 0); var config = {}; var buildConfig = {}; // Validate args if (options.debug && options.release) { throw new CordovaError('Cannot specify "debug" and "release" options together.'); } if (args.phone && args.win) { throw new CordovaError('Cannot specify "phone" and "win" options together.'); } // get build options/defaults config.buildType = options.release ? 'release' : 'debug'; var archs = options.archs || args.archs; config.buildArchs = archs ? archs.toLowerCase().split(' ') : ['anycpu']; config.phone = !!args.phone; config.win = !!args.win; config.projVerOverride = args.appx; // only set config.bundle if architecture is not anycpu if (args.bundle) { if (config.buildArchs.length > 1 && (config.buildArchs.indexOf('anycpu') > -1 || config.buildArchs.indexOf('any cpu') > -1)) { // Not valid to bundle anycpu with cpu-specific architectures. warn, then don't bundle events.emit('warn', '"anycpu" and CPU-specific architectures were selected. ' + 'This is not valid when enabling bundling with --bundle. Disabling bundling for this build.'); } else { config.bundle = true; } } // if build.json is provided, parse it var buildConfigPath = options.buildConfig || args.buildConfig; if (buildConfigPath) { buildConfig = parseBuildConfig(buildConfigPath, config.buildType); for (var prop in buildConfig) { config[prop] = buildConfig[prop]; } } // Merge buildFlags from build config and CLI arguments into // single array ensuring that ones from CLI take a precedence config.buildFlags = [].concat(buildConfig.buildFlag || [], args.buildFlag || []); // CLI arguments override build.json config if (args.packageCertificateKeyFile) { args.packageCertificateKeyFile = path.resolve(process.cwd(), args.packageCertificateKeyFile); config.packageCertificateKeyFile = args.packageCertificateKeyFile; } config.packageThumbprint = config.packageThumbprint || args.packageThumbprint; config.publisherId = config.publisherId || args.publisherId; return config; }
javascript
{ "resource": "" }
q44344
enterFullScreen
train
function enterFullScreen() { if (Windows.UI.ViewManagement.ApplicationViewBoundsMode) { // else crash on 8.1 var view = Windows.UI.ViewManagement.ApplicationView.getForCurrentView(); view.setDesiredBoundsMode(Windows.UI.ViewManagement.ApplicationViewBoundsMode.useCoreWindow); view.suppressSystemOverlays = true; } }
javascript
{ "resource": "" }
q44345
exitFullScreen
train
function exitFullScreen() { if (Windows.UI.ViewManagement.ApplicationViewBoundsMode) { // else crash on 8.1 var view = Windows.UI.ViewManagement.ApplicationView.getForCurrentView(); view.setDesiredBoundsMode(Windows.UI.ViewManagement.ApplicationViewBoundsMode.useVisible); view.suppressSystemOverlays = false; } }
javascript
{ "resource": "" }
q44346
colorizeTitleBar
train
function colorizeTitleBar() { var appView = Windows.UI.ViewManagement.ApplicationView.getForCurrentView(); if (isWin10UWP && !isBgColorTransparent) { titleInitialBgColor = appView.titleBar.backgroundColor; appView.titleBar.backgroundColor = titleBgColor; appView.titleBar.buttonBackgroundColor = titleBgColor; } }
javascript
{ "resource": "" }
q44347
revertTitleBarColor
train
function revertTitleBarColor() { var appView = Windows.UI.ViewManagement.ApplicationView.getForCurrentView(); if (isWin10UWP && !isBgColorTransparent) { appView.titleBar.backgroundColor = titleInitialBgColor; appView.titleBar.buttonBackgroundColor = titleInitialBgColor; } }
javascript
{ "resource": "" }
q44348
hide
train
function hide() { if (isVisible()) { var hideFinishCb = function () { WinJS.Utilities.addClass(splashElement, 'hidden'); splashElement.style.opacity = 1; enableUserInteraction(); exitFullScreen(); } // Color reversion before fading is over looks better: revertTitleBarColor(); // https://issues.apache.org/jira/browse/CB-11751 // This can occur when we directly replace whole document.body f.e. in a router. // Note that you should disable the splashscreen in this case or update a container element instead. if (document.getElementById(splashElement.id) == null) { hideFinishCb(); return; } if (fadeSplashScreen) { fadeOut(splashElement, fadeSplashScreenDuration, hideFinishCb); } else { hideFinishCb(); } } }
javascript
{ "resource": "" }
q44349
activated
train
function activated(eventObject) { // Retrieve splash screen object splash = eventObject.detail.splashScreen; // Retrieve the window coordinates of the splash screen image. coordinates = splash.imageLocation; // Register an event handler to be executed when the splash screen has been dismissed. splash.addEventListener('dismissed', onSplashScreenDismissed, false); // Listen for window resize events to reposition the extended splash screen image accordingly. // This is important to ensure that the extended splash screen is formatted properly in response to snapping, unsnapping, rotation, etc... window.addEventListener('resize', onResize, false); }
javascript
{ "resource": "" }
q44350
addBOMSignature
train
function addBOMSignature (directory) { shell.ls('-R', directory) .map(function (file) { return path.join(directory, file); }) .forEach(addBOMToFile); }
javascript
{ "resource": "" }
q44351
addBOMToFile
train
function addBOMToFile (file) { if (!file.match(/\.(js|htm|html|css|json)$/i)) { return; } // skip if this is a folder if (!fs.lstatSync(file).isFile()) { return; } var content = fs.readFileSync(file); if (content[0] !== 0xEF && content[1] !== 0xBE && content[2] !== 0xBB) { fs.writeFileSync(file, '\ufeff' + content); } }
javascript
{ "resource": "" }
q44352
updateProjectAccordingTo
train
function updateProjectAccordingTo (projectConfig, locations) { // Apply appxmanifest changes [MANIFEST_WINDOWS, MANIFEST_WINDOWS10, MANIFEST_PHONE] .forEach(function (manifestFile) { updateManifestFile(projectConfig, path.join(locations.root, manifestFile)); }); if (process.platform === 'win32') { applyUAPVersionToProject(path.join(locations.root, PROJECT_WINDOWS10), getUAPVersions(projectConfig)); } }
javascript
{ "resource": "" }
q44353
train
function (tag, elementToInstall, xml) { var frameworkCustomPathElement = xml.find(xpath); expect(frameworkCustomPathElement).not.toBe(null); var frameworkCustomPath = frameworkCustomPathElement.text; expect(frameworkCustomPath).not.toBe(null); var targetDir = elementToInstall.targetDir || ''; var frameworkCustomExpectedPath = path.join('plugins', dummyPluginInfo.id, targetDir, path.basename(elementToInstall.src)); expect(frameworkCustomPath).toEqual(frameworkCustomExpectedPath); }
javascript
{ "resource": "" }
q44354
train
function (framework) { var targetDir = framework.targetDir || ''; var dest = path.join(cordovaProjectWindowsPlatformDir, 'plugins', dummyPluginInfo.id, targetDir, path.basename(framework.src)); var copiedSuccessfully = fs.existsSync(path.resolve(dest)); expect(copiedSuccessfully).toBe(true); }
javascript
{ "resource": "" }
q44355
sortCapabilities
train
function sortCapabilities (manifest) { // removes namespace prefix (m3:Capability -> Capability) // this is required since elementtree returns qualified name with namespace function extractLocalName (tag) { return tag.split(':').pop(); // takes last part of string after ':' } var capabilitiesRoot = manifest.find('.//Capabilities'); var capabilities = capabilitiesRoot.getchildren() || []; // to sort elements we remove them and then add again in the appropriate order capabilities.forEach(function (elem) { // no .clear() method capabilitiesRoot.remove(elem); // CB-7601 we need local name w/o namespace prefix to sort capabilities correctly elem.localName = extractLocalName(elem.tag); }); capabilities.sort(function (a, b) { return (a.localName > b.localName) ? 1 : -1; }); capabilities.forEach(function (elem) { capabilitiesRoot.append(elem); }); }
javascript
{ "resource": "" }
q44356
train
function (callbackId, isSuccess, status, args, keepCallback) { try { var callback = cordova.callbacks[callbackId]; if (callback) { if (isSuccess && status === cordova.callbackStatus.OK) { callback.success && callback.success.apply(null, args); } else if (!isSuccess) { callback.fail && callback.fail.apply(null, args); } /* else Note, this case is intentionally not caught. this can happen if isSuccess is true, but callbackStatus is NO_RESULT which is used to remove a callback from the list without calling the callbacks typically keepCallback is false in this case */ // Clear callback if not expecting any more results if (!keepCallback) { delete cordova.callbacks[callbackId]; } } } catch (err) { var msg = 'Error in ' + (isSuccess ? 'Success' : 'Error') + ' callbackId: ' + callbackId + ' : ' + err; console && console.log && console.log(msg); console && console.log && err.stack && console.log(err.stack); cordova.fireWindowEvent('cordovacallbackerror', { 'message': msg }); throw err; } }
javascript
{ "resource": "" }
q44357
getPackageName
train
function getPackageName (platformPath) { // Can reliably read from package.windows.appxmanifest even if targeting Windows 10 // because the function is only used for desktop deployment, which always has the same // package name when uninstalling / reinstalling try { return Q.when(AppxManifest.get(path.join(platformPath, 'package.windows.appxmanifest')) .getIdentity().getName()); } catch (e) { return Q.reject('Can\'t read package name from manifest ' + e); } }
javascript
{ "resource": "" }
q44358
getInstalledVSVersions
train
function getInstalledVSVersions () { // Query all keys with Install value equal to 1, then filter out // those, which are not related to VS itself return spawn('reg', ['query', 'HKLM\\SOFTWARE\\Microsoft\\DevDiv\\vs\\Servicing', '/s', '/v', 'Install', '/f', '1', '/d', '/e', '/reg:32']) .fail(function () { return ''; }) .then(function (output) { return output.split('\n') .reduce(function (installedVersions, line) { var match = /(\d+\.\d+)\\(ultimate|professional|premium|community)/.exec(line); if (match && match[1] && installedVersions.indexOf(match[1]) === -1) { installedVersions.push(match[1]); } return installedVersions; }, []); }).then(function (installedVersions) { // If there is no VS2013 installed, the we have nothing to do if (installedVersions.indexOf('12.0') === -1) return installedVersions; // special case for VS 2013. We need to check if VS2013 update 2 is installed return spawn('reg', ['query', 'HKLM\\SOFTWARE\\Microsoft\\Updates\\Microsoft Visual Studio 2013\\vsupdate_KB2829760', '/v', 'PackageVersion', '/reg:32']) .then(function (output) { var updateVer = Version.fromString(/PackageVersion\s+REG_SZ\s+(.*)/i.exec(output)[1]); // if update version is lover than Update2, reject the promise if (VS2013_UPDATE2_RC.gte(updateVer)) return Q.reject(); return installedVersions; }).fail(function () { // if we got any errors on previous steps, we're assuming that // required VS update is not installed. installedVersions.splice(installedVersions.indexOf('12.0'), 1); return installedVersions; }); }) .then(function (installedVersions) { var willowVersions = MSBuildTools.getWillowInstallations().map(function (installation) { return installation.version; }); return installedVersions.concat(willowVersions); }); }
javascript
{ "resource": "" }
q44359
getInstalledWindowsSdks
train
function getInstalledWindowsSdks () { var installedSdks = []; return spawn('reg', ['query', 'HKLM\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows', '/s', '/v', 'InstallationFolder', '/reg:32']) .fail(function () { return ''; }) .then(function (output) { var re = /\\Microsoft SDKs\\Windows\\v(\d+\.\d+)\s*InstallationFolder\s+REG_SZ\s+(.*)/gim; var match; while ((match = re.exec(output))) { var sdkPath = match[2]; // Verify that SDKs is really installed by checking SDKManifest file at SDK root if (shell.test('-e', path.join(sdkPath, 'SDKManifest.xml'))) { installedSdks.push(Version.tryParse(match[1])); } } }).thenResolve(installedSdks); }
javascript
{ "resource": "" }
q44360
getInstalledPhoneSdks
train
function getInstalledPhoneSdks () { var installedSdks = []; return spawn('reg', ['query', 'HKLM\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows Phone\\v8.1', '/v', 'InstallationFolder', '/reg:32']) .fail(function () { return ''; }) .then(function (output) { var match = /\\Microsoft SDKs\\Windows Phone\\v(\d+\.\d+)\s*InstallationFolder\s+REG_SZ\s+(.*)/gim.exec(output); if (match && shell.test('-e', path.join(match[2], 'SDKManifest.xml'))) { installedSdks.push(Version.tryParse(match[1])); } }).then(function () { return spawn('reg', ['query', 'HKLM\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v10.0', '/v', 'InstallationFolder', '/reg:32']); }).fail(function () { return ''; }).then(function (output) { var match = /\\Microsoft SDKs\\Windows\\v(\d+\.\d+)\s*InstallationFolder\s+REG_SZ\s+(.*)/gim.exec(output); if (match && shell.test('-e', path.join(match[2], 'SDKManifest.xml'))) { installedSdks.push(Version.tryParse(match[1])); } }).thenResolve(installedSdks); }
javascript
{ "resource": "" }
q44361
train
function (windowsTargetVersion, windowsPhoneTargetVersion) { if (process.platform !== 'win32') { // Build Universal windows apps available for windows platform only, so we reject on others platforms return Q.reject('Cordova tooling for Windows requires Windows OS to build project'); } return getWindowsVersion().then(function (actualVersion) { var requiredOsVersion = getMinimalRequiredVersionFor('os', windowsTargetVersion, windowsPhoneTargetVersion); if ((actualVersion.gte(requiredOsVersion)) || // Special case for Windows 10/Phone 10 targets which can be built on Windows 7 (version 6.1) (actualVersion.major === 6 && actualVersion.minor === 1 && getConfig().getWindowsTargetVersion() === '10.0')) { return mapWindowsVersionToName(actualVersion); } return Q.reject('Current Windows version doesn\'t support building this project. ' + 'Consider upgrading your OS to ' + mapWindowsVersionToName(requiredOsVersion)); }); }
javascript
{ "resource": "" }
q44362
getWillowProgDataPaths
train
function getWillowProgDataPaths () { if (!process.env.systemdrive) { // running on linux/osx? return []; } var instancesRoot = path.join(process.env.systemdrive, 'ProgramData/Microsoft/VisualStudio/Packages/_Instances'); if (!shell.test('-d', instancesRoot)) { // can't seem to find VS instances dir, return empty result return []; } return fs.readdirSync(instancesRoot).map(function (file) { var instanceDir = path.join(instancesRoot, file); if (shell.test('-d', instanceDir)) { return instanceDir; } }).filter(function (progDataPath) { // make sure state.json exists return shell.test('-e', path.join(progDataPath, 'state.json')); }); }
javascript
{ "resource": "" }
q44363
train
function(symbol, c) { this.variable = variables(symbol)[0]; if(!symbol.isPoly()) throw core.exceptions.NerdamerTypeError('Polynomial Expected! Received '+core.Utils.text(symbol)); c = c || []; if(!symbol.power.absEquals(1)) symbol = _.expand(symbol); if(symbol.group === core.groups.N) { c[0] = symbol.multiplier; } else if(symbol.group === core.groups.S) { c[symbol.power.toDecimal()] = symbol.multiplier; } else { for(var x in symbol.symbols) { var sub = symbol.symbols[x], p = sub.power; if(core.Utils.isSymbol(p)) throw new core.exceptions.NerdamerTypeError('power cannot be a Symbol'); p = sub.group === N ? 0 : p.toDecimal(); if(sub.symbols){ this.parse(sub, c); } else { c[p] = sub.multiplier; } } } this.coeffs = c; this.fill(); }
javascript
{ "resource": "" }
q44364
train
function(x) { x = Number(x) || 0; var l = this.coeffs.length; for(var i=0; i<l; i++) { if(this.coeffs[i] === undefined) { this.coeffs[i] = new Frac(x); } } return this; }
javascript
{ "resource": "" }
q44365
train
function() { var l = this.coeffs.length; while(l--) { var c = this.coeffs[l]; var equalsZero = c.equals(0); if(c && equalsZero) { if(l === 0) break; this.coeffs.pop(); } else break; } return this; }
javascript
{ "resource": "" }
q44366
train
function(poly) { var l = Math.max(this.coeffs.length, poly.coeffs.length); for(var i=0; i<l; i++) { var a = (this.coeffs[i] || new Frac(0)), b = (poly.coeffs[i] || new Frac(0)); this.coeffs[i] = a.add(b); } return this; }
javascript
{ "resource": "" }
q44367
train
function() { var l = this.coeffs.length; for(var i=0; i<l; i++) { var e = this.coeffs[i]; if(!e.equals(0)) return false; } return true; }
javascript
{ "resource": "" }
q44368
train
function() { var lc = this.lc(), l = this.coeffs.length; for(var i=0; i<l; i++) this.coeffs[i] = this.coeffs[i].divide(lc); return this; }
javascript
{ "resource": "" }
q44369
train
function(poly) { //get the maximum power of each var mp1 = this.coeffs.length-1, mp2 = poly.coeffs.length-1, T; //swap so we always have the greater power first if(mp1 < mp2) { return poly.gcd(this); } var a = this; while(!poly.isZero()) { var t = poly.clone(); a = a.clone(); T = a.divide(t); poly = T[1]; a = t; } var gcd = core.Math2.QGCD.apply(null, a.coeffs); if(!gcd.equals(1)) { var l = a.coeffs.length; for(var i=0; i<l; i++) { a.coeffs[i] = a.coeffs[i].divide(gcd); } } return a; }
javascript
{ "resource": "" }
q44370
train
function() { var new_array = [], l = this.coeffs.length; for(var i=1; i<l; i++) new_array.push(this.coeffs[i].multiply(new Frac(i))); this.coeffs = new_array; return this; }
javascript
{ "resource": "" }
q44371
train
function() { var new_array = [0], l = this.coeffs.length; for(var i=0; i<l; i++) { var c = new Frac(i+1); new_array[c] = this.coeffs[i].divide(c); } this.coeffs = new_array; return this; }
javascript
{ "resource": "" }
q44372
train
function(toPolynomial) { //get the first nozero coefficient and returns its power var fnz = function(a) { for(var i=0; i<a.length; i++) if(!a[i].equals(0)) return i; }, ca = []; for(var i=0; i<this.coeffs.length; i++) { var c = this.coeffs[i]; if(!c.equals(0) && ca.indexOf(c) === -1) ca.push(c); } var p = [core.Math2.QGCD.apply(undefined, ca), fnz(this.coeffs)].toDecimal(); if(toPolynomial) { var parr = []; parr[p[1]-1] = p[0]; p = Polynomial.fromArray(parr, this.variable).fill(); } return p; }
javascript
{ "resource": "" }
q44373
train
function(a) { for(var i=0; i<a.length; i++) if(!a[i].equals(0)) return i; }
javascript
{ "resource": "" }
q44374
train
function() { var a = this.clone(), i = 1, b = a.clone().diff(), c = a.clone().gcd(b), w = a.divide(c)[0]; var output = Polynomial.fromArray([new Frac(1)], a.variable); while(!c.equalsNumber(1)) { var y = w.gcd(c); var z = w.divide(y)[0]; //one of the factors may have shown up since it's square but smaller than the //one where finding if(!z.equalsNumber(1) && i>1) { var t = z.clone(); for(var j=1; j<i; j++) t.multiply(z.clone()); z = t; } output = output.multiply(z); i++; w = y; c = c.divide(y)[0]; } return [output, w, i]; }
javascript
{ "resource": "" }
q44375
train
function() { var l = this.coeffs.length, variable = this.variable; if(l === 0) return new core.Symbol(0); var end = l -1, str = ''; for(var i=0; i<l; i++) { //place the plus sign for all but the last one var plus = i === end ? '' : '+', e = this.coeffs[i]; if(!e.equals(0)) str += (e+'*'+variable+'^'+i+plus); } return _.parse(str); }
javascript
{ "resource": "" }
q44376
MVTerm
train
function MVTerm(coeff, terms, map) { this.terms = terms || []; this.coeff = coeff; this.map = map; //careful! all maps are the same object this.sum = new core.Frac(0); this.image = undefined; }
javascript
{ "resource": "" }
q44377
train
function(symbol, factors) { if(symbol.isConstant() || symbol.group === S) return symbol; var poly = new Polynomial(symbol); var sqfr = poly.squareFree(); var p = sqfr[2]; //if we found a square then the p entry in the array will be non-unit if(p !== 1) { //make sure the remainder doesn't have factors var t = sqfr[1].toSymbol(); t.power = t.power.multiply(new Frac(p)); //send the factor to be fatored to be sure it's completely factored factors.add(__.Factor.factor(t)); return __.Factor.squareFree(sqfr[0].toSymbol(), factors); } return symbol; }
javascript
{ "resource": "" }
q44378
train
function(symbol, factors) { if(symbol.group !== PL) return symbol; //only PL need apply var d = core.Utils.arrayMin(keys(symbol.symbols)); var retval = new Symbol(0); var q = _.parse(symbol.value+'^'+d); symbol.each(function(x) { x = _.divide(x, q.clone()); retval = _.add(retval, x); }); factors.add(q); return retval; }
javascript
{ "resource": "" }
q44379
train
function(symbol, factors) { if(symbol.isComposite()) { var gcd = core.Math2.QGCD.apply(null, symbol.coeffs()); if(!gcd.equals(1)) { symbol.each(function(x) { if(x.isComposite()) { x.each(function(y){ y.multiplier = y.multiplier.divide(gcd); }); } else x.multiplier = x.multiplier.divide(gcd); }); } symbol.updateHash(); if(factors) factors.add(new Symbol(gcd)); } return symbol; }
javascript
{ "resource": "" }
q44380
train
function(c1, c2, n, p) { var candidate = Polynomial.fit(c1, c2, n, base, p, v); if(candidate && candidate.coeffs.length > 1) { var t = poly.divide(candidate); if(t[1].equalsNumber(0)) { factors.add(candidate.toSymbol()); return [t[0], candidate]; } } return null; }
javascript
{ "resource": "" }
q44381
train
function(symbol, factors) { if(symbol.group !== FN) { var vars = variables(symbol).reverse(); for(var i=0; i<vars.length; i++) { do { if(vars[i] === symbol.value){ //the derivative tells us nothing since this symbol is already the factor factors.add(symbol); symbol = new Symbol(1); continue; } var d = __.Factor.coeffFactor(core.Calculus.diff(symbol, vars[i])); if(d.equals(0)) break; var div = __.div(symbol, d.clone()), is_factor = div[1].equals(0); if(div[0].isConstant()) { factors.add(div[0]); break; } if(is_factor) { factors.add(div[0]); symbol = d; } } while(is_factor) } } return symbol; }
javascript
{ "resource": "" }
q44382
train
function(symbol, factors) { try { var remove_square = function(x) { return core.Utils.block('POSITIVE_MULTIPLIERS', function() { return Symbol.unwrapPARENS(math.sqrt(math.abs(x))); }, true); }; var separated = core.Utils.separate(symbol.clone()); var obj_array = []; //get the unique variables for(var x in separated) { if(x !== 'constants') { obj_array.push(separated[x]); } } obj_array.sort(function(a, b) { return b.power - a.power; }); //if we have the same number of variables as unique variables then we can apply the difference of squares if(obj_array.length === 2) { var a, b; a = obj_array.pop(); b = obj_array.pop(); if(a.isComposite() && b.power.equals(2)) { //remove the square from b b = remove_square(b); var f = __.Factor.factor(_.add(a, separated.constants)); if(f.power.equals(2)) { f.toLinear(); factors.add(_.subtract(f.clone(), b.clone())); factors.add(_.add(f, b)); symbol = new Symbol(1); } } else { a = a.powSimp(); b = b.powSimp(); if((a.group === S || a.fname === '') && a.power.equals(2) && (b.group === S || b.fname === '') && b.power.equals(2)) { if(a.multiplier.lessThan(0)) { var t = b; b = a; a = t; } if(a.multiplier.greaterThan(0)) { a = remove_square(a); b = remove_square(b); } factors.add(_.subtract(a.clone(), b.clone())); factors.add(_.add(a, b)); symbol = new Symbol(1); } } } } catch(e){;} return symbol; }
javascript
{ "resource": "" }
q44383
train
function(set) { var l = set.length; for(var i=0; i<l; i++) if(!__.isLinear(set[i])) return false; return true; }
javascript
{ "resource": "" }
q44384
train
function(symbol1, symbol2) { var result, remainder, factored, den; factored = core.Algebra.Factor.factor(symbol1.clone()); den = factored.getDenom(); if(!den.isConstant('all')) { symbol1 = _.expand(Symbol.unwrapPARENS(_.multiply(factored, den.clone()))); } else //reset the denominator since we're not dividing by it anymore den = new Symbol(1); result = __.div(symbol1, symbol2); remainder = _.divide(result[1], symbol2); return _.divide(_.add(result[0], remainder), den); }
javascript
{ "resource": "" }
q44385
train
function(arr) { var symbol = new Symbol(0); for(var i=0; i<arr.length; i++) { var x = arr[i].toSymbol(); symbol = _.add(symbol, x); } return symbol; }
javascript
{ "resource": "" }
q44386
train
function(term, any) { var max = Math.max.apply(null, term.terms), count = 0, idx; if(!any) { for(var i=0; i<term.terms.length; i++) { if(term.terms[i].equals(max)) { idx = i; count++; } if(count > 1) return; } } if(any) { for(i=0; i<term.terms.length; i++) if(term.terms[i].equals(max)) { idx = i; break; } } return [max, idx, term]; }
javascript
{ "resource": "" }
q44387
train
function(s, lookat) { lookat = lookat || 0; var det = s[lookat], l = s.length; if(!det) return; //eliminate the first term if it doesn't apply var umax = get_unique_max(det); for(var i=lookat+1; i<l; i++) { var term = s[i], is_equal = det.sum.equals(term.sum); if(!is_equal && umax) { break; } if(is_equal) { //check the differences of their maxes. The one with the biggest difference governs //e.g. x^2*y^3 vs x^2*y^3 is unclear but this isn't the case in x*y and x^2 var max1, max2, idx1, idx2, l2 = det.terms.length; for(var j=0; j<l2; j++) { var item1 = det.terms[j], item2 = term.terms[j]; if(typeof max1 === 'undefined' || item1.greaterThan(max1)) { max1 = item1; idx1 = j; } if(typeof max2 === 'undefined' || item2.greaterThan(max2)) { max2 = item2; idx2 = j; } } //check their differences var d1 = max1.subtract(term.terms[idx1]), d2 = max2.subtract(det.terms[idx2]); if(d2 > d1) { umax = [max2, idx2, term]; break; } if(d1 > d2) { umax = [max1, idx1, det]; break; } } else { //check if it's a suitable pick to determine the order umax = get_unique_max(term); //if(umax) return umax; if(umax) break; } umax = get_unique_max(term); //calculate a new unique max } //if still no umax then any will do since we have a tie if(!umax) return get_unique_max(s[0], true); var e, idx; for(var i=0; i<s2.length; i++) { var cterm = s2[i].terms; //confirm that this is a good match for the denominator idx = umax[1]; if(idx === cterm.length - 1) return ; e = cterm[idx]; if(!e.equals(0)) break; } if(e.equals(0)) return get_det(s, ++lookat); //look at the next term return umax; }
javascript
{ "resource": "" }
q44388
train
function(symbol, v, raw) { if(!core.Utils.isSymbol(v)) v = _.parse(v); var stop = function(msg) { msg = msg || 'Stopping'; throw new core.exceptions.ValueLimitExceededError(msg); }; //if not CP then nothing to do if(!symbol.isPoly()) stop('Must be a polynomial!'); //declare vars var deg, a, b, c, d, e, coeffs, sign, br, sym, sqrt_a; br = core.Utils.inBrackets; //make a copy symbol = symbol.clone(); deg = core.Algebra.degree(symbol, v); //get the degree of polynomial //must be in form ax^2 +/- bx +/- c if(!deg.equals(2)) stop('Cannot complete square for degree '+deg); //get the coeffs coeffs = core.Algebra.coeffs(symbol, v); a = coeffs[2]; //store the sign sign = coeffs[1].sign(); //divide the linear term by two and square it b = _.divide(coeffs[1], new Symbol(2)); //add the difference to the constant c = _.pow(b.clone(), new Symbol(2)); if(raw) return [a, b, d]; sqrt_a = math.sqrt(a); e = _.divide(math.sqrt(c), sqrt_a.clone()); //calculate d which is the constant d = _.subtract(coeffs[0], _.pow(e.clone(), new Symbol(2))); //compute the square part sym = _.parse(br(sqrt_a.clone()+'*'+v+(sign < 0 ? '-' : '+')+e)); return { a: sym, c: d, f: _.add(_.pow(sym.clone(), new Symbol(2)), d.clone()) }; }
javascript
{ "resource": "" }
q44389
train
function(eqn) { //If it's an equation then call its toLHS function instead if(eqn instanceof Equation) return eqn.toLHS(); var es = eqn.split('='); if(es[1] === undefined) es[1] = '0'; var e1 = _.parse(es[0]), e2 = _.parse(es[1]); return removeDenom(e1, e2); }
javascript
{ "resource": "" }
q44390
train
function(c, b, a, plus_or_min) { var plus_or_minus = plus_or_min === '-' ? 'subtract': 'add'; var bsqmin4ac = _.subtract(_.pow(b.clone(), Symbol(2)), _.multiply(_.multiply(a.clone(), c.clone()),Symbol(4)))/*b^2 - 4ac*/; var det = _.pow(bsqmin4ac, Symbol(0.5)); var retval = _.divide(_[plus_or_minus](b.clone().negate(), det),_.multiply(new Symbol(2), a.clone())); return retval; }
javascript
{ "resource": "" }
q44391
train
function(symbol, solve_for) { var sols = []; //see if we can solve the factors var factors = core.Algebra.Factor.factor(symbol); if(factors.group === CB) { factors.each(function(x) { x = Symbol.unwrapPARENS(x); sols = sols.concat(solve(x, solve_for)); }); } return sols; }
javascript
{ "resource": "" }
q44392
train
function(point, f, fp) { var maxiter = 200, iter = 0; //first try the point itself. If it's zero viola. We're done var x0 = point, x; do { var fx0 = f(x0); //store the result of the function //if the value is zero then we're done because 0 - (0/d f(x0)) = 0 if(x0 === 0 && fx0 === 0) { x = 0; break; } iter++; if(iter > maxiter) return; //naximum iterations reached x = x0 - fx0/fp(x0); var e = Math.abs(x - x0); x0 = x; } while(e > Number.EPSILON) return x; }
javascript
{ "resource": "" }
q44393
train
function(symbol) { var has_trig = symbol.hasTrig(); // we get all the points where a possible zero might exist var points1 = get_points(symbol, 0.1); var points2 = get_points(symbol, 0.05); var points3 = get_points(symbol, 0.01); var points = core.Utils.arrayUnique(points1.concat(points2).concat(points3)), l = points.length; //compile the function and the derivative of the function var f = build(symbol.clone()), fp = build(_C.diff(symbol.clone())); for(var i=0; i<l; i++) { var point = points[i]; add_to_result(Newton(point, f, fp), has_trig); } solutions.sort(); }
javascript
{ "resource": "" }
q44394
train
function(eq) { var lhs = new Symbol(0), rhs = new Symbol(0); eq.each(function(x) { if(x.contains(solve_for, true)) lhs = _.add(lhs, x.clone()); else rhs = _.subtract(rhs, x.clone()); }); return [lhs, rhs]; }
javascript
{ "resource": "" }
q44395
polydiff
train
function polydiff(symbol) { if(symbol.value === d || symbol.contains(d, true)) { symbol.multiplier = symbol.multiplier.multiply(symbol.power); symbol.power = symbol.power.subtract(new Frac(1)); if(symbol.power.equals(0)) { symbol = Symbol(symbol.multiplier); } } return symbol; }
javascript
{ "resource": "" }
q44396
train
function(x) { var g = x.group; if(g === FN) { var fname = x.fname; if(core.Utils.in_trig(fname) || core.Utils.in_htrig(fname)) parts[3].push(x); else if(core.Utils.in_inverse_trig(fname)) parts[1].push(x); else if(fname === LOG) parts[0].push(x); else { __.integration.stop(); } } else if(g === S || x.isComposite() && x.isLinear() || g === CB && x.isLinear()) { parts[2].push(x); } else if(g === EX || x.isComposite() && !x.isLinear()) parts[4].push(x); else __.integration.stop(); }
javascript
{ "resource": "" }
q44397
train
function(symbol) { var p = symbol.power, k = p/2, e; if(symbol.fname === COS) e = '((1/2)+(cos(2*('+symbol.args[0]+'))/2))^'+k; else e = '((1/2)-(cos(2*('+symbol.args[0]+'))/2))^'+k; return _.parse(e); }
javascript
{ "resource": "" }
q44398
train
function(integral, vars, point) { try { return _.parse(integral, vars); } catch(e) { //it failed for some reason so return the limit return __.Limit.limit(integral, dx, point); } }
javascript
{ "resource": "" }
q44399
interpolate
train
function interpolate(contours, accuracy) { return _.map(contours, function (contour) { var resContour = []; _.forEach(contour, function (point, idx) { // Never skip first and last points if (idx === 0 || idx === (contour.length - 1)) { resContour.push(point); return; } var prev = contour[idx - 1]; var next = contour[idx + 1]; var p, pPrev, pNext; // skip interpolateable oncurve points (if exactly between previous and next offcurves) if (!prev.onCurve && point.onCurve && !next.onCurve) { p = new math.Point(point.x, point.y); pPrev = new math.Point(prev.x, prev.y); pNext = new math.Point(next.x, next.y); if (pPrev.add(pNext).div(2).sub(p).dist() < accuracy) { return; } } // keep the rest resContour.push(point); }); return resContour; }); }
javascript
{ "resource": "" }