_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q48300
train
function () { return !!storage && function() { // in mobile safari if safe browsing is enabled, window.storage // is defined but setItem calls throw exceptions. var success = true var value = Math.random() value = "" + value + "" //ensure that we are dealing with a string try { var _set = {} _set[value] = value; storage.set(_set) } catch (e) { success = false } storage.remove(value) return success }() }
javascript
{ "resource": "" }
q48301
train
function () { return !!storage && function() { // in mobile safari if safe browsing is enabled, window.storage // is defined but setItem calls throw exceptions. var success = true var value = Math.random() try { storage.setItem(value, value) } catch (e) { success = false } storage.removeItem(value) return success }() }
javascript
{ "resource": "" }
q48302
train
function( callback ) { var me = this; root( this, function( store ) { ls( store.createReader(), function( entries ) { if ( callback ) me.fn( 'keys', callback ).call( me, entries ); }); }); return this; }
javascript
{ "resource": "" }
q48303
train
function( objs, callback ) { var me = this; var saved = []; for ( var i = 0, il = objs.length; i < il; i++ ) { me.save( objs[i], function( obj ) { saved.push( obj ); if ( saved.length === il && callback ) { me.lambda( callback ).call( me, saved ); } }); } return this; }
javascript
{ "resource": "" }
q48304
train
function () { for (var i = 0, l = methods.length; i < l; i++) { this.evented(methods[i]) } }
javascript
{ "resource": "" }
q48305
onupgradeneeded
train
function onupgradeneeded() { self.db = request.result; self.transaction = request.transaction; // NB! in case of a version conflict, we don't try to migrate, // instead just throw away the old store and create a new one. // this happens if somebody changed the try { self.db.deleteObjectStore(self.record); } catch (e) { /* ignore */ } // create object store. var objectStoreOptions = { autoIncrement: useAutoIncrement() } if( typeof( self.keyPath )) { objectStoreOptions.keyPath = self.keyPath; } self.db.createObjectStore(self.record, objectStoreOptions); }
javascript
{ "resource": "" }
q48306
onsuccess
train
function onsuccess(event) { // remember the db instance self.db = event.target.result; // storage is now possible self.store = true; // execute all pending operations while (self.waiting.length) { self.waiting.shift().call(self); } // we're done, fire the callback if (cb) { cb.call(self, self); } }
javascript
{ "resource": "" }
q48307
train
function (property, callback) { // if only one arg we count the collection if ([].slice.call(arguments).length === 1) { callback = property property = 'key' } var c = 0 this.each(function(e){ if (e[property]) c++ }) this.fn('count', callback).call(this, c) }
javascript
{ "resource": "" }
q48308
train
function (property, callback) { var sum = 0 this.each(function(e){ if (e[property]) sum += e[property] }) this.fn('sum', callback).call(this, sum) }
javascript
{ "resource": "" }
q48309
train
function (property, callback) { this.sum(property, function (sum) { this.count(property, function (count) { this.fn('avg', callback).call(this, sum/count) }) }) }
javascript
{ "resource": "" }
q48310
train
function() { // ever notice we do this sort thing lots? var args = [].slice.call(arguments) , tmpl = args.shift() , last = args[args.length - 1] , qs = tmpl.match(/\?/g) , q = qs && qs.length > 0 ? interpolate(tmpl, args.slice(0, qs.length)) : tmpl , is = new Function(this.record, 'return !!(' + q + ')') , r = [] , cb // iterate the entire collection // TODO should we allow for chained where() to filter __results? (I'm thinking no b/c creates funny behvaiors w/ callbacks) this.all(function(all){ for (var i = 0, l = all.length; i < l; i++) { if (is.call(all[i], all[i])) r.push(all[i]) } // overwrite working results this.__results = r // callback / chain if (args.length === 1) this.fn(this.name, last).call(this, this.__results) }) return this }
javascript
{ "resource": "" }
q48311
showDiff
train
function showDiff(acediff, editor, startLine, endLine, className) { var editor = acediff.editors[editor]; if (endLine < startLine) { // can this occur? Just in case. endLine = startLine; } const classNames = `${className} ${(endLine > startLine) ? 'lines' : 'targetOnly'}`; endLine--; // because endLine is always + 1 // to get Ace to highlight the full row we just set the start and end chars to 0 and 1 editor.markers.push(editor.ace.session.addMarker(new Range(startLine, 0, endLine, 1), classNames, 'fullLine')); }
javascript
{ "resource": "" }
q48312
updateGap
train
function updateGap(acediff, editor, scroll) { clearDiffs(acediff); decorate(acediff); // reposition the copy containers containing all the arrows positionCopyContainers(acediff); }
javascript
{ "resource": "" }
q48313
getSingleDiffInfo
train
function getSingleDiffInfo(editor, offset, diffString) { const info = { startLine: 0, startChar: 0, endLine: 0, endChar: 0, }; const endCharNum = offset + diffString.length; let runningTotal = 0; let startLineSet = false, endLineSet = false; editor.lineLengths.forEach((lineLength, lineIndex) => { runningTotal += lineLength; if (!startLineSet && offset < runningTotal) { info.startLine = lineIndex; info.startChar = offset - runningTotal + lineLength; startLineSet = true; } if (!endLineSet && endCharNum <= runningTotal) { info.endLine = lineIndex; info.endChar = endCharNum - runningTotal + lineLength; endLineSet = true; } }); // if the start char is the final char on the line, it's a newline & we ignore it if (info.startChar > 0 && getCharsOnLine(editor, info.startLine) === info.startChar) { info.startLine++; info.startChar = 0; } // if the end char is the first char on the line, we don't want to highlight that extra line if (info.endChar === 0) { info.endLine--; } const endsWithNewline = /\n$/.test(diffString); if (info.startChar > 0 && endsWithNewline) { info.endLine++; } return info; }
javascript
{ "resource": "" }
q48314
createCopyContainers
train
function createCopyContainers(acediff) { acediff.copyRightContainer = document.createElement('div'); acediff.copyRightContainer.setAttribute('class', acediff.options.classes.copyRightContainer); acediff.copyLeftContainer = document.createElement('div'); acediff.copyLeftContainer.setAttribute('class', acediff.options.classes.copyLeftContainer); document.getElementById(acediff.options.classes.gutterID).appendChild(acediff.copyRightContainer); document.getElementById(acediff.options.classes.gutterID).appendChild(acediff.copyLeftContainer); }
javascript
{ "resource": "" }
q48315
generatePrefixed
train
function generatePrefixed(prefix) { let output = ''; let children = ''; for (const part of allParts) { const parts = prefix.concat([part]); if (prefix.indexOf(part) !== -1 || !verify(parts, true)) { // Function already in prefix or not allowed here continue; } // If `parts` is not sorted, we alias it to the sorted chain if (!isArraySorted(parts)) { if (exists(parts)) { parts.sort(); let chain; if (hasChildren(parts)) { chain = parts.join('_') + '<T>'; } else { // This is a single function, not a namespace, so there's no type associated // and we need to dereference it as a property type const last = parts.pop(); const joined = parts.join('_'); chain = `${joined}<T>['${last}']`; } output += `\t${part}: Register_${chain};\n`; } continue; } // Check that `part` is a valid function name. // `always` is a valid prefix, for instance of `always.after`, // but not a valid function name. if (verify(parts, false)) { if (arrayHas(parts)('todo')) { // 'todo' functions don't have a function argument, just a string output += `\t${part}: (name: string) => void;\n`; } else { if (arrayHas(parts)('cb')) { output += `\t${part}: CallbackRegisterBase<T>`; } else { output += `\t${part}: RegisterBase<T>`; } if (hasChildren(parts)) { // This chain can be continued, make the property an intersection type with the chain continuation const joined = parts.join('_'); output += ` & Register_${joined}<T>`; } output += ';\n'; } } children += generatePrefixed(parts); } if (output === '') { return children; } const typeBody = `{\n${output}}\n${children}`; if (prefix.length === 0) { // No prefix, so this is the type for the default export return `export interface Register<T> extends RegisterBase<T> ${typeBody}`; } const namespace = ['Register'].concat(prefix).join('_'); return `interface ${namespace}<T> ${typeBody}`; }
javascript
{ "resource": "" }
q48316
hasChildren
train
function hasChildren(parts) { // Concatenate the chain with each other part, and see if any concatenations are valid functions const validChildren = allParts .filter(newPart => parts.indexOf(newPart) === -1) .map(newPart => parts.concat([newPart])) .filter(longer => verify(longer, false)); return validChildren.length > 0; }
javascript
{ "resource": "" }
q48317
exists
train
function exists(parts) { if (verify(parts, false)) { // Valid function name return true; } if (!verify(parts, true)) { // Not valid prefix return false; } // Valid prefix, check whether it has members for (const prefix of allParts) { if (parts.indexOf(prefix) === -1 && exists(parts.concat([prefix]))) { return true; } } return false; }
javascript
{ "resource": "" }
q48318
hash
train
function hash (str) { return crypto .createHash('sha1') .update(str, 'ascii') .digest('base64') .replace(PLUS_GLOBAL_REGEXP, '-') .replace(SLASH_GLOBAL_REGEXP, '_') .replace(EQUAL_GLOBAL_REGEXP, '') }
javascript
{ "resource": "" }
q48319
train
function(servers, options) { this.servers = servers; this.seq = 0; this.options = merge(options || {}, {failoverTime: 60, retries: 2, retry_delay: 0.2, expires: 0, logger: console}); }
javascript
{ "resource": "" }
q48320
prompt
train
function prompt (next) { var fields = ['name', 'author', 'description', 'homepage']; app.prompt.override = {name: name}; app.prompt.start(); app.prompt.addProperties(info, fields, next); }
javascript
{ "resource": "" }
q48321
ensureDestroy
train
function ensureDestroy(callback) { app.prompt.get(['destroy'], function (err, result) { if (result.destroy !== 'yes' && result.destroy !== 'y') { app.log.warn('Destructive operation cancelled'); return callback(true); } callback(); }); }
javascript
{ "resource": "" }
q48322
executeCommand
train
function executeCommand(parts, callback) { var name, shouldLoad = true, command, usage; if (typeof parts === 'undefined' || typeof parts === 'function') { throw(new Error('parts is a required argument of type Array')); } name = parts.shift(); if (app.cli.source || app.commands[name]) { if (app.commands[name]) { shouldLoad = false; if (typeof app.commands[name] != 'function' && !app.commands[name][parts[0]]) { shouldLoad = true; } } if (shouldLoad && !loadCommand(name, parts[0])) { return callback(); } command = app.commands[name]; while (command) { usage = command.usage; if (!app.argv.h && !app.argv.help && typeof command === 'function') { while (parts.length + 1 < command.length) { parts.push(null); } if (command.destructive) { return ensureDestroy(function (err) { return err ? callback() : command.apply(app, parts.concat(callback)); }) } command.apply(app, parts.concat(callback)); return; } command = command[parts.shift()]; } // // Since we have not resolved a needle, try and print out a usage message // if (usage || app.cli.usage) { showUsage(usage || app.cli.usage); callback(false); } } else if (app.usage) { // // If there's no directory we're supposed to search for modules, simply // print out usage notice if it's provided. // showUsage(app.cli.usage); callback(true); } }
javascript
{ "resource": "" }
q48323
randomatic
train
function randomatic(pattern, length, options) { if (typeof pattern === 'undefined') { throw new Error('randomatic expects a string or number.'); } var custom = false; if (arguments.length === 1) { if (typeof pattern === 'string') { length = pattern.length; } else if (isNumber(pattern)) { options = {}; length = pattern; pattern = '*'; } } if(typeOf(length) === 'object' && length.hasOwnProperty('chars')) { options = length; pattern = options.chars; length = pattern.length; custom = true; } var opts = options || {}; var mask = ''; var res = ''; // Characters to be used if (pattern.indexOf('?') !== -1) mask += opts.chars; if (pattern.indexOf('a') !== -1) mask += type.lower; if (pattern.indexOf('A') !== -1) mask += type.upper; if (pattern.indexOf('0') !== -1) mask += type.number; if (pattern.indexOf('!') !== -1) mask += type.special; if (pattern.indexOf('*') !== -1) mask += type.all; if (custom) mask += pattern; for (var i = 0; i < length; i++) { res += mask.charAt(parseInt(Math.random() * mask.length)); } return res; }
javascript
{ "resource": "" }
q48324
train
function (port = 9090) { return store => { const getId = idGenerator(); // initialize socket connection const socket = io('http://localhost:' + port); // register event noting connection to sockets (client app) let initEvent = buildEvent(getId(), 'CONNECTED TO SERVER', 'Successfully connected Vuetron to server.'); store.commit('addNewEvent', initEvent); socket.on('clientAppConnected', function () { let event = buildEvent(getId(), 'CLIENT APP CONNECTED', 'Successfully connected to client application.'); store.commit('addNewEvent', event); }); socket.on('setInitState', function (state) { let event = buildEvent(getId(), 'STATE INITIALIZED', state); // register event noting receipt of initial client state store.commit('addNewEvent', event); // initialize client state value store.commit('updateClientState', state); }); // listen for state changes from client and update // vuetron's client state store accordingly along // with mutation log socket.on('stateUpdate', function (changes, mutation, newState) { let updatedState = buildEvent(getId(), 'STATE CHANGE', {'changes': changes}); // add mutations updatedState.mutation = mutation; // add newState updatedState.state = JSON.stringify(newState); // register event for state change store.commit('addNewEvent', updatedState); // update client's current state to newState store.commit('updateClientState', newState); // check if any of the mutations are subscribed if (changes) { for (let change of changes) { const parsedPath = pathParser(JSON.stringify(change.path)); // if subscribed, push to that path's array for display for (let key of Object.keys(store.state.subscriptions)) { if (key === parsedPath || parsedPath.search(key) !== -1) { store.commit('addEventToSubscription', { key, change }); } } } } }); socket.on('eventUpdate', function (event) { let newEvent = buildEvent(getId(), 'EVENT EMITTED', event); store.commit('addNewEvent', newEvent); }); socket.on('domUpdate', function (dom) { store.commit('updateClientDom', dom); }); // listen for API responses made from FETCH requests and add to Event Stream socket.on('apiRequestResponse', function (response) { const display = { requestObj: response.requestConfig.slice(0), responseObj: response }; delete display.responseObj.requestConfig; const apiEvent = buildEvent(getId(), 'API REQUEST / RESPONSE', display); store.commit('addNewEvent', apiEvent); }); }; }
javascript
{ "resource": "" }
q48325
buildEvent
train
function buildEvent (id, title, display, hidden = {}) { const eventObj = { id, title, display, hidden, status: 'active', timestamp: new Date(Date.now()).toISOString() }; return eventObj; }
javascript
{ "resource": "" }
q48326
sendScreenshot
train
function sendScreenshot (name, runId, metaData, properties, compareSettings, png) { return _callServer('post', 'runs/' + runId + '/screenshots', null, { meta: JSON.stringify(metaData), properties: JSON.stringify(properties), compareSettings: JSON.stringify(compareSettings), screenshotName: name, file: { value: new Buffer(png, 'base64'), options: { filename: 'file.png', contentType: 'image/png' } } }).catch(function (error) { return q.reject('an error occured while sending a screenshot to the VisualReview server: ' + error); }); }
javascript
{ "resource": "" }
q48327
initRun
train
function initRun (projectName, suiteName, branchName) { if(_disabled) { return q.resolve(); } return _client.createRun(projectName, suiteName, branchName).then( function (createdRun) { if (createdRun) { _logMessage('created run with ID ' + createdRun.run_id); return _writeRunIdFile(JSON.stringify(createdRun)); } }.bind(this), function (err) { _throwError(err); }); }
javascript
{ "resource": "" }
q48328
takeScreenshot
train
function takeScreenshot (name) { if(_disabled) { return q.resolve(); } return browser.driver.controlFlow().execute(function () { return q.all([_getProperties(browser), _getMetaData(browser), browser.takeScreenshot(), _readRunIdFile()]).then(function (results) { var properties = results[0], metaData = results[1], compareSettings = _compareSettingsFn, png = results[2], run = results[3]; if (!run || !run.run_id) { _throwError('VisualReview-protractor: Could not send screenshot to VisualReview server, could not find any run ID. Was initRun called before starting this test? See VisualReview-protractor\'s documentation for more details on how to set this up.'); } return _client.sendScreenshot(name, run.run_id, metaData, properties, compareSettings, png) .catch(function (err) { _throwError('Something went wrong while sending a screenshot to the VisualReview server. ' + err); }); }); }.bind(this)); }
javascript
{ "resource": "" }
q48329
cleanup
train
function cleanup (exitCode) { if(_disabled) { return q.resolve(); } var defer = q.defer(); _readRunIdFile().then(function (run) { _logMessage('test finished. Your results can be viewed at: ' + 'http://' + _hostname + ':' + _port + '/#/' + run.project_id + '/' + run.suite_id + '/' + run.run_id + '/rp'); fs.unlink(RUN_PID_FILE, function (err) { if (err) { defer.reject(err); } else { defer.resolve(); } }); }); return defer.promise; }
javascript
{ "resource": "" }
q48330
extractionFunction
train
function extractionFunction(type) { if (utils.isObject(type)) { return type } else if (!fns.hasOwnProperty(type)) { throw new FieldError('Unknown DimExtractionFn type: ' + type) } var args = utils.args(arguments, 1) , fn = { type: type } fns[type].apply(fn, args) return fn }
javascript
{ "resource": "" }
q48331
loadFields
train
function loadFields(list, callback) { list.forEach(loadMethods) function loadMethods(field) { var module = require('./fields/' + field + '.js') , methods if (typeof module === 'function' || typeof module === 'string') { methods = {} methods[field] = module } else { methods = module } callback(methods) } }
javascript
{ "resource": "" }
q48332
Query
train
function Query(client, rawQuery) { if (client) { /** * If set, query is attached to given client instance * * @private * @type {Druid|Client} */ this.client = client } /** * Actual query object * * @private */ this._query = { queryType: this._queryType } if (rawQuery) { // we do not want to change query type, aren't we? this._queryType && delete rawQuery.queryType assign(this._query, rawQuery) } }
javascript
{ "resource": "" }
q48333
aggregation
train
function aggregation(type, name) { if (utils.isObject(type)) { return type } if (!name) { throw new FieldError('Missing aggregation output name') } else if (!aggregations.hasOwnProperty(type)) { throw new FieldError('Unknown aggregation type: ' + type) } var args = utils.args(arguments, 2) , aggregation = { type: type, name: name } aggregations[type].apply(aggregation, args) return aggregation }
javascript
{ "resource": "" }
q48334
asyncMap
train
function asyncMap(array, iterator, done) { if (!array || !array.length) { return done(null, []) } var error , out = [] , todo = array.length array.forEach(exec) function exec(item) { process.nextTick(function tick() { iterator(item, add) }) } function add(err, data) { if (error) { return } else if (err) { error = true return done(err) } out.push(data) if (--todo === 0) { done(null, out) } } }
javascript
{ "resource": "" }
q48335
getLessLoaded
train
function getLessLoaded(client, dataSource) { var ids = client.dataSources[dataSource] , nodes , node nodes = ids.map(id2client) function id2client(id) { return client.nodes[id] } node = nodes.reduce(lessLoaded) function lessLoaded(nodeA, nodeB) { if (nodeA.active < nodeB.active) { return nodeA } else { return nodeB } } return node }
javascript
{ "resource": "" }
q48336
getNodeData
train
function getNodeData(client, id, callback) { var path = client.discoveryPath + '/' + id , preferSSL = client.options.preferSSL client.zk.getData(path, handleData) function handleData(err, jsonBuffer) { if (err) { return callback(new DruidError('Error getting node data', err)) } debug('ZooKeeper data for path ' + path + ': ' + jsonBuffer) var data , proto , port try { data = JSON.parse(jsonBuffer.toString('utf8')) } catch (ex) { return callback(ex) } if (preferSSL && data.sslPort) { proto = 'https' port = data.sslPort } else { proto = 'http' port = data.port } data.path = path data.url = util.format('%s://%s:%s', proto, data.address, port) getDataSources(data, callback) } }
javascript
{ "resource": "" }
q48337
initZookeeper
train
function initZookeeper(client, connectionString) { var zk = zookeeper.createClient(connectionString, client.options.zookeeper) var error = false var connected = false client.ready = false client.zk = zk zk.connect() zk.on('connected', onconnected) zk.on('expired', setError) zk.on('authenticationFailed', setError) zk.on('disconnected', ondisconnected) zk.on('error', onerror) function onconnected() { if (!connected) { connected = true; client.updateBrokerList() } error = false; } function setError() { error = true; } function ondisconnected() { if (client.closed) { return } debug('Lost connection with ZooKeeper. Reconnecting...'); if (error) { zk.removeListener('error', onerror) zk.removeListener('disconnected', ondisconnected) zk.removeListener('expired', setError) zk.removeListener('authenticationFailed', setError) zk.close() initZookeeper(client, connectionString); } } function onerror(err) { client.emit('error', err) } }
javascript
{ "resource": "" }
q48338
Druid
train
function Druid(connectionString, discoveryPath, options) { EventEmitter.call(this) this.setMaxListeners(0) if (arguments.length === 2) { options = {} } /** * Services discovery path * * @protected * @type {string} */ this.discoveryPath = discoveryPath /** * Client options * * @protected */ this.options = options /** * (Re)loaded info about nodes and datasources * * @public * @type {boolean} */ this.ready; /** * Nodes (id -> node) * * @protected */ this.nodes = {} /** * Nodes associated with each data source (dataSource -> [nodeA, nodeB, ..., nodeN]) * * @protected */ this.dataSources = {} /** * ZooKeeper client * * @protected */ initZookeeper(this, connectionString) }
javascript
{ "resource": "" }
q48339
filter
train
function filter(type) { if (utils.isObject(type)) { return type } else if (!filters.hasOwnProperty(type)) { throw new FieldError('Bad filter type: ' + type) } var args = utils.args(arguments, 1) , filter = { type: type } filters[type].apply(filter, args) return filter }
javascript
{ "resource": "" }
q48340
dataSource
train
function dataSource(type) { if (arguments.length === 1 && (utils.isObject(type) || typeof type === 'string')) { return type } else if (!ds.hasOwnProperty(type)) { throw new FieldError('Unknown data source type: ' + type) } var args = utils.args(arguments, 1) , dataSource = { type: type } ds[type].apply(dataSource, args) return dataSource }
javascript
{ "resource": "" }
q48341
orderBy
train
function orderBy(dimension, direction) { if (arguments.length === 1) { direction = 'ASCENDING' } if (!dimension) { throw new FieldError('Dimension is not specified') } else if (!~['ascending', 'descending'].indexOf(direction.toLowerCase())) { throw new FieldError('Bad orderBy direction: ' + direction) } return { dimension: dimension, direction: direction } }
javascript
{ "resource": "" }
q48342
sort
train
function sort(type) { if (!~SORT_TYPES.indexOf(type)) { throw new FieldError('Sorting type can be ' + SORT_TYPES.join(' or ')) } return { type: type } }
javascript
{ "resource": "" }
q48343
dimension
train
function dimension(dimension, outputName, fn) { if (!dimension) { throw new FieldError('At least dimension must be specified') } if (arguments.length === 1 && typeof dimension === 'object') { return dimension } if (arguments.length === 1) { return { type: 'default', dimension: dimension } } else if (arguments.length === 2 && typeof outputName !== 'object') { return { type: 'default', dimension: dimension, outputName: outputName } } else if (arguments.length === 2) { fn = outputName return { type: 'extraction', dimension: dimension, dimExtractionFn: fn } } else if (arguments.length === 3) { return { type: 'extraction', dimension: dimension, outputName: outputName, dimExtractionFn: fn } } else { throw new FieldError('Bad arguments number: ' + arguments.length) } }
javascript
{ "resource": "" }
q48344
query
train
function query(type, value, caseSensitive) { if (utils.isObject(type)) { return type } else if (!type || !value) { throw new FieldError('Type or value is not specified') } // InsensitiveContainsSearchQuerySpec else if (type === 'insensitive_contains') { return { type: 'insensitive_contains', value: value + '' } } // FragmentSearchQuerySpec else if (type === 'fragment') { if (!Array.isArray(value)) { throw new FieldError('value is not an array') } return { type: 'fragment', values: value, caseSensitive: caseSensitive || false } } else if (type === 'contains') { return { type: 'contains', value: value + '', caseSensitive: caseSensitive || false } } else { throw new FieldError('Bad SearchQuerySpec type: ' + type) } }
javascript
{ "resource": "" }
q48345
limitSpec
train
function limitSpec(type, limit, orderByColumns) { if (utils.isObject(type)) { return type } if (typeof limit !== 'number') { limit = parseInt(limit, 10) } if (type !== 'default') { throw new FieldError('Currently only DefaultLimitSpec is supported') } else if (isNaN(limit)) { throw new FieldTypeError('limitSpec.limit', 'number') } else if (!Array.isArray(orderByColumns)) { throw new FieldTypeError('limitSpec.columns', 'array') } return { type: type, limit: parseInt(limit, 10), columns: orderByColumns } }
javascript
{ "resource": "" }
q48346
context
train
function context(value) { var out = {} value = value || {} ;['priority', 'timeout'].forEach(function eachIntKey(key) { if (value.hasOwnProperty(key)) { out[key] = parseInt(value[key], 10) if (isNaN(out[key])) { throw new FieldTypeError('context.' + key, 'number') } } }) if (value.hasOwnProperty('queryId')) { out.queryId = value.queryId + '' } ['bySegment', 'populateCache', 'useCache', 'finalize', 'skipEmptyBuckets'].forEach(function eachBoolKey(key) { if (value.hasOwnProperty(key)) { out[key] = !!((value[key]||false).valueOf()) } }) return out }
javascript
{ "resource": "" }
q48347
postAggregation
train
function postAggregation(type, name) { if (utils.isObject(type)) { return type } if (!name) { throw new FieldError('Missing post-aggregation name') } else if (!postAggregations.hasOwnProperty(type)) { throw new FieldError('Unknown post-aggregation type: ' + type) } var args = utils.args(arguments, 2) , postAggregation = { type: type, name: name } postAggregations[type].apply(postAggregation, args) return postAggregation }
javascript
{ "resource": "" }
q48348
toInclude
train
function toInclude(value) { if (Array.isArray(value)) { return { type: 'list', columns: value } } else if (typeof value === 'string' && (value === 'all' || value === 'none')) { return { type: value } } else if (utils.isObject(value)) { return value } else { throw new FieldError('Unknown toInclude value: ' + value) } }
javascript
{ "resource": "" }
q48349
interval
train
function interval(start, end) { if (arguments.length === 1 && typeof start === 'string') { return start } else if (arguments.length === 2) { var interval = utils.args(arguments, 0) return interval.map(function(original) { var arg = utils.date(original) if (!arg) { throw new FieldError('Bad date specified: ' + original) } return JSON.stringify(arg).replace(/"/g, '') }).join('/') } else { throw new FieldError('Bad arguments') } }
javascript
{ "resource": "" }
q48350
having
train
function having(type) { if (utils.isObject(type)) { return type } else if (!specs.hasOwnProperty(type)) { throw new FieldError('Bad having type: ' + type) } var args = utils.args(arguments, 1) , having = { type: type } specs[type].apply(having, args) return having }
javascript
{ "resource": "" }
q48351
createBody
train
function createBody(ast) { if (util.hasType(ast, 'tbody')) return; var open = ast.nodes.shift(); var close = ast.nodes.pop(); var started; var nodes = []; var tbody; var len = ast.nodes.length; var idx = -1; while (++idx < len) { var node = ast.nodes[idx]; if (node.type === 'tr' && !started) { started = true; tbody = { type: 'tbody', nodes: [] }; define(tbody, 'parent', ast); nodes.push(tbody); } if (started) { define(node, 'parent', tbody); tbody.nodes.push(node); } else { nodes.push(node); } } if (tbody) { util.wrapNodes(tbody, Node); } ast.nodes = [open]; ast.nodes = ast.nodes.concat(nodes); ast.nodes.push(close); }
javascript
{ "resource": "" }
q48352
needsSpace
train
function needsSpace(a, b) { var aa = a.slice(-1); var bb = b.charAt(0); if (bb === '.' && /\w/.test(b.charAt(1)) && aa !== '\n') { return true; } if (utils.isEndingChar(bb)) { return false; } if (aa === '`' && !/\s/.test(a.charAt(a.length - 2))) { return true; } if (/[*_]/.test(aa) && /\w/.test(bb)) { return true; } if (utils.isOpeningChar(aa)) { return false; } if (utils.isTightSeparator(aa) || utils.isTightSeparator(bb)) { return false; } if ((utils.isLooseSeparator(aa) || utils.isLooseSeparator(bb)) && !/\s/.test(aa)) { return true; } if (/\s/.test(aa) && utils.isStartingChar(bb)) { return false; } if (utils.isWrappingChar(aa) && utils.isStartingChar(bb)) { return true; } if (utils.isEndingChar(aa) && !/<br>$/.test(a) && !/\s/.test(bb) && !utils.isEndingChar(bb)) { return true; } if ((utils.isStartingChar(bb) || utils.isWrappingChar(bb) || utils.isWrappingChar(aa)) && !utils.isStartingChar(aa)) { return true; } if (utils.isWordChar(aa) && utils.isWordChar(bb)) { return true; } if (/\W/.test(bb) && !utils.isStartingChar(bb) && !utils.isOpeningChar(bb) && !utils.isEndingChar(bb) && !utils.isSpecialChar(bb) && !utils.isSeparator(bb) && !utils.isStartingChar(aa)) { return true; } return false; }
javascript
{ "resource": "" }
q48353
Breakdance
train
function Breakdance(options) { if (typeof options === 'string') { let proto = Object.create(Breakdance.prototype); Breakdance.call(proto); return proto.render.apply(proto, arguments); } if (!(this instanceof Breakdance)) { let proto = Object.create(Breakdance.prototype); Breakdance.call(proto); return proto; } this.define('cache', {}); this.options = extend({}, options); this.plugins = { fns: [], preprocess: [], handlers: {}, before: {}, after: {} }; }
javascript
{ "resource": "" }
q48354
replaceStringInAsset
train
function replaceStringInAsset(asset, source, target) { const sourceRE = new RegExp(source, 'g'); if (typeof asset === 'string') { return asset.replace(sourceRE, target); } // ReplaceSource if ('_source' in asset) { asset._source = replaceStringInAsset(asset._source, source, target); return asset; } // CachedSource if ('_cachedSource' in asset) { asset._cachedSource = asset.source().replace(sourceRE, target); return asset; } // RawSource / SourceMapSource if ('_value' in asset) { asset._value = asset.source().replace(sourceRE, target); return asset; } // ConcatSource if ('children' in asset) { asset.children = asset.children.map(child => replaceStringInAsset(child, source, target)); return asset; } throw new Error( `Unknown asset type (${asset.constructor.name})!. ` + 'Unfortunately this type of asset is not supported yet. ' + 'Please raise an issue and we will look into it asap' ); }
javascript
{ "resource": "" }
q48355
reHashChunk
train
function reHashChunk(chunk, assets, hashFn, nameMap) { const isMainFile = file => file.endsWith('.js') || file.endsWith('.css'); // Update the name of the main files chunk.files.filter(isMainFile).forEach((oldChunkName, index) => { const asset = assets[oldChunkName]; const { fullHash, shortHash: newHash } = hashFn(asset.source()); let newChunkName; if (oldChunkName.includes(chunk.renderedHash)) { // Save the hash map for replacing the secondary files nameMap[chunk.renderedHash] = newHash; newChunkName = oldChunkName.replace(chunk.renderedHash, newHash); // Keep the chunk hashes in sync chunk.hash = fullHash; chunk.renderedHash = newHash; } else { // This is a massive hack: // // The oldHash of the main file is in `chunk.renderedHash`. But some plugins add a // second "main" file to the chunk (for example, `mini-css-extract-plugin` adds a // css file). That other main file has to be rehashed too, but we don't know the // oldHash of the file, so we don't know what string we have to replace by the new // hash. // // However, the hash present in the file name must be one of the hashes of the // modules inside the chunk (modules[].renderedHash). So we try to replace each // module hash with the new hash. const module = Array.from(chunk.modulesIterable).find(m => oldChunkName.includes(m.renderedHash) ); // Can't find a module with this hash... not sure what is going on, just return and // hope for the best. if (!module) return; // Save the hash map for replacing the secondary files nameMap[module.renderedHash] = newHash; newChunkName = oldChunkName.replace(module.renderedHash, newHash); // Keep the module hashes in sync module.hash = fullHash; module.renderedHash = newHash; } // Change file name to include the new hash chunk.files[index] = newChunkName; asset._name = newChunkName; delete assets[oldChunkName]; assets[newChunkName] = asset; }); // Update the content of the rest of the files in the chunk chunk.files .filter(file => !isMainFile(file)) .forEach(file => { Object.keys(nameMap).forEach(old => { const newHash = nameMap[old]; replaceStringInAsset(assets[file], old, newHash); }); }); }
javascript
{ "resource": "" }
q48356
replaceOldHashForNewInChunkFiles
train
function replaceOldHashForNewInChunkFiles(chunk, assets, oldHashToNewHashMap) { chunk.files.forEach(file => { Object.keys(oldHashToNewHashMap).forEach(oldHash => { const newHash = oldHashToNewHashMap[oldHash]; replaceStringInAsset(assets[file], oldHash, newHash); }); }); }
javascript
{ "resource": "" }
q48357
AnimationFrame
train
function AnimationFrame(options) { if (!(this instanceof AnimationFrame)) return new AnimationFrame(options) options || (options = {}) // Its a frame rate. if (typeof options == 'number') options = {frameRate: options} options.useNative != null || (options.useNative = true) this.options = options this.frameRate = options.frameRate || AnimationFrame.FRAME_RATE this._frameLength = 1000 / this.frameRate this._isCustomFrameRate = this.frameRate !== AnimationFrame.FRAME_RATE this._timeoutId = null this._callbacks = {} this._lastTickTime = 0 this._tickCounter = 0 }
javascript
{ "resource": "" }
q48358
Intersector
train
function Intersector () { this.arrowHelper = this.createArrowHelper(); this.raycaster = new THREE.Raycaster(new THREE.Vector3(), new THREE.Vector3(), 0, 0.2); }
javascript
{ "resource": "" }
q48359
HandBody
train
function HandBody (el, handComponent) { this.el = el; this.handComponent = handComponent; this.system = this.el.sceneEl.systems.leap; this.physics = this.el.sceneEl.systems.physics; this.physics.addComponent(this); this.palmBody = /** @type {CANNON.Body} */ null; this.fingerBodies = /** @type {{string: CANNON.Body}} */ {}; }
javascript
{ "resource": "" }
q48360
HandMesh
train
function HandMesh(options) { this.options = options = Object.assign({}, DEFAULTS, options || {}); this.options.jointColor = this.options.jointColor || JOINT_COLORS[numInstances % 2]; this.object3D = new THREE.Object3D(); this.material = !isNaN(options.opacity) ? new THREE.MeshPhongMaterial({ fog: false, transparent: true, opacity: options.opacity }) : new THREE.MeshPhongMaterial({fog: false}); this.createFingers(); this.createArm(); numInstances++; }
javascript
{ "resource": "" }
q48361
exists
train
function exists(el, arr) { for (var i = 0; i < arr.length; i++) { if (arr[i].element.isEqualNode(el)) return arr[i]; } return false; }
javascript
{ "resource": "" }
q48362
argsByRules
train
function argsByRules(argsArray, rules) { var params = rules || ['x', 'y', 'width', 'height'], args = {}; for (var i = 0; i < argsArray.length; i++) { if (typeof(argsArray[i]) === "object") args["style"] = argsArray[i]; else if (params.length) args[params.shift()] = argsArray[i]; } args.style = normalizeStyle(args.style); if ((typeof(args.x) === 'string') && (typeof(args.y) === 'string')) args = smartCoordinates(args); return args; }
javascript
{ "resource": "" }
q48363
smartCoordinates
train
function smartCoordinates(args) { var x = args.x, y = args.y; var paper = Origami.getPaper(), elmWidth = paper.element.width, elmHeight = paper.element.height, radius = (args.r || 0); var width = (args.width || radius), height = (args.height || width); var axis = { x: [ 'right', 'center', 'left' ], y: [ 'top', 'center', 'bottom' ] }; if (axis.x.indexOf(x) !== -1) { if (x === 'right') x = Math.floor(elmWidth - width); else if (x === 'center') if (radius) x = Math.floor(elmWidth / 2) else x = Math.floor((elmWidth / 2) - (width / 2)); else if (x === 'left') x = radius; } else if ((x + '').substr(-1) === '%') { x = (elmWidth * parseInt(x, 10)) / 100; } else { x = 0; } if (axis.y.indexOf(y) !== -1) { if (y === 'top') y = radius; else if (y === 'center') if (radius) y = Math.floor(elmHeight / 2); else y = Math.floor((elmHeight / 2) - (height / 2)); else if (y === 'bottom') y = Math.floor(elmHeight - height); } else if ((y + '').substr(-1) === '%') { y = (elmHeight * parseInt(y, 10)) / 100; } else { y = 0; } args.y = y; args.x = x; return args; }
javascript
{ "resource": "" }
q48364
defineDocumentStyles
train
function defineDocumentStyles() { for (var i = 0; i < document.styleSheets.length; i++) { var mysheet = document.styleSheets[i], myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules; config.documentStyles.push(myrules); } }
javascript
{ "resource": "" }
q48365
styleRuleValueFrom
train
function styleRuleValueFrom(selector, documentStyleRules) { for (var j = 0; j < documentStyleRules.length; j++) { if (documentStyleRules[j].selectorText && documentStyleRules[j].selectorText.toLowerCase() === selector) { return documentStyleRules[j].style; } } }
javascript
{ "resource": "" }
q48366
setterFor
train
function setterFor(objName) { return function(name, value) { if(this["_"+objName+"sUsed"] === true) { this["_"+objName+"s"] = myUtil.extend({}, this["_"+objName+"s"]); this["_"+objName+"sUsed"] = false; } var obj = this["_"+objName+"s"]; if(!(name in obj)) throw new Error("Unknown "+objName+" `"+name+"`"); this.emit(objName+"change", name, value, obj[name]); obj[name] = value; }; }
javascript
{ "resource": "" }
q48367
TermState
train
function TermState(options) { TermState.super_.call(this, { decodeStrings: false }); options = myUtil.extend({ attributes: {}, }, options); this._defaultAttr = myUtil.extend({ fg: null, bg: null, bold: false, underline: false, italic: false, blink: false, inverse: false }, options.attributes); // This is used for copy on write. this._attributesUsed = true; this.rows = ~~options.rows || 24; this.columns = ~~options.columns || 80; this .on("newListener", this._newListener) .on("removeListener", this._removeListener) .on("pipe", this._pipe); // Reset all on first use this.reset(); }
javascript
{ "resource": "" }
q48368
getWidth
train
function getWidth(stringWidth, str) { if (!stringWidth || !stringWidth.toLowerCase) return str.length; switch (stringWidth.toLowerCase()) { case "wcwidth": return wcwidth(str); case "dbcs": return dbcswidth(str); case "length": return str.length; default: return str.length; } }
javascript
{ "resource": "" }
q48369
indexOfWidth
train
function indexOfWidth(stringWidth, str, width) { if (stringWidth === false) return width; for (var i = 0; i <= str.length; i++) { if (getWidth(stringWidth, str.substr(0, i)) > width) return i - 1; } return str.length; }
javascript
{ "resource": "" }
q48370
substrWidth
train
function substrWidth(stringWidth, str, startWidth, width) { var length = width; var start = startWidth; var prefixSpace = 0, suffixSpace; if (stringWidth !== false) { start = indexOfWidth(stringWidth, str, startWidth); if (getWidth(stringWidth, str.substr(0, start)) < startWidth) { start++; prefixSpace = getWidth(stringWidth, str.substr(0, start)) - startWidth; } length = indexOfWidth(stringWidth, str.substr(start), width - prefixSpace); suffixSpace = Math.min(width, getWidth(stringWidth, str.substr(start))) - (prefixSpace + getWidth(stringWidth, str.substr(start, length))); } return repeat(" ", prefixSpace) + str.substr(start, length) + repeat(" ", suffixSpace); }
javascript
{ "resource": "" }
q48371
Terminal
train
function Terminal(options) { Terminal.super_.call(this, { decodeStrings: false }); this.options = myUtil.extend({ columns: 80, rows: 24, attributes: {} }, options || {}); this.rows = ~~this.rows; this.columns = ~~this.columns; this.state = new TermState(this.options); this.oldChunk = null; this.on("pipe", this._pipe); }
javascript
{ "resource": "" }
q48372
ShadowAlphaBroken
train
function ShadowAlphaBroken() { var cv = NewCanvas(3,3), c, i; if(!cv) return false; c = cv.getContext('2d'); c.strokeStyle = '#000'; c.shadowColor = '#fff'; c.shadowBlur = 3; c.globalAlpha = 0; c.strokeRect(2,2,2,2); c.globalAlpha = 1; i = c.getImageData(2,2,1,1); cv = null; return (i.data[0] > 0); }
javascript
{ "resource": "" }
q48373
RoundImage
train
function RoundImage(i, r, iw, ih, s) { var cv, c, r1 = parseFloat(r), l = max(iw, ih); cv = NewCanvas(iw, ih); if(!cv) return null; if(r.indexOf('%') > 0) r1 = l * r1 / 100; else r1 = r1 * s; c = cv.getContext('2d'); c.globalCompositeOperation = 'source-over'; c.fillStyle = '#fff'; if(r1 >= l/2) { r1 = min(iw,ih) / 2; c.beginPath(); c.moveTo(iw/2,ih/2); c.arc(iw/2,ih/2,r1,0,2*Math.PI,false); c.fill(); c.closePath(); } else { r1 = min(iw/2,ih/2,r1); RRect(c, 0, 0, iw, ih, r1, true); c.fill(); } c.globalCompositeOperation = 'source-in'; c.drawImage(i, 0, 0, iw, ih); return cv; }
javascript
{ "resource": "" }
q48374
AddShadowToImage
train
function AddShadowToImage(i, w, h, scale, sc, sb, so) { var sw = abs(so[0]), sh = abs(so[1]), cw = w + (sw > sb ? sw + sb : sb * 2) * scale, ch = h + (sh > sb ? sh + sb : sb * 2) * scale, xo = scale * ((sb || 0) + (so[0] < 0 ? sw : 0)), yo = scale * ((sb || 0) + (so[1] < 0 ? sh : 0)), cv, c; cv = NewCanvas(cw, ch); if(!cv) return null; c = cv.getContext('2d'); sc && (c.shadowColor = sc); sb && (c.shadowBlur = sb * scale); so && (c.shadowOffsetX = so[0] * scale, c.shadowOffsetY = so[1] * scale); c.drawImage(i, xo, yo, w, h); return {image: cv, width: cw / scale, height: ch / scale}; }
javascript
{ "resource": "" }
q48375
train
function() { this.jsonInit({ "message0": "%1", "args0": [ { "type": "field_colour", "name": "COLOUR", "colour": "#ff0000" } ], "output": "Colour", "colour": Blockly.Blocks.colour.HUE, "helpUrl": Blockly.Msg.COLOUR_PICKER_HELPURL }); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; // Colour block is trivial. Use tooltip of parent block if it exists. this.setTooltip(function() { var parent = thisBlock.getParent(); return (parent && parent.tooltip) || Blockly.Msg.COLOUR_PICKER_TOOLTIP; }); }
javascript
{ "resource": "" }
q48376
train
function() { this.jsonInit({ "message0": Blockly.Msg.COLOUR_RANDOM_TITLE, "output": "Colour", "colour": Blockly.Blocks.colour.HUE, "tooltip": Blockly.Msg.COLOUR_RANDOM_TOOLTIP, "helpUrl": Blockly.Msg.COLOUR_RANDOM_HELPURL }); }
javascript
{ "resource": "" }
q48377
train
function() { this.setHelpUrl(Blockly.Msg.COLOUR_RGB_HELPURL); this.setColour(Blockly.Blocks.colour.HUE); this.appendValueInput('RED') .setCheck('Number') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.COLOUR_RGB_TITLE) .appendField(Blockly.Msg.COLOUR_RGB_RED); this.appendValueInput('GREEN') .setCheck('Number') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.COLOUR_RGB_GREEN); this.appendValueInput('BLUE') .setCheck('Number') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.COLOUR_RGB_BLUE); this.setOutput(true, 'Colour'); this.setTooltip(Blockly.Msg.COLOUR_RGB_TOOLTIP); }
javascript
{ "resource": "" }
q48378
train
function() { this.setHelpUrl(Blockly.Msg.COLOUR_BLEND_HELPURL); this.setColour(Blockly.Blocks.colour.HUE); this.appendValueInput('COLOUR1') .setCheck('Colour') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.COLOUR_BLEND_TITLE) .appendField(Blockly.Msg.COLOUR_BLEND_COLOUR1); this.appendValueInput('COLOUR2') .setCheck('Colour') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.COLOUR_BLEND_COLOUR2); this.appendValueInput('RATIO') .setCheck('Number') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.COLOUR_BLEND_RATIO); this.setOutput(true, 'Colour'); this.setTooltip(Blockly.Msg.COLOUR_BLEND_TOOLTIP); }
javascript
{ "resource": "" }
q48379
train
function() { this.appendDummyInput() .appendField('dropdown') .appendField(new Blockly.FieldTextInput('NAME'), 'FIELDNAME'); this.optionCount_ = 3; this.updateShape_(); this.setPreviousStatement(true, 'Field'); this.setNextStatement(true, 'Field'); this.setMutator(new Blockly.Mutator(['field_dropdown_option'])); this.setColour(160); this.setTooltip('Dropdown menu with a list of options.'); this.setHelpUrl('https://www.youtube.com/watch?v=s2_xaEvcVI0#t=386'); }
javascript
{ "resource": "" }
q48380
train
function() { this.setColour(160); this.appendDummyInput() .appendField('option'); this.setPreviousStatement(true); this.setNextStatement(true); this.setTooltip('Add a new option to the dropdown menu.'); this.setHelpUrl('https://www.youtube.com/watch?v=s2_xaEvcVI0#t=386'); this.contextMenu = false; }
javascript
{ "resource": "" }
q48381
train
function() { this.setColour(160); this.appendDummyInput() .appendField('variable') .appendField(new Blockly.FieldTextInput('item'), 'TEXT') .appendField(',') .appendField(new Blockly.FieldTextInput('NAME'), 'FIELDNAME'); this.setPreviousStatement(true, 'Field'); this.setNextStatement(true, 'Field'); this.setTooltip('Dropdown menu for variable names.'); this.setHelpUrl('https://www.youtube.com/watch?v=s2_xaEvcVI0#t=510'); }
javascript
{ "resource": "" }
q48382
train
function() { this.typeCount_ = 2; this.updateShape_(); this.setOutput(true, 'Type'); this.setMutator(new Blockly.Mutator(['type_group_item'])); this.setColour(230); this.setTooltip('Allows more than one type to be accepted.'); this.setHelpUrl('https://www.youtube.com/watch?v=s2_xaEvcVI0#t=677'); }
javascript
{ "resource": "" }
q48383
train
function() { this.appendDummyInput() .appendField('hue:') .appendField(new Blockly.FieldAngle('0', this.validator), 'HUE'); this.setOutput(true, 'Colour'); this.setTooltip('Paint the block with this colour.'); this.setHelpUrl('https://www.youtube.com/watch?v=s2_xaEvcVI0#t=55'); }
javascript
{ "resource": "" }
q48384
train
function() { this.setHelpUrl(Blockly.Msg.VARIABLES_GET_HELPURL); this.setColour(Blockly.Blocks.variables.HUE); this.appendDummyInput() .appendField(new Blockly.FieldVariable( Blockly.Msg.VARIABLES_DEFAULT_NAME), 'VAR'); this.setOutput(true); this.setTooltip(Blockly.Msg.VARIABLES_GET_TOOLTIP); this.contextMenuMsg_ = Blockly.Msg.VARIABLES_GET_CREATE_SET; }
javascript
{ "resource": "" }
q48385
train
function() { this.jsonInit({ "message0": Blockly.Msg.VARIABLES_SET, "args0": [ { "type": "field_variable", "name": "VAR", "variable": Blockly.Msg.VARIABLES_DEFAULT_NAME }, { "type": "input_value", "name": "VALUE" } ], "previousStatement": null, "nextStatement": null, "colour": Blockly.Blocks.variables.HUE, "tooltip": Blockly.Msg.VARIABLES_SET_TOOLTIP, "helpUrl": Blockly.Msg.VARIABLES_SET_HELPURL }); this.contextMenuMsg_ = Blockly.Msg.VARIABLES_SET_CREATE_GET; }
javascript
{ "resource": "" }
q48386
train
function() { this.jsonInit({ "message0": Blockly.Msg.CONTROLS_FOR_TITLE, "args0": [ { "type": "field_variable", "name": "VAR", "variable": null }, { "type": "input_value", "name": "FROM", "check": "Number", "align": "RIGHT" }, { "type": "input_value", "name": "TO", "check": "Number", "align": "RIGHT" }, { "type": "input_value", "name": "BY", "check": "Number", "align": "RIGHT" } ], "inputsInline": true, "previousStatement": null, "nextStatement": null, "colour": Blockly.Blocks.loops.HUE, "helpUrl": Blockly.Msg.CONTROLS_FOR_HELPURL }); this.appendStatementInput('DO') .appendField(Blockly.Msg.CONTROLS_FOR_INPUT_DO); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; this.setTooltip(function() { return Blockly.Msg.CONTROLS_FOR_TOOLTIP.replace('%1', thisBlock.getFieldValue('VAR')); }); }
javascript
{ "resource": "" }
q48387
train
function() { this.jsonInit({ "message0": Blockly.Msg.CONTROLS_FOREACH_TITLE, "args0": [ { "type": "field_variable", "name": "VAR", "variable": null }, { "type": "input_value", "name": "LIST", "check": "Array" } ], "previousStatement": null, "nextStatement": null, "colour": Blockly.Blocks.loops.HUE, "helpUrl": Blockly.Msg.CONTROLS_FOREACH_HELPURL }); this.appendStatementInput('DO') .appendField(Blockly.Msg.CONTROLS_FOREACH_INPUT_DO); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; this.setTooltip(function() { return Blockly.Msg.CONTROLS_FOREACH_TOOLTIP.replace('%1', thisBlock.getFieldValue('VAR')); }); }
javascript
{ "resource": "" }
q48388
updateBlocks
train
function updateBlocks(blocks) { for (var i = 0, block; block = blocks[i]; i++) { block.customUpdate && block.customUpdate(); } }
javascript
{ "resource": "" }
q48389
train
function(hasStatements) { if (this.hasStatements_ === hasStatements) { return; } if (hasStatements) { this.appendStatementInput('STACK') .appendField(Blockly.Msg.PROCEDURES_DEFNORETURN_DO); if (this.getInput('RETURN')) { this.moveInputBefore('STACK', 'RETURN'); } } else { this.removeInput('STACK', true); } this.hasStatements_ = hasStatements; }
javascript
{ "resource": "" }
q48390
train
function() { // Check for duplicated arguments. var badArg = false; var hash = {}; for (var i = 0; i < this.arguments_.length; i++) { if (hash['arg_' + this.arguments_[i].toLowerCase()]) { badArg = true; break; } hash['arg_' + this.arguments_[i].toLowerCase()] = true; } if (badArg) { this.setWarningText(Blockly.Msg.PROCEDURES_DEF_DUPLICATE_WARNING); } else { this.setWarningText(null); } // Merge the arguments into a human-readable list. var paramString = ''; if (this.arguments_.length) { paramString = Blockly.Msg.PROCEDURES_BEFORE_PARAMS + ' ' + this.arguments_.join(', '); } // The params field is deterministic based on the mutation, // no need to fire a change event. Blockly.Events.disable(); this.setFieldValue(paramString, 'PARAMS'); Blockly.Events.enable(); }
javascript
{ "resource": "" }
q48391
train
function(opt_paramIds) { var container = document.createElement('mutation'); if (opt_paramIds) { container.setAttribute('name', this.getFieldValue('NAME')); } for (var i = 0; i < this.arguments_.length; i++) { var parameter = document.createElement('arg'); parameter.setAttribute('name', this.arguments_[i]); if (opt_paramIds && this.paramIds_) { parameter.setAttribute('paramId', this.paramIds_[i]); } container.appendChild(parameter); } // Save whether the statement input is visible. if (!this.hasStatements_) { container.setAttribute('statements', 'false'); } return container; }
javascript
{ "resource": "" }
q48392
train
function(xmlElement) { this.arguments_ = []; for (var i = 0, childNode; childNode = xmlElement.childNodes[i]; i++) { if (childNode.nodeName.toLowerCase() == 'arg') { this.arguments_.push(childNode.getAttribute('name')); } } this.updateParams_(); Blockly.Procedures.mutateCallers(this); // Show or hide the statement input. this.setStatements_(xmlElement.getAttribute('statements') !== 'false'); }
javascript
{ "resource": "" }
q48393
train
function(options) { // Add option to create caller. var option = {enabled: true}; var name = this.getFieldValue('NAME'); option.text = Blockly.Msg.PROCEDURES_CREATE_DO.replace('%1', name); var xmlMutation = goog.dom.createDom('mutation'); xmlMutation.setAttribute('name', name); for (var i = 0; i < this.arguments_.length; i++) { var xmlArg = goog.dom.createDom('arg'); xmlArg.setAttribute('name', this.arguments_[i]); xmlMutation.appendChild(xmlArg); } var xmlBlock = goog.dom.createDom('block', null, xmlMutation); xmlBlock.setAttribute('type', this.callType_); option.callback = Blockly.ContextMenu.callbackFactory(this, xmlBlock); options.push(option); // Add options to create getters for each parameter. if (!this.isCollapsed()) { for (var i = 0; i < this.arguments_.length; i++) { var option = {enabled: true}; var name = this.arguments_[i]; option.text = Blockly.Msg.VARIABLES_SET_CREATE_GET.replace('%1', name); var xmlField = goog.dom.createDom('field', null, name); xmlField.setAttribute('name', 'VAR'); var xmlBlock = goog.dom.createDom('block', null, xmlField); xmlBlock.setAttribute('type', 'variables_get'); option.callback = Blockly.ContextMenu.callbackFactory(this, xmlBlock); options.push(option); } } }
javascript
{ "resource": "" }
q48394
train
function() { var nameField = new Blockly.FieldTextInput( Blockly.Msg.PROCEDURES_DEFRETURN_PROCEDURE, Blockly.Procedures.rename); nameField.setSpellcheck(false); this.appendDummyInput() .appendField(Blockly.Msg.PROCEDURES_DEFRETURN_TITLE) .appendField(nameField, 'NAME') .appendField('', 'PARAMS'); this.appendValueInput('RETURN') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.PROCEDURES_DEFRETURN_RETURN); this.setMutator(new Blockly.Mutator(['procedures_mutatorarg'])); if (Blockly.Msg.PROCEDURES_DEFRETURN_COMMENT) { this.setCommentText(Blockly.Msg.PROCEDURES_DEFRETURN_COMMENT); } this.setColour(Blockly.Blocks.procedures.HUE); this.setTooltip(Blockly.Msg.PROCEDURES_DEFRETURN_TOOLTIP); this.setHelpUrl(Blockly.Msg.PROCEDURES_DEFRETURN_HELPURL); this.arguments_ = []; this.setStatements_(true); this.statementConnection_ = null; }
javascript
{ "resource": "" }
q48395
train
function() { this.appendDummyInput() .appendField(Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TITLE); this.appendStatementInput('STACK'); this.appendDummyInput('STATEMENT_INPUT') .appendField(Blockly.Msg.PROCEDURES_ALLOW_STATEMENTS) .appendField(new Blockly.FieldCheckbox('TRUE'), 'STATEMENTS'); this.setColour(Blockly.Blocks.procedures.HUE); this.setTooltip(Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP); this.contextMenu = false; }
javascript
{ "resource": "" }
q48396
train
function(oldName, newName) { if (Blockly.Names.equals(oldName, this.getProcedureCall())) { this.setFieldValue(newName, 'NAME'); this.setTooltip( (this.outputConnection ? Blockly.Msg.PROCEDURES_CALLRETURN_TOOLTIP : Blockly.Msg.PROCEDURES_CALLNORETURN_TOOLTIP) .replace('%1', newName)); } }
javascript
{ "resource": "" }
q48397
train
function(paramNames, paramIds) { // Data structures: // this.arguments = ['x', 'y'] // Existing param names. // this.quarkConnections_ {piua: null, f8b_: Blockly.Connection} // Look-up of paramIds to connections plugged into the call block. // this.quarkIds_ = ['piua', 'f8b_'] // Existing param IDs. // Note that quarkConnections_ may include IDs that no longer exist, but // which might reappear if a param is reattached in the mutator. var defBlock = Blockly.Procedures.getDefinition(this.getProcedureCall(), this.workspace); var mutatorOpen = defBlock && defBlock.mutator && defBlock.mutator.isVisible(); if (!mutatorOpen) { this.quarkConnections_ = {}; this.quarkIds_ = null; } if (!paramIds) { // Reset the quarks (a mutator is about to open). return; } if (goog.array.equals(this.arguments_, paramNames)) { // No change. this.quarkIds_ = paramIds; return; } if (paramIds.length != paramNames.length) { throw 'Error: paramNames and paramIds must be the same length.'; } this.setCollapsed(false); if (!this.quarkIds_) { // Initialize tracking for this block. this.quarkConnections_ = {}; if (paramNames.join('\n') == this.arguments_.join('\n')) { // No change to the parameters, allow quarkConnections_ to be // populated with the existing connections. this.quarkIds_ = paramIds; } else { this.quarkIds_ = []; } } // Switch off rendering while the block is rebuilt. var savedRendered = this.rendered; this.rendered = false; // Update the quarkConnections_ with existing connections. for (var i = 0; i < this.arguments_.length; i++) { var input = this.getInput('ARG' + i); if (input) { var connection = input.connection.targetConnection; this.quarkConnections_[this.quarkIds_[i]] = connection; if (mutatorOpen && connection && paramIds.indexOf(this.quarkIds_[i]) == -1) { // This connection should no longer be attached to this block. connection.disconnect(); connection.getSourceBlock().bumpNeighbours_(); } } } // Rebuild the block's arguments. this.arguments_ = [].concat(paramNames); this.updateShape_(); this.quarkIds_ = paramIds; // Reconnect any child blocks. if (this.quarkIds_) { for (var i = 0; i < this.arguments_.length; i++) { var quarkId = this.quarkIds_[i]; if (quarkId in this.quarkConnections_) { var connection = this.quarkConnections_[quarkId]; if (!Blockly.Mutator.reconnect(connection, this, 'ARG' + i)) { // Block no longer exists or has been attached elsewhere. delete this.quarkConnections_[quarkId]; } } } } // Restore rendering and show the changes. this.rendered = savedRendered; if (this.rendered) { this.render(); } }
javascript
{ "resource": "" }
q48398
train
function() { for (var i = 0; i < this.arguments_.length; i++) { var field = this.getField('ARGNAME' + i); if (field) { // Ensure argument name is up to date. // The argument name field is deterministic based on the mutation, // no need to fire a change event. Blockly.Events.disable(); field.setValue(this.arguments_[i]); Blockly.Events.enable(); } else { // Add new input. field = new Blockly.FieldLabel(this.arguments_[i]); var input = this.appendValueInput('ARG' + i) .setAlign(Blockly.ALIGN_RIGHT) .appendField(field, 'ARGNAME' + i); input.init(); } } // Remove deleted inputs. while (this.getInput('ARG' + i)) { this.removeInput('ARG' + i); i++; } // Add 'with:' if there are parameters, remove otherwise. var topRow = this.getInput('TOPROW'); if (topRow) { if (this.arguments_.length) { if (!this.getField('WITH')) { topRow.appendField(Blockly.Msg.PROCEDURES_CALL_BEFORE_PARAMS, 'WITH'); topRow.init(); } } else { if (this.getField('WITH')) { topRow.removeField('WITH'); } } } }
javascript
{ "resource": "" }
q48399
train
function(options) { var option = {enabled: true}; option.text = Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF; var name = this.getProcedureCall(); var workspace = this.workspace; option.callback = function() { var def = Blockly.Procedures.getDefinition(name, workspace); def && def.select(); }; options.push(option); }
javascript
{ "resource": "" }