_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q56000
train
function() { if (typeof this.varsData !== 'string') { if (!this.varsFile) throw 'No theme variables file specified.'; this.varsFile = path.resolve(this.cwd, this.varsFile); this.varsData = fs.readFileSync(this.varsFile, 'utf-8'); } }
javascript
{ "resource": "" }
q56001
train
function(source) { if (typeof source === 'object') { this.ast = source; } else if (typeof source === 'string') { // JSON source: if (isJSON(source)) { this.ast = JSON.parse(source); } // Sass source: else { this.ast = gonzales.parse(source, {syntax: 'scss'}); } } else { throw 'Source could not be loaded.'; } return this.resetMapping(); }
javascript
{ "resource": "" }
q56002
train
function(opts) { var opts = opts || {}; this._template = !!(opts.hasOwnProperty('template') ? opts.template : this.template); this._treeRemoval = !!(opts.hasOwnProperty('treeRemoval') ? opts.treeRemoval : this.treeRemoval); this._varsRemoval = !!(opts.hasOwnProperty('varsRemoval') ? opts.varsRemoval : this.varsRemoval); this._parseNode(this.ast); return this; }
javascript
{ "resource": "" }
q56003
train
function(parent) { function error(usage) { return new Error('Template theme fields are not permitted '+ usage +':\n>>> '+ Node.toString(parent)); } // Check for arguments implementation: if (parent.type === NodeType.ARGUMENTS) { throw error('as arguments'); } // Check for interpolations implementation: if (parent.type === NodeType.INTERPOLATION) { throw error('in interpolations'); } // Check for operations implementation: for (var i=0; i < parent.content.length; i++) { if (NodeType.OPERATOR.test(parent.content[i].type)) { throw error('in operations'); } } }
javascript
{ "resource": "" }
q56004
train
function(field) { if (this.vars.hasOwnProperty(field)) { if (!this.usage.hasOwnProperty(field)) { this.usage[field] = 0; } this.usage[field]++; } }
javascript
{ "resource": "" }
q56005
train
function(field) { if (this._template) { var match = field.match(this.fieldRegex); return match && this.vars.hasOwnProperty(match[1]); } return false; }
javascript
{ "resource": "" }
q56006
train
function(opts, done) { if (typeof opts !== 'object') { done = opts; opts = null; } validateCallback(done); this.parse(opts); this.renderCSS(done); return this; }
javascript
{ "resource": "" }
q56007
train
function(done) { var isSync = (typeof done !== 'function'); var sass = require('node-sass'); var opts = this.sassCSSOptions(); if (isSync) { try { return sass.renderSync(opts).css.toString(); } catch (err) { throw formatSassError(err, opts.data); } } sass.render(opts, function(err, result) { if (err) return done(formatSassError(err, opts.data)); done(null, result.css.toString()); }); }
javascript
{ "resource": "" }
q56008
train
function(opts, done) { if (typeof opts !== 'object') { done = opts; opts = {}; } validateCallback(done); opts.template = true; this.parse(opts); this.renderTemplate(done); return this; }
javascript
{ "resource": "" }
q56009
train
function(done) { var isSync = (typeof done !== 'function'); var sass = require('node-sass'); var opts = this.sassTemplateOptions(); var self = this; if (isSync) { try { var result = sass.renderSync(opts); return this.fieldIdentifiersToInterpolations(result.css.toString()); } catch (err) { throw formatSassError(err, opts.data); } } sass.render(opts, function(err, result) { if (err) return done(formatSassError(err, opts.data)); done(null, self.fieldIdentifiersToInterpolations(result.css.toString())); }); }
javascript
{ "resource": "" }
q56010
train
function(sass) { var match; while ((match = this.fieldRegexAll.exec(sass)) !== null) { if (this.vars.hasOwnProperty(match[1])) { this._addFieldUsage(match[1]); } } return this; }
javascript
{ "resource": "" }
q56011
formatSassError
train
function formatSassError(err, data) { // Generate three-line preview around the error: var preview = data.split('\n'); preview = preview.slice(Math.max(0, err.line-2), Math.min(err.line+1, preview.length-1)); preview = preview.map(function(src) { return '>>> '+ src }); preview.unshift(err.message); var error = new Error('Error rendering theme Sass:\n'+ preview.join('\n')); error.line = err.line || null; error.column = err.column || null; return error; }
javascript
{ "resource": "" }
q56012
train
function(base) { for (var i=1; i < arguments.length; i++) { var ext = arguments[i]; for (var key in ext) { if (ext.hasOwnProperty(key)) base[key] = ext[key]; } } return base; }
javascript
{ "resource": "" }
q56013
train
function(opts) { return this.extend(gonzales.createNode({ type: 'stylesheet', syntax: 'scss', content: [], start: {line: 1, column: 1}, end: {line: 1, column: 1} }), opts || {}); }
javascript
{ "resource": "" }
q56014
train
function(parentFile, importedFile) { if (parentFile.includedFiles.indexOf(importedFile.file) < 0) { // Add imported file reference: parentFile.includedFiles.push(importedFile.file); // Add all of imported file's imports: for (var i=0; i < importedFile.includedFiles.length; i++) { var includeFile = importedFile.includedFiles[i]; if (parentFile.includedFiles.indexOf(includeFile) < 0) { parentFile.includedFiles.push(includeFile); } } } }
javascript
{ "resource": "" }
q56015
train
function(file) { if (!AST.cache) { return; } else if (typeof file === 'string') { if (!AST.cache[file]) AST.cache[file] = null; } else if (file.isParsed() && !file.timestamp) { file.timestamp = Date.now(); AST.cache[file.file] = file; } }
javascript
{ "resource": "" }
q56016
Importer
train
function Importer(opts) { var self = this; opts = opts || {}; EventEmitter.call(this); this.cwd = opts.cwd ? path.resolve(opts.cwd) : process.cwd(); this.file = opts.file ? path.resolve(opts.cwd, opts.file) : this.cwd; this.data = opts.data; this.includePaths = opts.includePaths || []; // Map all include paths to configured working directory: this.includePaths = this.includePaths.map(function(includePath) { return path.resolve(self.cwd, includePath); }); }
javascript
{ "resource": "" }
q56017
train
function(done) { this.async = true; var self = this; function finish(err, file) { var hasCallback = (typeof done === 'function'); if (err && !hasCallback) return self.emit('error', err); if (err) return done(err); done(null, file); } if (this.data) { this.createFile(this.file, this.uri, this.file, this.data, finish).parse(finish); } else { this.resolve(this.file, this.cwd, function(err, file) { if (err) return finish(err); file.parse(finish); }); } return this; }
javascript
{ "resource": "" }
q56018
train
function() { this.async = false; var file; if (this.data) { file = this.createFile(this.file, this.uri, this.file, this.data); } else { file = this.resolveSync(this.file, this.cwd); } return file.parse(); }
javascript
{ "resource": "" }
q56019
File
train
function File(filepath, data, importer) { this.file = filepath; this.data = data; this.importer = importer; this.includedFiles = []; this._cb = []; _.cacheFile(filepath); }
javascript
{ "resource": "" }
q56020
sectorify
train
function sectorify(file, ssz) { var nsectors = Math.ceil(file.length/ssz)-1; var sectors = new Array(nsectors); for(var i=1; i < nsectors; ++i) sectors[i-1] = file.slice(i*ssz,(i+1)*ssz); sectors[nsectors-1] = file.slice(nsectors*ssz); return sectors; }
javascript
{ "resource": "" }
q56021
makePath
train
function makePath(object, path, index) { index = index || 0; var obj; if (path.length > index + 1) { obj = object[path[index]]; // we always want the last object in an array if (_.isArray(obj)) obj = _.last(obj); makePath(obj, path, index + 1); } else { obj = object[path[index]]; if (!obj) { // object doesn't exist yet so make it object[path[index]] = {}; } else { if (!_.isArray(obj)) { // object isn't an array yet so make an array with the object as the first element object[path[index]] = [obj]; } // append the new object object[path[index]].push({}); } } }
javascript
{ "resource": "" }
q56022
setValueForPath
train
function setValueForPath(object, path, value, index) { index = index || 0; if (path.length > index + 1) { var obj = object[path[index]]; // we always want the last object in an array if (_.isArray(obj)) obj = _.last(obj); setValueForPath(obj, path, value, index + 1); } else { // found the object so set its value object[path[index]] = value; } }
javascript
{ "resource": "" }
q56023
overwriteFile
train
function overwriteFile(path, options) { let fileContent = null; let newData = null; try { fileContent = fs.readFileSync(path, 'utf8'); newData = visit(JSON.parse(fileContent), options); } catch (e) { console.error('Failed to retrieve json object from file'); throw e; } let indent; if (options && options.indentSize) { indent = options.indentSize; } else { indent = detectIndent(fileContent).indent || DEFAULT_INDENT_SIZE; } const newLine = detectNewline(fileContent) || '\n'; let newFileContent = JSON.stringify(newData, null, indent); if (!(options && options.noFinalNewLine)) { // Append a new line at EOF newFileContent += '\n'; } if (newLine !== '\n') { newFileContent = newFileContent.replace(/\n/g, newLine); } fs.writeFileSync(path, newFileContent, 'utf8'); return newData; }
javascript
{ "resource": "" }
q56024
overwrite
train
function overwrite(absolutePaths, options) { const paths = Array.isArray(absolutePaths) ? absolutePaths : [absolutePaths]; const results = paths.map(path => overwriteFile(path, options)); return results.length > 1 ? results : results[0]; }
javascript
{ "resource": "" }
q56025
visit
train
function visit(old, options) { const sortOptions = options || {}; const ignoreCase = sortOptions.ignoreCase || false; const reverse = sortOptions.reverse || false; const depth = sortOptions.depth || Infinity; const level = sortOptions.level || 1; const processing = level <= depth; if (typeof (old) !== 'object' || old === null) { return old; } const copy = Array.isArray(old) ? [] : {}; let keys = Object.keys(old); if (processing) { keys = ignoreCase ? keys.sort((left, right) => left.toLowerCase().localeCompare(right.toLowerCase())) : keys.sort(); } if (reverse) { keys = keys.reverse(); } keys.forEach((key) => { const subSortOptions = Object.assign({}, sortOptions); subSortOptions.level = level + 1; copy[key] = visit(old[key], subSortOptions); }); return copy; }
javascript
{ "resource": "" }
q56026
fetchOrders
train
function fetchOrders() { return new Promise((resolve, reject) => { https.get('https://services.odata.org/V4/Northwind/Northwind.svc/Orders', (result) => { var str = ''; result.on('data', (b) => str += b); result.on('error', reject); result.on('end', () => resolve(JSON.parse(str).value)); }); }) }
javascript
{ "resource": "" }
q56027
prepareDataSource
train
async function prepareDataSource() { const orders = await fetchOrders() const ordersByShipCountry = orders.reduce((a, v) => { a[v.ShipCountry] = a[v.ShipCountry] || [] a[v.ShipCountry].push(v) return a }, {}) return Object.keys(ordersByShipCountry).map((country) => { const ordersInCountry = ordersByShipCountry[country] const accumulated = {} ordersInCountry.forEach((o) => { o.OrderDate = new Date(o.OrderDate); const key = o.OrderDate.getFullYear() + '/' + (o.OrderDate.getMonth() + 1); accumulated[key] = accumulated[key] || { value: 0, orderDate: o.OrderDate }; accumulated[key].value++; }); return { rows: ordersInCountry, country, accumulated } }).slice(0, 2) }
javascript
{ "resource": "" }
q56028
buildFailureParams
train
function buildFailureParams (test) { const opts = test.error.operator ? { type: test.error.operator, message: test.raw } : { message: test.raw } if (test.error.raw && test.error.stack) { return [ opts, ` --- ${test.error.raw} ${test.error.stack} --- ` ] } return [opts] }
javascript
{ "resource": "" }
q56029
fetchAndInstantiate
train
function fetchAndInstantiate(url, importObject) { return fetch(url).then(response => response.arrayBuffer() ).then(bytes => WebAssembly.instantiate(bytes, importObject) ).then(results => results.instance ); }
javascript
{ "resource": "" }
q56030
openDatabase
train
function openDatabase() { return new Promise((resolve, reject) => { var request = indexedDB.open(dbName, dbVersion); request.onerror = reject.bind(null, 'Error opening wasm cache database'); request.onsuccess = () => { resolve(request.result) }; request.onupgradeneeded = event => { var db = request.result; if (db.objectStoreNames.contains(storeName)) { console.log(`Clearing out version ${event.oldVersion} wasm cache`); db.deleteObjectStore(storeName); } console.log(`Creating version ${event.newVersion} wasm cache`); db.createObjectStore(storeName) }; }); }
javascript
{ "resource": "" }
q56031
lookupInDatabase
train
function lookupInDatabase(db) { return new Promise((resolve, reject) => { var store = db.transaction([storeName]).objectStore(storeName); var request = store.get(url); request.onerror = reject.bind(null, `Error getting wasm module ${url}`); request.onsuccess = event => { if (request.result) resolve(request.result); else reject(`Module ${url} was not found in wasm cache`); } }); }
javascript
{ "resource": "" }
q56032
storeInDatabase
train
function storeInDatabase(db, module) { var store = db.transaction([storeName], 'readwrite').objectStore(storeName); try { var request = store.put(module, url); request.onerror = err => { console.log(`Failed to store in wasm cache: ${err}`) }; request.onsuccess = err => { console.log(`Successfully stored ${url} in wasm cache`) }; } catch (e) { console.warn('An error was thrown... in storing wasm cache...'); console.warn(e); } }
javascript
{ "resource": "" }
q56033
fetchAndInstantiate
train
function fetchAndInstantiate() { return fetch(url).then(response => response.arrayBuffer() ).then(buffer => WebAssembly.instantiate(buffer, importObject) ) }
javascript
{ "resource": "" }
q56034
Promise
train
function Promise(back) { this.emitter = new EventEmitter(); this.emitted = {}; this.ended = false; if ('function' == typeof back) this.onResolve(back); }
javascript
{ "resource": "" }
q56035
train
function (root) { var current = root.prototype ? root.prototype.addEventListener : root.addEventListener; var customAddEventListener = function (name, func, capture) { // Branch when a PointerXXX is used if (supportedEventsNames.indexOf(name) !== -1) { setTouchAware(this, name, true); } if (current === undefined) { this.attachEvent('on' + getMouseEquivalentEventName(name), func); } else { current.call(this, name, func, capture); } }; if (root.prototype) { root.prototype.addEventListener = customAddEventListener; } else { root.addEventListener = customAddEventListener; } }
javascript
{ "resource": "" }
q56036
train
function (root) { var current = root.prototype ? root.prototype.removeEventListener : root.removeEventListener; var customRemoveEventListener = function (name, func, capture) { // Release when a PointerXXX is used if (supportedEventsNames.indexOf(name) !== -1) { setTouchAware(this, name, false); } if (current === undefined) { this.detachEvent(getMouseEquivalentEventName(name), func); } else { current.call(this, name, func, capture); } }; if (root.prototype) { root.prototype.removeEventListener = customRemoveEventListener; } else { root.removeEventListener = customRemoveEventListener; } }
javascript
{ "resource": "" }
q56037
pointerDown
train
function pointerDown(e) { // don't register an activePointer if more than one touch is active. var singleFinger = e.pointerType === POINTER_TYPE_MOUSE || e.pointerType === POINTER_TYPE_PEN || (e.pointerType === POINTER_TYPE_TOUCH && e.isPrimary); if (!isScrolling && singleFinger) { activePointer = { id: e.pointerId, clientX: e.clientX, clientY: e.clientY, x: (e.x || e.pageX), y: (e.y || e.pageY), type: e.pointerType }; } }
javascript
{ "resource": "" }
q56038
pointerUp
train
function pointerUp(e) { // Does our event is the same as the activePointer set by pointerdown? if (activePointer && activePointer.id === e.pointerId) { // Have we moved too much? if (Math.abs(activePointer.x - (e.x || e.pageX)) < 5 && Math.abs(activePointer.y - (e.y || e.pageY)) < 5) { // Have we scrolled too much? if (!isScrolling || (Math.abs(sDistX - window.pageXOffset) < 5 && Math.abs(sDistY - window.pageYOffset) < 5)) { makePointertapEvent(e); } } } activePointer = null; }
javascript
{ "resource": "" }
q56039
makePointertapEvent
train
function makePointertapEvent(sourceEvent) { var evt = document.createEvent('MouseEvents'); var newTarget = document.elementFromPoint(sourceEvent.clientX, sourceEvent.clientY); // According to the MDN docs if the specified point is outside the visible bounds of the document // or either coordinate is negative, the result is null if (!newTarget) { return null; } // TODO: Replace 'initMouseEvent' with 'new MouseEvent' evt.initMouseEvent('pointertap', true, true, window, 1, sourceEvent.screenX, sourceEvent.screenY, sourceEvent.clientX, sourceEvent.clientY, sourceEvent.ctrlKey, sourceEvent.altKey, sourceEvent.shiftKey, sourceEvent.metaKey, sourceEvent.button, newTarget); evt.maskedEvent = sourceEvent; newTarget.dispatchEvent(evt); return evt; }
javascript
{ "resource": "" }
q56040
train
function() { _cbt = require('./cbt')(); _options = options || {}; // apply defaults // the min bytes of an incoming reply _options.minBytes = _options.minBytes || 1; // the max bytes of an incoming reply _options.maxBytes = _options.maxBytes || 1024 * 1024; // the group the client will join when using `.connect()` _options.group = _options.group || 'kafkaesqueGroup'; // the clientID when connecting to kafka _options.clientId = _options.clientId || 'kafkaesque' + Math.floor(Math.random() * 100000000); // the array of brokers _options.brokers = _options.brokers || [{host: 'localhost', port: 9092}]; // the amount of time it should take for this clients session within the group // to timeout _options.sessionTimeout = _options.sessionTimeout || 6000; // the amount of time to take to emit a heartbeat msg _options.heartbeat = _options.heartbeat || 2500; // the default amount of time that the kafka broker shoudl wait to send // a reply to a fetch request if the fetch reply is smaller than the minBytes _options.maxWait = _options.maxWait || 5000; _brokers = {}; _topics = {}; _groupMemberId = ''; _groupGeneration = 0; _.each(_options.brokers, function(broker) { broker = { host: broker.host, port: broker.port, maxBytes: _options.maxBytes, minBytes: _options.minBytes, clientId: _options.clientId }; _brokers[_makeBrokerKey(broker)] = api(broker); }); _metaBroker = _brokers[_makeBrokerKey(_options.brokers[0])]; }
javascript
{ "resource": "" }
q56041
train
function (cb) { _metaBroker.tearUp(function (err) { if (!err) { _metaBroker.connected = true; } cb(err); }); }
javascript
{ "resource": "" }
q56042
train
function(params, cb) { cb = cb || _noop; assert(params.topic); _metaBroker.metadata([params.topic], function(err, cluster) { cluster.topics.forEach(function(topic) { _partitions[topic.topicName] = topic.partitions; }); cb(err, cluster); }); }
javascript
{ "resource": "" }
q56043
train
function() { if (_polling) { _closing = true; setTimeout(function() { if( _closing) { _.each(_brokers, function(broker) { broker.tearDown(); }); } }, _options.maxWait); } else { _.each(_brokers, function(broker) { broker.tearDown(); }); } }
javascript
{ "resource": "" }
q56044
set
train
function set(key, value, options) { options = typeof options ==='object' ? options : { expires: options }; let expires = options.expires != null ? options.expires : defaults.expires; if (typeof expires === 'string' && expires !== '') { expires = new Date(expires); } else if (typeof expires === 'number') { expires = new Date(+new Date + (1000 * day * expires)); } if (expires && 'toGMTString' in expires) { expires = ';expires=' + expires.toGMTString(); } let path = ';path=' + (options.path || defaults.path); let domain = options.domain || defaults.domain; domain = domain ? ';domain=' + domain : ''; let secure = options.secure || defaults.secure ? ';secure' : ''; if (typeof value == 'object') { if (Array.isArray(value) || isPlainObject(value)) { value = JSON.stringify(value); } else { value = ''; } } document.cookie = encodeCookie(key) + '=' + encodeCookie(value) + expires + path + domain + secure; }
javascript
{ "resource": "" }
q56045
train
function(topics, cb) { var correlationId = _cbt.put(metaResponse(cb)); var msg = envelope(meta.encode() .correlation(correlationId) .client(_options.clientId) .topics(topics) .end()); sendMsg(msg, correlationId, cb); }
javascript
{ "resource": "" }
q56046
train
function(params, messages, cb) { var correlationId = _cbt.put(prodResponse(cb)); var msg = envelope(prod.encode() .correlation(correlationId) .client(_options.clientId) .timeout() .topic(params.topic) .partition(params.partition) .messages(messages) .end()); sendMsg(msg, correlationId, cb); }
javascript
{ "resource": "" }
q56047
train
function(params, cb) { var correlationId = _cbt.put(fetchResponse(cb)); var msg = envelope(fech.encode() .correlation(correlationId) .client(_options.clientId) .maxWait(params.maxWait) .minBytes(params.minBytes) .topic(params.topic) .partition(params.partition) .offset(params.offset) .maxBytes(_options.maxBytes) .end()); sendMsg(msg, correlationId, cb); }
javascript
{ "resource": "" }
q56048
train
function(params, cb) { var correlationId = _cbt.put(offsetResponse(cb)); var msg = envelope(off.encode() .correlation(correlationId) .client(_options.clientId) .replica() .topic(params.topic) .partition(params.partition) .timestamp() .maxOffsets() .end()); sendMsg(msg, correlationId, cb); }
javascript
{ "resource": "" }
q56049
train
function(params, cb) { var correlationId = _cbt.put(offFetchResponse(cb)); var msg = envelope(offFetch.encode(params.fetchFromCoordinator ? 1 : 0) .correlation(correlationId) .client(_options.clientId) .group(params.group) .topic(params.topic) .partition(params.partition) .end()); sendMsg(msg, correlationId, cb); }
javascript
{ "resource": "" }
q56050
train
function(params, cb) { var correlationId = _cbt.put(offCommitResponse(cb)); var msg = envelope(offCommit.encode() .correlation(correlationId) .client(_options.clientId) .group(params.group) .topic(params.topic) .partition(params.partition) .offset(params.offset) // .when(params.when) //disabled in api ver1 .meta(params.meta) .end()); sendMsg(msg, correlationId, cb); }
javascript
{ "resource": "" }
q56051
train
function(cb) { // return early if already connected if (_socket) { return cb(null, {host: _options.host, port: _options.port}); } _socket = net.createConnection(_options.port, _options.host); _socket.on('connect', function() { if (cb) { cb(null, {host: _options.host, port: _options.port}); } }); _socket.on('data', function(buf) { var res; var rblock; var decoder; if (!_rcvBuf) { _rcvBuf = kb(); } _rcvBuf.append(buf); res = response.decodeHead(_rcvBuf.get()); // console.log(res) // buffer can have more than one msg... // don't want to drop msgs while (_rcvBuf.length() > 0 && _rcvBuf.length() >= res.size + 4) { decoder = _cbt.remove(res.correlation); rblock = decoder.decode(_rcvBuf.get(), res); _rcvBuf.slice(res.size + 4); if (_rcvBuf.length() > 0) { res = response.decodeHead(_rcvBuf.get()); } decoder.callback(rblock.err, rblock.result); } }); _socket.on('end', function() {}); _socket.on('timeout', function(){ console.log('socket timeout'); }); _socket.on('drain', function(){}); _socket.on('error', function(err){ console.log('SOCKET ERROR: ' + err); }); _socket.on('close', function(){}); }
javascript
{ "resource": "" }
q56052
animationEnd
train
function animationEnd() { let el = document.createElement('tiny'); let animEndEventNames = { WebkitAnimation : 'webkitAnimationEnd', MozAnimation : 'animationend', OAnimation : 'oAnimationEnd oanimationend', animation : 'animationend' }; for (let name in animEndEventNames) { if (animEndEventNames.hasOwnProperty(name) && el.style[name] !== undefined) { return { end: animEndEventNames[name] }; } } return false; }
javascript
{ "resource": "" }
q56053
getFixedParent
train
function getFixedParent (el) { let currentParent = el.offsetParent, parent; while (parent === undefined) { if (currentParent === null) { parent = null; break; } if (css(currentParent, 'position') !== 'fixed') { currentParent = currentParent.offsetParent; } else { parent = currentParent; } } return parent; }
javascript
{ "resource": "" }
q56054
train
function (name, value, options) { if (options) { return validator[name](value, options) ? null : (_a = {}, _a[name] = { valid: false }, _a); } return validator[name](value) ? null : (_b = {}, _b[name] = { valid: false }, _b); var _a, _b; }
javascript
{ "resource": "" }
q56055
getParamValidator
train
function getParamValidator(name) { return function (options) { return function (c) { return getValidator(name, c.value != null ? c.value : '', options); }; }; }
javascript
{ "resource": "" }
q56056
placeBets
train
function placeBets() { // check input bets list var error; for ( var i = 0; i < req.request.bets.length; ++i) { var desc = req.request.bets[i]; error = checkPlaceBetItem(self, desc); // console.log('EMU bet', desc, "error", error); if (error) break; } // It is very strange, but Betfair returns 'OK' // when bet size or price is invalid res.response.errorCode = 'OK'; res.response.betResults = []; if (error) { // Prepare response, no bets placed for ( var i = 0; i < req.request.bets.length; ++i) { var resItem = { averagePriceMatched : '0.0', betId : '0', resultCode : error, sizeMatched : '0.0', success : 'false' }; res.response.betResults.push(resItem); } cb(null, res); return; } // Create bets var betIds = []; for ( var i = 0; i < req.request.bets.length; ++i) { var desc = req.request.bets[i]; var bet = new EmulatorBet(desc.marketId, desc.selectionId, desc.betType, desc.price, desc.size); betIds.push(bet.betId); self.bets[bet.betId] = bet; } // Try to match bets using price matching var bets = betIds.map(function(id) { return self.bets[id]; }); matchBetsUsingPrices(self, bets); // Prepare response for ( var id in betIds) { var betId = betIds[id]; var bet = self.bets[betId]; var resItem = { averagePriceMatched : bet.averageMatchedPrice(), betId : bet.betId, resultCode : 'OK', sizeMatched : bet.matchedSize(), success : 'true' }; res.response.betResults.push(resItem); } // placeBets was OK cb(null, res); }
javascript
{ "resource": "" }
q56057
cancelBets
train
function cancelBets() { // check request bets list var error; for ( var i = 0; i < req.request.bets.length; ++i) { var desc = req.request.bets[i]; error = checkCancelBetItem(self, desc); // console.log('EMU bet', desc, "error", error); if (error) break; } if (error) { res.response.errorCode = 'MARKET_IDS_DONT_MATCH'; cb(null, res); return; } // cancel bets res.response.errorCode = 'OK'; res.response.betResults = []; for ( var i = 0; i < req.request.bets.length; ++i) { var betId = req.request.bets[i].betId; console.log('EMU: cancel id=', betId); var bet = self.bets[betId]; // do cancel work var result = bet.cancel(); var resItem = { betId : bet.betId, resultCode : result.code, sizeCancelled : result.sizeCancelled, sizeMatched : result.sizeMatched, success : result.success }; res.response.betResults.push(resItem); } // cancelBets was OK cb(null, res); }
javascript
{ "resource": "" }
q56058
checkPlaceBetItem
train
function checkPlaceBetItem(self, desc) { if (desc.asianLineId !== '0' || desc.betCategoryType !== 'E') return 'UNKNOWN_ERROR'; if (desc.betPersistenceType !== 'NONE' && desc.betPersistenceType !== 'IP') return 'INVALID_PERSISTENCE'; if (desc.betType !== 'B' && desc.betType !== 'L') return 'INVALID_BET_TYPE'; if (desc.bspLiability !== '0') return 'BSP_BETTING_NOT_ALLOWED'; var price = betfairPrice.newBetfairPrice(desc.price); if (Math.abs(price.size - 1 * desc.price) > 0.0001) return 'INVALID_PRICE'; if (!self.players[desc.selectionId]) return 'SELECTION_REMOVED'; if (1 * desc.size < minimumBetSize || 1 * desc.size > maximumBetSize) return 'INVALID_SIZE'; // no checks failed, then bet is OK return null; }
javascript
{ "resource": "" }
q56059
skipWhitespace
train
function skipWhitespace() { while (i < input.length) { if (isWhitespace(input[i])) { i++; parser.pos_++; continue; } break; } }
javascript
{ "resource": "" }
q56060
DisableIEConditionalComments
train
function DisableIEConditionalComments(state, i){ if (state === htmlState.STATE_COMMENT && this.input[i] === ']' && this.input[i+1] === '>') { // for lazy conversion this._convertString2Array(); this.input.splice(i + 1, 0, ' '); this.inputLen++; } }
javascript
{ "resource": "" }
q56061
train
function (collectionIdentity) { if (!collectionIdentity) return; var schema = connectionObject.collections[collectionIdentity].attributes; if(!schema) return 'id'; var key; for(key in schema){ if(schema[key].primaryKey) return key; } return 'id'; }
javascript
{ "resource": "" }
q56062
securityAssert
train
function securityAssert(ctx) { // all disabled. don't need check if (!csrfEnable && !validateReferrer) return; // pass referrer check const referrer = ctx.get('referrer'); if (validateReferrer && validateReferrer(referrer)) return; if (csrfEnable && validateCsrf(ctx)) return; const err = new Error('jsonp request security validate failed'); err.referrer = referrer; err.status = 403; throw err; }
javascript
{ "resource": "" }
q56063
train
function(conn, cb) { log.debug('teardown:', conn); /* istanbul ignore if: standard waterline-adapter code */ if ( typeof conn == 'function') { cb = conn; conn = null; } /* istanbul ignore if: standard waterline-adapter code */ if (!conn) { connections = {}; return cb(); } /* istanbul ignore if: standard waterline-adapter code */ if (!connections[conn]) return cb(); delete connections[conn]; cb(); }
javascript
{ "resource": "" }
q56064
train
function(connection, collection, object, cb) { utils.removeCircularReferences(object); if (cb) { cb(object); } return object; }
javascript
{ "resource": "" }
q56065
train
function(node, highlighter) { this.div.classList.add('MJX_LiveRegion_Show'); var rect = node.getBoundingClientRect(); var bot = rect.bottom + 10 + window.pageYOffset; var left = rect.left + window.pageXOffset; this.div.style.top = bot + 'px'; this.div.style.left = left + 'px'; var color = highlighter.colorString(); this.inner.style.backgroundColor = color.background; this.inner.style.color = color.foreground; }
javascript
{ "resource": "" }
q56066
train
function(type) { var element = MathJax.HTML.Element( 'div', {className: 'MJX_LiveRegion'}); element.setAttribute('aria-live', type); return element; }
javascript
{ "resource": "" }
q56067
train
function() { if (!Assistive.getOption('speech')) return; LiveRegion.announced = true; MathJax.Ajax.Styles(LiveRegion.styles); var div = LiveRegion.Create('polite'); document.body.appendChild(div); LiveRegion.Update(div, LiveRegion.ANNOUNCE); setTimeout(function() {document.body.removeChild(div);}, 1000); }
javascript
{ "resource": "" }
q56068
train
function(msg) { if (!Assistive.hook) return; var script = document.getElementById(msg[1]); if (script && script.id) { var jax = MathJax.Hub.getJaxFor(script.id); if (jax && jax.enriched) { Explorer.StateChange(script.id, jax); Explorer.liveRegion.Add(); Explorer.AddEvent(script); } } }
javascript
{ "resource": "" }
q56069
train
function(jax) { Explorer.RemoveHook(); Explorer.hook = MathJax.Hub.Register.MessageHook( 'End Math', function(message) { var newid = message[1].id + '-Frame'; var math = document.getElementById(newid); if (jax && newid === Explorer.expanded) { Explorer.ActivateWalker(math, jax); math.focus(); Explorer.expanded = false; } }); }
javascript
{ "resource": "" }
q56070
train
function() { if (Explorer.hook) { MathJax.Hub.UnRegister.MessageHook(Explorer.hook); Explorer.hook = null; } }
javascript
{ "resource": "" }
q56071
train
function(script) { var id = script.id + '-Frame'; var sibling = script.previousSibling; if (!sibling) return; var math = sibling.id !== id ? sibling.firstElementChild : sibling; Explorer.AddAria(math); Explorer.AddMouseEvents(math); if (math.className === 'MathJax_MathML') { math = math.firstElementChild; } if (!math) return; math.onkeydown = Explorer.Keydown; Explorer.Flame(math); math.addEventListener( Explorer.focusinEvent, function(event) { if (!Assistive.hook) return; if (!LiveRegion.announced) LiveRegion.Announce(); }); math.addEventListener( Explorer.focusoutEvent, function(event) { if (!Assistive.hook) return; // A fix for Edge. if (Explorer.ignoreFocusOut) { Explorer.ignoreFocusOut = false; if (Explorer.walker.moved === 'enter') { event.target.focus(); return; } } if (Explorer.walker) Explorer.DeactivateWalker(); }); // if (Assistive.getOption('speech')) { Explorer.AddSpeech(math); } // }
javascript
{ "resource": "" }
q56072
train
function(math) { var id = math.id; var jax = MathJax.Hub.getJaxFor(id); var mathml = jax.root.toMathML(); if (!math.getAttribute('haslabel')) { Explorer.AddMathLabel(mathml, id); } if (math.getAttribute('hasspeech')) return; switch (Assistive.getOption('generation')) { case 'eager': Explorer.AddSpeechEager(mathml, id); break; case 'mixed': var complexity = math.querySelectorAll('[data-semantic-complexity]'); if (complexity.length >= Assistive.eagerComplexity) { Explorer.AddSpeechEager(mathml, id); } break; case 'lazy': default: break; } }
javascript
{ "resource": "" }
q56073
train
function(mathml, id) { Explorer.MakeSpeechTask( mathml, id, sre.TreeSpeechGenerator, function(math, speech) {math.setAttribute('hasspeech', 'true');}, 5); }
javascript
{ "resource": "" }
q56074
train
function(mathml, id) { Explorer.MakeSpeechTask( mathml, id, sre.SummarySpeechGenerator, function(math, speech) { math.setAttribute('haslabel', 'true'); math.setAttribute('aria-label', speech);}, 5); }
javascript
{ "resource": "" }
q56075
train
function(mathml, id, constructor, onSpeech, time) { var messageID = Explorer.AddMessage(); setTimeout(function() { var speechGenerator = new constructor(); var math = document.getElementById(id); var dummy = new sre.DummyWalker( math, speechGenerator, Explorer.highlighter, mathml); var speech = dummy.speech(); if (speech) { onSpeech(math, speech); } Explorer.RemoveMessage(messageID); }, time); }
javascript
{ "resource": "" }
q56076
train
function(event) { if (event.keyCode === KEY.ESCAPE) { if (!Explorer.walker) return; Explorer.RemoveHook(); Explorer.DeactivateWalker(); FALSE(event); return; } // If walker is active we redirect there. if (Explorer.walker && Explorer.walker.isActive()) { if (typeof(Explorer.walker.modifier) !== 'undefined') { Explorer.walker.modifier = event.shiftKey; } var move = Explorer.walker.move(event.keyCode); if (move === null) return; if (move) { if (Explorer.walker.moved === 'expand') { Explorer.expanded = Explorer.walker.node.id; // This sometimes blurs in Edge and sometimes it does not. if (MathJax.Hub.Browser.isEdge) { Explorer.ignoreFocusOut = true; Explorer.DeactivateWalker(); return; } // This does not blur in FF, IE. if (MathJax.Hub.Browser.isFirefox || MathJax.Hub.Browser.isMSIE) { Explorer.DeactivateWalker(); return; } } Explorer.liveRegion.Update(Explorer.walker.speech()); Explorer.Highlight(); } else { Explorer.PlayEarcon(); } FALSE(event); return; } var math = event.target; if (event.keyCode === KEY.SPACE) { if (event.shiftKey && Assistive.hook) { var jax = MathJax.Hub.getJaxFor(math); Explorer.ActivateWalker(math, jax); Explorer.AddHook(jax); } else { MathJax.Extension.MathEvents.Event.ContextMenu(event, math); } FALSE(event); return; } }
javascript
{ "resource": "" }
q56077
train
function(node) { sre.HighlighterFactory.addEvents( node, {'mouseover': Explorer.MouseOver, 'mouseout': Explorer.MouseOut}, {renderer: MathJax.Hub.outputJax['jax/mml'][0].id, browser: MathJax.Hub.Browser.name} ); }
javascript
{ "resource": "" }
q56078
train
function() { Explorer.liveRegion.Clear(); Explorer.liveRegion.Hide(); Explorer.Unhighlight(); Explorer.currentHighlight = null; Explorer.walker.deactivate(); Explorer.walker = null; }
javascript
{ "resource": "" }
q56079
train
function() { Explorer.Reset(); var speechItems = ['Subtitles', 'Generation']; speechItems.forEach( function(x) { var item = MathJax.Menu.menu.FindId('Accessibility', x); if (item) { item.disabled = !item.disabled; }}); Explorer.Regenerate(); }
javascript
{ "resource": "" }
q56080
train
function() { for (var i = 0, all = MathJax.Hub.getAllJax(), jax; jax = all[i]; i++) { var math = document.getElementById(jax.inputID + '-Frame'); if (math) { math.removeAttribute('hasSpeech'); Explorer.AddSpeech(math); } } }
javascript
{ "resource": "" }
q56081
train
function (jax,id,script) { delete jax.enriched; if (this.config.disabled) return; try { this.running = true; var mml = sre.Enrich.semanticMathmlSync(jax.root.toMathML()); jax.root = MathJax.InputJax.MathML.Parse.prototype.MakeMML(mml); jax.root.inputID = script.id; jax.enriched = true; this.running = false; } catch (err) { this.running = false; throw err; } }
javascript
{ "resource": "" }
q56082
train
function (update,menu) { this.config.disabled = false; if (update) MathJax.Hub.Queue(["Reprocess",MathJax.Hub]); }
javascript
{ "resource": "" }
q56083
train
function() { var items = Array(this.modules.length); for (var i = 0, module; module = this.modules[i]; i++) items[i] = module.placeHolder; var menu = MENU.FindId('Accessibility'); if (menu) { items.unshift(ITEM.RULE()); menu.submenu.items.push.apply(menu.submenu.items,items); } else { var renderer = (MENU.FindId("Settings","Renderer")||{}).submenu; if (renderer) { // move AssitiveMML and InTabOrder from Renderer to Accessibility menu items.unshift(ITEM.RULE()); items.unshift(renderer.items.pop()); items.unshift(renderer.items.pop()); } items.unshift("Accessibility"); var menu = ITEM.SUBMENU.apply(ITEM.SUBMENU,items); var locale = MENU.IndexOfId('Locale'); if (locale) { MENU.items.splice(locale,0,menu); } else { MENU.items.push(ITEM.RULE(), menu); } } }
javascript
{ "resource": "" }
q56084
copyLICENSE
train
function copyLICENSE(pkg) { fs.copy(__dirname + '/../LICENSE', __dirname + '/../packages/' + pkg + '/LICENSE', err => { errorOnFail(err) console.log('LICENSE was successfully copied into the ' + pkg + ' package.') }) }
javascript
{ "resource": "" }
q56085
updateVersion
train
function updateVersion(pkg) { fs.readFile(__dirname + '/../package.json', 'utf8', (err, data) => { errorOnFail(err) const globalVersion = JSON.parse(data).version fs.readFile(__dirname + '/../packages/' + pkg + '/package.json', (err, data) => { errorOnFail(err) const packageJSON = JSON.parse(data) packageJSON.version = globalVersion // Update react-look-core dependency version if (pkg !== 'react-look-core') { packageJSON.dependencies['react-look-core'] = '^' + globalVersion } // Update react-look dependency version if (pkg === 'react-look-test-utils') { packageJSON.peerDependencies['react-look'] = '^' + globalVersion } const newPackageJSON = JSON.stringify(packageJSON, null, 4) fs.writeFile(__dirname + '/../packages/' + pkg + '/package.json', newPackageJSON, err => { errorOnFail(err) console.log('Successfully updated ' + pkg + ' version and react-look-core dependency version to ' + globalVersion + '.') }) }) }) }
javascript
{ "resource": "" }
q56086
train
function(tag, nodes) { var xmlNodes = nodes.map(function(x) {return x.xml(xml, opt_brief);}); var tagNode = xml.createElementNS('', tag); for (var i = 0, child; child = xmlNodes[i]; i++) { tagNode.appendChild(child); } return tagNode; }
javascript
{ "resource": "" }
q56087
train
function (element) { if (this.config.disabled) return; this.GetContainerWidths(element); var jax = HUB.getAllJax(element); var state = {collapse: [], jax: jax, m: jax.length, i: 0, changed:false}; return this.collapseState(state); }
javascript
{ "resource": "" }
q56088
train
function (SRE,state) { var w = SRE.width, m = w, M = 1000000; for (var j = SRE.action.length-1; j >= 0; j--) { var action = SRE.action[j], selection = action.selection; if (w > SRE.cwidth) { action.selection = 1; m = action.SREwidth; M = w; } else { action.selection = 2; } w = action.SREwidth; if (SRE.DOMupdate) { document.getElementById(action.id).setAttribute("selection",action.selection); } else if (action.selection !== selection) { state.changed = true; } } SRE.m = m; SRE.M = M; }
javascript
{ "resource": "" }
q56089
train
function (jax,state) { if (!jax.root.SRE.actionWidths) { MathJax.OutputJax[jax.outputJax].getMetrics(jax); try {this.computeActionWidths(jax)} catch (err) { if (!err.restart) throw err; return MathJax.Callback.After(["collapseState",this,state],err.restart); } state.changed = true; } return null; }
javascript
{ "resource": "" }
q56090
train
function (jax) { var SRE = jax.root.SRE, actions = SRE.action, j, state = {}; SRE.width = jax.sreGetRootWidth(state); for (j = actions.length-1; j >= 0; j--) actions[j].selection = 2; for (j = actions.length-1; j >= 0; j--) { var action = actions[j]; if (action.SREwidth == null) { action.selection = 1; action.SREwidth = jax.sreGetActionWidth(state,action); } } SRE.actionWidths = true; }
javascript
{ "resource": "" }
q56091
train
function (mml,id) { var child = this.FindChild(mml,id); return (child ? child.data.join("") : "?"); }
javascript
{ "resource": "" }
q56092
train
function (mml) { this.UncollapseChild(mml,1); if (mml.complexity > this.COLLAPSE.fenced) { if (mml.attr["data-semantic-role"] === "leftright") { var marker = mml.data[0].data.join("") + mml.data[mml.data.length-1].data.join(""); mml = this.MakeAction(this.Marker(marker),mml); } } return mml; }
javascript
{ "resource": "" }
q56093
train
function (mml) { this.UncollapseChild(mml,0); if (mml.complexity > this.COLLAPSE.sqrt) mml = this.MakeAction(this.Marker(this.MARKER.sqrt),mml); return mml; }
javascript
{ "resource": "" }
q56094
train
function (mml) { if (this.SplitAttribute(mml,"children").length === 1) { var child = (mml.data.length === 1 && mml.data[0].inferred ? mml.data[0] : mml); if (child.data[0] && child.data[0].collapsible) { // // Move menclose into the maction element // var maction = child.data[0]; child.SetData(0,maction.data[1]); maction.SetData(1,mml); mml = maction; } } return mml; }
javascript
{ "resource": "" }
q56095
train
function (mml) { if (mml.complexity > this.COLLAPSE.bigop || mml.data[0].type !== "mo") { var id = this.SplitAttribute(mml,"content").pop(); var op = Collapsible.FindChildText(mml,id); mml = this.MakeAction(this.Marker(op),mml); } return mml; }
javascript
{ "resource": "" }
q56096
train
function (mml) { if (mml.complexity > this.COLLAPSE.relseq) { var content = this.SplitAttribute(mml,"content"); var marker = Collapsible.FindChildText(mml,content[0]); if (content.length > 1) marker += "\u22EF"; mml = this.MakeAction(this.Marker(marker),mml); } return mml; }
javascript
{ "resource": "" }
q56097
train
function (mml) { this.UncollapseChild(mml,0,2); if (mml.complexity > this.COLLAPSE.superscript) mml = this.MakeAction(this.Marker(this.MARKER.superscript),mml); return mml; }
javascript
{ "resource": "" }
q56098
basicWorker
train
function basicWorker (job) { return Promise.try(() => { const tid = getNamespace('ponos').get('tid') if (!job.message) { throw new WorkerStopError('message is required', { tid: tid }) } console.log(`hello world: ${job.message}. tid: ${tid}`) }) }
javascript
{ "resource": "" }
q56099
train
function(){ var uri = 'https://img.youtube.com/vi/' + this.url.videoId + '/maxresdefault.jpg'; try { var image = new Image(); image.onload = function(){ // Onload may still be called if YouTube returns the 120x90 error thumbnail if('naturalHeight' in image){ if (image.naturalHeight <= 90 || image.naturalWidth <= 120) { return; } } else if(image.height <= 90 || image.width <= 120) { return; } this.poster_ = uri; this.trigger('posterchange'); }.bind(this); image.onerror = function(){}; image.src = uri; } catch(e){} }
javascript
{ "resource": "" }