query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
Function: deleteRemote remove remote data, then clear local diff. Fires: error | function deleteRemote(path, local, remote) {
logger.info('DELETE', path, 'LOCAL -> REMOTE');
return remoteAdapter.
remove(path).
then(function() {
store.clearDiff(path);
});
} | [
"function deleteRemote(path, local, remote) {\n logger.info('DELETE', path, 'LOCAL -> REMOTE');\n wireClient.remove(\n path,\n makeErrorCatcher(path, util.curry(store.clearDiff, path, undefined))\n );\n }",
"async function deleteRemote ({\n core = 'default',\n dir,\n gitdir = join(dir, '.git'),\n fs: _fs = cores.get(core).get('fs'),\n remote\n}) {\n try {\n const fs = new FileSystem(_fs);\n if (remote === undefined) {\n throw new GitError(E.MissingRequiredParameterError, {\n function: 'deleteRemote',\n parameter: 'remote'\n })\n }\n const config = await GitConfigManager.get({ fs, gitdir });\n await config.deleteSection('remote', remote);\n await GitConfigManager.save({ fs, gitdir, config });\n } catch (err) {\n err.caller = 'git.deleteRemote';\n throw err\n }\n}",
"function deleteLocal(path, local, remote) {\n logger.info('DELETE', path, 'REMOTE -> LOCAL');\n var oldValue = store.getNodeData(path);\n store.removeNode(path, remote.timestamp);\n }",
"function deleteLocal(path, local, remote) {\n logger.info('DELETE', path, 'REMOTE -> LOCAL');\n return store.removeNode(path, remote.timestamp);\n }",
"function remoteLeaving(id) {\n if (!remotes) return;\n if (remotes[id].dom) remotes[id].dom.parentNode.removeChild(remotes[id].dom);\n remoteCount -= delete remotes[id];\n}",
"function removeRemote(url) {\n console.log('Deleting remote site:', url);\n var xhr = new XMLHttpRequest();\n xhr.open('POST', 'https://sl9n39xipj.execute-api.us-east-1.amazonaws.com/alpha/deleteRemote', true);\n xhr.send(JSON.stringify({apiURI: url}));\n\n xhr.onloadend = function() { \n if(xhr.readyState == XMLHttpRequest.DONE) {\n console.log('Response:' + xhr.response);\n getRemotes();\n }\n };\n}",
"function _remoteEditClear() {\n _remoteEditStop();\n\n _clearTarget();\n\n shouldrefresh = false;\n clearHtml('editNodeIdent');\n var errhold = $('remoteEditError');\n clearHtml(errhold);\n errhold.hide();\n}",
"function vms_delete() {\n var post_data = elements.vms_form.serialize() + '&action=delete';\n\n _.each(server_list, function(data, hostname, i) {\n post_data += '&hostname=' + hostname;\n });\n\n ajax('POST', elements.vms_form.data('source'), ATIMEOUT, function(data, textStatus, xhr) {\n if (xhr.status == 278) {\n ajax_move(null, xhr.getResponseHeader('Location'));\n }\n }, post_data);\n\n self.reset_server_list();\n }",
"function remove(path, remote, callback) {\n\n if (repository(path)) {\n\n var command = 'git remote rm ' + remote;\n var stdin = \"\"; // must be an empty String or buffer;\n var result = SystemWorker.exec(BIC + ' \"' + command + '\"', stdin, path);\n\n if (result != null) {\n\n var stdout = result.output.toString();\n var stderror = result.error.toString();\n var stdStatus = result.exitStatus;\n\n // if error, pass error object into callback\n if (stderror != \"\") {\n\n if (callback) {\n callback.call(this, {\n error: stderror\n });\n }\n // if successful pass the result objet\n }\n else if (stdout) {\n\n if (callback) {\n callback.call(this, {\n message: 'Remote \"' + remote + '\" removed!'\n });\n }\n }\n\n }\n\n\n }\n else {\n callback.call(this, {\n error: 'Invalid repository'\n });\n }\n }",
"removeReleaseTask(done) {\r\n this.logger.subhead('Remove releases on remote');\r\n\r\n const command = \"rm -rf \" + this.options.deployPath;\r\n this.remote.exec(command, () => {\r\n this.logger.ok('Done');\r\n done();\r\n });\r\n }",
"function resetRemote (from, cloneURL, treeish, cachedRemote, cb) {\n\t log.info('resetRemote', 'resetting', cachedRemote, 'for', from)\n\t rm(cachedRemote, function (er) {\n\t if (er) return cb(er)\n\t mirrorRemote(from, cloneURL, treeish, cachedRemote, false, cb)\n\t })\n\t}",
"function revokeRemote() {\n\tsocket.emit(\"dismissRemoteClient\", cubeLocation, function() {\n\t\twriteLog(\"Successfully unregistered. You are not remote client anymore\");\n\t\tinitState = \"noRemoteConnection\";\n\t\tclearTimeout(myDisconnectTimer);\n\t\t$(\"#initElements\").show(0);\n\t\t$(\"#movieControls\").hide(0);\n\t\t$(\"#feedback\").html(\"Bevor du den Trailer am Fernseher ansehen kannst, tippe hier, um eine Verbindung herzustellen.\");\n\t});\n}",
"remoteDelete(char, peerId) {\t \r\n\t console.log(\"Remote delete\"+ char.value);\r\n const index = this.findIndexByPosition(char);\r\n this.struct.splice(index, 1);\r\n this.deleteChar(index);\r\n return this.text;\r\n }",
"destroyRemoteSource(id) {\n if (this.remoteStreams.has(id)) {\n this.connections.cutoffConnection(id);\n this.connections.removeConnection(id);\n this.remoteStreams.delete(id);\n }\n }",
"function testSyncCustomWallpaperDelete() {\n var localOriginalPath = Constants.WallpaperDirNameEnum.ORIGINAL + '/' +\n 'deletewallpapername';\n var localThumbnailPath = Constants.WallpaperDirNameEnum.THUMBNAIL + '/' +\n 'deletewallpapername';\n var originalFE = mockLocalFS.mockTestFile(localOriginalPath);\n var thumbnailFE = mockLocalFS.mockTestFile(localThumbnailPath);\n var syncFSChanges = {};\n syncFSChanges.status = 'synced';\n syncFSChanges.direction = 'remote_to_local';\n syncFSChanges.action = 'deleted';\n syncFSChanges.fileEntry = new FileEntry('deletewallpapername');\n var mockRemoveOriginal = mockController.createFunctionMock(originalFE,\n 'remove');\n mockRemoveOriginal.addExpectation(function() {}, null);\n var mockRemoveThumbnail = mockController.createFunctionMock(thumbnailFE,\n 'remove');\n mockRemoveThumbnail.addExpectation(function() {}, null);\n chrome.syncFileSystem.onFileStatusChanged.dispatch(syncFSChanges);\n}",
"async _remoteDelete(hostBufferProxyId, charObj) {\n const logObj = {\n hostBufferProxyId: hostBufferProxyId,\n charObj: charObj,\n value: charObj.getValue(),\n };\n log.debug('Doing remote delete: ', logObj);\n\n // Get text-buffer-proxy and CRDT\n let bufferProxy;\n let crdt;\n const guestBufferProxyId = this.bufferProxyIdMap.get(hostBufferProxyId);\n\n if (!guestBufferProxyId) {\n [bufferProxy, crdt] =\n await this._createBufferProxyAndCRDT(hostBufferProxyId);\n } else {\n [bufferProxy, crdt] =\n await this._getTextBufferProxyAndCRDT(guestBufferProxyId);\n }\n\n // Delete from CRDT and compute positions\n const startPos = await crdt.handleRemoteDelete(charObj);\n let line = startPos.lineIndex;\n let endPos;\n if (line < crdt.length &&\n startPos.charIndex < crdt.lineArray[line].length) {\n endPos = {lineIndex: line, charIndex: startPos.charIndex + 1};\n } else {\n endPos = {lineIndex: line + 1, charIndex: 0};\n }\n const deletionRange = convertPositionsToRange(startPos, endPos);\n\n log.debug('CRDT line array: ', {lineArray: crdt.getLineArray()});\n\n // Delete from text-buffer-proxy\n await bufferProxy.deleteFromTextBuffer(deletionRange);\n }",
"function deleteLocal(model, opt) {\n\tif (model instanceof Backbone.Collection) {\n\t\t// Call \"delete\" on every element if this is a Collection\n\t\treturn Q.all(model.map(function(mod) {\n\t\t\treturn Q.promise(function(resolve, reject) {\n\t\t\t\t// TODO try/catch?\n\t\t\t\tremoveInfo(mod);\n\t\t\t\t_.each(getSyncs(mod), removeSyncRow);\n\n\t\t\t\tgetLocalAdapter(model).sync('delete', mod, _.extend({}, opt, {\n\t\t\t\t\tsuccess: resolve,\n\t\t\t\t\terror: reject\n\t\t\t\t}));\n\t\t\t});\n\t\t}));\n\t} else {\n\t\t// Simply call \"delete\" on the Model otherwise\n\t\treturn Q.promise(function(resolve, reject) {\n\t\t\t// TODO try/catch?\n\t\t\tremoveInfo(model);\n\t\t\t_.each(getSyncs(model), removeSyncRow);\n\n\t\t\tgetLocalAdapter(model).sync('delete', model, _.extend({}, opt, {\n\t\t\t\tsuccess: resolve,\n\t\t\t\terror: reject\n\t\t\t}));\n\t\t});\n\t}\n}",
"function clearServerData( callback ){\n\n var sendData = {\n action: \"remove_all\"\n };\n\n //dump( \"Start remove all\\n\" );\n\n makeRequest(sendData, function( error ){\n //dump( \"End remove all(\"+error+\")\\n\" );\n callback( error );\n });\n\n }",
"_deleteTicker(remote_id) {\n delete this.tickerMap.delete(remote_id);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
newCommandName can be any camelCased command name | setCommandName(newCommandName) {
this.test.commandName = newCommandName
} | [
"changeCommandName(name) {}",
"changeCommandName(name) {\n database.updateCommand(this.state.command.id, {\n name: name,\n });\n }",
"function newCommandHelpFucntion(){\n console.log('\"new\" command is used to create a new instance of client/server. ');\n console.log('The syntax of the command is the follows:');\n console.log('');\n console.log('new [client/server] -name name')\n console.log('');\n}",
"addCommand(name, command) {\n\t\tconst comm = new command(this);\n\t\tcomm.name = name;\n\t\tthis.commands.push({\n\t\t\tname: name,\n\t\t\tcommand: comm\n\t\t});\n\t}",
"getCommandName() {\n return this.commandName;\n }",
"function addCommand(name, command) {\n codemirror_1.default.commands[name] = command;\n }",
"function commandConstructor(name) {\r\n\r\n var newCommand = Object.create(command);\r\n newCommand.name = name;\r\n\r\n return newCommand;\r\n}",
"AddNewCommand(NewCommand)\n {\n this.Commands.push(NewCommand); \n }",
"function addCommand(name, command) {\n CodeMirror.commands[name] = command;\n }",
"get commandName() {}",
"getFullCommandName() {\n return `${this.getPrefix()}${this.getCommandName()}`\n }",
"function checkNewCommandName(element) {\n var unique = true;\n var name = element.value;\n var foundError = false;\n var feedback = $(\"#commandNameFeedback\");\n\n if (name.indexOf(\" \") >= 0 || name === \"\") {\n feedback.text(\"Der Name (\" + name + \") darf nicht leer sein und keine Leerzeichen enthalten!\");\n if (!$(element).hasClass(\"dangerInput\")) {\n $(element).addClass(\"dangerInput\");\n }\n foundError = true;\n\n if (!$(element).hasClass(\"newCommandError\")) {\n $(element).addClass(\"newCommandError\");\n }\n\n setCommitButton(true);\n return;\n }\n\n for (var i = 0; i < Object.keys(botCommandObject).length; i++) {\n if (Object.keys(botCommandObject)[i] === name) {\n unique = false;\n foundError = true;\n }\n }\n\n if (unique) {\n feedback.text(\"\");\n if ($(element).hasClass(\"dangerInput\")) {\n $(element).removeClass(\"dangerInput\");\n }\n } else {\n feedback.text(\"Der command '\" + name + \"' exsistiert bereits!\");\n if (!$(element).hasClass(\"dangerInput\")) {\n $(element).addClass(\"dangerInput\");\n }\n }\n\n if (foundError) {\n if (!$(element).hasClass(\"newCommandError\")) {\n $(element).addClass(\"newCommandError\");\n }\n } else {\n if ($(element).hasClass(\"newCommandError\")) {\n $(element).removeClass(\"newCommandError\");\n }\n }\n\n setCommitButton(true);\n}",
"_parseCommand(name) {\n this.commandNamesList = name.split(',').map(commandName => commandName.trim());\n\n let lastCommandName = this.commandNamesList.pop();\n\n let [commandName, ...expectedArguments] = lastCommandName.split(' ');\n\n this.commandNamesList.push(commandName);\n\n this.parseExpectedArguments(expectedArguments);\n\n this.name = commandName;\n }",
"function addCommand(newCommand){\n newCommand.stop = function(){\n gotoState.call(this, stateIds.exit, 'Ok, stoping now.');\n }\n newCommand.error = function(){\n gotoState.call(this, active.id, 'I didn’t hear you well');\n }\n stateCommands[newCommand.id] = newCommand;\n}",
"function addAction(commandName, command) {\n var CodeMirror = window.CodeMirror;\n\n if (!CodeMirror.commands[commandName]) {\n CodeMirror.commands[commandName] = command;\n }\n }",
"function commandName (command) {\n const name = commandNames[command]\n return name == null ? command : `${name} (${command})`\n}",
"updateParameterName(commandId, oldName, newName) {\n this.db\n .get(\"commands\")\n .getById(commandId)\n .get(\"parameters\")\n .find({ name: oldName })\n .assign({ name: newName })\n .write();\n builder.build();\n return this.getCommandForId(commandId);\n }",
"function commitNewCommandButton() {\n var commandName = $('#newCommandName').val();\n\n if (commandName === \"\") {\n $(\"#commandNameFeedback\").text(\"Der command muss einen Namen haben!\");\n return;\n }\n\n if (commandHasChanges()) {\n //changes -> öffne modal\n $('#resetButtonChanges').attr(\"onclick\", \"closeUCAndNCModals()\");\n $('#discardChangesButton').attr(\"onclick\", \"commitNewCommand()\");\n $('#uncommitedChangesModal').modal('show');\n } else {\n commitNewCommand();\n }\n}",
"buildCommand(name) {\n return new CommandBuilder({\n listener: description => {\n if (this.#commands_.has(description.commandName))\n throw new Error(`A command named \"/${name}\" has already been registered.`);\n\n this.#commands_.set(description.commandName, description);\n },\n\n name: name,\n prefix: '/',\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates the `MotionInput` module instance. | function MotionInput() {
_classCallCheck(this, MotionInput);
/**
* Pool of all available modules.
*
* @this MotionInput
* @type {object}
* @default {}
*/
this.modules = {};
} | [
"function MotionInput() {\n\t _classCallCheck(this, MotionInput);\n\t /**\n\t * Pool of all available modules.\n\t *\n\t * @this MotionInput\n\t * @type {object}\n\t * @default {}\n\t */\n\n\n\t this.modules = {};\n\t }",
"constructor() {\n\n /**\n * Pool of all available modules.\n *\n * @this MotionInput\n * @type {object}\n * @default {}\n */\n this.modules = {};\n }",
"function DeviceMotionModule() {\n _classCallCheck(this, DeviceMotionModule);\n\n /**\n * Raw values coming from the `devicemotion` event sent by this module.\n *\n * @this DeviceMotionModule\n * @type {number[]}\n * @default [null, null, null, null, null, null, null, null, null]\n */\n var _this = _possibleConstructorReturn(this, (DeviceMotionModule.__proto__ || Object.getPrototypeOf(DeviceMotionModule)).call(this, 'devicemotion'));\n\n _this.event = [null, null, null, null, null, null, null, null, null];\n\n /**\n * The `AccelerationIncludingGravity` module.\n * Provides unified values of the acceleration including gravity.\n *\n * @this DeviceMotionModule\n * @type {DOMEventSubmodule}\n */\n _this.accelerationIncludingGravity = new _DOMEventSubmodule2.default(_this, 'accelerationIncludingGravity');\n\n /**\n * The `Acceleration` submodule.\n * Provides unified values of the acceleration.\n * Estimates the acceleration values from `accelerationIncludingGravity`\n * raw values if the acceleration raw values are not available on the\n * device.\n *\n * @this DeviceMotionModule\n * @type {DOMEventSubmodule}\n */\n _this.acceleration = new _DOMEventSubmodule2.default(_this, 'acceleration');\n\n /**\n * The `RotationRate` submodule.\n * Provides unified values of the rotation rate.\n * (coming soon, waiting for a bug on Chrome to be resolved)\n * Estimates the rotation rate values from `orientation` values if\n * the rotation rate raw values are not available on the device.\n *\n * @this DeviceMotionModule\n * @type {DOMEventSubmodule}\n */\n _this.rotationRate = new _DOMEventSubmodule2.default(_this, 'rotationRate');\n\n /**\n * Required submodules / events.\n *\n * @this DeviceMotionModule\n * @type {object}\n * @property {bool} accelerationIncludingGravity - Indicates whether the `accelerationIncludingGravity` unified values are required or not (defaults to `false`).\n * @property {bool} acceleration - Indicates whether the `acceleration` unified values are required or not (defaults to `false`).\n * @property {bool} rotationRate - Indicates whether the `rotationRate` unified values are required or not (defaults to `false`).\n */\n _this.required = {\n accelerationIncludingGravity: false,\n acceleration: false,\n rotationRate: false\n };\n\n /**\n * Resolve function of the module's promise.\n *\n * @this DeviceMotionModule\n * @type {function}\n * @default null\n * @see DeviceMotionModule#init\n */\n _this._promiseResolve = null;\n\n /**\n * Unifying factor of the motion data values (`1` on Android, `-1` on iOS).\n *\n * @this DeviceMotionModule\n * @type {number}\n */\n _this._unifyMotionData = _platform2.default.os.family === 'iOS' ? -1 : 1;\n\n /**\n * Unifying factor of the period (`1` on Android, `1` on iOS). in sec\n * @todo - unify with e.interval specification (in ms) ?\n *\n * @this DeviceMotionModule\n * @type {number}\n */\n _this._unifyPeriod = _platform2.default.os.family === 'Android' ? 0.001 : 1;\n\n /**\n * Acceleration calculated from the `accelerationIncludingGravity` raw values.\n *\n * @this DeviceMotionModule\n * @type {number[]}\n * @default [0, 0, 0]\n */\n _this._calculatedAcceleration = [0, 0, 0];\n\n /**\n * Time constant (half-life) of the high-pass filter used to smooth the acceleration values calculated from the acceleration including gravity raw values (in seconds).\n *\n * @this DeviceMotionModule\n * @type {number}\n * @default 0.1\n * @constant\n */\n _this._calculatedAccelerationTimeConstant = 0.1;\n\n /**\n * Latest `accelerationIncludingGravity` raw value, used in the high-pass filter to calculate the acceleration (if the `acceleration` values are not provided by `'devicemotion'`).\n *\n * @this DeviceMotionModule\n * @type {number[]}\n * @default [0, 0, 0]\n */\n _this._lastAccelerationIncludingGravity = [0, 0, 0];\n\n /**\n * Rotation rate calculated from the orientation values.\n *\n * @this DeviceMotionModule\n * @type {number[]}\n * @default [0, 0, 0]\n */\n _this._calculatedRotationRate = [0, 0, 0];\n\n /**\n * Latest orientation value, used to calculate the rotation rate (if the `rotationRate` values are not provided by `'devicemotion'`).\n *\n * @this DeviceMotionModule\n * @type {number[]}\n * @default [0, 0, 0]\n */\n _this._lastOrientation = [0, 0, 0];\n\n /**\n * Latest orientation timestamps, used to calculate the rotation rate (if the `rotationRate` values are not provided by `'devicemotion'`).\n *\n * @this DeviceMotionModule\n * @type {number[]}\n * @default [0, 0, 0]\n */\n _this._lastOrientationTimestamp = null;\n\n _this._processFunction = null;\n _this._process = _this._process.bind(_this);\n _this._devicemotionCheck = _this._devicemotionCheck.bind(_this);\n _this._devicemotionListener = _this._devicemotionListener.bind(_this);\n\n _this._checkCounter = 0;\n return _this;\n }",
"function DeviceMotionModule() {\n _classCallCheck(this, DeviceMotionModule);\n\n _get(Object.getPrototypeOf(DeviceMotionModule.prototype), 'constructor', this).call(this, 'devicemotion');\n\n /**\n * Raw values coming from the `devicemotion` event sent by this module.\n *\n * @this DeviceMotionModule\n * @type {number[]}\n * @default [null, null, null, null, null, null, null, null, null]\n */\n this.event = [null, null, null, null, null, null, null, null, null];\n\n /**\n * The `AccelerationIncludingGravity` module.\n * Provides unified values of the acceleration including gravity.\n *\n * @this DeviceMotionModule\n * @type {DOMEventSubmodule}\n */\n this.accelerationIncludingGravity = new DOMEventSubmodule(this, 'accelerationIncludingGravity');\n\n /**\n * The `Acceleration` submodule.\n * Provides unified values of the acceleration.\n * Estimates the acceleration values from `accelerationIncludingGravity`\n * raw values if the acceleration raw values are not available on the\n * device.\n *\n * @this DeviceMotionModule\n * @type {DOMEventSubmodule}\n */\n this.acceleration = new DOMEventSubmodule(this, 'acceleration');\n\n /**\n * The `RotationRate` submodule.\n * Provides unified values of the rotation rate.\n * (coming soon, waiting for a bug on Chrome to be resolved)\n * Estimates the rotation rate values from `orientation` values if\n * the rotation rate raw values are not available on the device.\n *\n * @this DeviceMotionModule\n * @type {DOMEventSubmodule}\n */\n this.rotationRate = new DOMEventSubmodule(this, 'rotationRate');\n\n /**\n * Required submodules / events.\n *\n * @this DeviceMotionModule\n * @type {object}\n * @property {bool} accelerationIncludingGravity - Indicates whether the `accelerationIncludingGravity` unified values are required or not (defaults to `false`).\n * @property {bool} acceleration - Indicates whether the `acceleration` unified values are required or not (defaults to `false`).\n * @property {bool} rotationRate - Indicates whether the `rotationRate` unified values are required or not (defaults to `false`).\n */\n this.required = {\n accelerationIncludingGravity: false,\n acceleration: false,\n rotationRate: false\n };\n\n /**\n * Number of listeners subscribed to the `DeviceMotion` module.\n *\n * @this DeviceMotionModule\n * @type {number}\n */\n this._numListeners = 0;\n\n /**\n * Resolve function of the module's promise.\n *\n * @this DeviceMotionModule\n * @type {function}\n * @default null\n * @see DeviceMotionModule#init\n */\n this._promiseResolve = null;\n\n /**\n * Unifying factor of the motion data values (`1` on Android, `-1` on iOS).\n *\n * @this DeviceMotionModule\n * @type {number}\n */\n this._unifyMotionData = platform.os.family === 'iOS' ? -1 : 1;\n\n /**\n * Unifying factor of the period (`0.001` on Android, `1` on iOS).\n *\n * @this DeviceMotionModule\n * @type {number}\n */\n this._unifyPeriod = platform.os.family === 'Android' ? 0.001 : 1;\n\n /**\n * Acceleration calculated from the `accelerationIncludingGravity` raw values.\n *\n * @this DeviceMotionModule\n * @type {number[]}\n * @default [0, 0, 0]\n */\n this._calculatedAcceleration = [0, 0, 0];\n\n /**\n * Time constant (half-life) of the high-pass filter used to smooth the acceleration values calculated from the acceleration including gravity raw values (in seconds).\n *\n * @this DeviceMotionModule\n * @type {number}\n * @default 0.1\n * @constant\n */\n this._calculatedAccelerationTimeConstant = 0.1;\n\n /**\n * Latest `accelerationIncludingGravity` raw value, used in the high-pass filter to calculate the acceleration (if the `acceleration` values are not provided by `'devicemotion'`).\n *\n * @this DeviceMotionModule\n * @type {number[]}\n * @default [0, 0, 0]\n */\n this._lastAccelerationIncludingGravity = [0, 0, 0];\n\n /**\n * Rotation rate calculated from the orientation values.\n *\n * @this DeviceMotionModule\n * @type {number[]}\n * @default [0, 0, 0]\n */\n this._calculatedRotationRate = [0, 0, 0];\n\n /**\n * Latest orientation value, used to calculate the rotation rate (if the `rotationRate` values are not provided by `'devicemotion'`).\n *\n * @this DeviceMotionModule\n * @type {number[]}\n * @default [0, 0, 0]\n */\n this._lastOrientation = [0, 0, 0];\n\n /**\n * Latest orientation timestamps, used to calculate the rotation rate (if the `rotationRate` values are not provided by `'devicemotion'`).\n *\n * @this DeviceMotionModule\n * @type {number[]}\n * @default [0, 0, 0]\n */\n this._lastOrientationTimestamp = null;\n\n /**\n * Method binding of the sensor check.\n *\n * @this DeviceMotionModule\n * @type {function}\n */\n this._devicemotionCheck = this._devicemotionCheck.bind(this);\n\n /**\n * Method binding of the `'devicemotion'` event callback.\n *\n * @this DeviceMotionModule\n * @type {function}\n */\n this._devicemotionListener = this._devicemotionListener.bind(this);\n }",
"function DeviceMotionModule() {\n\t _classCallCheck(this, DeviceMotionModule);\n\t /**\n\t * Raw values coming from the `devicemotion` event sent by this module.\n\t *\n\t * @this DeviceMotionModule\n\t * @type {number[]}\n\t * @default [null, null, null, null, null, null, null, null, null]\n\t */\n\n\n\t var _this = _possibleConstructorReturn(this, (DeviceMotionModule.__proto__ || Object.getPrototypeOf(DeviceMotionModule)).call(this, 'devicemotion'));\n\n\t _this.event = [null, null, null, null, null, null, null, null, null];\n\t /**\n\t * The `AccelerationIncludingGravity` module.\n\t * Provides unified values of the acceleration including gravity.\n\t *\n\t * @this DeviceMotionModule\n\t * @type {DOMEventSubmodule}\n\t */\n\n\t _this.accelerationIncludingGravity = new _DOMEventSubmodule2.default(_this, 'accelerationIncludingGravity');\n\t /**\n\t * The `Acceleration` submodule.\n\t * Provides unified values of the acceleration.\n\t * Estimates the acceleration values from `accelerationIncludingGravity`\n\t * raw values if the acceleration raw values are not available on the\n\t * device.\n\t *\n\t * @this DeviceMotionModule\n\t * @type {DOMEventSubmodule}\n\t */\n\n\t _this.acceleration = new _DOMEventSubmodule2.default(_this, 'acceleration');\n\t /**\n\t * The `RotationRate` submodule.\n\t * Provides unified values of the rotation rate.\n\t * (coming soon, waiting for a bug on Chrome to be resolved)\n\t * Estimates the rotation rate values from `orientation` values if\n\t * the rotation rate raw values are not available on the device.\n\t *\n\t * @this DeviceMotionModule\n\t * @type {DOMEventSubmodule}\n\t */\n\n\t _this.rotationRate = new _DOMEventSubmodule2.default(_this, 'rotationRate');\n\t /**\n\t * Required submodules / events.\n\t *\n\t * @this DeviceMotionModule\n\t * @type {object}\n\t * @property {bool} accelerationIncludingGravity - Indicates whether the `accelerationIncludingGravity` unified values are required or not (defaults to `false`).\n\t * @property {bool} acceleration - Indicates whether the `acceleration` unified values are required or not (defaults to `false`).\n\t * @property {bool} rotationRate - Indicates whether the `rotationRate` unified values are required or not (defaults to `false`).\n\t */\n\n\t _this.required = {\n\t accelerationIncludingGravity: false,\n\t acceleration: false,\n\t rotationRate: false\n\t };\n\t /**\n\t * Resolve function of the module's promise.\n\t *\n\t * @this DeviceMotionModule\n\t * @type {function}\n\t * @default null\n\t * @see DeviceMotionModule#init\n\t */\n\n\t _this._promiseResolve = null;\n\t /**\n\t * Unifying factor of the motion data values (`1` on Android, `-1` on iOS).\n\t *\n\t * @this DeviceMotionModule\n\t * @type {number}\n\t */\n\n\t _this._unifyMotionData = _platform2.default.os.family === 'iOS' ? -1 : 1;\n\t /**\n\t * Unifying factor of the period (`1` on Android, `1` on iOS). in sec\n\t * @todo - unify with e.interval specification (in ms) ?\n\t *\n\t * @this DeviceMotionModule\n\t * @type {number}\n\t */\n\n\t _this._unifyPeriod = _platform2.default.os.family === 'Android' ? 0.001 : 1;\n\t /**\n\t * Acceleration calculated from the `accelerationIncludingGravity` raw values.\n\t *\n\t * @this DeviceMotionModule\n\t * @type {number[]}\n\t * @default [0, 0, 0]\n\t */\n\n\t _this._calculatedAcceleration = [0, 0, 0];\n\t /**\n\t * Time constant (half-life) of the high-pass filter used to smooth the acceleration values calculated from the acceleration including gravity raw values (in seconds).\n\t *\n\t * @this DeviceMotionModule\n\t * @type {number}\n\t * @default 0.1\n\t * @constant\n\t */\n\n\t _this._calculatedAccelerationTimeConstant = 0.1;\n\t /**\n\t * Latest `accelerationIncludingGravity` raw value, used in the high-pass filter to calculate the acceleration (if the `acceleration` values are not provided by `'devicemotion'`).\n\t *\n\t * @this DeviceMotionModule\n\t * @type {number[]}\n\t * @default [0, 0, 0]\n\t */\n\n\t _this._lastAccelerationIncludingGravity = [0, 0, 0];\n\t /**\n\t * Rotation rate calculated from the orientation values.\n\t *\n\t * @this DeviceMotionModule\n\t * @type {number[]}\n\t * @default [0, 0, 0]\n\t */\n\n\t _this._calculatedRotationRate = [0, 0, 0];\n\t /**\n\t * Latest orientation value, used to calculate the rotation rate (if the `rotationRate` values are not provided by `'devicemotion'`).\n\t *\n\t * @this DeviceMotionModule\n\t * @type {number[]}\n\t * @default [0, 0, 0]\n\t */\n\n\t _this._lastOrientation = [0, 0, 0];\n\t /**\n\t * Latest orientation timestamps, used to calculate the rotation rate (if the `rotationRate` values are not provided by `'devicemotion'`).\n\t *\n\t * @this DeviceMotionModule\n\t * @type {number[]}\n\t * @default [0, 0, 0]\n\t */\n\n\t _this._lastOrientationTimestamp = null;\n\t _this._processFunction = null;\n\t _this._process = _this._process.bind(_this);\n\t _this._devicemotionCheck = _this._devicemotionCheck.bind(_this);\n\t _this._devicemotionListener = _this._devicemotionListener.bind(_this);\n\t _this._checkCounter = 0;\n\t return _this;\n\t }",
"makeInputManager() {\n var manager = KeyInput();\n this.registerHandler('down', input=>downHandler.call(manager, input));\n this.registerHandler('up', input=>upHandler.call(manager, input));\n return manager;\n }",
"positionInputModule() {\n var position = new PositionModule();\n position.x = 10;\n position.y = window.innerHeight / 2;\n return position;\n }",
"function ModuleInput(config) {\n // Store node for further use\n var node = this;\n node.input = config.input;\n\n // Create the Node-RED node\n RED.nodes.createNode(this, config);\n setStatus(node, statusEnum.disconnected);\n getClient().then(function(client){\n setStatus(node, statusEnum.connected);\n // Act on module input messages\n node.log(\"Module Input created: \" + node.input);\n client.on('inputMessage', function (inputName, msg) {\n outputMessage(client, node, inputName, msg);\n });\n })\n .catch(function(err){\n node.log(\"Module Input can't be loaded: \" + err);\n });\n \n node.on('close', function(done) {\n setStatus(node, statusEnum.disconnected);\n done();\n });\n }",
"function createInput( inputObject = new THREE.Group() ){\n const input = {\n raycast: new THREE.Raycaster( new THREE.Vector3(), new THREE.Vector3() ),\n laser: createLaser(),\n cursor: createCursor(),\n object: inputObject,\n pressed: false,\n gripped: false,\n events: new Emitter(),\n interaction: {\n grip: undefined,\n press: undefined,\n hover: undefined\n }\n };\n\n input.laser.add( input.cursor );\n\n return input;\n }",
"createInput()\n\t\t{\n\t\t\tvar input = new E.Input();\n\t\t\tinput.setup(document.body);\n\t\t\treturn input;\n\t\t}",
"_initEvents() {\n Input._init(this, {\n joystick: true\n });\n }",
"createInput()\n {\n this.input = createInput(this.text)\n this.input.position(this.x,this.y)\n }",
"function TouchMouseInput() {\n Input.apply(this, arguments);\n var handler = bindFn(this.handler, this);\n this.touch = new TouchInput(this.manager, handler);\n this.mouse = new MouseInput(this.manager, handler);\n}",
"makePlayer() { // Declare the makePlayer() method\n player = new Player(this, 400, 300, currentIdleAnimation); // Create a new Player object\n player.setDataEnabled(); // Set the player object to accept data\n player.data.set('inMotion', false); // Save the inMotion state to the player\n }",
"function TouchMouseInput() {\n Input.apply(this, arguments);\n\n var handler = bindFn(this.handler, this);\n this.touch = new TouchInput(this.manager, handler);\n this.mouse = new MouseInput(this.manager, handler);\n}",
"function InputManager() {\n\t// the state of each key (up to 255)\n\tthis.mKeyStates = new Array();\n\tfor (var i = 0; i < 255; ++i) {\n\t\tthis.mKeyStates[i] = 0;\n\t}\n\t\n\t// the state of each mouse button (left, right and middle)\n\tthis.mButtonStates = new Array();\n\tfor (var i = 0; i < 3; ++i) {\n\t\tthis.mButtonStates[i] = 0;\n\t}\n\t\n\tthis.mMouseInCanvas = false; // is the mouse inside the canvas\n\tthis.mLocalMouseCoords = new Vec2(0, 0); // coordinates of the mouse in the canvas\n\tthis.mGlobalMouseCoords = new Vec2(0, 0); // coordinates of the mouse in the page\n\tthis.mWheelDelta = 0;\n\t\n\tthis.mTextInput = \"\"; // current text string that has been input since last frame\n\t\n\tthis.mDisableBackspace = true; // should backspace functionality be disabled (usually 'back')\n\tthis.mDisableMouseWheel = false; // should mouse wheel functionality be disabled (usually 'page scrolling')\n}",
"_initEvents() {\n Input.init(/*{\n joystick: true\n }*/);\n\n this._addVisibilityEvents();\n }",
"function ModularInput() {\n\t this._inputDefinition = null;\n\t this._service = null;\n\t }",
"function GetCurrentInputManagerImpl()\r\n { \r\n// var inputManager = null;\r\n// var dispatcher = Dispatcher.CurrentDispatcher;\r\n// inputManager = dispatcher.InputManager instanceof InputManager ? dispatcher.InputManager : null; \r\n\r\n if (_INSTANCE == null) \r\n { \r\n \t_INSTANCE = new InputManager();\r\n }\r\n\r\n return _INSTANCE;\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
internal function called in the process of unlocking a tag. | function unlockTagInternal(array) {
var message = [
ndef.uriRecord(array[0]),
ndef.textRecord(array[1]),
ndef.textRecord(array[2]),
ndef.textRecord(array[3]),
ndef.textRecord("unlock")
];
nfc.write(
message,
function () {
alert("Tag Unlocked");
},
function (reason) {
alert("problem in writing.." + reason);
}
);
} | [
"function HandleUnlock() {}",
"unlock() {\n\t\tthis.locked = false;\n\t}",
"unlock() {\n this._locked = false;\n }",
"function unlock()\r\n{\r\n\tlocked = false;\r\n}",
"unlock() {\n Atomics.store(this.sabArr, this.lockIndex, this.UNLOCKED);\n Atomics.notify(this.sabArr, this.lockIndex);\n }",
"onReleaseLock(type) {}",
"unlock()\n {\n this._buffer.unlock();\n }",
"unlock() {\n const iab = this.iab;\n const stateIdx = this.ibase;\n var v0 = Atomics.sub(iab, stateIdx, 1); // A\n // Wake up a waiter if there are any\n if (v0 !== LOCKED_NO_WAITERS) {\n Atomics.store(iab, stateIdx, UNLOCKED);\n Atomics.wake(iab, stateIdx, 1);\n }\n }",
"function unlock() {\n\n setEventLock(EVENT_LOCK_LOCKED);\n }",
"function unlock_() {\n try {\n LockService.getScriptLock().releaseLock();\n } catch (x) {\n try {\n Utilities.sleep(manager.sleepConstantForUnlockBug);\n LockService.getScriptLock().releaseLock();\n } catch (ex) {\n logError(ex);\n }\n }\n}",
"release() {\n lock.release();\n }",
"function fnPostUnlock() {\n\tdebugs(\"In fnPostUnlock\", \"A\");\n}",
"async unlock() {\n if (this.locked) {\n clearTimeout(this.lockTimeout);\n if (this.lockRefreshing) {\n // First await the promise we held onto to make sure there is\n // no race condition that leaves the lock in place\n await this.lockRefreshing;\n }\n try {\n await apos.http.patch(this.lockApiUrl, {\n body: {\n _advisoryLock: {\n tabId: apos.adminBar.tabId,\n lock: false\n }\n },\n draft: true,\n busy: true\n });\n } catch (e) {\n // Not our concern, just being polite\n }\n }\n }",
"Unlock()\n {\n this.doNotPurge = Math.max(this.doNotPurge - 1, 0);\n }",
"async function unlock()\n {\n if (await bookmarks.is_unlocked()) { return; }\n\n transition_to(\"authentication\",\n {\n message: \"\",\n\n on_acceptance: async hashed_password =>\n {\n try\n {\n const unlocking = bookmarks.unlock(hashed_password);\n transition_to(\"on_hold\", \"unlock-status-update\");\n await new Promise(resolve => { setTimeout(resolve, 1000); });\n await unlocking;\n\n const title =\n format_folder_name(await bookmarks.get_front_title());\n const parent_title =\n format_folder_name(await bookmarks.get_front_parent_title());\n\n transition_to(\"success\",\n {\n details: browser.i18n.getMessage(\n \"success_unlock\",\n [title, parent_title]\n ),\n transition: MAIN_MENU_TRANSITION\n });\n remind_to_backup();\n }\n catch (error)\n {\n transition_to(\"error\",\n {\n title: \"Error during unlock\",\n message: error.message\n });\n }\n },\n on_cancellation: () => { transition_to(\"main_menu\"); }\n });\n }",
"handleUnlock () {\n if (this.waitingForUnlock.length > 0) {\n while (this.waitingForUnlock.length > 0) {\n this.waitingForUnlock.shift().resolve()\n }\n this.emit('updateBadge')\n }\n }",
"handleUnlockAction() {\n const prNumber = this.appContext.payload.issue.number\n let prLock = new PrLock()\n\n // if user wants to unlock, and lock is held by current PR, unlock\n if (prLock.getPrNumber() == prNumber) {\n this.appContext.log(\"received unlock request, unlocking...\")\n prLock.unlock(prNumber)\n return ArgoBot.respondWithComment(this.appContext, \"Lock has been released!\")\n }\n else {\n // notify user to unlock from the PR that owns the lock\n this.appContext.log(\"received unlock request from the wrong PR\")\n const lockMessage = prLock.getLockInfo() + \"; is holding the lock, please comment on that PR to unlock\"\n return ArgoBot.respondWithComment(this.appContext, lockMessage)\n }\n }",
"unlock() {\n this[kWorker].unlock();\n }",
"function handleUnlock() {\n\t// Switch to unlocked logo if there\n\tif (tkSettings.tkTextKeyUnloackSound != \"\") {\n\t\t$(\"#tkSound\").html('<audio src=\"'+tkSettings.tkTextKeyUnloackSound+'\" autoplay></audio>');\n\t};\n\tsetTimeout(\"changeLock()\",1500);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
removeTreeNode(element) this function removes the node from the tree | function removeTreeNode(element)
{
var removeRow = element.parentNode;
var removeTable = removeRow.parentNode.parentNode;
var removeRowIndex = removeRow.rowIndex;
var rowLength = removeTable.rows.length;
removeTable.deleteRow(removeRowIndex+1);
removeTable.deleteRow(removeRowIndex);
if (rowLength > 2) {
var index = removeTable.rows.length-2;
redrawRowTMB(removeTable.rows(index), "bottom");
} else {
var parentRow = removeTable.parentNode.parentNode;
var parentTable = parentRow.parentNode.parentNode;
var parentRowIndex = parentRow.rowIndex;
parentTable.rows(parentRowIndex).cells(0).innerHTML = " ";
parentTable.rows(parentRowIndex).cells(1).innerHTML = " ";
parentTable.rows(parentRowIndex).style.display = "none";
parentRow = parentTable.rows(parentRowIndex-1);
var removeTMB = parentRow.TMB;
parentRow.HASCHILDREN = "NO";
parentRow.isOpen = "false";
if(parentRow.TMB!='top')
parentRow.cells(0).innerHTML = "<img alt='' src=/wcs/images/tools/dtree/line"+removeTMB+".gif border=0>";
}
return;
} | [
"function removeTreeFromElement()/*: void*/ {\n this.emitSync(\"willDetachFromParent\");\n this[_renderElement].removeChild(this.elementTree);\n this[_renderElement] = null;\n this[_attached] = false;\n this.emit(\"didDetachFromParent\");\n}",
"function removeElement(node){\n\tif (node.parentNode){\n\t\tvar parent = node.parentNode;\n\t\tparent.removeChild(node);\t\t\n\t}\n}",
"function removeNode() {\n if (selectedCacheNode) {\n var node = cachedTree.findNode(selectedCacheNode);\n if (node.isElementDeleted)\n alert('This element is already deleted');\n else {\n node.remove();\n for (var i = 0; i < node.children.length; i++)\n if (!node.children[i].isElementDeleted)\n node.children[i].remove();\n }\n render(cachedTree, 'CachedTreeView');\n } else\n alert('No cache node selected!');\n}",
"function removeElement(elem){ elem.parentNode.removeChild(elem) }",
"removeNode(node) {\n var index = this.nodes.indexOf(node);\n this.nodes.splice(index, 1);\n var nodeToRemove = document.getElementById(node.id);\n if (nodeToRemove != undefined) {\n nodeToRemove.parentNode.removeChild(nodeToRemove);\n }\n }",
"removeElement(_element) {\n const element = this.getElementOrDie(_element);\n const parent = this.getParentOrDie(element);\n\n const index = parent.indexOf(element);\n return this.remove(parent, index);\n }",
"remove(){\n this.node.remove();\n }",
"function removeElement(elem){ if (elem) elem.parentNode.removeChild(elem) }",
"remove() {\n this.node.remove()\n }",
"function deleteBranch(element){\n delete myTree[element]; // deleting element will allow edits to not error out\n resetBranch(); \n websocket.send(JSON.stringify(myTree));\n growTree();\n}",
"function removeEl(element) {\n element.parentNode.removeChild(element);\n}",
"function bstRemove (tree, node) {\n var z = node,\n y;\n if (z.left === NIL) {\n tree = bstTransplant(tree,z,z.right);\n } else if (z.right === NIL) {\n tree = bstTransplant(tree,z,z.left);\n } else {\n y = bstMin(z.right);\n if (y.p !== z) {\n tree = bstTransplant(tree,y,y.right);\n y.right = z.right;\n y.right.p = y;\n }\n tree = bstTransplant(tree,z,y);\n y.left = z.left;\n y.left.p = y;\n }\n return tree;\n}",
"remove(value) {\n if (this.root === null) {\n console.log(`Tree is empty.`);\n return;\n } else {\n let currentNode = this.root;\n let parentNode = null;\n while (currentNode) {\n if (value < currentNode.value) {\n parentNode = currentNode;\n currentNode = currentNode.left;\n } else if (value > currentNode.value) {\n parentNode = currentNode;\n currentNode = currentNode.right;\n } else if (currentNode.value === value) {\n \n //a. If the node being removed does not have a right child it can be removed directly:\n if (currentNode.right === null) {\n //If parentNode is still null, it means the node being deleted is the root and, as there is no right tree, replace it with its left node.\n if (parentNode === null) {\n this.root = currentNode.left;\n }\n else {\n //if the value being removed is at the left of its parent, update its parent left reference to point to the node's left child (it doesn't matter if there is a left child or if it is null).\n if (currentNode.value < parentNode.value) {\n parentNode.left = currentNode.left;\n }\n //if the value being removed is at the right of its parent, update its parent right reference to point to the node's left child (it doesn't matter if there is a left child or if it is null).\n else if (currentNode.value > parentNode.value) {\n parentNode.right = currentNode.left;\n }\n }\n return;\n } \n //b. If the node being removed has a right child which DOES NOT have a left child, it can also be removed directly, but remember to update the references.\n else if (currentNode.right.left === null) {\n //since in this case \"currentNode\" will be replaced by \"currentNode.right\", the reference to \"currentNode.left\" must be updated to \"currentNode.right.left\" (it doesn't matter if there is a \"currentNode.left\" or if it is null), which is available.\n currentNode.right.left = currentNode.left;\n //If parentNode is still null, it means the node being deleted is the root and, as there is no right tree, replace it with its left node.\n if (parentNode === null) {\n this.root = currentNode.left;\n }\n else {\n //if the value being removed is at the left of its parent, update its parent left reference to point to the node's right child (it doesn't matter if there is a left child or if it is null).\n if (currentNode.value < parentNode.value) {\n parentNode.left = currentNode.right;\n }\n //if the value being removed is at the right of its parent, update its parent right reference to point to the node's right child (it doesn't matter if there is a left child or if it is null).\n else if (currentNode.value > parentNode.value) {\n parentNode.right = currentNode.right;\n }\n }\n return;\n }\n //c. If the node to be removed has a right child which DOES have a left child, we have to find its leftmost node and use replace the node being removed with this node. The tricky part here is to update the references correctly.\n else {\n //In this case, we need to keep track of the \"currentNode.right\" leftmost node, which will be used to replace the value being removed. Initially, this leftmost node is equal to \"currentNode.right.left\".\n let leftmost = currentNode.right.left;\n\n //As we'll need to update the references which point to the node that will be used to replace the node being removed, we also need to keep track of its parent node, which initially will be equal to \"currentNode.right\".\n let leftmostParent = currentNode.right;\n\n //Traverse the \"currentNode.right\" left tree until we find the leftmost node.\n while (leftmost.left !== null) {\n leftmostParent = leftmost;\n leftmost = leftmost.left;\n }\n\n //As we use the leftmost node value to replace the node being removed (currentNode), we still need to keep track of its right reference \"leftmost.right\" (it doesn't matter if there is a right child or if it is null). Therefore, we update the parent node left reference \"leftmostParent.left\" which now is free since we used \"leftmost\" to replace \"currentNode\" to point to \"leftmost.right\" so nothing is left out.\n leftmostParent.left = leftmost.right;\n\n //Now we can update the \"leftmost\" references to point to the \"currentNode\" references.\n leftmost.right = currentNode.right;\n leftmost.left = currentNode.left;\n\n //If parentNode is still null, it means the node being deleted is the root and, as there is no right tree, replace it with its left node.\n if (parentNode === null) {\n this.root = leftmost;\n }\n else {\n //if the value being removed is at the left of its parent, update its parent left reference to point to the node's left child.\n if (currentNode.value < parentNode.value) {\n parentNode.left = leftmost;\n }\n //if the value being removed is at the right of its parent, update its parent right reference to point to the node's left child.\n else if (currentNode.value > parentNode.value) {\n parentNode.right = leftmost;\n }\n }\n return;\n }\n }\n }\n }\n return `${value} is not in the tree.`;\n }",
"remove(e) {\n var node = this._find(e);\n if (!node) {\n throw new Error('Item not found in the tree');\n }\n\n if (node.left && node.right) {\n /**\n * If the node to be removed has both left and right children,\n * replace the node's value by the minimum value of the right\n * sub-tree, and remove the leave containing the value\n */\n var successor = this._findMin(node.right);\n this.remove(successor.value);\n node.value = successor.value;\n } else {\n /**\n * If the node is a leaf, just make the parent point to null,\n * and if it has one child, make the parent point to this child\n * instead\n */\n this._replaceNodeInParent(node, node.left || node.right);\n this._size--;\n }\n }",
"function removeTraverse(node){\n\t\t\tif (node){\n\t\t\t\tremoveTraverse(node.left);\n\t\t\t\tif(val === node.value){\n\t\t\t\t\tdeleteTree(node);\n\t\t\t\t} else {\n\t\t\t\t\tremoveTraverse(node.right);\n\t\t\t\t}\n\t\t\t}\n\t\t}",
"function removeNode(node) {\n if (node && node.parentNode) {\n node.parentNode.removeChild(node);\n }\n }",
"delete(input){\n\n let searchResult;\n\n if ( input instanceof InterfaceRadixTreeNode === false) {\n\n if (!Buffer.isBuffer(input))\n input = WebDollarCryptoData.createWebDollarCryptoData(input).buffer\n\n searchResult = this.search(input);\n\n //console.log(\"searchResult\", searchResult)\n if ( !searchResult.node )\n return false;\n\n } else {\n searchResult = {node: input, }\n }\n\n //it is the last element, we should delete it\n let finished = false;\n\n if (!searchResult.node.isLeaf())\n throw {message: \"couldn't delete because input is not a leaf node\"};\n\n let node = searchResult.node;\n\n node.value = null;\n node._previousEdges = node.edges.slice();\n node.edges = [];\n\n\n // node must be deleted\n while ( !finished && node !== null){\n\n let toDelete = node;\n let nodeParent = node.parent;\n\n finished = true;\n\n //remove empty parent nodes\n\n if ( node !== null && node.value === null && nodeParent !== null && nodeParent.edges.length > 0 && node.edges.length === 0){\n\n //console.log(\"node simplu before\", node, node.parent);\n\n //removing edge to current node from my direct parent\n let deletedParentEdge = null;\n for (let i = 0; i < nodeParent.edges.length; i++)\n if (nodeParent.edges[i].targetNode === node) {\n deletedParentEdge = nodeParent.edges[i];\n nodeParent.edges.splice(i, 1);\n break;\n }\n\n if (deletedParentEdge !== null){\n\n // remove now useless prefixes nodes\n\n // prefix slow => slowly\n if ( node._previousEdges.length === 1 ){\n\n nodeParent.edgesPush( this.root.createNewEdge( Buffer.concat( [ deletedParentEdge.label, node._previousEdges[0].label ] ), node._previousEdges[0].targetNode) );\n\n node = node._previousEdges[0].targetNode;\n node.parent = nodeParent;\n\n //console.log(\"this._changedNode 1_0\");\n\n break;\n\n } else\n\n // prefix slow => slowly\n // => slowby\n\n if ( node._previousEdges.length > 1 ){\n\n node.edges = node._previousEdges;\n nodeParent.edgesPush( deletedParentEdge ) ;\n\n //console.log(\"this._changedNode 1_1\");\n\n break;\n\n } else\n if ( !nodeParent.isLeaf() && nodeParent.edges.length === 1 ){ // my parent has one more node\n\n if (nodeParent.parent !== null){\n\n let edge = nodeParent.edges[0];\n node = nodeParent.edges[0].targetNode;\n let grandParent = nodeParent.parent;\n\n //replace grand parent edge child\n for (let i = 0; i < grandParent.edges.length; i++)\n if (grandParent.edges[i].targetNode === nodeParent) {\n\n\n let label = Buffer.concat( [ grandParent.edges[i].label, edge.label ]);\n grandParent.edges.splice(i,1);\n grandParent.edgesPush( this.root.createNewEdge( label, node )) ;\n\n node.parent = grandParent;\n\n // it is not necessary its parent\n //console.log(\"this._changedNode 1_2\");\n\n //console.log(\"grandParent deletion\", node, nodeParent);\n break;\n }\n\n } else {\n node = node.parent;\n //console.log(\"this._changedNode 1_3\");\n }\n\n }\n else {\n node = nodeParent;\n //console.log(\"this._changedNode 1_4\");\n }\n\n nodeParent = node.parent;\n\n finished = false;\n\n //console.log(\"this._changedNode 2\");\n\n\n }\n\n //console.log(\"node simplu after\", node, node.parent);\n }\n\n if (node !== null && nodeParent !== null && node.value === null && node.edges.length === 0 && node !== this.root ){\n\n //console.log(\"node22..... \", node.value, node.edges)\n\n for (let i = nodeParent.edges.length - 1; i >= 0; i--)\n if (nodeParent.edges[i].targetNode === node) {\n\n nodeParent.edges.splice(i, 1);\n\n node = node.parent;\n nodeParent = node.parent;\n\n finished = false;\n\n //console.log(\" this._changedNode 3 \");\n\n break;\n }\n }\n\n // in case we actually deleted a node\n if (toDelete !== node ) {\n toDelete.edges = [];\n toDelete._previousEdges = [];\n toDelete.destroyNode();\n\n }\n\n }\n\n //for testing only\n\n //console.log(\"this.printLevelSearch() node\", node);\n //this.printLevelSearch();\n\n // try {\n // let serialization = this._serializeTree();\n // this._deserializeTree(serialization);\n // } catch (exception){\n // console.error(\"ERRROR!!!\");\n // }\n\n node._changedNode( );\n\n\n return true;\n }",
"function remove_node(node)\n\t{\n\t\t// if the node's parent is null, it's already been removed\n\t\tif ( node.parentNode == null )\n\t\t\treturn;\n\n\t\tnode.parentNode.removeChild(node);\n\t}",
"function removeElement(element) {\n while (element.getParent() && !element.removeFromParent) {\n element = element.getParent();\n }\n if (element.removeFromParent) {\n element.removeFromParent();\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Styles is an array of properties returned by `create()`, a POJO, or an array thereof. POJOs are treated as inline styles. This version of the resolve function explicitly flips inline styles for an RTL context. This function returns an object to be spread onto an element. | function resolveRTL(css, styles) {
var flattenedStyles = (0, _arrayPrototype2['default'])(styles, Infinity);
var _separateStyles = (0, _separateStyles3['default'])(flattenedStyles),
aphroditeStyles = _separateStyles.aphroditeStyles,
hasInlineStyles = _separateStyles.hasInlineStyles,
inlineStyles = _separateStyles.inlineStyles;
var result = {};
if (aphroditeStyles.length > 0) {
result.className = css.apply(undefined, _toConsumableArray(aphroditeStyles));
}
if (hasInlineStyles) {
result.style = (0, _rtlCssJs2['default'])(inlineStyles);
}
return result;
} | [
"_resolveStyle(reactNativeStyle, options) {\n const flatStyle = flattenStyle(reactNativeStyle);\n const domStyle = createReactDOMStyle(options.i18n === false ? flatStyle : i18nStyle(flatStyle));\n\n const props = Object.keys(domStyle).reduce(\n (props, styleProp) => {\n const value = domStyle[styleProp];\n if (value != null) {\n const className = this.styleManager.getClassName(styleProp, value);\n if (className) {\n props.classList.push(className);\n } else {\n if (!props.style) {\n props.style = {};\n }\n // 4x slower render\n props.style[styleProp] = value;\n }\n }\n return props;\n },\n { classList: [] }\n );\n\n props.className = classListToString(props.classList);\n if (props.style) {\n props.style = prefixInlineStyles(props.style);\n }\n return props;\n }",
"resolveStyles(props = {}) {\n const styles = {\n animationDuration: props.duration,\n borderColor: props.secondaryColor,\n borderTopColor: props.color,\n borderWidth: props.borderWidth,\n height: props.size,\n width: props.size,\n }\n const overrides = props.style || {}\n\n return {...styles, ...overrides}\n }",
"function _resolveStyles(props, theme, tokens) {\r\n var allStyles = [];\r\n for (var _i = 3; _i < arguments.length; _i++) {\r\n allStyles[_i - 3] = arguments[_i];\r\n }\r\n return styling_1.concatStyleSets.apply(void 0, allStyles.map(function (styles) {\r\n return typeof styles === 'function' ? styles(props, theme, tokens) : styles;\r\n }));\r\n }",
"function makeResolveFn(direction, stylesInterface) {\n var directionSelector = direction === _WithStylesContext.DIRECTIONS.RTL ? 'RTL' : 'LTR';\n var resolve = stylesInterface[\"resolve\".concat(directionSelector)] || stylesInterface.resolve;\n var original = resolve;\n\n if (false) {}\n\n return {\n resolve: resolve,\n original: original\n };\n } // The function that wraps the provided component in a wrapper",
"resolveStateful(rnStyleNext, domStyleProps, options) {\n const { classList: rdomClassList, style: rdomStyle } = domStyleProps;\n\n // Convert the DOM classList back into a React Native form\n // Preserves unrecognized class names.\n const { classList: rnClassList, style: rnStyle } = rdomClassList.reduce(\n (styleProps, className) => {\n const { prop, value } = this.styleManager.getDeclaration(className);\n if (prop) {\n styleProps.style[prop] = value;\n } else {\n styleProps.classList.push(className);\n }\n return styleProps;\n },\n { classList: [], style: {} }\n );\n\n // Create next DOM style props from current and next RN styles\n const { classList: rdomClassListNext, style: rdomStyleNext } = this.resolve(\n [rnStyle, rnStyleNext],\n options\n );\n\n // Next class names take priority over current inline styles\n const style = { ...rdomStyle };\n rdomClassListNext.forEach(className => {\n const { prop } = this.styleManager.getDeclaration(className);\n if (style[prop]) {\n style[prop] = '';\n }\n });\n\n // Next inline styles take priority over current inline styles\n Object.assign(style, rdomStyleNext);\n\n // Add the current class names not managed by React Native\n const className = classListToString(rdomClassListNext.concat(rnClassList));\n\n return { className, style };\n }",
"function _resolveStyles(props, theme, tokens) {\n var allStyles = [];\n for (var _i = 3; _i < arguments.length; _i++) {\n allStyles[_i - 3] = arguments[_i];\n }\n return _uifabric_styling__WEBPACK_IMPORTED_MODULE_2__[\"concatStyleSets\"].apply(void 0, allStyles.map(function (styles) {\n return typeof styles === 'function' ? styles(props, theme, tokens) : styles;\n }));\n}",
"function getDynamicStyles(styles){var to=null;for(var key in styles){var value=styles[key];var type=typeof value==='undefined'?'undefined':_typeof(value);if(type==='function'){if(!to)to={};to[key]=value;}else if(type==='object'&&value!==null&&!Array.isArray(value)){var extracted=getDynamicStyles(value);if(extracted){if(!to)to={};to[key]=extracted;}}}return to;}",
"function _resolveStyles(props, theme, tokens) {\n var allStyles = [];\n for (var _i = 3; _i < arguments.length; _i++) {\n allStyles[_i - 3] = arguments[_i];\n }\n return _fluentui_style_utilities__WEBPACK_IMPORTED_MODULE_1__.concatStyleSets.apply(void 0, allStyles.map(function (styles) {\n return typeof styles === 'function' ? styles(props, theme, tokens) : styles;\n }));\n}",
"function resolve (stylesheets, properties, type, attributes, params) {\n var memoKey = type + \"#\" + attributes.id + \".\" + attributes['class'];\n\n var collapsed;\n\n if (resolveMemo[memoKey]) {\n collapsed = resolveMemo[memoKey];\n } \n \n else {\n var selectorList = buildSelectorList(type, attributes);\n var out = [];\n\n selectorList.forEach(function (iter) {\n resolveSubtree(stylesheets, properties, out, iter.concat(), 0);\n });\n\n // Collapse the styles according to specificty\n collapsed = collapse(out);\n\n if (_) for (var prop in collapsed) if (collapsed.hasOwnProperty(prop)) {\n // we replace the computed style string with a template function\n // this way we generate the template function once instead of\n // every time. We also try to parse it as a number or bool here\n\n var res;\n if (typeof (res = tryNumber(collapsed[prop])) == \"Number\") \n collapsed[prop] = res;\n\n else if (typeof (res = tryBoolean(collapsed[prop])) == \"Boolean\") \n collapsed[prop] = res;\n\n else if (typeof(collapsed[prop]) == \"string\") {\n collapsed[prop] = _.template(collapsed[prop]);\n collapsed[prop].__templatefn = true; // mark it as a template function\n }\n }\n\n resolveMemo[memoKey] = collapsed;\n }\n\n var styles = {};\n apply(styles, collapsed);\n \n if (_) {\n var computedVars = {};\n apply(computedVars, params);\n apply(computedVars, properties);\n for (var ii in styles) \n if (styles[ii] && styles[ii].__templatefn) {\n try {\n styles[ii] = styles[ii](computedVars);\n // remove \"\"\n if (styles[ii][0] == '\"') styles[ii] = styles[ii].slice(1, -1);\n if (styles[ii][0] == \"'\") styles[ii] = styles[ii].slice(1, -1);\n }\n\n catch (e) {\n Ti.API.debug(\"Template error in template for \" + ii + \" type \" + type + \":\");\n Ti.API.debug(e);\n }\n }\n }\n\n return styles;\n}",
"function resolveWithNode(rnStyleNext, node) {\n function getDeclaration(className) {\n return lookup.byClassName[className] || createStyleResolver_emptyObject;\n }\n\n var _getDOMStyleInfo = getDOMStyleInfo(node),\n rdomClassList = _getDOMStyleInfo.classList,\n rdomStyle = _getDOMStyleInfo.style; // Convert the DOM classList back into a React Native form\n // Preserves unrecognized class names.\n\n\n var _rdomClassList$reduce = rdomClassList.reduce(function (styleProps, className) {\n var _getDeclaration = getDeclaration(className),\n prop = _getDeclaration.prop,\n value = _getDeclaration.value;\n\n if (prop) {\n styleProps.style[prop] = value;\n } else {\n styleProps.classList.push(className);\n }\n\n return styleProps;\n }, {\n classList: [],\n style: {}\n }),\n rnClassList = _rdomClassList$reduce.classList,\n rnStyle = _rdomClassList$reduce.style; // Create next DOM style props from current and next RN styles\n\n\n var _resolve = resolve([StyleSheet_i18nStyle(rnStyle), rnStyleNext]),\n rdomClassListNext = _resolve.classList,\n rdomStyleNext = _resolve.style; // Final className\n // Add the current class names not managed by React Native\n\n\n var className = classListToString(rdomClassListNext.concat(rnClassList)); // Final style\n // Next class names take priority over current inline styles\n\n var style = createStyleResolver_objectSpread({}, rdomStyle);\n\n rdomClassListNext.forEach(function (className) {\n var _getDeclaration2 = getDeclaration(className),\n prop = _getDeclaration2.prop;\n\n if (style[prop]) {\n style[prop] = '';\n }\n }); // Next inline styles take priority over current inline styles\n\n Object.assign(style, rdomStyleNext);\n return {\n className: className,\n style: style\n };\n }",
"static resolveStyle(style, definitions, contextLogger) {\n if (Theme_1.isJsonExprReference(style)) {\n // expand and instantiate references to style definitions.\n const def = definitions && definitions[style[1]];\n if (!def) {\n contextLogger.warn(`invalid reference '${style[1]}' - not found`);\n return undefined;\n }\n if (!Theme_1.isActualSelectorDefinition(def)) {\n contextLogger.warn(`invalid reference '${style[1]}' - expected style definition`);\n return undefined;\n }\n // instantiate the style\n style = harp_utils_1.cloneDeep(def);\n }\n style = style;\n if (Array.isArray(style.when)) {\n contextLogger.pushAttr(\"when\");\n const resolvedWhen = this.resolveExpressionReferences(style.when, definitions, contextLogger);\n contextLogger.pop();\n if (resolvedWhen === undefined) {\n return undefined;\n }\n style.when = resolvedWhen;\n }\n if (style.attr !== undefined) {\n const attr = style.attr;\n contextLogger.pushAttr(\"attr\");\n for (const prop in attr) {\n if (!attr.hasOwnProperty(prop)) {\n continue;\n }\n const value = attr[prop];\n if (!Array.isArray(value)) {\n continue; // nothing to do\n }\n contextLogger.pushAttr(prop);\n const resolvedValue = this.resolveExpressionReferences(value, definitions, contextLogger);\n contextLogger.pop();\n if (resolvedValue !== undefined) {\n attr[prop] = resolvedValue;\n }\n else {\n delete attr[prop];\n }\n }\n contextLogger.pop();\n }\n return style;\n }",
"applyStyles() {\n if (this.options.styles === {}) return;\n if (this.options.styles.domField) {\n let s = '';\n let styles = this.options.styles.domField;\n let element = document.getElementById('domField');\n for (let prop in styles) {\n let key = prop.replace(\"_\", \"-\");\n s = s + `${key}: ${styles[prop]}; `;\n }\n element.style = s;\n }\n if (this.options.styles.node) {\n let s = '';\n let styles = this.options.styles.node;\n let element = document.getElementById('node');\n for (let prop in styles) {\n let key = prop.replace(\"_\", \"-\");\n s = s + `${key}: ${styles[prop]}; `;\n }\n element.style = s;\n }\n if (this.options.styles.cursor) {\n let s = '';\n let styles = this.options.styles.cursor;\n let element = document.getElementById('cursor');\n for (let prop in styles) {\n let key = prop.replace(\"_\", \"-\");\n s = s + `${key}: ${styles[prop]}; `;\n }\n element.style = s;\n }\n return this;\n }",
"function wrapStyle(style) {\n Object.getOwnPropertyNames(style).forEach((attr) => {\n const v = style[attr];\n if (v instanceof AttrReference) {\n wrapAttrRef(style, attr, v);\n } else if (isPlainObject(v)) {\n wrapStyle(v);\n }\n });\n\n return style;\n}",
"_resolveStyleIfNeeded(style, options, key) {\n const dir = I18nManager.isRTL ? 'rtl' : 'ltr';\n if (key) {\n if (!this.cache[dir][key]) {\n // slow: convert style object to props and cache\n this.cache[dir][key] = this._resolveStyle(style, options);\n }\n return this.cache[dir][key];\n }\n return this._resolveStyle(style, options);\n }",
"function resolveWithNode(rnStyleNext, node) {\n function getDeclaration(className) {\n return lookup.byClassName[className] || emptyObject;\n }\n\n var _getDOMStyleInfo = getDOMStyleInfo(node),\n rdomClassList = _getDOMStyleInfo.classList,\n rdomStyle = _getDOMStyleInfo.style; // Convert the DOM classList back into a React Native form\n // Preserves unrecognized class names.\n\n\n var _rdomClassList$reduce = rdomClassList.reduce(function (styleProps, className) {\n var _getDeclaration = getDeclaration(className),\n prop = _getDeclaration.prop,\n value = _getDeclaration.value;\n\n if (prop) {\n styleProps.style[prop] = value;\n } else {\n styleProps.classList.push(className);\n }\n\n return styleProps;\n }, {\n classList: [],\n style: {}\n }),\n rnClassList = _rdomClassList$reduce.classList,\n rnStyle = _rdomClassList$reduce.style; // Create next DOM style props from current and next RN styles\n\n\n var _resolve = resolve([(0, _i18nStyle.default)(rnStyle), rnStyleNext]),\n rdomClassListNext = _resolve.classList,\n rdomStyleNext = _resolve.style; // Final className\n // Add the current class names not managed by React Native\n\n\n var className = classListToString(rdomClassListNext.concat(rnClassList)); // Final style\n // Next class names take priority over current inline styles\n\n var style = _objectSpread({}, rdomStyle);\n\n rdomClassListNext.forEach(function (className) {\n var _getDeclaration2 = getDeclaration(className),\n prop = _getDeclaration2.prop;\n\n if (style[prop]) {\n style[prop] = '';\n }\n }); // Next inline styles take priority over current inline styles\n\n Object.assign(style, rdomStyleNext);\n return {\n className: className,\n style: style\n };\n }",
"function getStylesAtOffset(inlineStyles, offset) {\n var styles = {};\n\n if (inlineStyles.COLOR[offset]) {\n styles.COLOR = inlineStyles.COLOR[offset];\n }\n\n if (inlineStyles.BGCOLOR[offset]) {\n styles.BGCOLOR = inlineStyles.BGCOLOR[offset];\n }\n\n if (inlineStyles.FONTSIZE[offset]) {\n styles.FONTSIZE = inlineStyles.FONTSIZE[offset];\n }\n\n if (inlineStyles.FONTFAMILY[offset]) {\n styles.FONTFAMILY = inlineStyles.FONTFAMILY[offset];\n }\n\n if (inlineStyles.UNDERLINE[offset]) {\n styles.UNDERLINE = true;\n }\n\n if (inlineStyles.ITALIC[offset]) {\n styles.ITALIC = true;\n }\n\n if (inlineStyles.BOLD[offset]) {\n styles.BOLD = true;\n }\n\n if (inlineStyles.STRIKETHROUGH[offset]) {\n styles.STRIKETHROUGH = true;\n }\n\n if (inlineStyles.CODE[offset]) {\n styles.CODE = true;\n }\n\n if (inlineStyles.SUBSCRIPT[offset]) {\n styles.SUBSCRIPT = true;\n }\n\n if (inlineStyles.SUPERSCRIPT[offset]) {\n styles.SUPERSCRIPT = true;\n }\n\n return styles;\n }",
"function getStylesAtOffset(inlineStyles, offset) {\n var styles = {};\n if (inlineStyles.COLOR[offset]) {\n styles.COLOR = inlineStyles.COLOR[offset];\n }\n if (inlineStyles.BGCOLOR[offset]) {\n styles.BGCOLOR = inlineStyles.BGCOLOR[offset];\n }\n if (inlineStyles.FONTSIZE[offset]) {\n styles.FONTSIZE = inlineStyles.FONTSIZE[offset];\n }\n if (inlineStyles.FONTFAMILY[offset]) {\n styles.FONTFAMILY = inlineStyles.FONTFAMILY[offset];\n }\n if (inlineStyles.UNDERLINE[offset]) {\n styles.UNDERLINE = true;\n }\n if (inlineStyles.ITALIC[offset]) {\n styles.ITALIC = true;\n }\n if (inlineStyles.BOLD[offset]) {\n styles.BOLD = true;\n }\n if (inlineStyles.STRIKETHROUGH[offset]) {\n styles.STRIKETHROUGH = true;\n }\n if (inlineStyles.CODE[offset]) {\n styles.CODE = true;\n }\n if (inlineStyles.SUBSCRIPT[offset]) {\n styles.SUBSCRIPT = true;\n }\n if (inlineStyles.SUPERSCRIPT[offset]) {\n styles.SUPERSCRIPT = true;\n }\n return styles;\n}",
"function _mergeStyles(styles) {\n var styleProp = {};\n\n styles.forEach(style => {\n if (!style || typeof style !== 'object') {\n return;\n }\n\n var styleObj = style; // flow :(\n\n Object.keys(styleObj).forEach(name => {\n if (name.indexOf(':') === 0) {\n styleProp[name] = styleProp[name] || {};\n Object.assign(styleProp[name], styleObj[name]);\n } else {\n styleProp[name] = styleObj[name];\n }\n });\n });\n\n return styleProp;\n}",
"getStyles() {\n if (this.props.styles) {\n return {\n style: [styles.style, this.props.styles.style],\n textStyle: [textStyles.buttonText, this.props.styles.textStyle],\n backdropStyle: [styles.backdropStyle, this.props.styles.backdropStyle],\n optionListStyle: [styles.optionListStyle, this.props.styles.optionListStyle],\n }\n } else {\n return styles\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
readonly attribute boolean canSubscribe; | get canSubscribe()
{
return true;
} | [
"get isSubscribed(): boolean {\n return this._rawEvent.event === 'subscribed';\n }",
"get isSubscribed() {\r\n return this.subTypes.includes('message_allow');\r\n }",
"get isSubscribed() {\n return this._rawEvent.event === 'subscribed';\n }",
"get _isSubscribed() {\n return this._subscription != null;\n }",
"get isSubscribeActive() {\n return !this._receiverHelper.isSuspended();\n }",
"setSubscribed() {\n this.currentState = gpState.SUBSCRIBED;\n }",
"isSubscribed() {\n return this.accessToken.get() !== null;\n }",
"get isUbsubscribed() {\r\n return this.subTypes.includes('message_deny');\r\n }",
"supportsSubscriptions() {\n return false;\n }",
"function Subscribable() {\n }",
"canSubscribe() {\n try {\n return new Promise((resolve) => {\n try {\n const status = localStorage.getItem(KEY_SUBSCRIPTION_STATUS);\n const sessionStatus = sessionStorage.getItem(KEY_SUBSCRIPTION_STATUS);\n if (\n status !== SUBSCRIPTION_STATUS.DENIED &&\n status !== SUBSCRIPTION_STATUS.UNSUBSCRIBED &&\n status !== SUBSCRIPTION_STATUS.PENDING &&\n sessionStatus !== SUBSCRIPTION_STATUS.DENIED\n ) {\n resolve(status || true);\n } else {\n resolve(false);\n }\n } catch (e) {\n resolve(true);\n }\n });\n } catch (err) {\n return Promise.resolve(true);\n }\n }",
"supportsSubscriptions() {\n\t\treturn true;\n\t}",
"function Subscribable() {\n }",
"function isSubscribable(obj) {\n return !!obj && typeof obj.subscribe === 'function';\n}",
"getSubscribe() {\n return {\n supportedModes: ['polling']\n }\n }",
"function isSubscribable(obj) {\n return !!obj && typeof obj.subscribe === 'function';\n}",
"getSubscribe() {\n return {\n supportedModes: ['postbackUrl', 'polling']\n }\n }",
"get isBroadcast() {\r\n return this.checkBooleanInProperty('live');\r\n }",
"get producerUpdatesAllowed() {\n return activeConsumer?.consumerAllowSignalWrites !== false;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add more space for schedule. | function addMore() {
var new_div = document.createElement('div');
new_div.appendChild(create_checkbox('Sun'));
new_div.appendChild(create_checkbox('Mon'));
new_div.appendChild(create_checkbox('Tue'));
new_div.appendChild(create_checkbox('Wed'));
new_div.appendChild(create_checkbox('Thur'));
new_div.appendChild(create_checkbox('Fri'));
new_div.appendChild(create_checkbox('Sat'));
index++;
new_div.appendChild(create_time('start'));
var span = document.createElement('span');
span.appendChild(document.createTextNode('to'));
new_div.appendChild(span);
new_div.appendChild(create_time('end'));
var schedule = document.getElementById('schedule');
schedule.insertBefore(new_div, document.getElementById('add-btn'));
} | [
"function showMoreSchedules() {\n\t\tdisplayNextSchedules(10);\n\t}",
"addNewSchedule() {\n var length = this.schedules.length;\n this.schedules.push({\n groupId: this.id,\n start: 0,\n end: 0,\n heatingOn: false,\n waterOn: false,\n monday: false,\n tuesday: false,\n wednesday: false,\n thursday: false,\n friday: false,\n saturday: false,\n sunday: false\n });\n this.editSchedule(length, true);\n }",
"function addSchedule(date, line, direction, stop, schedule) {\n\t\t// update stop set by line\n\t\n\t\n\t\t// update schedule of a line, stop\n\t}",
"function drawScheduleHeight() {\n\tvar $schHeight = $('.schedule').height();\n\t$schHeight += 22; //hard coded yes, can be fixed later... \n\t$('.schedule').height($schHeight);\n}",
"function createTimeSlots(){\n\tfor(var i = 0; i <= 6; ++i){\n\t\tfor (var j = 8; j < 24; ++j){\n\t\t\tdb.run(`insert into timeslots (day, startTime, endTime) values (?, ?, ?)`, [i, j, j+1]);\n\t\t}\n\t}\n}",
"function updateSchedule() {\n // clear all textblocks\n $(\"textarea\").empty();\n // check the time and formatting]\n styleSchedule(startHr, endHr);\n // insert the text items\n // i is the id of the textarea associated\n // with each hour on the schedule\n for (i = startHr; i <= endHr; i++) {\n indx = i - startHr;\n var nextEl = $(`#${i}`);\n nextEl.text(scheduleList[indx].task);\n }\n }",
"function addPlannerRows(){\n\n const schedule = $(\".schedule\");\n\n for(i = 0; i <= 24; i++){\n\n schedule.append(drawHourRow(i));\n }\n }",
"function addNewSlot(){\n var slot = $('.js-slot:last-child').clone().empty();\n $timeline.append(slot);\n }",
"function addCourseToSchedule(courseToAdd) {\n \n }",
"function realignScheduleItems_forTerm(iTerm) {\n $(\"#term-\"+iTerm+\" div.ui-schedule-events li\").each(function() {\n var aStartTime = $(this).data(\"start\").split(\":\");\n var aEndTime = $(this).data(\"end\").split(\":\");\n \n var nStartTime = parseInt(aStartTime[0]) + parseInt(aStartTime[1]) / 60;\n var nEndTime = parseInt(aEndTime[0]) + parseInt(aEndTime[1]) / 60;\n \n var nDuration = nEndTime - nStartTime;\n var nHeight = nDuration * 50 - 4;\n \n var nYPos = (nStartTime - 8) * 50 + 50;\n \n $(this).css(\"top\", nYPos + \"px\");\n $(this).css(\"height\", nHeight + \"px\");\n });\n\t}",
"function displaySchedules() {\n\t\tclearSchedules();\n\t\t\n\t\tdisplayNextSchedules(10);\n\t}",
"static async addSchedule(req, res) {}",
"function addBreak() {\n setBreakTime(prevTime => prevTime < 15 ? prevTime + 1 : prevTime);\n }",
"function dayPlan (hours, tasks, duration){\n var schedule = [];\n var numBreaks = tasks - 1;\n var breakLength = Math.round((hours * 60 - tasks * duration) / numBreaks);\n if (tasks * duration > hours * 60) {\n schedule = \"You're not sleeping tonight!\"\n } else {\n for (var i = 1; i <= tasks; i++){\n schedule.push(duration, breakLength)\n }\n schedule.pop();\n }\n return schedule;\n}",
"enterPreciseSchedule(ctx) {\n\t}",
"function addTaskToSlot(task) {\n // If the task is not in list already\n if (data.times[data.timeSlot].tasks.indexOf(task) === -1) {\n var slot = data.times[data.timeSlot];\n slot.tasks.push(task);\n \n var length = data.times[data.timeSlot].tasks.length - 1;\n slot.tasks[length].schedule = data.timeSlot;\n }\n }",
"_allocateSpaceOnLine() {\n this.lines[this.y] += \" \".repeat(Math.max(0, this.x - this.lines[this.y].length));\n }",
"function addEvent() {\n var start = selectedIntValue(document.getElementById('time')),\n end = selectedIntValue(document.getElementById('duration'));\n \n end = Math.min(start + end, 720);\n events.push({start: start, end: end, id: lastId++});\n\n CalendarView.displayEvents(events);\n }",
"function genSchedule(day) {\n var startMins = 490; //8:10 AM\n var endMins = 1410; //11:30 PM\n for (var i = 0; i < ctrlThis.selectedActivities.length; i++) {\n var t = ctrlThis.selectedActivities[i].times[day].split('/')[0];\n if (t==\"-1:00\") continue;\n var tmp = timeToMins(t);\n if (tmp < startMins) startMins = tmp;\n }\n //tms is what we'll build on to generate the schedule - we'll pad it first with dummy events to handle edge cases\n var tms = [{ name: \"wakeup\", offsets: [0, 0], superCategory: \"\" }, { name: \"bedtime\", offsets: [endMins, endMins], superCategory: \"\" }];\n var flexTms = [];\n for (var i = 0; i < ctrlThis.selectedActivities.length; i++) {\n //times contains the start and end times of this activity on this day\n var times = ctrlThis.selectedActivities[i].times[day].split('/');\n if (times[0] == '-1:00') {\n //if the activity contains a duration, add it in later to give scheduled activities their slots\n if (times[1] == '0:00' || times[1] == '00:00') continue;\n flexTms.push({ name: ctrlThis.selectedActivities[i].name, duration: timeToMins(times[1]), superCategory: ctrlThis.selectedActivities[i].superCategory });\n continue;\n }\n var leftOffset = timeToMins(times[0]) - startMins;\n var rightOffset = timeToMins(times[1]) - startMins;\n //start later to avoid scheduling anything before the day starts\n //the nature of splicing prevents us from scheduling after the day ends\n for (var j = 1; j < tms.length; j++) {\n if (tms[j - 1].offsets[1] <= leftOffset && tms[j].offsets[0] >= rightOffset) {\n tms.splice(j, 0, { name: ctrlThis.selectedActivities[i].name, offsets: [leftOffset, rightOffset], superCategory: ctrlThis.selectedActivities[i].superCategory });\n break;\n }\n if ((tms[j - 1].offsets[1] <= leftOffset && tms[j].offsets[0] >= leftOffset) || (tms[j].offsets[0] <= leftOffset && tms[j].offsets[1] >= rightOffset)) {\n //the schedule is impossible due to conflict between the end of this activity and the start of the next one (TODO)\n return { err: \"Error: Conflict between \" + ctrlThis.selectedActivities[i].name + \" and \" + tms[j].name };\n }\n if (tms[j - 1].offsets[1] <= rightOffset && tms[j].offsets[0] >= rightOffset) {\n //the schedule is impossible due to conflict between the start of this activity and the end of the previous one (TODO)\n return { err: \"Error: Conflict between \" + ctrlThis.selectedActivities[i].name + \" and \" + tms[j - 1].name };\n }\n }\n }\n //now that we've inserted all firmly scheduled activities, start building in the flexible ones\n for (var i = 1; i < tms.length; i++) {\n if (flexTms.length == 0) break;\n var lastEnded = tms[i - 1].offsets[1];\n var openTime = tms[i].offsets[0] - lastEnded;\n //don't schedule parts of an activity in a period of less than 10 minutes between other activities\n if (openTime < 10) continue;\n if (openTime >= flexTms[0].duration) {\n tms.splice(i, 0, { name: flexTms[0].name, offsets: [lastEnded, lastEnded + flexTms[0].duration], superCategory: flexTms[0].superCategory });\n flexTms.shift();\n continue;\n }\n //openTime can only make a dent in flexTms, so add it in to the schedule and subtract it out from flexTms\n tms.splice(i, 0, { name: flexTms[0].name, offsets: [lastEnded, tms[i].offsets[0]], superCategory: flexTms[0].superCategory });\n flexTms[0].duration -= openTime;\n }\n //if flexTms.length != 0, the schedule is impossible, so throw an error\n if (flexTms.length != 0) {\n return { err: \"Error: you don't have enough time in the day for all your activities!\" };\n }\n\n //tms now contains a complete schedule, but we need an object with offsets rescaled to fit the div and empty divs {color, width}\n var retVal = [];\n //90.0 is 90% of the viewscreen width - the width of the day bar's div\n var viewRatio = 90.0 / (endMins - startMins);\n var freeTime = endMins - startMins;\n\n //create an object representing time consumed and initialize it to contain zeroes\n var consumed = {};\n for (var key in ctrlThis.categories) { consumed[key] = \"0:00\"; }\n\n for (var i = 1; i < tms.length; i++) {\n if (tms[i].offsets[0] > tms[i - 1].offsets[1]) {\n //add in a blank div for padding\n retVal.push({ color: \"white\", width: (viewRatio * (tms[i].offsets[0] - tms[i - 1].offsets[1])).toFixed(2).toString() + 'vw' });\n }\n if (i != tms.length - 1) {\n var taken = tms[i].offsets[1] - tms[i].offsets[0];\n retVal.push({ name: tms[i].name, width: (viewRatio * (tms[i].offsets[1] - tms[i].offsets[0])).toFixed(2).toString() + 'vw' });\n if (tms[i].superCategory) consumed[tms[i].superCategory] = minsToTime(timeToMins(consumed[tms[i].superCategory]) + taken);\n freeTime -= taken;\n }\n }\n return {\n displayBarInfo: retVal,\n \"freeTime\": Math.floor(freeTime / 60) + \" hours, \" + freeTime % 60 + \" minutes\",\n \"timeConsumed\": consumed,\n start: startMins,\n end: endMins\n };\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Navigate to the settings page | function navigateToSettings() {
//initializeSettingsFields();
$.mobile.changePage("#setting_dialog", {
role : "dialog",
allowSamePageTransition : true
});
} | [
"function gotoSettings() {\n navigation.navigate('settingsScreen');\n }",
"openSettingsPage() {\n cy.visit(this.#settingURL)\n }",
"function goToSettings() {\n window.location.href = \"settings.html\";\n}",
"function openSettingsPage() {\n let winid = browser.windows.getCurrent({populate: true});\n // close settings tab, if open\n winid.then(isSettingsOpen)\n .then(function(res) {\n if (res == true) {\n browser.tabs.remove([g_lastTabId]);\n }\n });\n // in parallel\n // open new settings tab next to current tab\n winid.then(getCurrentTab)\n .then(function(index) {\n let tabcfg = {\n active: true,\n index: index + 1,\n url: g_optionsURL\n };\n browser.tabs.create(tabcfg)\n .then(function(tab) {\n g_lastTabId = tab.id;\n }, onError);\n }, onError);\n }",
"function settings(){\n window.location = \"./settings.html\";\n}",
"function _settings_page() {\n}",
"handleSettings() {\n this.handleError();\n\n HashNavigation.navigateTo(HashNavigation.setUrlSidePanel(window.location.hash,\n this.state.myUserId ? 'edit' : 'settings'));\n }",
"settingsPage() {\r\n Actions.settingsPage()\r\n }",
"function displaySettings() {\n // TODO functionality to parse and display settings\n // This function interacts with SettingsView to display the page with appropriate data\n}",
"function openSettingsPage(params) {\n if (params) {\n chrome.storage.local.set({ openSettingsPageParam: params }, function () {\n chrome.runtime.openOptionsPage();\n });\n } else {\n chrome.runtime.openOptionsPage();\n }\n return;\n}",
"function GoSetting() {\n Global.change_pg(now_page, setting_page_id);\n Global.set_last_page(now_page);\n Global.set_now_page(setting_page_id);\n}",
"function showSettings(){\r\n\t\tshowModal('settingsScreen');\r\n\t\tesc = closeSettings;\r\n\t}",
"function navigateToSettings(e) {\n return CardService.newUniversalActionResponseBuilder()\n .displayAddOnCards(\n [buildSettingsCard()])\n .build();\n}",
"function settings(e) {\n e.detail.applicationcommands = {\n \"divAccount\": { href: \"accountSettings.html\", title: \"Account\" },\n \"divPrivacy\": { href: \"privacySettings.html\", title: \"Privacy\" },\n };\n WinJS.UI.SettingsFlyout.populateSettings(e);\n }",
"function switchToSettingsUI() {\r\n\t\t\tif (urlViewerWindow) {\r\n\t\t\t\twindow.nativeWindow.activate();\r\n\t\t\t\turlViewerWindow.close();\r\n\t\t\t}\r\n\t\t}",
"function handleClick() {\n\tdocument.getElementById(\"settings_button\").addEventListener(\"click\", function () {\n\t\twindow.location.href = \"settings.html\"; //Redirect to settings page\n\t});\n}",
"function HomePageSettings() {}",
"function openSettingsTab() {\n\tvar settingsTabs = utils.getTabsFromURL(data.url('panels/settings.html'));\n\tif(settingsTabs.length === 0) {\n\t\ttabs.open(data.url('panels/settings.html'));\n\t} else {\n\t\tsettingsTabs[0].activate();\n\t}\n}",
"handleRedirectToAccoutingSettings() {\n // For testing purposes\n alert(\"Redirecting to Account Settings...oops we don't have an account settings page\");\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set scene and rewire render loop for scene | set scene(val) {
if (this.scene) {
//console.log(this.engine, this.name);
}
if (this._scene && this._scene._engine) {
this._scene._engine.stopRenderLoop();
}
this._scene = val;
this._scene._engine.runRenderLoop( () => this.tick() );
} | [
"function renderLoop() {\r\n requestAnimFrame(renderLoop);\r\n drawScene();\r\n}",
"function scene_init() {\n\tscene_render();\n\tscene_activate();\n}",
"function render()\n {\n sceneManager.render();\n }",
"static updateScene() { if (this._scene) this._updateExistingScene(); }",
"function renderScene(){\r\n\trenderer.render(scene, camera);\r\n}",
"runScene(scene) {\n for (const param of scene.values) {\n if (param.type === \"static\") {\n this.runStaticScene(param)\n } else if (param.type === \"animation\") {\n this.runAnimationScene(param)\n } else if (param.type === \"script\") {\n this.runScriptScene(param)\n }\n }\n\n this.activeScenes.push(scene.id)\n }",
"setScene(scene) {\n if (scene !== this.scene) {\n if (this.scene) {\n this.deactivate();\n }\n this.scene = scene;\n if (scene) {\n this.activate();\n }\n this.forEachChild(node => node.setScene(scene));\n }\n }",
"function renderScene() {\n if (m_initialized === false) {\n initScene();\n }\n m_viewer.render();\n }",
"render() {\n if (this.currentScene) {\n this.currentScene.render();\n }\n }",
"function render() {\n var now = Date.now();\n sceneContainer.render(now);\n}",
"update()\n {\n this.scenes[this.currentScene].render(true);\n }",
"startScene() {\n console.log('[Game] startScene');\n var that = this;\n\n if (this.scene) {\n console.log('[Game] loading scene');\n this.scene.load().then(() => {\n console.log('[Game] Scene', that.scene.name, 'loaded: starting run & render loops');\n // setTimeout(function() {\n debugger;\n that.scene.start();\n debugger;\n that._runSceneLoop();\n that._renderSceneLoop();\n // }, 0);\n });\n } else {\n console.log('[Game] nothing to start: no scene selected!!');\n }\n }",
"setScene (scene) {\n this.scene = scene\n }",
"setScene(scene) {\n this.scene = scene;\n }",
"static _setScene(node) {\n node._updateScene();\n }",
"changeScene(sceneName) {\n this.currentScene.stop();\n\n /* Setup new scene */\n this.currentScene = this.scenes[sceneName].scene;\n this.application.renderer.backgroundColor = this.scenes[sceneName].backgroundColor;\n this.currentScene.start();\n this.application.stage = this.currentScene.stage;\n }",
"setupScene() {\n this.scene = new Scene();\n }",
"setupScenes() {\n this.scenes = [];\n this.scene = new THREE.Scene();\n this.scenes.push(this.scene);\n }",
"playScene(scene) {\n this.fireMaxData('live_set scenes ' + scene);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes a talent point from talents | function removePoint(talentId, talents, details, talentDetails) {
var row = talentDetails[talentId].row,
tree = talentDetails[talentId].tree,
lastActiveRow = details[tree].lastActiveRow;
// need to have points in there to remove it
if (talents[talentId] <= 0)
return false;
// check it talent is prequisite for any talents down the road we chose
if (talentDetails[talentId].allows) {
for (var i=0; i < talentDetails[talentId].allows.length; i+=1) {
if (talents[talentDetails[talentId].allows[i]] > 0)
return false;
}
}
// check if talents further down the tree depend on this talent
if (row != lastActiveRow) {
var i = 0;
while (lastActiveRow - i > row) {
if (sumRows(lastActiveRow - i, details[tree].row) <= (lastActiveRow - i) * 5)
return false;
i += 1;
}
}
// update associated variables
talents[talentId] -= 1;
details[tree].row[row] -= 1;
details[tree].total -= 1;
details.remaining += 1;
if (row == lastActiveRow && details[tree].row[row] == 0)
details[tree].lastActiveRow -= 1;
return true;
} | [
"function removePoint() {\n var pointRemoved = talentHelper.removePoint(scope.talentId, scope.talentsSpent, scope.talentsSpentDetails, scope.talentDetails);\n update(pointRemoved);\n }",
"function remove_point(point) {\n\tpoint.map_point.setMap(null);\n\tdelete spawned_points[point.index];\n\tvisible_points--;\n}",
"removePoint() {\n this.points -= 1;\n this.updateScore();\n }",
"removePoint() {\n const i = this.pointObjects.indexOf(this.selectedPoint);\n this.splinePoints.splice(i, 1);\n this.deselectPoint();\n this.updateTrajectory();\n }",
"function removeFacetChoice(type, target) {\n\t execForMatchingChoice(target.slice(), type, removeFacet);\n\t\n\t function removeFacet(facet) {\n\t target.splice(target.indexOf(facet), 1);\n\t }\n\t }",
"function removeTeammate(teammate){\n\tif(selectedAnimal == teammate){\n\t\tdeselectAnimal(teammate);\n\t}\n\tfor(var i=0;i<numTeammates();i++){\n\t\tif(team[i].hash == teammate.hash){\n\t\t\tteam.splice(i,1);\n\t\t}\n\t}\n}",
"remove_tetramino() {\n this.tetraminoes.get_points().forEach( p => {\n this.free_blocks[p[1]][p[0]] = [0, null]\n })\n }",
"function removeSavedTalent(id) {\n for (var key in savedTalents) {\n if (savedTalents[key].id === id) {\n savedTalents.splice(key, 1);\n }\n }\n }",
"removePoint(p) {\n p.mean = null\n this.x_sum -= p.x\n this.y_sum -= p.y\n this.amount--\n }",
"function deleteTemp(e, t) {\n\t\tsetInput((prev) => ({ ...prev, temperament: prev.temperament.filter((temp) => temp !== parseInt(t)) }));\n\t}",
"function removeSkill(mentors,newSkill){\r\n return mentors.forEach(skill => skill.skills.splice(skill.skills.indexOf(newSkill),1));\r\n //your code here\r\n}",
"delete() {\n this.points.pop()\n }",
"removeAnt(ant) {\n const index = this.ants.findIndex((findAnt) => { return findAnt === ant; });\n if (index !== -1)\n this.ants.splice(index);\n }",
"function removePoints () {\n self.points = undefined;\n }",
"function removePoint() {\n if(point) {\n point.style.display = \"none\";\n }\n }",
"function removePoint(id) {\n for( var i=0; i<points.length; i++){ \n if ( points[i].id === id) { points.splice(i,1); }\n }\n}",
"function removePellet(pellet){\r\n\tupdateScore();\r\n\tif(pellet.getAttribute('class') == 'pellet'){\r\n\tcontainer.removeChild(pellet);\r\n\t--pelletCount;\r\n\t}\r\n}",
"function removeSkill(mentors,newSkill){\n mentors.forEach(mentor => mentor.skills.remove(newSkill))\n}",
"removeFromCombat() {\n if (!this.isInCombat()) {\n return;\n }\n\n for (const combatant of this.combatants) {\n this.removeCombatant(combatant);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method, that returns promise, that returns Model instance with 'this.url' URI, if api query was successful. | get() {
if(this.cache) {
return Promise.resolve(this.cache);
}
return this.formQueryAndSend('get').then(response => {
let instance = this.model.getInstance(response.data, this);
let prefetch_fields = this._getPrefetchFields();
// if prefetch fields exist, loads prefetch data.
if(prefetch_fields && prefetch_fields.length > 0) {
return this._loadPrefetchData(prefetch_fields, [instance]).then(() => {
this.cache = instance;
return instance;
});
}
// otherwise, returns instance.
this.cache = instance;
return instance;
}).catch(error => {
debugger;
throw error;
});
} | [
"async fetchResource() {\n if (!this.id || this.type === 'url' || !this.type) {\n // No fetch required\n return this.getResource();\n }\n\n // Fetch model\n const model = await this.#urlTranslator.getResourceById(this.id, this.type, {absolute: true});\n return this.getResource(model);\n }",
"async getExistingModel () {\n\t\tconst queryData = this.checkExistingQuery();\n\t\tif (!queryData) {\n\t\t\t// derived class doesn't care\n\t\t\treturn;\n\t\t}\n\t\t// look for a matching document, according to the query\n\t\tconst options = {\n\t\t\thint: queryData.hint\n\t\t};\n\t\treturn this.collection.getOneByQuery(queryData.query, options);\n\t}",
"resolveModel() {\n\t\tif (_.isFunction(this.service.modelResolver)) {\n\t\t\tlet idParamName = this.service.$settings.idParamName || \"id\";\n\n\t\t\tlet id = this.params[idParamName];\n\n\t\t\tif (id != null) {\n\t\t\t\treturn this.service.modelResolver.call(this.service, this, id).then( (model) => {\n\t\t\t\t\tthis.model = model;\n\t\t\t\t\treturn model;\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn Promise.resolve(null);\n\t}",
"fetch(options) {\n const privateCollection = (sd.CURRENT_USER != null ? sd.CURRENT_USER.id : undefined) === this.get('userId');\n const model = new Backbone.Model;\n model.url = this.url();\n return model.fetch({\n data: {\n user_id: this.get('userId'),\n private: privateCollection\n },\n success: response => {\n this.collectionExists = true;\n this.set(response);\n this.set({fetched: true});\n return __guardMethod__(options, 'success', o => o.success(response));\n },\n error: response => {\n this.collectionExists = false;\n this.set({fetched: true});\n return __guardMethod__(options, 'error', o => o.error(response));\n }\n });\n }",
"initModel() {\n return new Promise((resolve, reject) => {\n let myMongooseConnection = db_connections_1.myAppConnectionMap.getConnection(this.connectionName);\n if (myMongooseConnection.isInitialized()) {\n this.mongooseConnection = myMongooseConnection.currentDb();\n this.mongooseModel = myMongooseConnection.getModel(this.modelName);\n resolve(this.mongooseModel);\n }\n else {\n myMongooseConnection.openConnection()\n .then((msg) => {\n this.mongooseConnection = myMongooseConnection.currentDb();\n this.mongooseModel = myMongooseConnection.getModel(this.modelName);\n resolve(this.mongooseModel);\n })\n .catch((err) => reject(err));\n }\n });\n }",
"request() {\n this.requestUrl()\n return fetch(this.url)\n }",
"function fetchModel(url) {\n return axios.get(url)\n .then((response)=>{\n if(response.status===200){\n //console.log(response.data[0]);\n return {data:response.data};\n }else{\n throw(new Error(response.status+response.statusText));\n }\n })\n /*\n return new Promise(function(resolve, reject) {\n let xhttp= new XMLHttpRequest();\n xhttp.onreadystatechange=function(){\n if(this.readyState===4){\n if(this.status===200){\n let response=JSON.parse(this.responseText)\n resolve({data:response})\n }else{\n reject({status:this.status,\n statusText:this.statusText})\n }\n }\n }\n xhttp.open(\"GET\",url);\n xhttp.send();\n \n \n //console.log(url);\n //setTimeout(() => reject({status: 501, statusText: \"Not Implemented\"}),0);\n // On Success return:\n // resolve({data: getResponseObject});\n });\n */\n}",
"get_model(model_id) {\n // TODO: Perhaps we should return a Promise.reject if the model is not\n // found. Right now this isn't a true async function because it doesn't\n // always return a promise.\n return this._models[model_id];\n }",
"async findOne(Model, query) {\n // Get collection ID of provided Model\n const collectionId = modelCollectionId(Model);\n\n // Find single Model instance data matching provided query\n const foundValue = await this._plug.findOne(collectionId, query);\n\n // Return null if no data was found\n if (foundValue == null) {\n return null;\n }\n\n // Return Model instance constructed from fetched data\n return new Model(foundValue.object, foundValue.id);\n }",
"static fetchFromApi(endpoint, query) {\n return new Promise((resolve) => {\n // still testing\n // mock delay url : https://www.mocky.io/v2/5185415ba171ea3a00704eed?mocky-delay={}ms\n //https://immense-bastion-95607.herokuapp.com/query/\n fetch(`${endpoint}${query}`)\n .then((res) => {\n const status = res.status;\n if (status === 200) {\n return res.json();\n } else {\n UI.showAlert(\"danger\", `Connection Error : ${status}`);\n }\n })\n .then((data) => {\n resolve(data);\n })\n .catch((err) => UI.showAlert(\"danger\", err));\n });\n }",
"getData(isForcedReload = false) {\n //TODO(Igor) flushCanonical here once our syncing is not stupid\n var record = this.inverseInternalModel ? this.inverseInternalModel.getRecord() : null;\n\n if (this.shouldMakeRequest()) {\n var promise = void 0;\n\n if (this.link) {\n promise = this._fetchLink();\n } else {\n promise = this._fetchRecord();\n }\n\n promise = promise.then(() => handleCompletedFind(this), e => handleCompletedFind(this, e));\n\n promise = promise.then(internalModel => {\n return internalModel ? internalModel.getRecord() : null;\n });\n\n this.fetchPromise = promise;\n this._updateLoadingPromise(promise);\n }\n\n if (this.isAsync) {\n if (this._promiseProxy === null) {\n var _promise = proxyRecord(this.inverseInternalModel);\n this._updateLoadingPromise(_promise, record);\n }\n\n return this._promiseProxy;\n } else {\n (true && !(record === null || !record.get('isEmpty') || isForcedReload) && Ember.assert(\"You looked up the '\" + this.key + \"' relationship on a '\" + this.internalModel.modelName + \"' with id \" + this.internalModel.id + ' but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.belongsTo({ async: true })`)', record === null || !record.get('isEmpty') || isForcedReload));\n\n return record;\n }\n }",
"fetchRestaurantFromURL() {\n if (this.restaurant) { // restaurant already fetched!\n return Promise.resolve(this.restaurant);\n }\n const id = RestaurantInfo.getParameterByName('id');\n\n if (!id) { // no id found in URL\n throw new Error('No restaurant id in URL');\n } else {\n return DBHelper.fetchRestaurantById(id).then((restaurant) => {\n this.restaurant = restaurant;\n\n this.getRestaurantReviews();\n this.fillRestaurantHTML(this.restaurant);\n return this.restaurant;\n });\n }\n }",
"fetchResource(url) {\n return Resource.create(url);\n }",
"getData(options, isForcedReload = false) {\n //TODO(Igor) flushCanonical here once our syncing is not stupid\n var record = this.inverseInternalModel ? this.inverseInternalModel.getRecord() : null;\n\n if (this.shouldMakeRequest()) {\n var promise = void 0;\n\n if (this.link) {\n promise = this._fetchLink(options);\n } else {\n promise = this._fetchRecord(options);\n }\n\n promise = promise.then(() => handleCompletedFind(this), e => handleCompletedFind(this, e));\n\n promise = promise.then(internalModel => {\n return internalModel ? internalModel.getRecord() : null;\n });\n\n this.fetchPromise = promise;\n this._updateLoadingPromise(promise);\n }\n\n if (this.isAsync) {\n if (this._promiseProxy === null) {\n var _promise = proxyRecord(this.inverseInternalModel);\n this._updateLoadingPromise(_promise, record);\n }\n\n return this._promiseProxy;\n } else {\n (true && !(record === null || !record.get('isEmpty') || isForcedReload) && Ember.assert(\"You looked up the '\" + this.key + \"' relationship on a '\" + this.internalModel.modelName + \"' with id \" + this.internalModel.id + ' but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.belongsTo({ async: true })`)', record === null || !record.get('isEmpty') || isForcedReload));\n\n return record;\n }\n }",
"static loadModel() {\r\n var me = this;\r\n\r\n return new Promise((resolve, reject) => {\r\n if (!!Logicker.mnModel) {\r\n // If it's already loaded, resolve with it.\r\n this.lm('returning cached copy of model.');\r\n resolve(Logicker.mnModel);\r\n }\r\n else if (Logicker.loadingModel === true) {\r\n //this.lm('Model is loading. We will wait a the end of the promise chain.');\r\n\r\n // If it's still loading, we chain onto the promise. This way we do not double-load,\r\n // and we continue execution once it's been loaded by the first caller.\r\n Logicker.modelLoadPromiseChain.then(() => {\r\n if (!!Logicker.mnModel) {\r\n resolve(Logicker.mnModel);\r\n }\r\n else {\r\n reject('Mobilenet model came back null.')\r\n }\r\n });\r\n }\r\n else {\r\n Logicker.loadingModel = true;\r\n me.lm('Loading model...');\r\n const startTime = performance.now();\r\n\r\n Logicker.modelLoadPromiseChain =\r\n Logicker.modelLoadPromiseChain.then(() => {\r\n //return Promise.reject('No current mobilenet support');\r\n return mobilenet.load().then((mnModel) => {\r\n Logicker.mnModel = mnModel;\r\n Logicker.loadingModel = false;\r\n\r\n if (!!Logicker.mnModel) {\r\n resolve(Logicker.mnModel);\r\n }\r\n else {\r\n reject('Mobilenet model came back null.')\r\n }\r\n });\r\n });\r\n\r\n const totalTime = Math.floor(performance.now() - startTime);\r\n me.lm(`Model loaded and initialized in ${totalTime}ms...`);\r\n }\r\n });\r\n }",
"async findOne() {\n // Call internally stored DB API to return one model matching self query\n return await this._db.findOne(this._Model, this);\n }",
"async readModelFromUrl(url)\r\n {\r\n return this.readObject(url);\r\n }",
"async fetch() {\n // Reject removals of unsaved models\n if (this.isNew()) {\n throw new Error('cannot fetch unsaved model')\n }\n\n // Run before fetch hook\n await this.beforeFetch()\n\n // Get remote state and merge into itself\n var data = await this.collection.findOne(fixId({ _id: this._id }))\n extend(this, data)\n\n // Run after fetch hook\n await this.afterFetch()\n }",
"fetchModel ({dispatch, commit}, {link, params}) {\n return dispatch('request', {method: 'get', link: link + '.json', params})\n .then(\n response => {\n commit('SET_MODELS', response.data, {root: true}) // Run root mutation\n return Promise.resolve(response.data)\n }\n )\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find children for row's parent id | function children(id) {
var items = []
rows.forEach(function(r, i) {
if (skip.indexOf(i) === -1 && r[parentRef] === id) {
items.push(r)
skip.push(i)
}
})
cleanUpRows()
items.forEach(function(row) {
var id = row[parentId] || ''
row[childrenName] = children(id)
})
return items
} | [
"static async getChildren(nested=true, id=null) {\n if (typeof id != \"number\" && id !== null) throw new BadRequestError(`${id} is not an integer`)\n\n if (id){\n let {rows:[loc]} = await db.query(\n `SELECT id, name, notes, parent_id as \"parentId\"\n FROM location\n WHERE id=$1\n `,\n [id]);\n if (!loc) throw new NotFoundError(`No location: ${id}`);\n };\n\n const idQuery = id?`WHERE child.id=${id}`:\"WHERE NOT child.id IS NULL\";\n const query = `WITH RECURSIVE findchildren AS ( \n SELECT \n child.parent_id AS \"parentId\", \n child.id AS \"locationId\",\n child.name AS \"locationName\"\n FROM location AS child\n LEFT JOIN location AS parent ON child.parent_id=parent.id\n ${idQuery}\n\n UNION ALL\n\n SELECT child.parent_id,child.id, child.name\n FROM findchildren AS r\n JOIN location AS parent ON parent.id=r.\"locationId\"\n JOIN location AS child ON parent.id=child.parent_id\n )\n\n SELECT * FROM findchildren\n GROUP BY \"parentId\", \"locationId\", \"locationName\"\n ORDER BY \"parentId\" NULLS FIRST`\n const result = await db.query(query)\n if (!nested) return result.rows\n \n const recursiveLoc = (arr, targetId=null)=>{\n return arr.reduce((acc, next, idx)=>{\n if (targetId===next.parentId || next.locationId===id) {\n const children = recursiveLoc(arr.slice(idx+1), next.locationId)\n if (children.length>0) next.children=children\n return acc.concat(next)\n }\n return acc\n },[])\n\n };\n return recursiveLoc(result.rows)\n }",
"function selectParentNodes(parent_id) {\n if(parent_id > 0) {\n var parentNodes = _.where(flatten_data, {\"id\": parent_id});\n _.each(parentNodes, function(d) {\n selectParentNodes(d.parent_id);\n selected.push(d.elemNum)\n })\n } else {\n //do nothing\n }\n }",
"getChildren(parentId) {\n\n }",
"function findParentsById(id) {\n return db('parents').where({ id: id });\n}",
"collectRowsChildrenAndDirectParents(rowsToBeProcessed, visibleRowIDs) {\n const processedRowsParents = new Set();\n Array.from(rowsToBeProcessed).forEach((rowID) => {\n const rowTreeRecord = this.grid.gridAPI.get_rec_by_id(rowID);\n const rowAndAllChildren = this.get_all_children(rowTreeRecord);\n rowAndAllChildren.forEach(row => {\n if (visibleRowIDs.indexOf(row.rowID) >= 0) {\n rowsToBeProcessed.add(row.rowID);\n }\n });\n if (rowTreeRecord && rowTreeRecord.parent) {\n processedRowsParents.add(rowTreeRecord.parent);\n }\n });\n return processedRowsParents;\n }",
"GetParents(id) {\n let selected = this.FindById(id);\n if (selected) return selected.parents;\n else return null;\n }",
"function searchInOriginalMenu(children, id){\n \n for (var i = 0; i < children.length; i++) {\n \n if(children[i].id === id){\n return children[i];\n } \n if(children[i].children){\n var result = searchInOriginalMenu(children[i].children, id);\n if(result){\n return result;\n }\n } \n }\n }",
"function findChildrenByParentId(parentId, callback) {\n componentQueries.getChildrenByParentId(parentId, callback);\n}",
"get children() {\n const children = [];\n this.groupRow.records.forEach((rec, i) => {\n const row = new IgxGridRow(this.grid, this.index + 1 + i, rec);\n children.push(row);\n });\n return children;\n }",
"get parent() {\n var _a;\n const row = this.grid.getRowByKey((_a = this.treeRow.parent) === null || _a === void 0 ? void 0 : _a.rowID);\n return row;\n }",
"function getJustChildIds ( idd ) { //this function returns array of just child nodes including the envoking node at 0 location.\r\n \r\n\tvar index = -1 ; \r\n\tvar pid = -1 ; \r\n\tvar pindex = -1 ; \r\n\tq.length = 0 ; \r\n\r\n\tresetStatus ( ) ; \r\n\r\n\r\n\tq [ 0 ] = idd ; \r\n\tfor ( var i = 0 ; i < model.length ; i += 1 ) {\r\n\t \r\n\t\tif ( model [ i ] .pid === q [ 0 ] ) {\r\n\t\t \r\n\t\tq [ q.length ] = model [ i ] .id ; \r\n\t\t}\r\n\t}\r\n\r\nreturn q ; \r\n\r\n}",
"function historyListSearchChildIds (hl, id) {\r\n let record;\r\n let childIds = undefined;\r\n let hnList = hl.hnList;\r\n for (let i=hnList.length-1 ; i>= 0 ; i--) {\r\n\trecord = hnList[i];\r\n\tif ((record.id == id)\r\n\t\t&& (((childIds = record.toChildIds) != undefined) || ((childIds = record.childIds) != undefined))\r\n\t ) {\r\n\t break;\r\n\t}\r\n }\r\n return(childIds);\r\n}",
"async getChildChildren(mediaId) {\n if (!this.checkId(mediaId)) {\n console.error(\"getChildChildrenIds: Invalid entries \");\n return null;\n }\n\n var sql =\n \" SELECT * FROM `media`\" +\n \" WHERE parent_id IN (SELECT id FROM media WHERE parent_id = \" +\n mediaId +\n \")\";\n var results = await this.query(sql);\n\n return results;\n }",
"function loadChildData(rowid) {\n\t\tvar selRec = grid.getModelRecord(rowid);//current parent grid selection\n\t\tgrid.triggerHandler(\"jaduBeforeLoadChild\", [rowid,selRec]);\n\t\tvar selectionChangeFunc = grid.getGridParam('onSelectionChange');\n\t\tif(selectionChangeFunc) {\n\t\t\tselectionChangeFunc(rowid,selRec);\n\t\t}\n\t\tvar children = grid.getGridParam('hasMany');\n\t\tlog.debug(children+' loadChildData '+rowid);\n\t\tif(children && children.length > 0) {\t\t\t\n\t\t\tfor(var i=0; i < children.length; i++){\n\t\t\t\tvar child = children[i];\n\t\t\t\tchild.container.onParentChange({crudIndicator:\"selectionchange\"})\n\t\t\t\tlog.debug(\"selected record: \"+JSON.stringify(selRec));\n\t\t\t\tchild.container.loadDataForParentRecord(selRec,child);\n\t\t\t}\n\t\t}\t\n\t}",
"get children() {\n const children = [];\n if (this.treeRow.expanded) {\n this.treeRow.children.forEach((rec, i) => {\n const row = new IgxTreeGridRow(this.grid, this.index + 1 + i, rec.data);\n children.push(row);\n });\n }\n return children;\n }",
"function RbmCheckParentById(parentId,child){ \n \n //alert('parent ' + parentId);\n while(child != null){\n if(child.id == parentId) return true;\n // alert('child ' + child.id);\n child = child.parentNode;\n }\n return false;\n}",
"function getAssignedChoresParent(parentId, callback) {\n let assignedChores = [];\n knex.select(\n 'assigned_chore.id as chore_id',\n 'assigned_chore.name as chore_name',\n 'assigned_chore.description',\n 'assigned_chore.value',\n 'assigned_chore.status',\n 'child.name as child_name',\n 'child.id as child_id')\n .from('assigned_chore')\n .leftOuterJoin('child', 'child.id', 'assigned_chore.owner')\n .where('child.p_id', '=', parentId)\n .then ( function (row) {\n for (let i = 0; i < row.length; i++) {\n assignedChores.push(row[i]);\n }\n callback(null, {assigned_chores: assignedChores});\n });\n}",
"function getChildren() {\n props.loading = true;\n if (st.cacheChildren && props.children) {\n var deferred = $q.defer();\n $timeout(function() {\n deferred.resolve(props.children);\n }, 100);\n return deferred.promise;\n }\n else {\n return st.getChildren({id: row.id}).then(setChildren);\n }\n }",
"getAllChildren() {\n const children = this.jq.wrapper.find(this.jq.child)\n return children\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Balanced number is the number that The sum of all digits to the left of the middle digit(s) and the sum of all digits to the right of the middle digit(s) are equal. Task Given a number, Find if it is Balanced or not . Warmup (Highly recommended) Playing With Numbers Series Notes If the number has an odd number of digits then there is only one middle digit, e.g. 92645 has middle digit 6; otherwise, there are two middle digits , e.g. 1301 has middle digits 3 and 0 The middle digit(s) should not be considered when determining whether a number is balanced or not, e.g 413023 is a balanced number because the left sum and right sum are both 5. Number passed is always Positive . Return the result as String Input >> Output Examples 1 balancedNum (7) ==> return "Balanced" . Explanation: Since , The sum of all digits to the left of the middle digit (0) and the sum of all digits to the right of the middle digit (0) are equal , then It's Balanced 2 balancedNum (295591) ==> return "Not Balanced" . Explanation: Since , The sum of all digits to the left of the middle digits (11) and the sum of all digits to the right of the middle digits (10) are equal , then It's Not Balanced Note : The middle digit(s) are 55 . 3 balancedNum (959) ==> return "Balanced" . Explanation: Since , The sum of all digits to the left of the middle digits (9) and the sum of all digits to the right of the middle digits (9) are equal , then It's Balanced Note : The middle digit is 5 . 4 balancedNum (27102983) ==> return "Not Balanced" . Explanation: Since , The sum of all digits to the left of the middle digits (10) and the sum of all digits to the right of the middle digits (20) are equal , then It's Not Balanced Note : The middle digit(s) are 02 . | function balancedNum(number) {
let str = '' + number, num = str.length, h = num >> 1;
let sum = str => str.split('').reduce((a, b) => a + +b, 0);
return `${sum(str.slice(0, h - ((num & 1) == 0 ? 1 : 0))) != sum(str.slice(h + 1)) ? 'Not ' : ''}Balanced`;
} | [
"function balancedNum(number) {\n const str = number.toString();\n const length = str.length;\n const halfLength = Math.ceil(length /2) -1;\n const firstHalf = str.slice(0, halfLength);\n const lastHalf = str.slice(length - halfLength, length);\n const firstTotal = firstHalf.split('').reduce((prev, curr) => {\n return prev + +curr;\n }, 0);\n const lastTotal = lastHalf.split('').reduce((prev, curr) => {\n return prev + +curr;\n }, 0);\n return firstTotal === lastTotal ? \"Balanced\": \"Not Balanced\";\n}",
"function balancedNum(number)\n{\n var le = String(number).length;\n var left;\n var right;\n var half = Math.floor(le / 2);\n\n if(le === 1 || le === 2) return \"Balanced\";\n\n if(le % 2 === 0) {\n left = String(number).slice(0, half - 1).split('');\n right = String(number).slice(half + 1).split('');\n } else {\n left = String(number).slice(0, half).split('');\n right = String(number).slice(half+1).split('');\n }\n\n let totalLeft = left.reduce((total, current) => Number(total) + Number(current), 0);\n let totalRight = right.reduce((total, current) => Number(total) + Number(current), 0);\n\n if(totalLeft === totalRight) return \"Balanced\";\n return \"Not Balanced\";\n}",
"function balance(str) {\n let balanced = 0\n let answer = 0\n\n for (let i = 0; i < str.length; i++) {\n let char = str[i]\n\n if (char == '(') {\n balanced++\n } else {\n balanced--\n }\n\n if (balanced === -1) {\n answer++\n balanced++\n }\n }\n return Math.abs(answer + balanced)\n}",
"function checkBalance(bankNum) {\n\t// 1. Search bankaccount (object)\n\tlet bankAccount = searchAcctHolder(bankNum);\n\t// 2. Return balance\n\treturn formatNum(bankAccount.balance);\n}",
"function isBalanced(s) {\n\t// Write your code here\n\tconst sLength = s.length\n\tif (sLength % 2 !== 0) return 'NO'\n\tconst openBrackets = new Set(['{', '[', '('])\n\tconst stack = []\n\tconst table = {\n\t\t'}': '{',\n\t\t')': '(',\n\t\t']': '['\n\t}\n\n\tfor (let i = 0; i < sLength; i++) {\n\t\tif (openBrackets.has(s[i])) stack.unshift(s[i])\n\t\telse {\n\t\t\tconst openBracket = stack.shift()\n\t\t\tconst closeBracket = s[i]\n\t\t\tif (openBracket === table[closeBracket]) continue\n\t\t\treturn 'NO'\n\t\t}\n\t}\n\treturn stack.length === 0 ? 'YES' : 'NO'\n}",
"function balancedSums(arr) {\n\n //0 제외하고 [] 혹은 [1]같은 경우는 무조건 YES\n arr = arr.filter((el) => el > 0);\n\n let length = arr.length;\n if (length <= 1) {\n return \"YES\";\n }\n\n let total = getSumOfArray(arr);\n let leftSum = 0;\n for (let i = 1; i <= length; i++) {\n leftSum += arr[i - 1];\n if ((leftSum * 2) == (total - arr[i])) {\n return \"YES\";\n }\n }\n return \"NO\";\n}",
"function balancedSums(arr) {\n let sum=0;\n let leftSum =0;\n for(let i=0;i<arr.length;i++){\n sum+=arr[i];\n }\n for (let i = 0; i < arr.length; ++i) { \n sum -= arr[i]; // sum is now right sum for index i \n \n if (leftSum == sum) \n return \"YES\"; \n \n leftSum += arr[i]; \n } \n \n return \"NO\";\n \n}",
"function balancedSums(arr) {\n // console.log(arr);\n let leftSum = 0;\n let rightSum = 0;\n let l = 0;\n let r = arr.length - 1;\n while (l < r) {\n // console.log(\"leftSum = \" + leftSum);\n // console.log(\"rightSum = \" + rightSum);\n // console.log(\"l = \" + l);\n // console.log(\"r = \" + r);\n if (leftSum > rightSum) {\n rightSum += arr[r];\n r--;\n } else if (leftSum < rightSum) {\n leftSum += arr[l];\n l++;\n } else if (arr[l] > arr[r]) {\n rightSum += arr[r];\n r--;\n } else if (arr[l] < arr[r]) {\n leftSum += arr[l];\n l++;\n } else {\n rightSum += arr[r];\n r--;\n leftSum += arr[l];\n l++;\n }\n \n }\n // console.log(\"Final leftSum = \" + leftSum);\n // console.log(\"Final rightSum = \" + rightSum);\n // console.log(\"Final l = \" + l);\n // console.log(\"Final r = \" + r);\n if ((l == r) && (leftSum == rightSum)) {\n return \"YES\";\n } else {\n return \"NO\";\n }\n\n\n\n}",
"function checkIsBalanced() {\n var parensStr = document.getElementById('input-one');\n var inputStr = parensStr.value;\n printToScreen(isBalanced(inputStr));\n}",
"function balance(left, right){\n const count = function(side){\n let sideArr = side.split('');\n let sub = sideArr.map(l => l === '!' ? l = 2 : l = 3);\n return sub.reduce((total, el) => total += el);\n };\n if(count(left) > count(right)){\n return 'left';\n }\n else if(count(left) < count(right)){\n return 'right';\n }\n else{\n return 'balanced';\n }\n}",
"function balance(left,right){\n const totalWeight = string => {\n let weight = 0;\n for(let i = 0; i < string.length; i++) {\n switch(string[i]) {\n case '!': \n weight += 2;\n break;\n case '?': \n weight += 3;\n break;\n }\n }\n return weight;\n }\n \n let leftWeight = totalWeight(left);\n let rightWeight = totalWeight(right);\n \n return leftWeight > rightWeight ? 'Left' : leftWeight < rightWeight ? 'Right' : 'Balance';\n \n }",
"function balance(left,right){\n let rightSum = 0;\n let leftSum = 0;\n for (let i = 0; i < left.length; i++) {\n left[i] === \"!\" ? leftSum+= 2 : leftSum+= 3;\n }\n for (let i = 0; i < right.length; i++) {\n right[i] === \"!\" ? rightSum+= 2 : rightSum+= 3;\n }\n return leftSum === rightSum ? \"Balance\" : leftSum > rightSum ? \"Left\" : \"Right\";\n}",
"isBalanced() {\n let balanced = function (node) {\n if (node === null) { // Base case\n return true;\n }\n let heightDifference = Math.abs(this.findHeight(node.left) - this.findHeight(node.right));\n if (heightDifference > 1) {\n return false;\n } else {\n return balanced(node.left) && balanced(node.right);\n }\n }\n return balanced(this.root);\n }",
"function balance(formulaStr) {\n\t// Clear output\n\tsetMessage(\"\");\n\tvar balancedElem = document.getElementById(\"balanced\");\n\tvar codeOutElem = document.getElementById(\"codeOutput\");\n\tremoveAllChildren(balancedElem);\n\tremoveAllChildren(codeOutElem);\n\tappendText(\" \", codeOutElem);\n\n\t// Parse equation\n\tvar eqn;\n\ttry {\n\t\teqn = parse(formulaStr);\n\t} catch (e) {\n\t\tif (typeof e == \"string\") { // Simple error message string\n\t\t\tsetMessage(\"Syntax error: \" + e);\n\n\t\t} else if (\"start\" in e) { // Error message object with start and possibly end character indices\n\t\t\tsetMessage(\"Syntax error: \" + e.message);\n\n\t\t\tvar start = e.start;\n\t\t\tvar end = \"end\" in e ? e.end : e.start;\n\t\t\twhile (end > start && (formulaStr.charAt(end - 1) == \" \" || formulaStr.charAt(end - 1) == \"\\t\"))\n\t\t\t\tend--; // Adjust position to eliminate whitespace\n\t\t\tif (start == end)\n\t\t\t\tend++;\n\n\t\t\tappendText(formulaStr.substring(0, start), codeOutElem);\n\t\t\tvar highlight = document.createElement(\"u\");\n\t\t\tif (end <= formulaStr.length) {\n\t\t\t\tappendText(formulaStr.substring(start, end), highlight);\n\t\t\t\tcodeOutElem.appendChild(highlight);\n\t\t\t\tappendText(formulaStr.substring(end, formulaStr.length), codeOutElem);\n\t\t\t} else {\n\t\t\t\tappendText(\" \", highlight);\n\t\t\t\tcodeOutElem.appendChild(highlight);\n\t\t\t}\n\n\t\t} else {\n\t\t\tsetMessage(\"Assertion error\");\n\t\t}\n\t\treturn;\n\t}\n\n\ttry {\n\t\tvar matrix = buildMatrix(eqn); // Set up matrix\n\t\tsolve(matrix); // Solve linear system\n\t\tvar coefs = extractCoefficients(matrix); // Get coefficients\n\t\tcheckAnswer(eqn, coefs); // Self-test, should not fail\n\t\tbalancedElem.appendChild(eqn.toHtml(coefs)); // Display balanced equation\n\t} catch (e) {\n\t\tsetMessage(e.toString());\n\t}\n}",
"function balance(left,right){\n let leftSum = left.split('').map(x=>{\n if(x==='?'){\n return 3;\n } else {return 2}\n }).reduce((acc, cv) => \n acc + cv\n );\n\n let rightSum = right.split('').map(y=>{\n if(y==='?'){\n return 3;\n } else {return 2}\n }).reduce((acc, cv) => \n acc + cv\n );\n \n return leftSum > rightSum ? 'Left' : rightSum > leftSum ? 'Right' : 'Balance';\n}",
"function balance(left,right){\n let leftCounter = {\"!\": 0, \"?\": 0}\n let rightCounter = {\"!\": 0, \"?\": 0}\n for (let i = 0; i < left.length; i++) {\n let char = left[i];\n leftCounter[char] += 1 ;\n } \n for (let i = 0; i < right.length; i++) {\n let char = right[i];\n rightCounter[char] += 1 ;\n } \n \n const leftWeight = leftCounter[\"!\"]*2 + leftCounter[\"?\"]*3\n const rightWeight = rightCounter[\"!\"]*2 + rightCounter[\"?\"]*3\n \n if ( leftWeight === rightWeight) { return \"Balance\"}\n else if ( leftWeight > rightWeight) { return \"Left\"}\n else { return \"Right\"}\n }",
"function balancedString(str) {\n // Assuming the input string is all in lower case as mentioned, \n // using split to split the string between each character\n let arrOfStrings = str.split('');\n let mapOfCharCount = new Map();\n let charCount = 1;\n\n if(arrOfStrings.length === 0 || arrOfStrings.length === 1) {\n return true;\n } else {\n for(let i = 0; i <= arrOfStrings.length; i++) {\n // arrOfStrings.length is 0 or 1 ===> true\n // arrOfStrings.length > 1\n // check if text[i] is in the map\n // if yes, increment map.value by 1\n // else, add text[i] to map and value count 1\n // compare all map.values to see if they are the same\n // if yes, it's true that str is balanced\n // else, its false, that str is not balance\n if(arrOfStrings[i] === arrOfStrings[i + 1]) {\n if(mapOfCharCount.has(arrOfStrings[i])) {\n mapOfCharCount.set(arrOfStrings[i], (mapOfCharCount.get(arrOfStrings[i]) + 1)); \n } else {\n mapOfCharCount.set(arrOfStrings[i], 1);\n }\n } else {\n if (mapOfCharCount.has(arrOfStrings[i])) {\n mapOfCharCount.set(arrOfStrings[i], (mapOfCharCount.get(arrOfStrings[i]) + 1));\n } else {\n mapOfCharCount.set(arrOfStrings[i], 1);\n }\n }\n return mapOfCharCount;\n }\n }\n\n // traverse the values in the map to see if\n // they are equal\n const mapValues = mapOfCharCount.values();\n for(let i = 1; i <= mapValues; i++) {\n if(mapValues[0] !== mapValues[i]) {\n return false;\n }\n return true;\n }\n }",
"function balance(left,right) {\n const weight = s => [...s].map(c => c === '!' ? 2 : c === '?' ? 3 : 0).reduce((s, x) => s + x, 0);\n let diff = weight(left) - weight(right);\n return diff === 0 ? 'Balance' : diff > 0 ? 'Left' : 'Right';\n }",
"function balance(left,right){\n let leftECtr = left.split('').filter(x => x == '!').length;\n let leftQCtr = left.length - leftECtr;\n let rightECtr = right.split('').filter(x => x == '!').length;\n let rightQCtr = right.length - rightECtr;\n \n return (leftECtr * 2) + (leftQCtr * 3) > (rightECtr * 2) + (rightQCtr * 3) \n ? 'Left' \n : (leftECtr * 2) + (leftQCtr * 3) < (rightECtr * 2) + (rightQCtr * 3)\n ? 'Right'\n : 'Balance';\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
funzione prevImg toglie la classe active al nodo corrente e la mette al precedente | function prevImg() {
// def var locali
let imgActive = $('.images img.active');
let circleActive = $('.nav i.active');
// rimozione class .active
imgActive.removeClass('active');
circleActive.removeClass('active');
// if block
if (imgActive.hasClass('first')) {
$('.images img.last').addClass('active');
$('.nav i.last').addClass('active');
} else {
imgActive.prev().addClass('active');
circleActive.prev().addClass('active')
}
} | [
"function prev() {\n\t\t\tgoToImage((curImage-1 < 0 ? numImages-1 : curImage-1), next ,true);\n\t\t}",
"function prev() {\r\n --current;\r\n showImage('l');\r\n }",
"function getPrevImage() {\r\n // I create the variables for the active image and the active circle\r\n var activeImage = $('.images img.active');\r\n var activeCircle = $('.nav i.active');\r\n\r\n // I remove the class active from the active image and circle\r\n activeImage.removeClass('active');\r\n activeCircle.removeClass('active');\r\n\r\n // If the active image and circle have the class first,\r\n // I add the class active to the image and circle that have the class last\r\n if (activeImage.hasClass('first')) {\r\n $('.images img.last').addClass('active');\r\n $('.nav i.last').addClass('active');\r\n }\r\n // Otherwise I add the class active to the previous image and circle\r\n else {\r\n activeImage.prev('img').addClass('active');\r\n activeCircle.prev('i').addClass('active');\r\n }\r\n}",
"function prevImage() {\n\tif (imageIndex === 0) {\n\t\timageIndex = imageCount-1;\n\t}\n\telse {\n\t\timageIndex--;\n\t}\n\tshowImage(imageIndex);\n}",
"previous() {\n this.slides[this.index].classList.remove(\"active\");\n //opérateur ternaire\n (this.index == this.slides.length-1) ? this.index = 0 : this.index++;\n\n this.slides[this.index].classList.add(\"active\");\n }",
"function prevImage() {\r\n if (currentImage > 0) {\r\n currentImage--;\r\n } else {\r\n currentImage = images.length - 1;\r\n }\r\n sliderImage.src = images[currentImage];\r\n}",
"function previousImage() {\n if (imageIndex > 0) {\n setImageIndex(imageIndex - 1);\n } else {\n setImageIndex(2);\n }\n }",
"function prevImg(){\r\n\t\tif(counter === 0){\r\n\t\t\treturn counter;\r\n\t\t}\r\n\t\telse{\r\n\t\t\tcounter--;\r\n\t\t\tdocument.getElementById('photo1').src = gallery[counter];\r\n\t\t\tdisplayArrows()\r\n\t\t}\r\n\t}",
"function findPrevImage() {\n\t\tcurrentImg = images.filter(':visible');\n\t\tprevImg = currentImg.prev( selector );\n\n\t\t// if there's no prev, we get the last\n\t\tif ( ! prevImg.length ) {\n\t\t\tprevImg = images.filter(':last');\n\t\t}\n\t}",
"function nextPrevSlide(direction) {\n console.log(direction);\n // prendi per specificità sia il papà che la img, e poi la classe \n var activeImage = $('.images img.active');\n // prendi per specificità \n var activeCircle = $('.nav i.active');\n\n // reset\n activeImage.removeClass('active');\n activeCircle.removeClass('active');\n\n\n // next \n if(direction === 'next') {\n if(activeImage.hasClass('last')) { // se fa questo, ha anche questo\n $('.images img.first').addClass('active');\n $('.nav i.first').addClass('active');\n } else {\n activeImage.next('img').addClass('active');\n activeCircle.next('i').addClass('active');\n }\n\n // activeImage.next('img').addClass('active');\n }\n\n // prev\n else if(direction === 'prev'){\n if(activeImage.hasClass('first')){\n $('.images img.last').addClass('active');\n $('.nav i.last').addClass('active');\n } else {\n activeImage.prev('img').addClass('active');\n activeCircle.prev('i').addClass('active');\n }\n } \n}",
"function prevImage() {\n\timageCounter -=1;\n\t\n\tif ( imageCounter < 0 ) {\n\t\timageCounter = imagesNumber - 1;\n\t}\n\tshowImage();\n}",
"function previousPhoto() {\n if(!galleryTl.isActive()) {\n if (curPhoto === 0) {\n removePhotoEvent(curPhoto);\n galleryTl.to(photos[0], 1, {left: \"-\"+photoSize+\"px\"});\n galleryTl.to(photos[photos.length-1], 1, {left: 0}, \"-=0.9\");\n curPhoto = photos.length-1;\n addPhotoEvent(curPhoto);\n }\n else {\n removePhotoEvent(curPhoto);\n galleryTl.to(photos[curPhoto-1], 0, {visibility: \"hidden\", left: \"-\"+photoSize+\"px\"});\n galleryTl.to(photos[curPhoto], 1, {left: photoSize+\"px\"});\n galleryTl.to(photos[curPhoto-1], 1, {visibility: \"visible\", left: 0}, \"-=0.9\");\n curPhoto = curPhoto - 1;\n addPhotoEvent(curPhoto);\n }\n }\n}",
"function prevPic(){\n pics[0].src = pics[1].src;\n pics[1].src = last;\n pics[2].src = first;\n}",
"showPrevImage(e) {\n this.index--;\n this.img.src = this.imgArr[this.index];\n this.nextButton.disabled = false;\n\n if (this.index === 0) {\n this.prevButton.disabled = true;\n }\n }",
"function previousPhoto() {\n currentImage--;\n if (currentImage < 0) {\n currentImage = myCalicos.length - 1;\n }\n slide.src = `photos/${myCalicos[currentImage]}`;\n }",
"function prevPic() {\n var prev = window.currentPic;\n prev--;\n generatePic(prev);\n}",
"function previousPhoto2() {\n currentImage2--;\n if (currentImage2 < 0) {\n currentImage2 = myChubs.length - 1;\n }\n slide2.src = `photos/${myChubs[currentImage2]}`;\n }",
"function prev_slide(ev)\n {\n ev.preventDefault();\n if (current == 0) return; // Already at first element\n activate(current - 1); // Move the \"active\" class\n //console.log(\"prev: current = \"+current+\" t -> \"+timecodes[current]);\n seek_video();\n }",
"function visualizzareImmaginePrecedente() {\n var immagineCorrente = $('.images img.active');\n var pallinoCorrente = $('.nav i.active');\n\n immagineCorrente.removeClass('active');\n pallinoCorrente.removeClass('active');\n\n // Se l'elemento ha anche classe first, aggiungo\n // la classe active all'elemento con classe last.\n if ( immagineCorrente.hasClass('first') ) {\n $('.images img.last').addClass('active');\n $('.nav i.last').addClass('active');\n }\n else {\n immagineCorrente.prev('img').addClass('active');\n pallinoCorrente.prev('i').addClass('active');\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updating waiting room status | function updateIsWaitingRoom() {
setIsWaitingRoom(!isWaitingRoom);
} | [
"async function updateWaitingRoomStatus(){\n await runningQuizDocument\n .update({\n isWaitingRoomActive: false\n }, {merge: true})\n setWaitingRoomActive(false)\n }",
"function roomWaiting(data) {\n // Change the host's room status to 'waiting'\n rooms[data.gameId].status = 'waiting';\n // Update the rooms listing for everyone in 'room1' AKA main chat room\n // Emit to 'room1' to update their global rooms list\n io.to('room1').emit('updateRooms', rooms, 'room1');\n }",
"function updateWaiting() {\n var d = new Date();\n var diff = d.getTime() - waitingTime;\n waiting = Math.floor(diff / 1000);\n }",
"function checkWaitlist(searchId){\n var roomIndex = findRoom(searchId, \"roomId\")\n if(helpeeWaitlist.length>0 && roomIndex){\n console.log(\"FOUND A WAITING HELPEE AFTER BECOMING FREE\");\n var waitingHelpee = helpeeWaitlist.shift()\n rooms[roomIndex].width = waitingHelpee.width;\n rooms[roomIndex].height = waitingHelpee.height;\n io.to(waitingHelpee.id).emit('helperStatus',{\"available\":\"yes\",\"id\":rooms[roomIndex].roomId})\n } else {\n return\n }\n}",
"function updateBookingStatus() {\n\n }",
"function updateGameStatus(){\n\tpost_data = {\n\t\t'action': 'get_status',\n\t\t'gameboard': JSON.stringify(calcGameboard())\n\t}\n\tgamePost(post_data, function(response){\n\t\t$('._gamestatus').html(response.status);\n\t\t$('._p1_cells').html(response.p1_cells);\n\t\t$('._p2_cells').html(response.p2_cells);\n\t\tif (response.gameboard) {\n\t\t\t$('._gameboard_wrapper').html(response.gameboard);\n\t\t}\n\t\tswitch (response.next_action) {\n\t\t\tcase 'wait':\n\t\t\t\tsetTimeout(updateGameStatus, request_interval);\n\t\t\t\tbreak;\n\t\t\tcase 'add_cell':\n\t\t\t\talert('Your turn to add cells! Good luck!');\n\t\t\t\tbreak;\n\t\t\tcase 'game_over':\n\t\t\t\talert('Game over! Thanks for playing!');\n\t\t\t\tbreak;\n\t\t}\n\t})\n}",
"statusUpdate() {\n this.io.emit(\"NEED_STATUS_UPDATE\", { for: 'everyone' });\n }",
"getChangedRoomStatus() {\n this.lastSendRoomStatusTime = Date.now();\n\n let gameStatus = {\n now: this.lastSendRoomStatusTime,\n players: this.getPlayersGraphicsInfo(),\n newPlayers: this.newPlayersStaticInfo,\n newGems: this.newGems,\n deletedGemsIDs: this.deletedGemsIDs,\n newTraps: this.newTraps,\n deletedTrapsIDs: this.deletedTrapsIDs\n };\n\n // Reset new players and new gems\n this.newPlayersStaticInfo = {};\n this.newGems = {};\n this.deletedGemsIDs = [];\n this.newTraps = {};\n this.deletedTrapsIDs = [];\n\n return gameStatus;\n }",
"function update_while_waiting_1(game, upd) {\n if(!upd.state) {\n onerror(\"Unexpected update while wating!\\n\", \"0x51\");\n }\n update_game_state(game, upd.state);\n}",
"async function updateRoomStatus(event, roomIdx, isUnreadByMe) {\n let newLatestRoom = {\n title: '',\n behindMembers: '',\n caughtUpMembers: ''\n };\n\n if (userInfo.roomStates[roomIdx].isUnreadByMe !== isUnreadByMe) {\n // We have a change in status for a space update the tables\n userInfo.roomStates[roomIdx].isUnreadByMe = isUnreadByMe;\n if (isUnreadByMe === false) {\n userInfo.readSpacesCount += 1;\n userInfo.unreadSpacesCount -= 1;\n }\n else {\n userInfo.readSpacesCount -= 1;\n userInfo.unreadSpacesCount += 1;\n }\n if (((!isUnreadByMe) && (userInfo.unreadSpacesCount > 0)) ||\n ((isUnreadByMe) && (userInfo.readSpacesCount > 0))) {\n const newIdx =\n userInfo.roomStates.findIndex((x) => x.isUnreadByMe !== isUnreadByMe);\n\n newLatestRoom = await initMemberDetails({\n id: userInfo.roomStates[newIdx].id,\n ...(userInfo.roomStates[newIdx].title && {title: userInfo.roomStates[newIdx].title}),\n lastActivityDate: userInfo.roomStates[newIdx].lastActivityDate\n });\n }\n }\n // The room state has not changed so we return the existing \"latest\"\n else if (!isUnreadByMe) {\n newLatestRoom = userInfo.lastUnread;\n }\n else {\n newLatestRoom = userInfo.lastRead;\n }\n\n return newLatestRoom;\n}",
"function updateRooms() {\n RoomManager.updateRooms().then(() => {\n console.log(RoomManager.room_states)\n }).then(() => {\n for (let key in room_states) {\n const room = room_states[key]\n if (room.status === 'running' && !room.is_broadcasting) {\n openRoom(key)\n }\n else if (room.status === 'closed' && room.is_broadcasting) {\n closeRoom(key)\n }\n }\n })\n}",
"checkStatus() {\n let status_elm = this.ui_elements.statusUpdate;\n this.status.on('value', function (status_details) {\n let status_value = status_details.val();\n let status__tag = status_elm.getElementsByTagName(\"span\")[0];\n if (status_value === false) {\n status__tag.innerText = \"Waiting for bot to come online...\";\n } else {\n status__tag.innerText = status_value;\n }\n })\n }",
"async updateRoomPot() {\n let newTotal = this.props.room.gamePot + this.state.betAmount;\n await this.updateRoom.updateRoomPot(\"room\", this.props.room.id, newTotal, this.state.betAmount);\n }",
"function setReadyStateForRoom(ready) {\n getClientSocketsInRoom(socket.room).forEach( clientSocket => {\n clientSocket.ready = ready;\n })\n }",
"_incWaiting() {\n this.waiting += 1;\n }",
"async setRoom(room, status = 'normal', active = true) {\n const { db } = this.server.common.storage;\n const data = await db.rooms.find({ _id: room });\n if (data.length > 0) {\n await db.rooms.update({ _id: room }, { $set: { status, active } });\n } else {\n await db.rooms.insert({ _id: room, status, active });\n }\n await this.server.driver.updateAccessibleRoomsList();\n }",
"static updateRoomStatus(room) {\n if (!room) {\n return;\n }\n if (room.controller) {\n if (room.controller.owner && !room.controller.my) {\n room.memory.avoid = 1;\n }\n else {\n delete room.memory.avoid;\n }\n }\n }",
"function updateRunning() {\r\n\tcommunicator.requestStatus(onReceiveStatus);\r\n}",
"function updateGameStatus() {\n if(gameScore >= 10) {\n gameStatus = 'win'\n } else if( timeLeft === -1) {\n gameStatus = 'gameOver'\n } else {\n gameStatus = null\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to reset our buffs to false. | function resetCombatVariables()
{ for(var i=0;i < currentBuffStatus.length;i++)
{ currentBuffStatus[i] = false;
}
weakenCount = 0;
lastHP = 0;
} | [
"resetBuffer() {\n while (this.blocked == true) { }; // dangerous ...\n if (this.copybuffer != undefined) {\n this.copybuffer.length = 0;\n this.copybuffer = undefined;\n\n for (let idx = 0; idx > this.PreStageFilter.length; idx++) {\n this.PreStageFilter.resetMemories();\n }\n }\n }",
"function resetBuffs(isChallenger){\n\tif (isChallenger){\n\t\tif (challenger.buffs.hp != 0 || challenger.debuffs.hp != 0){\n\t\t\tchallenger.buffs.hp = 0;\n\t\t\tchallenger.debuffs.hp = 0;\n\t\t\tsetStats(challenger);\n\t\t}\n\t\tchallenger.buffs = {\"hp\":0,\"atk\":0,\"spd\":0,\"def\":0,\"res\":0};\n\t\tchallenger.debuffs = {\"hp\":0,\"atk\":0,\"spd\":0,\"def\":0,\"res\":0};\n\t\tchallenger.spur = {\"hp\":0,\"atk\":0,\"spd\":0,\"def\":0,\"res\":0};\n\t\tupdateChallengerUI();\n\t}else{\n\t\t//Reset all custom list hero buffs and debuffs to 0\n\t\tenemies.cl.list.forEach(function(hero){\n\t\t\tif (hero.buffs.hp != 0 || hero.debuffs.hp != 0){\n\t\t\t\thero.buffs.hp = 0;\n\t\t\t\thero.debuffs.hp = 0;\n\t\t\t\tsetStats(hero);\n\t\t\t}\n\t\t\thero.buffs = {\"hp\":0,\"atk\":0,\"spd\":0,\"def\":0,\"res\":0};\n\t\t\thero.debuffs = {\"hp\":0,\"atk\":0,\"spd\":0,\"def\":0,\"res\":0};\n\t\t\thero.spur = {\"hp\":0,\"atk\":0,\"spd\":0,\"def\":0,\"res\":0};\n\t\t});\n\n\t\t//Update enemy UI\n\t\tupdateEnemyUI();\n\t}\n}",
"function clear_buffer() {\n buffer = [];\n}",
"reset() {\n CSOUND.reset(this.csound);\n this.started = false;\n this.compiled = false;\n }",
"function resetVariables() {\n pitchChanged = false;\n rateChanged = false;\n feedback = false;\n nbAnwersIncremented = false;\n}",
"setOff() {\n this.setFrame(0);\n this.on = false;\n }",
"function resetBatcherState() {\n queue.length = 0;\n userQueue.length = 0;\n has = {};\n circular = {};\n waiting = false;\n }",
"function resetDirty() {\n\tDIRTY = 0;\n}",
"function resetBatcherState() {\n queue.length = 0;\n userQueue.length = 0;\n has = {};\n circular = {};\n waiting = false;\n }",
"clear(){\n debug('%s clearing RingBuffer', this.class_uid)\n this.buffer = new Array(this.size)\n this.pointer = 0\n return true\n }",
"reset() {\n this.modified = false;\n }",
"function setAllFalse (a) {\n\tfor (var i = 0; i < a.length; i++) {\n\t\ta[i].setOff();\n\t}\n}",
"function resetBatcherState() {\n queue.length = 0;\n userQueue.length = 0;\n has = {};\n circular = {};\n waiting = false;\n}",
"resetFlags() {\n let k;\n for (k in this.lastPressed) {\n this.lastPressed[k] = false;\n }\n for (k in this.lastReleased) {\n this.lastReleased[k] = false;\n }\n }",
"function C101_KinbakuClub_BlindMansBuff_SomeoneUncuff() {\n\tC101_KinbakuClub_BlindMansBuff_TouchSomebody = false;\n\tC101_KinbakuClub_BlindMansBuff_FeelSomebody = false;\n\tif (C101_KinbakuClub_BlindMansBuff_PlayerCuffCall && !C101_KinbakuClub_BlindMansBuff_PlayerRobbed) {\n\t\tC101_KinbakuClub_BlindMansBuff_Theft()\n\t}\n\tC101_KinbakuClub_BlindMansBuff_PlayerCuffCall = true;\n}",
"resetBuffer() {\n this.waitUntilStop().then(() => {\n this.STFTBuffer.fill();\n this.startSTFTCalculation();\n });\n }",
"_clearBuffer() {\n\t\tthis._audioRecording = [];\n\t\tthis._audioBuffer = [];\n\t}",
"function setFalse(){\r\n startmenu = false;\r\n newGame = false;\r\n loadGame = false;\r\n\toptions = false;\r\n \r\n tutorial = false;\r\n pdfReading = false;\r\n tutorialpage = 0;\r\n\ttutorial_video = false;\r\n credits = false;\r\n \t\r\n \ttwoPlayerGame = false;\r\n \tthreePlayerGame = false;\r\n fourPlayerGame = false;\r\n\r\n\tsetHandFalse();\r\n\r\n\tshouldEndTurn = false;\r\n\tplayerTurn = true;\r\n\tUserCanDiscard = true;\r\n\tgameEnd = false;\r\n boardDone = false;\r\n numberOfMytCards = 28;\r\n numberOfLandCards = 60;\r\n\tnumberOfBonusCards = 20;\r\n\tnumberOfProCards = 8;\r\n\tstartingSpace =false;\r\n\tlandBoardState = [[\"\",\"\",\"\",\"\",\"\"],[\"\",\"\",\"\",\"\",\"\"],[\"\",\"\",\"\",\"\",\"\"],\r\n\t\t\t\t\t[\"\",\"\",\"\",\"\",\"\"],[\"\",\"\",\"\",\"\",\"\"]];\r\n\tmytDiscard = [];\r\n\tmytComplete = [];\r\n\tmytComputerComplete = [];\r\n\tlandDiscard = [];\r\n\tlandDeckState = [];\r\n\tmytDeckState = [];\r\n\tlandHandState = [];\r\n}",
"function falseShifts() {\n startShiftCr = false;\n startShiftCy = false;\n startShiftBags = false;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function checkApostrophe parameter : array return : array | function checkApostrophe(array) {
array.forEach(function(element, index) {
//console.log(element+" : "+element.indexOf('\''));
if (element.indexOf('\'') == 1) {
//console.log('index: '+index);
var tmp = element.replace(/'/g, '');
array[index] = tmp.substr(1);
}
});
return array;
} | [
"function checkSafety(text) {\n text = text.toLowerCase();\n if (text.includes('\"') || text.includes('\\'') || text.includes('--') || text.includes('union')) {\n return false;\n }\n return true;\n}",
"function checkCharactersValid() {\r\n //var lstSpecialCharacters = ['\"', \"'\", ';', ':', '<', '>', ')', '(', '*', '^', '%', '$', '#', '!', '~', '&', '*', '+', '=', '{', '}', '[', ']', ',', '|'];\r\n var lstSpecialCharacters = ['<', '>'];\r\n var ok = true;\r\n $('input[type=text]').each(function (idx1, item1) {\r\n var a = $(this).val();\r\n $.each(lstSpecialCharacters, function (idx, item) {\r\n if (a.indexOf(item) >= 0) {\r\n ok = false; \r\n } else {\r\n // alert(item + '|' + );\r\n }\r\n });\r\n });\r\n $('textarea').each(function () {\r\n var b = $(this).val();\r\n $.each(lstSpecialCharacters, function (idx, item) {\r\n if (b.indexOf(item) >= 0) {\r\n ok = false; \r\n }\r\n });\r\n });\r\n if (!ok) {\r\n alert(\"Vui lòng không sử dụng ký tự đặc biệt\");\r\n return false;\r\n }\r\n return ok;\r\n}",
"function hasBalancedQuotes(value){var outsideSingle=true;var outsideDouble=true;for(var i=0;i<value.length;i++){var c=value.charAt(i);if(c==='\\''&&outsideDouble){outsideSingle=!outsideSingle;}else if(c==='\"'&&outsideSingle){outsideDouble=!outsideDouble;}}return outsideSingle&&outsideDouble;}",
"function checkForApos(formField) {\n var fieldToValidate = formField.value;\n var regexpValidated = fieldToValidate.replace(/'/g, \" \");\n if (fieldToValidate.match(/'/g)){\n \talert('Apostrophe found in text!\\nIt will be replaced with a space.');\n \tformField.value = regexpValidated;\n }\n return false;\n}",
"function checkForAbba(arr) {\n return arr.some((el) => {\n return checkString(el, 0, abba)\n })\n}",
"function escapeApostrophe(input){\n // 'typeof string == string' means if the datatype of the item is a string. if it's an integer, then dont check for an apostrophe\n // 'string.indexOf(\"'\") > -1' means if there is an apostrophe in the string\n // if both statements equate to true, then run the logic in between the {}, which is 'string = string.replace(\"'\", \"\\\\'\")'\n if(typeof input == \"string\" && input.indexOf(\"'\") > -1){\n // re-assigning the value of input to have the ' replaced with a \\'\n input = input.replace(\"'\", \"\\\\'\")\n }\n // this function will return the input value, where the value of the input was changed or not\n return input;\n}",
"function ValidaLetrasYEspacios(PsCadena){\n\tvar SsValue=PsCadena;\n\tvar ScChar=null;\n\tvar SsValidos='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ';\n\tfor(i=0; i!=SsValue.length; i++) {\n\t\t ScChar=SsValue.substring(i,i+1)\n\t\t //VERIFICA QUE INGRESE SOLO LETRAS Y ESPACIOS\n\t\t if (SsValidos.indexOf(ScChar) == -1) {\n\t\t\t alert(MENSAJE_079);\n\t\t\t return(false);\n\t\t }//EXISTE SOLO LETRAS Y ESPACIOS\n\t}\n\treturn(true);\n}",
"function nombreApostrophe(x) {\n return x.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, \"\\'\");\n\n }// Fin fonction nombreApostrophe",
"checkLetter(letter) {\n const text = this.phrase;\n const textArray = [...text];\n\n if (textArray.includes(letter)) {\n // if the letter array includes the single letter passed in return true else false\n return true;\n } else {\n return false;\n }\n }",
"function isSingleQuote(fld) \r\n{\r\n\tvar val = \"\";\r\n\tfor (i=0; i<fld.length ; i++) \r\n\t{\r\n\t\tif(fld.charAt(i) == \"'\")\r\n\t\t{\r\n\t\t\treturn false;\r\n \t}\r\n\t}\r\n\treturn true;\r\n}",
"function validate(phrase)\n{\n\tvar re = new RegExp(\"^[a-z ,'’-]{6,}$\"); // only lowercase, space, comma, etc, 6+ characters\n\tif (!re.test(phrase) || phrase.indexOf('undefined') !== -1)\n\t{\n\t\tconsole.log(\"INVALD \" + phrase);\n\t\treturn false;\n\t}\n\telse\n\t{\n\t\tconsole.log(\"VALID \" + phrase);\n\t}\n\n\treturn true;\n}",
"function ValidaSoloLetras(PsCadena){\n\tvar SsValue=PsCadena;\n\tvar ScChar=null;\n\tvar SsValidos='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n\tfor(i=0; i!=SsValue.length; i++) {\n\t\t ScChar=SsValue.substring(i,i+1)\n\t\t //VERIFICA QUE SE INGRESE LETRAS SIN ESPACIOS\n\t\t if (SsValidos.indexOf(ScChar) == -1) {\n\t\t\t alert(MENSAJE_080);\n\t\t\t return(false);\n\t\t }//EXISTE LETRAS SIN ESPACIOS\n\t}\n\treturn(true);\n}",
"function validateOrderName(elem)\n {\n var str = elem.value;\n //alert(\"Entered into function\");\n if(str.length>75)\n {\n alert(\"Order Name is too long\");\n return false;\n }\n else\n {\n if(str.indexOf('\\'')!=-1)\n {\n alert(\"Special character is included in the order name\");\n return false;\n }\n }\n return true;\n }",
"function wordCheck(word, standard) {\n var arrayCharacters = [];\n wordToArray(word, arrayCharacters);\n testIfAlpha(standard, arrayCharacters);\n return alphaCheck;\n }",
"function check(stringName){\n var msg = true;\n if(typeof stringName != \"string\"){\n stringName = String(stringName);\n } \n\n var theString = stringName.split('');\n for(var i=0;i<theString.length;i++){\n if(theString[i]===\",\"){\n msg = false;\n }\n }\n\n return msg;\n}",
"function listWords(arr) {\n var result = \"\";\n for (var i = 0, n = arr.length; i < n; i++) {\n var badWord = arr[i].length > 1 ? \"'\" + arr[i] + \"'\" : arr[i];\n result += \",\" + badWord;\n }\n result = result.length === 0 ? result : result.substring(1);\n result = result.replace(/ /g, \"spaces\").replace(/,/g, \", \").replace(/&/g, \"&\").replace(/</g, \"<\").replace(/>/g, \">\");\n return result;\n }",
"function validateSpecialCharsAdvancedSearch(inputStr)\r\n\t{\r\n\r\n \r\n \r\n\t\tvar iChars = \":~^&(){\\\"}][~\";\r\n\t\tif(inputStr!=\"\" && inputStr != null)\r\n\t\t\t{\r\n\t\t\t\r\n\r\n\t\tfor (var i = 0; i < inputStr.length; i++) {\r\n\t\t\t\r\n\t\t\tif (iChars.indexOf(inputStr.charAt(i)) != -1) {\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\treturn false;\r\n\t\t}\r\n\t }\r\n\t\t\r\n }\r\n\t\treturn true;\r\n}",
"getApostrophizedWords(preWord) {\n const apostrophes = ['’', '\\'']\n const word = preWord.slice(0, preWord.length - 1) // minus apostrophe\n const apostrophe = preWord.slice(-1)\n\n // If no final apostrophe, return empty suggestion\n if(apostrophes.indexOf(apostrophe) === -1) {\n return []\n }\n\n const personalPronouns = [\n 'he',\n 'i',\n 'it',\n 'she',\n 'they',\n 'we',\n 'you',\n ]\n const results = []\n\n // I’m\n if(this._testApostropheWord(word, ['i'])) {\n results.push(`${word}${apostrophe}m`)\n }\n\n // 'are' words\n if(this._testApostropheWord(word, [\n 'they',\n 'we',\n 'you',\n ])) {\n results.push(`${word}${apostrophe}re`)\n }\n\n // 'will' words\n if(this._testApostropheWord(word, personalPronouns)) {\n results.push(`${word}${apostrophe}ll`)\n }\n\n // 'not' words\n if(this._testApostropheWord(word, [\n 'aren',\n 'can',\n 'couldn',\n 'didn',\n 'doesn',\n 'don',\n 'hadn',\n 'hasn',\n 'haven',\n 'isn',\n 'mustn',\n 'needn',\n 'oughtn',\n 'shan',\n 'shouldn',\n 'wasn',\n 'weren',\n 'won',\n 'wouldn',\n ])) {\n results.push(`${word}${apostrophe}t`)\n }\n\n // 'have' words\n if(this._testApostropheWord(word, [\n 'i',\n 'they',\n 'we',\n 'you',\n ])) {\n results.push(`${word}${apostrophe}ve`)\n }\n\n // 'had' words\n if(this._testApostropheWord(word, personalPronouns)) {\n results.push(`${word}${apostrophe}d`)\n }\n\n // personal ownership words\n if(this._testApostropheWord(word, [\n 'he',\n 'it',\n 'she',\n ])) {\n results.push(`${word}${apostrophe}s`)\n }\n\n // will words\n if(this._testApostropheWord(word, personalPronouns)) {\n results.push(`${word}${apostrophe}ll`)\n }\n\n if(results.length === 0) {\n // Default to `’s`\n return [`${word}${apostrophe}s`]\n }\n return results\n }",
"checkname(array, strName){\r\n const nombres = array.map((elem) => elem.getName().toLowerCase());\r\n if(nombres.includes(strName.toLowerCase())){\r\n throw ({cod: 409, message:'Ya existe ese nombre'});\r\n }\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the full path of the template file for generating charts based on config. | function getTemplatePath(templateFileName, config) {
if (config.templatePath !== undefined) {
return path.join(untildify(config.templatePath), `${templateFileName}.pug`);
}
return path.join(fileURLToPath(import.meta.url), '../../views/chart', `${templateFileName}.pug`);
} | [
"function getTemplatePath(templateFileName, config) {\n if (config.templatePath !== undefined) {\n return path.join(untildify(config.templatePath), `${templateFileName}.pug`);\n }\n\n return path.join(__dirname, '..', 'views/chart/', `${templateFileName}.pug`);\n}",
"get templateFullPath() {\n return path.join(this.assembly.directory, this.templateFile);\n }",
"function getTemplatePath(templateFileName, config) {\n let fullTemplateFileName = templateFileName;\n if (config.noHead !== true) {\n fullTemplateFileName += '_full';\n }\n\n if (config.templatePath !== undefined) {\n return path.join(\n untildify(config.templatePath),\n `${fullTemplateFileName}.pug`\n );\n }\n\n return path.join(\n fileURLToPath(import.meta.url),\n '../../views/default',\n `${fullTemplateFileName}.pug`\n );\n}",
"getFullTemplateFile(config, templateFile) {\n let template = config.templateDir() + File.separator + templateFile;\n if (new File(template).exists()) {\n return template;\n }\n else {\n let library = config.getLibrary();\n if (library) {\n const libTemplateFile = 'resources' + File.separator + config.embeddedTemplateDir() + File.separator + \"libraries\" + File.separator + library + File.separator + templateFile;\n if (this.embeddedTemplateExists(libTemplateFile)) {\n return libTemplateFile;\n }\n }\n const fp = 'resources' + File.separator + config.embeddedTemplateDir() + File.separator + templateFile;\n return fp;\n }\n }",
"getTemplatePath() {\n\t\treturn path.join(this.getTempPath(), 'node_modules', this.templateName);\n\t}",
"async getTemplatePath(template) {\n let juiceRenderResources = {};\n\n if (_.isObject(template)) {\n juiceRenderResources = template.juiceResources;\n template = template.path;\n }\n\n const [root, view] = path.isAbsolute(template)\n ? [path.dirname(template), path.basename(template)]\n : [this.config.views.root, template];\n const paths = await getPaths(\n root,\n view,\n this.config.views.options.extension\n );\n const filePath = path.resolve(root, paths.rel);\n return { filePath, paths, juiceRenderResources };\n }",
"static get _templatePath() {\n return 'public/modules/fvtt-enhancement-suite/templates';\n }",
"function getTemplateURL(template) {\n return base_url + '/js/app/my-dashboard/partials/' + template;\n }",
"function getDocTemplatePath() {\n return _path2.default.resolve(__dirname, '..', '..', 'tpl', 'doc.md.mustache');\n}",
"templatePath (template_path = './') {\n return this.runtime.templatePath(this.resolved, template_path)\n }",
"function getSidebarTemplatePath() {\n return _path2.default.resolve(__dirname, '..', '..', 'tpl', 'sidebars.json.mustache');\n}",
"function get_path_to_rendered_template(path_to_file, path_to_layout, destination) {\n\n // remove src (options.src) from beginning of path\n var path_to_rendered_template = path_to_file.replace(path_to_layout, \"\");\n\n // add destination (options.dest) to beginning of path\n path_to_rendered_template = destination + path_to_rendered_template;\n\n return path_to_rendered_template; \n \n }",
"_getTemplateFile(htmlFilePath) {\n const filePath = path.join(config.reports.templates_folder, htmlFilePath);\n return fs.readFileSync(filePath);\n }",
"getFilePath() {\n let filePath = callsites()[2].getFileName(); // [0] and [1] return global fractal.config.js.\n return filePath.replace('.js', '.yml');\n }",
"function getSettingsFilePath() {\n var dir = getSettingsDirPath();\n return path_1.default.join(dir, config.fileName);\n}",
"function getTemplate() {\n const config = admin.remoteConfig();\n config.getTemplate()\n .then(template => {\n console.log('ETag from server: ' + template.etag);\n const templateStr = JSON.stringify(template);\n fs.writeFileSync('config.json', templateStr);\n })\n .catch(err => {\n console.error('Unable to get template');\n console.error(err);\n });\n}",
"function getFilePath() {\n\t\t\treturn $BASE_PATH + 'adminPanel/flatForms/export';\n\t\t}",
"function gen_conf(config) {\n return ejs_render(__dirname + '/../nginx.ejs', config);\n}",
"get template() {\n\t\t return(\"systems/mysystem/templates/sheets/thing_sheet.html\");\n\t }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the height of a line, propagating the height change upwards to parent nodes. | function updateLineHeight(line, height) {
var diff = height - line.height;
if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
} | [
"function updateLineHeight(line, height) {\n var diff = height - line.height;\n if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }\n }",
"function updateLineHeight(line, height) {\n var diff = height - line.height;\n if (diff) for (var n = line; n; n = n.parent) n.height += diff;\n }",
"function updateLineHeight(line, height) {\n var diff = height - line.height;\n if (diff) {\n for (var n = line; n; n = n.parent) {\n n.height += diff;\n }\n }\n }",
"function updateLineHeight(line, height) {\n\t\t var diff = height - line.height;\n\t\t if (diff) for (var n = line; n; n = n.parent) n.height += diff;\n\t\t }",
"function updateLineHeight(line, height) { // 6972\n var diff = height - line.height; // 6973\n if (diff) for (var n = line; n; n = n.parent) n.height += diff; // 6974\n } // 6975",
"function updateWidgetHeight(line) {\n if (line.widgets) for (let i = 0; i < line.widgets.length; ++i) {\n let w = line.widgets[i], parent = w.node.parentNode\n if (parent) w.height = parent.offsetHeight\n }\n}",
"function updateWidgetHeight(line) {\n if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)\n line.widgets[i].height = line.widgets[i].node.offsetHeight;\n }",
"function updateWidgetHeight(line) {\r\n if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)\r\n line.widgets[i].height = line.widgets[i].node.offsetHeight;\r\n }",
"function updateWidgetHeight(line) { // 819\n if (line.widgets) for (var i = 0; i < line.widgets.length; ++i) // 820\n line.widgets[i].height = line.widgets[i].node.offsetHeight; // 821\n } // 822",
"lineHeight(lineHeight) {\n this.lh = lineHeight;\n }",
"function heightAtLine(lineObj) {\n\t\t lineObj = visualLine(lineObj);\n\t\t\n\t\t var h = 0, chunk = lineObj.parent;\n\t\t for (var i = 0; i < chunk.lines.length; ++i) {\n\t\t var line = chunk.lines[i];\n\t\t if (line == lineObj) break;\n\t\t else h += line.height;\n\t\t }\n\t\t for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {\n\t\t for (var i = 0; i < p.children.length; ++i) {\n\t\t var cur = p.children[i];\n\t\t if (cur == chunk) break;\n\t\t else h += cur.height;\n\t\t }\n\t\t }\n\t\t return h;\n\t\t }",
"function heightAtLine(lineObj) {\n lineObj = visualLine(lineObj);\n var h = 0,\n chunk = lineObj.parent;\n for (var i = 0; i < chunk.lines.length; ++i) {\n var line = chunk.lines[i];\n if (line == lineObj) {\n break;\n } else {\n h += line.height;\n }\n }\n for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {\n for (var i$1 = 0; i$1 < p.children.length; ++i$1) {\n var cur = p.children[i$1];\n if (cur == chunk) {\n break;\n } else {\n h += cur.height;\n }\n }\n }\n return h;\n }",
"setLineHeight(lineHeight) {\r\n this._lineHeight = lineHeight;\r\n }",
"function _heightAtLine(lineObj) {\n lineObj = visualLine(lineObj);\n\n var h = 0,\n chunk = lineObj.parent;\n for (var i = 0; i < chunk.lines.length; ++i) {\n var line = chunk.lines[i];\n if (line == lineObj) {\n break;\n } else {\n h += line.height;\n }\n }\n for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {\n for (var i$1 = 0; i$1 < p.children.length; ++i$1) {\n var cur = p.children[i$1];\n if (cur == chunk) {\n break;\n } else {\n h += cur.height;\n }\n }\n }\n return h;\n }",
"function heightAtLine(lineObj) {\n\t\t lineObj = visualLine(lineObj);\n\n\t\t var h = 0, chunk = lineObj.parent;\n\t\t for (var i = 0; i < chunk.lines.length; ++i) {\n\t\t var line = chunk.lines[i];\n\t\t if (line == lineObj) { break }\n\t\t else { h += line.height; }\n\t\t }\n\t\t for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {\n\t\t for (var i$1 = 0; i$1 < p.children.length; ++i$1) {\n\t\t var cur = p.children[i$1];\n\t\t if (cur == chunk) { break }\n\t\t else { h += cur.height; }\n\t\t }\n\t\t }\n\t\t return h\n\t\t }",
"function heightAtLine(lineObj) {\n\t lineObj = visualLine(lineObj);\n\t\n\t var h = 0, chunk = lineObj.parent;\n\t for (var i = 0; i < chunk.lines.length; ++i) {\n\t var line = chunk.lines[i];\n\t if (line == lineObj) break;\n\t else h += line.height;\n\t }\n\t for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {\n\t for (var i = 0; i < p.children.length; ++i) {\n\t var cur = p.children[i];\n\t if (cur == chunk) break;\n\t else h += cur.height;\n\t }\n\t }\n\t return h;\n\t }",
"function heightAtLine(lineObj) {\n\t\t lineObj = visualLine(lineObj);\n\t\t\n\t\t var h = 0, chunk = lineObj.parent;\n\t\t for (var i = 0; i < chunk.lines.length; ++i) {\n\t\t var line = chunk.lines[i];\n\t\t if (line == lineObj) { break }\n\t\t else { h += line.height; }\n\t\t }\n\t\t for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {\n\t\t for (var i$1 = 0; i$1 < p.children.length; ++i$1) {\n\t\t var cur = p.children[i$1];\n\t\t if (cur == chunk) { break }\n\t\t else { h += cur.height; }\n\t\t }\n\t\t }\n\t\t return h\n\t\t}",
"function changeLineHeight(lineHeight) {\n const css = `\n tr.sourceLine {\n height: ${lineHeight}px !important;\n }\n `;\n\n changeCSS(css);\n\n // update the display\n lineHeightDisplay.textContent = lineHeight;\n lineHeightDisplay.setAttribute('value', lineHeight);\n}",
"function changeLineHeight(lineHeight) {\n const css = `\n tr.sourceLine {\n height: ${lineHeight}px;\n }\n `;\n changeCSS(css);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
compile all tests and fire a callback when the all code is compiled and ready to be executed | function compileAll(tests, cb) {
var results = [];
var pending = tests.length;
tests.forEach(function (name, idx) {
compile(name, function (err, result) {
if (err) return cb(err);
results[idx] = result;
if (--pending === 0) {
cb(null, results);
}
});
});
} | [
"runTests() {\n this.testCorrect()\n this.testComplete()\n }",
"exec () {\n this.setupTests()\n return this.runTests()\n }",
"function testsRun() {\n for (var i = 0; i < _testsAllTests.length; i++) {\n var test = _testsAllTests[i];\n test();\n }\n}",
"async runTests() {\n for (let file of this.testFiles) {\n console.log(chalk.gray(`--- ${file.shortName}`));\n const beforeEaches = [];\n\n global.render = render;//jsdom\n\n global.beforeEach = (fn) => {\n beforeEaches.push(fn)\n };\n global.it = async (desc, fn) => {\n // console.log(desc);\n beforeEaches.forEach(func => func());\n //to handle errors ocurred during our test we need to do try and catch to avoid the test to collapse\n try {\n await fn();\n console.log(chalk.green(`\\tOK - ${desc}`));\n } catch (err) {\n const message = err.message.replace(/\\n/g, '\\n\\t\\t');\n console.log(chalk.red(`\\tX - ${desc}`));\n console.log(chalk.red('\\t', message));// \\t is tab \n }\n\n };\n //to skip the typo in stopping test for running\n try {\n require(file.name);//when we require the file inside a func node will find it and execute the file here\n } catch (err) {\n console.log(chalk.red('X - Error Loading File'), file.name);\n console.log(chalk.red(err));\n }\n\n }\n }",
"onCompiled() {\n console.log(\"Compilation finished!\")\n }",
"function compileAllTests(testFilePaths) {\n return new Promise(function(resolve, reject) {\n var compileProcess = compile(testFilePaths, {\n output: \"/dev/null\",\n verbose: args.verbose,\n yes: true,\n spawn: spawnCompiler,\n pathToMake: pathToMake,\n warn: args.warn,\n processOpts: processOptsForReporter(args.report)\n });\n\n compileProcess.on(\"close\", function(exitCode) {\n if (exitCode !== 0) {\n reject(\n \"Compilation failed while attempting to build \" +\n testFilePaths.join(\" \")\n );\n } else {\n resolve();\n }\n });\n });\n}",
"function startTests() {\n async.waterfall([\n onBeforeAll,\n runTests,\n onAfterAll\n ], function() {\n \n complete = true;\n \n if (running === 0) {\n onDone();\n }\n });\n }",
"onCompiled() {\n console.log(\"Compilation finished!\")\n }",
"run() {\n const onCompiled = () => { }\n const run = () => {\n this.hooks.beforRun.callAsync(this, err => {\n this.hooks.run.callAsync(this, err => {\n this.compile(onCompiled)\n })\n })\n };\n // 不管是否空闲,都会执行run方法\n run();\n }",
"function runTests() {\n// runTestsEx3();\n// runTestsEx4();\n runTestsEx5();\n}",
"function runAllTests(){\n\t\n\texec(\"expresso tests/unit/*\", function(err, stdout, stdin) {\n\t\t\n\t \tconsole.log(err);\n\t\t\n\t\tconsole.log(\"Finished running all tests in tests/unit/*\");\n\t\tconsole.log(stdout);\n\t\t\n\t});\n}",
"function runTests(cb) {\n async.eachSeries(opt.platforms, function (platform, cb) {\n ee.emit('log', 'Running tests on browser: ' + platform.browserName);\n var child = cp.fork(path.join(__dirname, 'lib', 'child'));\n child.on('close', function (code, signal) {\n failures += code;\n cb();\n });\n child.send({\n type: 'init',\n remote: opt.remote,\n platform: platform,\n files: files\n });\n }, cb);\n }",
"function startTests() {\n async.waterfall([\n execBeforeAll,\n task._start,\n execAfterAll\n ], function() {\n complete = true;\n\n if (running === 0) {\n onDone();\n }\n });\n }",
"registerTests() {}",
"function compileAll(compiler, files) {\n // compiler.compile(file) each file and combine into a single deferred\n return $.when.apply($, files.map(function (file) {\n return compiler.compile(file.src, file.dst);\n }));\n }",
"function main() {\n if (isPushBuild()) {\n log('Running all tests because this is a push build...');\n runLintChecks();\n APPS_TO_TEST.forEach(runAppTests);\n } else {\n printChangeSummary();\n runLintChecks();\n determineBuildTargets().forEach(runAppTests);\n }\n}",
"function runAllTests() {\n var testFunctions = _getAllTestFunctions();\n\n for (var i=0; i<testFunctions.length; i++) {\n console.log('-- ' +testFunctions[i]+ ' --');\n eval(testFunctions[i]+ '()'); // Call the function\n\n str = 'Passed: ' +testsPassed+ '. Failed: ' +testsFailed+ '.';\n if (testsFailed == 0) {\n console.log(str);\n } else {\n console.error(str);\n }\n testsPassed = 0;\n testsFailed = 0;\n }\n}",
"function compile(compiler, files) {\n\t\tvar tasks = [];\n\t\tfiles.forEach(function (file) {\n\t\t\ttasks.push(compiler.compile(file));\n\t\t});\n\t\treturn $.when.apply($, tasks);\n\t}",
"function buildAll() {\n\tconsole.log(\"Building files...\")\n\t// buildTypescript()\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set auto launch option | function setAutoLaunch(autoLaunchValue) {
const appLauncher = new AutoLaunch({
name: 'Oversetter',
mac: {
useLaunchAgent: true,
},
});
autoLaunchValue ? appLauncher.enable() : appLauncher.disable();
} | [
"function start_auto_launch() {\n \n var quarkclientAutoLauncher = new AutoLaunch({\n name: 'QuarkClient',\n // path: '/Applications/QuarkClient.app',\n // path: '\"C:\\\\Users\\\\C9G\\\\AppData\\\\Roaming\\\\uTorrent Web\\\\utweb.exe\" /MINIMIZED',\n path: basepath + '\\\\quarkclient.exe',\n });\n\n quarkclientAutoLauncher.enable();\n\n quarkclientAutoLauncher.isEnabled()\n .then(function(isEnabled){\n if(isEnabled){\n return;\n }\n quarkclientAutoLauncher.enable();\n })\n .catch(function(err){\n // handle error\n });\n}",
"ensureCorrectAutolaunch() {\n this.autolaunch.isEnabled().then(enabled => {\n if (enabled != this.config.start_on_boot) {\n if (this.config.start_on_boot) this.autolaunch.enable();\n else this.autolaunch.disable();\n }\n }).catch(err => console.log(\"Autolaunch Error: \" + err))\n }",
"function autoLaunch() {\n const AutoLauncher = new AutoLaunch({\n name: 'Tiny-Timer',\n mac: {\n useLaunchAgent: true,\n },\n });\n\n AutoLauncher.isEnabled()\n .then((isEnable) => {\n if (!isEnable) {\n AutoLauncher.enable();\n } else {\n AutoLauncher.disable();\n }\n });\n}",
"function autoLaunch() {\n\tconst appFolder = path.dirname(process.execPath)\n\tconst updateExe = path.resolve(appFolder, '..', 'Update.exe')\n\tconst exeName = path.basename(process.execPath)\n\t \n\tapp.setLoginItemSettings({\n\t openAtLogin: true,\n\t path: updateExe,\n\t args: [\n\t '--processStart', `\"${exeName}\"`,\n\t '--process-start-args', `\"--hidden\"`\n\t ]\n\t})\n}",
"function setAutoMode(isAuto) {\n runInAutoMode = isAuto;\n}",
"function setAutoMode(isAuto) { runInAutoMode = isAuto; }",
"function changeRadarAppAutoStart()\n{\n app.radar_app_auto_start = !app.radar_app_auto_start;\n \n if (app.radar_app_auto_start)\n setLocalStorageItem(\"radar_app_auto_start\", \"true\");\n else\n setLocalStorageItem(\"radar_app_auto_start\", \"false\"); \n \n showRadarAppAutoStart();\n}",
"function setLaunch(val) {\n\tLAUNCH = val;\n}",
"function manageStartup(enable) {\n let appLauncher = new AutoLaunch({\n // Change this to the name of the application or what\n // should appear in the startup menu.\n name: 'BB'\n });\n if (enable) {\n appLauncher.isEnabled().then(function(enabled){\n if(enabled) return;\n return appLauncher.enable();\n }).then(function(err){\n // If you want to remove all console output, remove lines that contain \"console.error(err)\"\n if (err !== undefined) console.error(err);\n });\n } else {\n appLauncher.isEnabled().then(function(enabled){\n if(!enabled) return;\n return appLauncher.disable();\n }).then(function(err){\n if (err !== undefined) console.error(err);\n }); \n }\n}",
"setKiosk(flag) {\r\n this.native.setKiosk(flag);\r\n }",
"SetOption() {\n\n }",
"set autoPlay(autoPlay) {\n this.api.conf.autoplay = autoPlay\n }",
"function init(){\n\n\t_.defaults(args,defaultOptions);\n\n\tif(args.autoShowed){\n\t\tshow();\n\t};\n}",
"function startInstancesWithAutoStartEnabled() {\n _.each(configProvider.getConfigs(), function startInstances(config) {\n if (config.autoStartEnabled) {\n self.start(config.id);\n }\n });\n }",
"function addtoStart() {\n\n const exeName = path.basename(process.execPath);\n app.setLoginItemSettings({\n openAtLogin: true,\n path: process.execPath,\n args: [\n '--processStart', \"${exeName}\",\n '--process-start-args', \"--hidden\"\n ]\n });\n}",
"function launch() {}",
"autostart() {\n this.logger.debug('Bio: detectors.js: autostart()');\n\n this.autostartContextMenu();\n }",
"function SwitchAutoPlay () { SetAutoPlay (!isAutoPlayOn); }",
"setAutoPlay(state, autoPlay) {\n state.autoPlay = autoPlay\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates an instance of error terms store service. | function ErrorTermsStoreService() {
this.errorTerminologies = null;
this.errorCodeBase = {};
} | [
"function createStore(){}",
"function LoginTermsService(baseTermsService) {\n this.baseTermsService = baseTermsService;\n /**\n * Login terminologies of login terms service\n */\n this._loginTerminologies = null;\n this.terms = null;\n }",
"function createTerm(term) {\n term.created_at = new java.util.Date();\n if(!term.ontology_id || !term.ontology_name)\n throw new Error(\"Missing references to ontology\");\n\n term.parent = term.parent || null; // important to track the roots\n\n term.normalized = normalize(term); // important for search\n\n if(term.comment)\n term.comment = new Text(term.comment);\n if(term.def)\n term.def = new Text(term.def);\n\n\n var termEntity = googlestore.entity(\"term\", term.id, term);\n\n googlestore.put(termEntity);\n }",
"function createStore(options) {\n return new _Store.Store(options);\n}",
"function createTerm(term) {\n term.created_at = new java.util.Date();\n if(!term.ontology_id || !term.ontology_name)\n throw new Error(\"Missing references to ontology\");\n\n //term.parent = term.parent || null; // important to track the roots\n\n //term.normalized = normalize(term); // important for search\n\n if(term.comment)\n term.comment = new Text(term.comment);\n if(term.def)\n term.def = new Text(term.def);\n\n // XXX a bit hacky - make it faster\n for(var i in term) {\n if(term[i] != null && term[i].length && term[i].length > 400)\n term[i] = new Text(term[i]);\n }\n\n // create in datastore\n var termEntity;\n try {\n var termKey = googlestore.createKey(\"term\", term.id),\n termEntity = googlestore.get(termKey);\n googlestore.set(termEntity, term);\n } catch (e) {\n // no entity foudn with this id, create it\n termEntity = googlestore.entity(\"term\", term.id, term);\n }\n\n\n googlestore.put(termEntity);\n }",
"function createStore (options, id) {\n debug('Creating FS store ' + id + ' with following parameters', options)\n return store(options)\n}",
"function BaseTermsService(baseConnectionService, payloadCommandService) {\n this.baseConnectionService = baseConnectionService;\n this.payloadCommandService = payloadCommandService;\n this.appResources = null;\n this.appPropertyList = {};\n /**\n * Common terms of base terms service\n */\n this._commonTerms = null;\n }",
"setupErrorServiceProvider(errorService) {\n initializeErrorServiceProvider(errorService)\n .then(errorService => {\n this.errorService = errorService;\n })\n .catch(e => {\n console.error(\"Failed to initialize error service\", e);\n });\n }",
"function storeErrorLog (e) {\n const errors = store.get('errors') || []\n const newError = {\n kind: 'API comms error',\n date: moment().format(),\n details: JSON.stringify(e)\n }\n const currentErrors = errors.length >= 50 ? errors.slice(1) : errors\n store.set('errors', [...currentErrors, newError])\n}",
"function createStores() {\n for (let i = 0; i < locations.length; i++)\n {\n new Store(locations[i], minHourlyCustomersPerStore[i], maxHourlyCustomersPerStore[i], avgCookiesPerSalePerStore[i]);\n }\n}",
"init() {\n if (this._store) throw new Error('Store is already initiated, you cannot initiate it twice.');\n\n this._store = Redux.createStore(this._reducer.bind(this), this._initialState, this._enhancer);\n }",
"constructor () {\n this.rootStore = new Store();\n }",
"function Store() {\n if (!(this instanceof Store)) {\n return new Store();\n };\n}",
"function defineStore(){\n Store = _requireById(store_id).default;\n console.log(Store);\n initHandler();\n}",
"async store({ request }) {\n\t\tconst { taxonomy, description } = request.all();\n\t\treturn Taxonomy.create({ taxonomy, description });\n\t}",
"createService() {\r\n this._service = new CurrencyService();\r\n }",
"async storeCreate(_newStore) {\n return new Promise((resolve, reject) => {\n var newStore = new Store(_newStore);\n newStore.save()\n .then(docs => {\n resolve(docs);\n })\n .catch(err => {\n reject(err);\n })\n });\n }",
"function FlattenerStoreError(message) { this.message = message; }",
"constructor() { \n \n OntologyTerm.initialize(this);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Displays the profile of the user with code 'code', or an error message if code does not exist | function displayProfile(code, req, res) {
User.getUserByCode(code, function (err, user) {
if (!user) {
req.flash('error_msg', 'No user found');
res.redirect('/');
} else if (err) {
req.flash('error_msg', 'Error encountered, please try again');
res.redirect('/');
} else {
res.render('profile', {
displayUser: user
});
}
});
} | [
"function displayProfile() {\n //Format and display the profile bits\n $('#profile-view .nickname').text(userProfile.nickname);\n $('#profile-view .full-profile').text(JSON.stringify(userProfile, null, 2));\n $('#profile-view img').attr('src', userProfile.picture);\n }",
"function showProfile(profile, currentUser) {\n profile.children.item(0).innerHTML = currentUser.username;\n profile.children.item(1).innerHTML = currentUser.title;\n profile.children.item(2).innerHTML = currentUser.score;\n profile.children.item(1).style.color = '#e40046';\n profile.children.item(1).style.fontWeight = 'bold';\n profile.children.item(2).style.color = '#e40046';\n profile.children.item(2).style.fontWeight = 'bold';\n profile.children.item(3).innerHTML = currentUser.email;\n return;\n}",
"function showProfileInfo() {\n if (currentUser) {\n $navWelcome.text(currentUser.name);\n $myProfileName.text(`Name: ${currentUser.name}`);\n $myUsername.text(`UserName: ${currentUser.username}`);\n $myProfileAccountDate.text(`Account Created: ${currentUser.createdAt}`);\n }\n }",
"function displayProfile(){\n\t\tGlobalFactory.getUserInfo($stateParams.id).then(function(res){\n\t\t\tvm.profile = res.data;\n\t\t\tconsole.log(vm.profile);\n\t\t});\n\t}",
"function displayUser() {\r\n if (liff.isLoggedIn()) {\r\n liff.getProfile()\r\n .then(profile => {\r\n document.getElementsByClassName('greeting')[0].innerHTML = `Hallo ${profile.displayName}, Welcome to JAJAN SOLO. Happy Foodie`;\r\n document.querySelector('#account > img').src = profile.pictureUrl;\r\n })\r\n .catch((err) => {\r\n console.log('error', err);\r\n });\r\n }\r\n}",
"function showProfile() {\n $(\"#pName\").text(currentUser.name);\n $(\"#pUser\").text(currentUser.username);\n $(\"#pCreated\").text(currentUser.createdAt);\n $userProfile.show();\n }",
"function renderProfile() {\n if (userId) {\n userService\n .findUserById(userId, function (currentUser) {\n console.log(currentUser);\n $usernameFld.val(currentUser.username);\n $firstNameFld.val(currentUser.firstName);\n $lastNameFld.val(currentUser.lastName);\n $phoneNumberFld.val(currentUser.phone);\n $emailFld.val(currentUser.email);\n $dobFld.val(currentUser.dateOfBirth);\n $roleFld.val(currentUser.role);\n });\n } else {\n throw new Error(\"User not logged in\");\n }\n }",
"function getUserProfile () {\n if (!userProfile) {\n var accessToken = localStorage.getItem('access_token');\n\n if (!accessToken) {\n swal({\n type: 'warning',\n title: 'Missing Data',\n text: 'Access token must exist to fetch user profile'\n });\n }\n\n webAuth.client.userInfo(accessToken, (err, profile) => {\n if (profile) {\n userProfile = profile;\n displayProfile();\n }\n });\n } else {\n displayProfile();\n }\n }",
"function DisplayStatus(code) {\n switch (code) {\n case 2:\n InvalidStatus(\"Failed to add new user account into the system\");\n break;\n case 4:\n InvalidStatus(\"IP/Username already exists in the database\");\n break;\n case 10:\n SuccessStatus(\"System updated successfully\");\n break;\n case 11:\n InvalidStatus(\"You have reached the Maximum User Limit\");\n break;\n case 12:\n InvalidStatus(\"You have entered an invalid email to the system\");\n break;\n default:\n return -1;\n }\n}",
"function getAndRenderUsername(){\n\tgetUserProfile(renderUsername);\n}",
"function profile(req, res, next) {\n // Save the requested id in side a variable\n var id = req.params.id;\n\n // Connect to the database and check if the id exists then start the done callback\n connection.query('SELECT * FROM users WHERE id = ?', id, done);\n\n function done(err, data) {\n if (err) {\n next(err);\n } else if (data.length === 0) {\n next();\n } else {\n // If the id exists render profile.ejs with the associated information of the user\n res.render('profile.ejs', {data: data[0], user: req.session.user});\n }\n }\n}",
"function renderUsername(data){\n\t$('#js-user-header').html(`<p>Welcome ${data.userprofile[0].name}`);\n}",
"function getUser() {\n axios.get('https://api.github.com/users/Ahisanz')\n .then(res => showProfile(res))\n .catch(err => showPreMade())\n }",
"function generateProfile() {\n $(\"#profile-name\").text(`Name: ${currentUser.name}`);\n $(\"#profile-username\").text(`Username: ${currentUser.username}`);\n $(\"#profile-account-date\").text(\n `Account Created: ${currentUser.createdAt.slice(0, 10)}`\n );\n $navUserProfile.text(`${currentUser.username}`);\n }",
"function getProfile() {\n if (!userProfile) {\n var accessToken = localStorage.getItem('access_token');\n\n if (!accessToken) {\n console.log('Access token must exist to fetch profile');\n }\n\n webAuth.client.userInfo(accessToken, function(err, profile) {\n if (profile) {\n userProfile = profile;\n displayProfile();\n }\n });\n } else {\n displayProfile();\n }\n }",
"async function profilePage() {\n if (getPath() === 'profile.html') {\n const params = new URLSearchParams(document.location.search.substring(1));\n let overview;\n if (params.has('user')) {\n // Hide edit button\n document.querySelector('a.edit').classList.add('hide');\n\n // Fetch user profile\n const id = params.get('user');\n const [user] = await UserAPI.fetchUser(id);\n // Fetch user records\n const baseUrl = RecordAPI.uri;\n const url = `${baseUrl}/records?user=${id}`;\n const records = await RecordAPI.fetchRecords(url);\n overview = generateOverview(records);\n renderProfile(user, overview);\n } else {\n const { user } = auth();\n overview = getOverview();\n renderProfile(user, overview);\n }\n }\n}",
"function getProfile(userName){\n\n\t\tvar profileValues = getProfileData(userName);\n\t\n\t\tif(profileValues != null)\n\t\t\treturn \"<div class='miniprofile'> \" +\n\t\t\t\t\t\t\t\t\t\"@\"+profileValues.name +\n\t\t\t\t\t\t\t\t\t\"<br/>\"+profileValues.description +\n\t\t\t\t\t\t\t\t\t\"<br/>\"+profileValues.location +\n\t\t\t\t\t\t\t\t\t\"<br/>\"+profileValues.followers + \" followers\" +\n\t\t\t\t\t\t\t\t\t\"<br/>\"+profileValues.following + \" following\" +\n\t\t\t\t\t\t\t\t\t\"<br/>\"+profileValues.tweetcount + \" tweets\" +\n\t\t\t\t\t\t\t\t\t\"<br/>Last Tweet: '\"+profileValues.lasttweet +\n\t\t\t\t\t\t\t\t\t\"'<br/></div>\";\n\t\telse\n\t\t\treturn \"<div id='miniprofile'> Sorry user is no longer online </div>\";\n\t}",
"function showUserInfo() {\n let user = auth.currentUser;\n $mainAvatar.html('<img src=\"' + user.photoURL + '\"></div>');\n $mainUserName.html(user.displayName);\n }",
"getUserProfile(success, failure) {\n ApolloService.query({\n query: Queries.GET_USER_PROFILE\n }).then(data => { success(this.handleResponse(data.data.getUserProfile, \"user\")) }).catch(error => failure(error));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verifies the error thrown by a LocalStore operation. If a LocalStore operation fails because the primary lease has been taken by another client, we ignore the error (the persistence layer will immediately call `applyPrimaryLease` to propagate the primary state change). All other errors are rethrown. | function Li(t) {
return r(this, void 0, void 0, (function() {
return s(this, (function(n) {
if (t.code !== T.FAILED_PRECONDITION || t.message !== Ji) throw t;
return di("LocalStore", "Unexpectedly lost primary lease"), [ 2 /*return*/ ];
}));
}));
} | [
"function tr(t) {\n return e.__awaiter(this, void 0, void 0, function () {\n return e.__generator(this, function (e) {\n if (t.code !== h.FAILED_PRECONDITION || t.message !== Ve) throw t;\n return de(\"LocalStore\", \"Unexpectedly lost primary lease\"), [2\n /*return*/\n ];\n });\n });\n}",
"function ai(t) {\n return e.__awaiter(this, void 0, void 0, function () {\n return e.__generator(this, function (e) {\n if (t.code !== x.FAILED_PRECONDITION || t.message !== xn)\n throw t;\n return (\n h(\"LocalStore\", \"Unexpectedly lost primary lease\"),\n [\n 2,\n /*return*/\n ]\n );\n });\n });\n }",
"function Do(e) {\n return t.__awaiter(this, void 0, void 0, (function() {\n return t.__generator(this, (function(t) {\n if (e.code !== a.FAILED_PRECONDITION || e.message !== ti) throw e;\n return l(\"LocalStore\", \"Unexpectedly lost primary lease\"), [ 2 /*return*/ ];\n }));\n }));\n}",
"_onSilentRenewError(error) {\n this.props.store.dispatch(silentRenewError(error));\n }",
"notifyIfError() {\n if (this.store.error) {\n Notifications.error(`${this.store.error} ${noteOwner}`);\n }\n }",
"_onStoreError(error, operationId, data) {\n\t\tif (operationId==this.state.saveOperation) {\n\t\t\tlogger.trace(this.constructor.name + \":ControllerComponent# _onStoreError()\");\n\t\t\tthis.setState({\n\t\t\t\tsaving: false,\n\t\t\t\tsaveOperation: null\n\t\t\t});\n\t\t}\n\t}",
"_validateIsReady(){if(!this._cacheStore.isReady()){throw getLdsInternalError(\"INVALID_LDS_CACHE_ACCESS\",\"Programmer Error: LDS Cache had attempted access before it was ready!\",true);}}",
"function testVerifyPhoneNumberForExisting_invalidRequest_missingTempProof() {\n var expectedRequest = {\n 'phoneNumber': '+16505550101',\n 'operation': 'REAUTH'\n };\n asyncTestCase.waitForSignals(1);\n rpcHandler\n .verifyPhoneNumberForExisting(expectedRequest)\n .thenCatch(function (error) {\n fireauth.common.testHelper.assertErrorEquals(\n new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR),\n error\n );\n asyncTestCase.signal();\n });\n}",
"function TableResource_LocalSecondaryIndexPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n errors.collect(cdk.propertyValidator('indexName', cdk.requiredValidator)(properties.indexName));\n errors.collect(cdk.propertyValidator('indexName', cdk.validateString)(properties.indexName));\n errors.collect(cdk.propertyValidator('keySchema', cdk.requiredValidator)(properties.keySchema));\n errors.collect(cdk.propertyValidator('keySchema', cdk.listValidator(TableResource_KeySchemaPropertyValidator))(properties.keySchema));\n errors.collect(cdk.propertyValidator('projection', cdk.requiredValidator)(properties.projection));\n errors.collect(cdk.propertyValidator('projection', TableResource_ProjectionPropertyValidator)(properties.projection));\n return errors.wrap('supplied properties not correct for \"LocalSecondaryIndexProperty\"');\n }",
"function testVerifyAssertionForExisting_error() {\n asyncTestCase.waitForSignals(1);\n // Same client side validation as verifyAssertion.\n rpcHandler\n .verifyAssertionForExisting({\n 'requestUri': 'http://localhost/callback#oauthResponse'\n })\n .thenCatch(function (error) {\n fireauth.common.testHelper.assertErrorEquals(\n new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR),\n error\n );\n asyncTestCase.signal();\n });\n}",
"function localStoreNotifyLocalViewChanges(localStore, viewChanges) {\n return tslib.__awaiter(this, void 0, void 0, function () {\n var localStoreImpl, e_2, _i, viewChanges_1, viewChange, targetId, targetData, lastLimboFreeSnapshotVersion, updatedTargetData;\n return tslib.__generator(this, function (_d) {\n switch (_d.label) {\n case 0:\n localStoreImpl = debugCast(localStore);\n _d.label = 1;\n case 1:\n _d.trys.push([1, 3, , 4]);\n return [4 /*yield*/, localStoreImpl.persistence.runTransaction('notifyLocalViewChanges', 'readwrite', function (txn) {\n return PersistencePromise.forEach(viewChanges, function (viewChange) {\n return PersistencePromise.forEach(viewChange.addedKeys, function (key) { return localStoreImpl.persistence.referenceDelegate.addReference(txn, viewChange.targetId, key); }).next(function () { return PersistencePromise.forEach(viewChange.removedKeys, function (key) { return localStoreImpl.persistence.referenceDelegate.removeReference(txn, viewChange.targetId, key); }); });\n });\n })];\n case 2:\n _d.sent();\n return [3 /*break*/, 4];\n case 3:\n e_2 = _d.sent();\n if (isIndexedDbTransactionError(e_2)) {\n // If `notifyLocalViewChanges` fails, we did not advance the sequence\n // number for the documents that were included in this transaction.\n // This might trigger them to be deleted earlier than they otherwise\n // would have, but it should not invalidate the integrity of the data.\n logDebug(LOG_TAG$c, 'Failed to update sequence numbers: ' + e_2);\n }\n else {\n throw e_2;\n }\n return [3 /*break*/, 4];\n case 4:\n for (_i = 0, viewChanges_1 = viewChanges; _i < viewChanges_1.length; _i++) {\n viewChange = viewChanges_1[_i];\n targetId = viewChange.targetId;\n if (!viewChange.fromCache) {\n targetData = localStoreImpl.targetDataByTarget.get(targetId);\n lastLimboFreeSnapshotVersion = targetData.snapshotVersion;\n updatedTargetData = targetData.withLastLimboFreeSnapshotVersion(lastLimboFreeSnapshotVersion);\n localStoreImpl.targetDataByTarget = localStoreImpl.targetDataByTarget.insert(targetId, updatedTargetData);\n }\n }\n return [2 /*return*/];\n }\n });\n });\n}",
"validateState(state, cachedState) {\n if (!state) {\n throw NodeAuthError.createStateNotFoundError();\n }\n if (state !== cachedState) {\n throw msalCommon.ClientAuthError.createStateMismatchError();\n }\n }",
"function verifyLocalFoldersAccount(am) {\n let localMailServer;\n try {\n localMailServer = am.localFoldersServer;\n } catch (ex) {\n localMailServer = null;\n }\n\n try {\n if (!localMailServer) {\n // creates a copy of the identity you pass in\n am.createLocalMailAccount();\n try {\n localMailServer = am.localFoldersServer;\n } catch (ex) {\n AccountCreationUtils.ddump(\n \"Error! we should have found the local mail server \" +\n \"after we created it.\"\n );\n }\n }\n } catch (ex) {\n AccountCreationUtils.ddump(\"Error in verifyLocalFoldersAccount \" + ex);\n }\n}",
"_throwIfRoot(name) {\n if (this._location.path === '') {\n throw invalidRootOperation(name);\n }\n }",
"function testVerifyAssertionForExisting_invalidRequestError() {\n // Test when request is invalid.\n asyncTestCase.waitForSignals(1);\n rpcHandler\n .verifyAssertionForExisting({ 'postBody': '....' })\n .thenCatch(function (error) {\n fireauth.common.testHelper.assertErrorEquals(\n new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR),\n error\n );\n asyncTestCase.signal();\n });\n}",
"function FlattenerStoreError(message) { this.message = message; }",
"function error (args, err, cb) {\n if (err) {\n seneca.log.debug('error: ' + err)\n seneca.fail({code: 'entity/error', store: NAME}, cb)\n\n if ('ECONNREFUSED' === err.code || 'notConnected' === err.message || 'Error: no open connections' === err) {\n minwait = opts.minwait\n if (minwait) {\n reconnect(args)\n }\n }\n return true\n }\n return false\n }",
"function CfnTable_LocalSecondaryIndexPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n errors.collect(cdk.propertyValidator('indexName', cdk.requiredValidator)(properties.indexName));\n errors.collect(cdk.propertyValidator('indexName', cdk.validateString)(properties.indexName));\n errors.collect(cdk.propertyValidator('keySchema', cdk.requiredValidator)(properties.keySchema));\n errors.collect(cdk.propertyValidator('keySchema', cdk.listValidator(CfnTable_KeySchemaPropertyValidator))(properties.keySchema));\n errors.collect(cdk.propertyValidator('projection', cdk.requiredValidator)(properties.projection));\n errors.collect(cdk.propertyValidator('projection', CfnTable_ProjectionPropertyValidator)(properties.projection));\n return errors.wrap('supplied properties not correct for \"LocalSecondaryIndexProperty\"');\n}",
"_throwIfRoot(name) {\n if (this._location.path === '') {\n throw invalidRootOperation(name);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
===========================================================// Utility functions for generating lists of frame parameters // =========================================================== | function generatePathFrameParameters() {
var path_sizes = [20, 50, 200, 300, 400];
var quantities = [10, 20, 50, 100, 500, 1000, 2000];
var shadow_blurs = [0, 1, 10, 20];
// Only draw combinations that contain shadows with this probability
// to reduce the number of permutations.
var shadowedPermutationProbability = 0.1;
var list_of_frame_parameters = [];
for (shape_type in SHAPE_TYPE) {
for (var size_i = 0; size_i < path_sizes.length; size_i++) {
for (var qty_i = 0; qty_i < quantities.length; qty_i++) {
for (var sh_i = 0; sh_i < shadow_blurs.length; sh_i++) {
for (fill_style in SHAPE_STYLE) {
if (shadow_blurs[sh_i] == 0
|| getTrueWithProbability(shadowedPermutationProbability)) {
list_of_frame_parameters.push([
new DrawParameter(CALL_TYPE.PATH, shape_type,
path_sizes[size_i], shadow_blurs[sh_i],
quantities[qty_i], fill_style)]);
}
}
}
}
}
}
return list_of_frame_parameters;
} | [
"function list() {\n\t//create a variable to hold the number of incoming values from a list\n\tvar numberOfArgumentsEntered = arguments.length;\n\t//if that value is greater than the number of parameters, make that number smaller\n\tif(numberOfArgumentsEntered > 4) {\n\t\tnumberOfArgumentsEntered = 4;\n\t\t}\n\t//fill the params array with the incoming arguments\n\tfor(var i = 0; i < numberOfArgumentsEntered; i++) {\n\t\t\tparams[i] = arguments[i];\n\t\t}\n\tcheckExponent();\n\tcheckMode();\n}",
"function getParamListContents() {\n\tvar retArray = new Array();\n\tvar tempArray;\n\n//\tvar contents = _ParamList.getValue(\"all\");\n//\tfor (var i=0; i<contents.length; i++) {\n//\t\tretArray.push(new Array());\n//\t\tretArray[i].push(contents[i].name);\n//\t\tretArray[i].push(contents[i].type);\n//\t\tretArray[i].push(contents[i].defaultVal);\n//\t\tretArray[i].push(contents[i].runtimeVal);\n//\t}\n\n\tretArray = _ParamList.getValue(\"all\");\n\n\treturn retArray;\n}",
"getSignAndFrameInfo() {\n//------------------\n// Handle frame beyond end of animation\nif (this.fCur === this.fCount) {\nreturn [\"[none]\", this.signs.length, this.fCur];\n} else {\n// Rely on @frameCur being set according to @fCur\nreturn [this.frameCur.sign.gloss, this.frameCur.sign.i, this.fCur];\n}\n}",
"function getFrameMetaData() {\n let ret = [];\n for(let i=1; i<total_frame+1; i++) {\n let tab_indexes = preparation_editor.getTrackletsIndexes(i, false, true);\n let keypoints = frames_data[i];\n let o = {};\n o.ActsOnStage = [];\n for( let obj of tab_indexes) {\n if(obj.act && keypoints[obj.ind]) {\n let meta_data = {};\n meta_data.ActName = obj.act.actor_name;\n let bbox = getBBox(keypoints[obj.ind]['KeyPoints']);\n meta_data.BoundingBox = {w:int(bbox[2]-bbox[0]),l:int(bbox[3]-bbox[1])};\n meta_data.Surface = meta_data.BoundingBox.w * meta_data.BoundingBox.l;\n meta_data.GazeVect = p5VectToJson(getGazevect(keypoints[obj.ind]['KeyPoints']));\n meta_data.VelocityVect = p5VectToJson(obj.act.getVelocityVect(i));\n meta_data.KeyPoints = keypoints[obj.ind]['KeyPoints'];\n o.ActsOnStage.push(meta_data);\n }\n }\n ret.push(o);\n }\n // console.log(ret);\n createStringDict(ret).saveJSON('frames_metadata');\n }",
"function getPlayerParams() {\n let params = [[],[]]\n const names = ['blue','red','green','yellow','purple','orange','pink','skyblue'];\n let max = parseInt(document.getElementById('player_num').value);\n params[0] = names.slice(0,max)\n params[1].push(true);\n params[1].push(document.getElementById('player_faceup').checked);\n params[1].push(document.getElementById('player_stack').checked);\n params[1].push(document.getElementById('player_vert').checked);\n params[1].push(document.getElementById('player_secret').checked);\n params[1].push(parseInt(document.getElementById('player_max').value));\n return params;\n}",
"function getParams() {\n if (!window.frameElement.hasAttribute('data-params')) {\n return;\n }\n params = JSON.parse(decodeURIComponent(window.frameElement.getAttribute('data-params')));\n }",
"function parameters() {\n\n // Initialize parameter array if necessary\n if ( typeof parameters.values === \"undefined\" )\n parameters.values = new paramObject();\n\n // Define default values for parameters\n if ( typeof parameters.values.mode == 'undefined' )\n parameters.values.mode = \"View\";\n if ( typeof parameters.values.elem == 'undefined' )\n parameters.values.elem = \"C\";\n if ( typeof parameters.values.clouds == 'undefined' )\n parameters.values.clouds = 4;\n if ( typeof parameters.values.add == 'undefined' )\n parameters.values.add = \"Add\";\n if ( typeof parameters.values.bond == 'undefined' )\n parameters.values.bond = \"Add\";\n if ( typeof parameters.values.bondtype == 'undefined' )\n parameters.values.bondtype = \"single\";\n if ( typeof parameters.values.action == 'undefined' )\n parameters.values.action = \"press\";\n if ( typeof parameters.values.mousedownxyz == 'undefined' )\n parameters.values.mousedownxyz = [0,0,0];\n if ( typeof parameters.values.centermove == 'undefined' )\n parameters.values.centermove = [0,0,0];\n // End of parameters routine\n return parameters.values;\n }",
"getFrameValues(){\n this.frameWidth = $(this.frame).children().width() * $(this.frame).children().length;\n var itemPadding = parseInt($($(this.frame).children()).css(\"padding-right\")) * $(this.frame).children().length;\n\n this.frameWidth = itemPadding + this.frameWidth;\n this.containerFrame = $(this.swipperContainer).width();\n this.childFrameWidth = $($(this.frame).children()[0]).width() + parseInt($($(this.frame).children()[0]).css(\"padding-right\"));\n }",
"static get parameterDescriptors() {\n\treturn [\n\t {\n\t\tname: 'azimuth',\n\t\tdefaultValue: 0.0\n\t },\n\t {\n\t\tname: 'elevation',\n\t\tdefaultValue: -1.57\n\t }\n\t]\n }",
"function buildFrameLIs(){\n $('#action-frames').html('');\n var l = viking.sprites[sprite][action].frames.length;\n \n for(i=0; i< l; i++ ){\n var data = viking.sprites[sprite][action].frames[i];\n $('#action-frames').append( '<li><canvas id=\"action-frame-'+i+'\" width=\"64\" height=\"64\"></canvas></li>' );\n var ctxx = $('#action-frames canvas:last')[0].getContext('2d');\n ctxx.clearRect(0,0,64,64);\n ctxx.putImageData(data,0,0);\n }\n }",
"function getParameterNames(f) {\n var fnStr = getSourceCode(f).replace(STRIP_COMMENTS, '');\n var parameterNames = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')'))\n .match(ARGUMENT_NAMES);\n if (parameterNames === null) {\n return [];\n }\n return parameterNames;\n}",
"async compileParameterList () {\n this.pushScope('compile parameter list')\n await this.pause()\n const { tokenizer } = this\n const isParameterEnd = this.lookAhead(')')\n if (isParameterEnd) {\n this.popScope()\n return\n }\n\n while (true) {\n await this.compileType()\n const type = this.tokenizer.tokenValue()\n this.assert({ [TOKEN_TYPE.IDENTIFIER]: null })\n const name = tokenizer.tokenValue()\n this.symbolTable.define(name, type, KIND_TYPE.ARG)\n tokenizer.advance()\n if (tokenizer.tokenValue() !== ',') {\n tokenizer.back()\n break\n }\n }\n\n this.popScope()\n }",
"getAllParameters(headerStr) {\n headerStr = headerStr.replace(/[\\r\\n]+[ \\t]+/g, \"\");\n let hdrMap = jsmime.headerparser.parseParameterHeader(\n \";\" + headerStr,\n true,\n true\n );\n\n let paramArr = [];\n let i = hdrMap.entries();\n let p = i.next();\n while (p.value) {\n paramArr[p.value[0].toLowerCase()] = p.value[1];\n p = i.next();\n }\n\n return paramArr;\n }",
"makeFrame(arg) {\n let frame = new Array(this.arity);\n let n = this.fixedArgs;\n let i = 0;\n for (; i < n && arg !== null; i++) { // Set the list of fiexed args.\n frame[i] = arg.car;\n arg = cdrCell(arg);\n }\n if (i !== n || (arg !== null && !this.hasRest))\n throw new EvalException(\"arity not matched\", this);\n if (this.hasRest)\n frame[n] = arg;\n return frame;\n }",
"function prepareStackInfo() {\n \tvar stackInfo = [];\n \tframeInfo = [];\n \t\n \tfor (var i=callStackDepth-1; i >= 0; i--) {\n \t\t\n \t\tvar frameInfo = {};\n \t\tframeInfo.callFrameId = \"stack:\"+i;\n \t\tframeInfo.functionName = callStack[i].name;\n \t\tframeInfo.location = {\n \t\t\tscriptId : i == callStackDepth-1 ? lastFile : callStack[i+1].lastFile,\n \t\t\tlineNumber : i == callStackDepth-1 ? lastLine : callStack[i+1].lastLine,\n \t\t\tcolumnNumber : 0\n \t\t};\n \t\t\n \t\t// add frame 'scopeChain[]' info\n \t\tframeInfo.scopeChain = [];\n \t\tvar scope = { object : {}, type : 'local'};\n \t\t\n \t\tscope.object = {\n \t\t\ttype : 'object',\n \t\t\tobjectId : 'stack:' + i,\n \t\t\tclassName : 'Object',\n \t\t\tdescription : 'Object'\n \t\t};\n \t\tframeInfo.scopeChain.push(scope);\n \t\t\n \t\t// add frame 'this' info\n \t\tframeInfo['this'] = {\n \t\t\ttype : typeof(callStack[i].that),\n \t\t\tobjectId : 'stack:' + i + ':this',\n \t\t\tclassName : callStack[i].that.constructor.name,\n \t\t\tdescription : callStack[i].that.constructor.name\n \t\t};\n \t\t\n \t\tstackInfo.push(frameInfo);\n \t}\n \treturn stackInfo;\n }",
"function make_frame(names, values) {\n return pair(names, values);\n}",
"function getKeyframes() {\n postxt = '';\n var comp = app.project.activeItem;\n var lyr = comp.selectedLayers[0];\n var maxFrames = comp.duration * 30;\n\n for (var frame = 0; frame < maxFrames; frame++) {\n var pos = lyr.transform.position.valueAtTime(comp.frameDuration * frame, true);\n posx = pos[0];\n posy = pos[1];\n postxt += Math.round(posx) + ',' + Math.round(posy) + '\\n';\n }\n\n return postxt;\n}",
"static get paramIds () { return [] }",
"function _createImplicitFrame(flags){var frame={};for(var key in flags){if(flags[key]!==undefined){frame['@'+key]=[flags[key]];}}return[frame];}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the quadrant of an angle. | _getQuadrant(angle) {
if (angle > 270) {
return 4;
}
else if (angle > 180) {
return 3;
}
else if (angle > 90) {
return 2;
}
else {
return 1;
}
} | [
"get quadrant() {\n const a = this.normalize().value;\n\n if (a > 0 && a < Angle.SPI) return 1;\n if (a > Angle.SPI && a < Angle.PI) return 4;\n if (a > -Angle.PI && a < -Angle.SPI) return 3;\n if (a > -Angle.SPI && a < 0) return 2;\n return undefined;\n }",
"function getQuadrant(angle) { \n return (angle >= 0 && angle < 90)? 1:\n (angle >= 90 && angle < 180)? 2:\n (angle >= 180 && angle < 270)? 3: 4;\n}",
"function getQuadrant({ x, y }) {\n\t\tif (x >= -epsilon && y < -epsilon) {\n\t\t\treturn 0;\n\t\t} else if (x < -epsilon && y < -epsilon) {\n\t\t\treturn 1;\n\t\t} else if (x < 0 && y >= -epsilon) {\n\t\t\treturn 2;\n\t\t} else if (x >= -epsilon && y >= -epsilon) {\n\t\t\treturn 3;\n\t\t}\n\t\treturn null;\n\t}",
"getQuadrangle()\n {\n return this.quad;\n }",
"function getQuadrantForCoords(x, y) {\n if (x >= 0 && y >= 0) return 1\n else if (x >= 0 && y <= -0) return 2\n else if (x <= -0 && y <= -0) return 3\n else if (x <= -0 && y >= 0) return 4\n}",
"getDragQuadrant (x,y) {\n const relx = this.locked[0] - x;\n const rely = this.locked[1] - y;\n if ((relx < 0) && (rely < 0)) return 'br';\n else if ((relx >= 0) && (rely >= 0)) return 'tl';\n else if ((relx < 0) && (rely >= 0)) return 'tr';\n else return 'bl';\n }",
"function getQuadrant(){\n var ns = \"S\";\n var ew = \"W\";\n var concat;\n\n if(pos.lat > 45.523063){\n ns = \"N\";\n }\n if(pos.lng > -122.667677){\n ew = \"E\";\n }\n concat = ns + ew;\n return concat;\n}",
"function Quadrant() {\n var _this;\n\n _this = _ComponentInterface.call(this) || this;\n var quadrant = (0, _assertThisInitialized2[\"default\"])(_this);\n quadrant.pIndex = 1;\n quadrant.components = {};\n quadrant.conf = {};\n quadrant.graphics = {};\n return _this;\n }",
"function getLongitudeQuadrant(longitude) {\n const oneOverPI = 1 / Math.PI;\n const quadrantIndex = Math.floor(2 * (longitude * oneOverPI + 1));\n return MathUtils_1.MathUtils.clamp(quadrantIndex, 0, 4);\n}",
"function judgeAngleInQuadrant (angle, counterclockwise) {\n if (counterclockwise) {\n if (0 <= angle && angle < 0.5 * Math.PI) {\n return 1\n }\n else if (0.5 * Math.PI <= angle && angle < Math.PI) {\n return 2\n }\n else if (Math.PI <= angle && angle < 1.5 * Math.PI) {\n return 3\n }\n else if (1.5 * Math.PI <= angle && angle < 2 * Math.PI) {\n return 4\n }\n }\n else {\n if (1.5 * Math.PI <= angle && angle < 2 * Math.PI) {\n return 1\n }\n else if (Math.PI <= angle && angle < 1.5 * Math.PI) {\n return 2\n }\n else if (0.5 * Math.PI <= angle && angle < Math.PI) {\n return 3\n }\n else if (0 <= angle && angle < 0.5 * Math.PI) {\n return 4\n }\n }\n return null\n}",
"function angle(quat) {\n var a = quat[0];\n if (a < -1.0 || a > 1.0)\n return 0.0;\n var angle = 2 * Math.acos(a);\n if (angle > Math.PI)\n return (angle - 2 * Math.PI);\n return angle;\n}",
"getPositionQuadrant(x, y)\n {\n //Quadrants clockwise from a 0 top-left\n let top = null;\n let left = null;\n\n if (y < Math.floor(this.width/2))\n {\n top = true;\n }\n else\n {\n top = false;\n }\n\n if (x < Math.floor(this.height/2))\n {\n left = true;\n }\n else\n {\n left = false;\n }\n\n let quadrant = 0;\n\n if (top && left)\n {\n quadrant = 0;\n }\n else if (top && !left)\n {\n quadrant = 1;\n }\n else if (!top && !left)\n {\n quadrant = 2;\n }\n else if (!top && left)\n {\n quadrant = 3;\n }\n\n return quadrant;\n }",
"function getTextRotationByQuadrant(_angle) {\n var rotationAngle = _angle;\n\n if (isAngleInLeftHemisphere(rotationAngle)) {\n rotationAngle = rotationAngle - 180;\n }\n\n return rotationAngle;\n}",
"function getQuadrant(pointerPos) {\n switch(pointerPos.x < 0) {\n case true:\n switch(pointerPos.y < 0) {\n case true: return 3;\n case false: return 4;\n }\n break;\n case false:\n switch(pointerPos.y < 0) {\n case true: return 2;\n case false: return 1;\n }\n break;\n }\n}",
"function areaQuadrado(lado) {\n return lado * lado;\n }",
"function perimetroQuadrado(lado) {\n \n return lado * 3;\n}",
"function findQuadrant() {\n var area = 0;\n var slot = null;\n function find(node) {\n if (node instanceof Desktop) {\n find(node.child);\n }\n else if (node instanceof Split) {\n find(node.first);\n find(node.second);\n }\n else if (node instanceof Window) {\n var winArea = node.width * node.height / 2;\n if (winArea > area) {\n area = winArea;\n slot = node;\n node.quadrant = (node.width > node.height) ?\n 'right' : 'bottom';\n }\n }\n else if (node instanceof Empty) {\n var newArea = node.width * node.height;\n if (newArea > area) {\n area = newArea;\n slot = node;\n }\n }\n }\n find(desktop);\n return slot;\n }",
"function Circolare2Quadrantale(rotta){\n let rottaQuad;\n if (rotta<=90){\n rottaQuad=rotta;\n }else if ((rotta>90) && (rotta<=180)){\n rottaQuad=180-rotta;\n }else if ((rotta>180) && (rotta<=270)){\n rottaQuad=rotta-180;\n }else if ((rotta>270) && (rotta<=360)){\n rottaQuad=360-rotta;\n }else{\n alert(\"Errore trasformazione rotta da circolare in quadrantale.\");\n }\n\n return rottaQuad;\n}//end funcction Circolare2Quadrantale(...)",
"function getLongitudeQuadrant(longitude) {\n const oneOverPI = 1 / Math.PI;\n const quadrantIndex = Math.floor(2 * (longitude * oneOverPI + 1));\n return THREE.Math.clamp(quadrantIndex, 0, 4);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function fetches css applied styles. x needs to be a js object. y needs to be a css property. | function reqStyle(x, y){
return parseInt(window.getComputedStyle(x, null).getPropertyValue(y));
} | [
"function getRecStyle(x, y){\n return parseInt(window.getComputedStyle(x, null).getPropertyValue(y));\n}",
"function getStyles(el,arg) {\n\n\tlist = (arg||\"\").split( /\\s+/ );\n\t//console.log([\"getStyle\",el,arg,list]);\n\n\t// el = element or query\n\t//console.log( \"gbysel\", bySel( el ) );\n\tvar x = bySel( el );\n\n\t// get document\n\tvar doc = x.ownerDocument,\n\t\twin = doc.defaultView;\n\n\t// get effective style object\n\tvar y = ( x.currentStyle )\n\t\t\t\t? x.currentStyle\t\t// IE hack\n\t\t\t\t: win.getComputedStyle(x,null);\n\t//console.log([\"getStyles\", x, y, doc, y['left'], y['top'], x.style.left, x.offsetLeft]);\n\n\t// if 1 arg, return raw style object\n\tif ( arguments.length == 1 ) return y;\n\n\tvar ret = { };\n\tfor (var i=0, prop; prop = list[i]; i++) {\n\t\tif ( y.hasOwnProperty( prop ) )\n\t\t\tret[ prop ] = y[ prop ];\n\t}\n\treturn ret;\n}",
"_getImageStyle (s, x, y) {\n\n x = Math.floor(x);\n y = Math.floor(y);\n x *= s;\n y *= s;\n s *= 100;\n\n return `width:${s}%; top:${y}px; left:${x}px;`;\n\n }",
"function getCSSObj()\n {\n return cssObj;\n }",
"getStyleData(x, y) {\n try {\n return this._styleDataMatrix[x][y]\n }\n catch (err) {\n this._onError(err, `tried to access style of cell ${x}, ${y}`)\n }\n }",
"function accessCSS(layerID)\r\n{ \r\n\treturn document.getElementById(layerID).style;\r\n}",
"function css(node,obj,value){if(node instanceof $.fn.init){node.each(function(){css(this,obj,value);});}else if($.isPlainObject(obj)){Object.keys(obj).forEach(function(key){node.style.setProperty(key,obj[key]);});}else if(typeof value==='undefined'){return node.style.getPropertyValue(obj);}else{node.style.setProperty(obj,value);}}// -----------------------------------------------------------------------",
"function getCustomPropertiesFromCSSFile(_x) {\n return _getCustomPropertiesFromCSSFile.apply(this, arguments);\n}",
"function objCss(o, p, v) {\r\n if (o == null) return null;\r\n if (v != null) o.style[p] = v;\r\n\r\n // Check the inline style first.\r\n var s = o.style[p];\r\n if (s != '' && s != null) {\r\n return s;\r\n }\r\n\r\n // Check MSIE's currentStyle property.\r\n if(o.currentStyle) {\r\n var s = o.currentStyle[p];\r\n if (s != '' && s != null) {\r\n return s;\r\n }\r\n }\r\n\r\n var slctrs = [\"id\", \"class\"];\r\n // Do it the hard way using styleSheets.\r\n for (var i = 0; i < slctrs.length; i++) {\r\n if (!objAtt(o, slctrs[i])) continue;\r\n s = probeCss(objAtt(o, slctrs[i]), p, slctrs[i]);\r\n if(s != '' && s != null) {\r\n return s;\r\n }\r\n }\r\n return null;\r\n\r\n // probeCss ---------------------------------------------------------------\r\n //\r\n // Return the css property p for selector s.\r\n //\r\n // s ... a selector string\r\n // p ... a css property name\r\n // t ... a css selector type (i.e, class, id or tag)\r\n function probeCss(s, p, t) {\r\n if (!s || !p || !document.styleSheets) return null;\r\n if (t == \"class\") s = '.' + s;\r\n if (t == \"id\") s = '#' + s;\r\n\r\n var css = document.styleSheets;\r\n if (css.length > 0) {\r\n // Check each style sheet.\r\n for (var i = 0; i < css.length; i++) {\r\n var rules;\r\n if (css[i].cssRules) {\r\n rules = css[i].cssRules;\r\n } else if (css[i].rules) {\r\n rules = css[i].rules;\r\n } else {\r\n return null;\r\n }\r\n\r\n if (rules.length > 0) {\r\n // Check each rule.\r\n for (var j = 0; j < rules.length; j++) {\r\n var st = rules[j].style;\r\n if (st[p] != '' && st[p] != null &&\r\n rules[j].selectorText == s) {\r\n return st[p];\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return null;\r\n }\r\n}",
"function _css(p, v) {\r\n return objCss(this, p, v);\r\n}",
"function getStyles(el, arguments){\r\n var ret = {};\r\n total = arguments.length ;\r\n for (var n=0; n<total; n++ )\r\n ret[ arguments[n] ] = el.getStyle(arguments[n]); \r\n return ret;\r\n }",
"function xGetCSSRules(ss) { return ss.rules ? ss.rules : ss.cssRules; }",
"function css$get$0() {\n if ( !this.cssCached ) this.stringify();\n return this.cssCached;\n }",
"function photo_getCSSxy(canvas,prop) {\n\tvar nums = canvas.css(prop).split(\" \");\n\t\n\tfor(var i=0;i<nums.length;i++) {\n\t\tnums[i] = Number(nums[i].replace(/[^0-9-]/g, ''));\n\t}\n\treturn nums;\n}",
"function _css(obj)\n{\n return Object.keys(obj).reduce(function(acc, x) {\n return acc + x + \"{\" + (\n x.charAt(0) == '@' ? _css(obj[x]) : Object.keys(obj[x]).reduce(function(acc, y) {\n return acc + y + \":\" + obj[x][y] + \";\";\n }, \"\")) + \"}\";\n }, \"\");\n}",
"async grabCssPropertyFrom(locator, cssProperty) {\n const els = await this._locate(locator);\n const res = await Promise.all(els.map(el => el.executionContext().evaluate(el => JSON.parse(JSON.stringify(getComputedStyle(el))), el)));\n const cssValues = res.map(props => props[cssProperty]);\n\n if (res.length > 0) {\n return cssValues;\n }\n return cssValues[0];\n }",
"function redraw_css(world) {\n\treturn jsworld.map((dragging(world) ? apply_drag(world) : world).styles,\n\t\t\t\t\t\tfunction(style){\n\t\t\t\t\t\t\t return [style.id, \n\t\t\t\t\t\t\t\t\t [\"position\",\tstyle.position],\n\t\t\t\t\t\t\t\t\t [\"left\",\t\tstyle.left + \"px\"],\n\t\t\t\t\t\t\t\t\t [\"top\",\t\tstyle.top + \"px\"],\n\t\t\t\t\t\t\t\t\t [\"opacity\",\tstyle.opacity],\n\t\t\t\t\t\t\t\t\t [\"z-index\",\tstyle.zIndex],\n\t\t\t\t\t\t\t\t\t [\"background\",\tstyle.background]\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\t });\n}",
"calculatePositionStyles(x, y) {\n let viewport = this.map.getViewport()\n\n // compute scale\n let { avatarScale, avatarFarScale } = this.map.room.architecture\n let worldScale = viewport.width / 1000\n if (Number.isFinite(avatarScale)) {\n if (Number.isFinite(avatarFarScale)) {\n var scale = Math.round(((avatarScale * y) + (avatarFarScale * (1.0 - y))) * worldScale * 5000) / 5000\n } else {\n var scale = Math.round(avatarScale * worldScale * 5000) / 5000\n }\n } else {\n var scale = Math.round(1.0 * worldScale * 5000) / 5000\n }\n \n // return css properties appropriate for this object to place it in the supplied coordinates\n return {\n zIndex: `${this.map.xyToZIndex(x, y)}`,\n left: `${Math.round((x * viewport.width) - (this.width * (1.0 - this.anchor.x)))}px`,\n top: `${Math.round((y * viewport.height) - (this.height * (1.0 - this.anchor.y)))}px`,\n transform: `scale(${scale}) translateY(${Math.round(this.height * (1.0 - scale))}px)`,\n // TODO: Experiment with translate using a percentage\n // transform: `scale(${scale}) translateY(${(1.0 - scale) * 100}%)`\n }\n }",
"function getStyleList(o) {\r\n\t\t\tvar cssList = new Array(\"accelerator\",\"azimuth\",\"background\",\"background-attachment\",\"background-color\",\"background-image\",\"background-position\",\"background-position-x\",\"background-position-y\",\"background-repeat\",\"behavior\",\"border\",\"border-bottom\",\"border-bottom-color\",\"border-bottom-style\",\"border-bottom-width\",\"border-collapse\",\"border-color\",\"border-left\",\"border-left-color\",\"border-left-style\",\"border-left-width\",\"border-right\",\"border-right-color\",\"border-right-style\",\"border-right-width\",\"border-spacing\",\"border-style\",\"border-top\",\"border-top-color\",\"border-top-style\",\"border-top-width\",\"border-width\",\"bottom\",\"caption-side\",\"clear\",\"clip\",\"color\",\"content\",\"counter-increment\",\"counter-reset\",\"cue\",\"cue-after\",\"cue-before\",\"cursor\",\"direction\",\"display\",\"elevation\",\"empty-cells\",\"filter\",\"float\",\"font\",\"font-family\",\"font-size\",\"font-size-adjust\",\"font-stretch\",\"font-style\",\"font-variant\",\"font-weight\",\"height\",\"ime-mode\",\"include-source\",\"layer-background-color\",\"layer-background-image\",\"layout-flow\",\"layout-grid\",\"layout-grid-char\",\"layout-grid-char-spacing\",\"layout-grid-line\",\"layout-grid-mode\",\"layout-grid-type\",\"left\",\"letter-spacing\",\"line-break\",\"line-height\",\"list-style\",\"list-style-image\",\"list-style-position\",\"list-style-type\",\"margin\",\"margin-bottom\",\"margin-left\",\"margin-right\",\"margin-top\",\"marker-offset\",\"marks\",\"max-height\",\"max-width\",\"min-height\",\"min-width\",\"-moz-binding-moz-border-radius\",\"-moz-border-radius-topleft\",\"-moz-border-radius-topright\",\"-moz-border-radius-bottomright\",\"-moz-border-radius-bottomleft\",\"-moz-border-top-colors\",\"-moz-border-right-colors\",\"-moz-border-bottom-colors\",\"-moz-border-left-colors\",\"-moz-opacity\",\"-moz-outline\",\"-moz-outline-color\",\"-moz-outline-style\",\"-moz-outline-width\",\"-moz-user-focus\",\"-moz-user-input\",\"-moz-user-modify\",\"-moz-user-select\",\"orphans\",\"outline\",\"outline-color\",\"outline-style\",\"outline-width\",\"overflow\",\"overflow-X\",\"overflow-Y\",\"padding\",\"padding-bottom\",\"padding-left\",\"padding-right\",\"padding-top\",\"page\",\"page-break-after\",\"page-break-before\",\"page-break-inside\",\"pause\",\"pause-after\",\"pause-before\",\"pitch\",\"pitch-range\",\"play-during\",\"position\",\"quotes\",\"-replace\",\"richness\",\"right\",\"ruby-align\",\"ruby-overhang\",\"ruby-position\",\"-set-link-source\",\"size\",\"speak\",\"speak-header\",\"speak-numeral\",\"speak-punctuation\",\"speech-rate\",\"stress\",\"scrollbar-arrow-color\",\"scrollbar-base-color\",\"scrollbar-dark-shadow-color\",\"scrollbar-face-color\",\"scrollbar-highlight-color\",\"scrollbar-shadow-color\",\"scrollbar-3d-light-color\",\"scrollbar-track-color\",\"table-layout\",\"text-align\",\"text-align-last\",\"text-decoration\",\"text-indent\",\"text-justify\",\"text-overflow\",\"text-shadow\",\"text-transform\",\"text-autospace\",\"text-kashida-space\",\"text-underline-position\",\"top\",\"unicode-bidi\",\"-use-link-source\",\"vertical-align\",\"visibility\",\"voice-family\",\"volume\",\"white-space\",\"widows\",\"width\",\"word-break\",\"word-spacing\",\"word-wrap\",\"writing-mode\",\"z-index\",\"zoom\");\r\n\t\t\tvar retCssList = \"\", cssVal = \"\";\r\n\r\n\t\t\t// Iterate through each item in array\r\n\t\t\tfor (var i = 0; i < cssList.length; i++) {\r\n\t\t\t\tcssVal = $(o[\"o\"]).css(cssList[i]);\r\n\t\t\t\tretCssList = retCssList + '<br />' + cssList[i] + ': <span class=\"' + dEdit + ' mk-edit-css-prop_' + cssList[i] + '\">' + cssVal + '</span>';\r\n\t\t\t}\r\n\r\n\t\t\t// Return list\r\n\t\t\treturn retCssList;\r\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
endregion region function ValidateCheckBoxInputFields(groupName, errId) A standardized validation function that will check to see if the checkbox button input field group is validate according to the web browser, and if not report the problem in the errId tag innerHTML | function ValidateCheckBoxInputFields(groupName, errId) {
var isFieldValid = true;
// see https://www.w3schools.com/js/js_validation_api.asp
// Test the field based upon the id and if it fails, we set the isValidForm to false
var testCheckBoxElements = document.getElementsByName(groupName);
if (testCheckBoxElements && testCheckBoxElements.length > 0) {
for (let idx = 0; idx < testCheckBoxElements.length; idx++) {
var checkBoxInput = testCheckBoxElements[idx];
if (checkBoxInput && checkBoxInput.checkValidity() !== undefined) {
if (checkBoxInput.checkValidity() == false) {
var validationProblem = GetValidationMessage(checkBoxInput.id);
// We need to find the label associated with this radio button
// and it should be the next element in the DOM
var label = checkBoxInput.nextElementSibling;
if (label && label.innerHTML !== undefined) {
// Tell the user what is wrong by highlighting the field with a different color background
/// and update the error message display area to describe the actual error
label.classList.toggle("InputInError", true);
}
var updateElement = document.getElementById(errId);
if (updateElement && updateElement.innerHTML !== undefined) {
updateElement.classList.toggle('hidden', false);
updateElement.innerHTML = `<div>Please check the radio buttons indicated
<p class='problem-description'>${validationProblem}</p></div>`;
}
isFieldValid = false;
}
else {
// There is no error so we need to remove any background color that indicated the error
// to show that the error has gone away, and we need to blank out the error message display area
// We need to find the label associated with this radio button
// and it should be the next element in the DOM
var label = checkBoxInput.nextElementSibling;
if (label && label.innerHTML !== undefined) {
// Tell the user what is wrong by highlighting the field with a different color background
/// and update the error message display area to describe the actual error
label.classList.toggle("InputInError", false);
}
var updateElement = document.getElementById(errId);
if (updateElement && updateElement.innerHTML !== undefined) {
updateElement.classList.toggle('hidden', true);
updateElement.innerHTML = "";
}
}
}
else {
console.log(`Checkbox field with the id of '${checkBoxInput.Id}' does not support validity checks`);
}
}
}
else {
console.log(`Could not find any checkboxs in group with the id of '${groupName}'`);
}
return isFieldValid;
} | [
"function ValidateRadioButtonInputField(groupName, errId) {\n var isFieldValid = true;\n // see https://www.w3schools.com/js/js_validation_api.asp\n\n // Test the field based upon the id and if it fails, we set the isValidForm to false\n var testRadioButtonElements = document.getElementsByName(groupName);\n if (testRadioButtonElements && testRadioButtonElements.length > 0) {\n for (let idx = 0; idx < testRadioButtonElements.length; idx++) {\n var radioButtonInput = testRadioButtonElements[idx];\n if (radioButtonInput && radioButtonInput.checkValidity() !== undefined) {\n if (radioButtonInput.checkValidity() == false) {\n var validationProblem = GetValidationMessage(radioButtonInput.id);\n // We need to find the label associated with this radio button\n // and it should be the next element in the DOM\n var label = radioButtonInput.nextElementSibling;\n if (label && label.innerHTML !== undefined) {\n // Tell the user what is wrong by highlighting the field with a different color background\n /// and update the error message display area to describe the actual error\n label.classList.toggle(\"InputInError\", true);\n }\n var updateElement = document.getElementById(errId);\n if (updateElement && updateElement.innerHTML !== undefined) {\n updateElement.classList.toggle('hidden', false);\n updateElement.innerHTML = `<div>Please check the radio buttons indicated\n <p class='problem-description'>${validationProblem}</p></div>`;\n }\n isFieldValid = false;\n }\n else {\n // There is no error so we need to remove any background color that indicated the error\n // to show that the error has gone away, and we need to blank out the error message display area\n // We need to find the label associated with this radio button\n // and it should be the next element in the DOM\n var label = radioButtonInput.nextElementSibling;\n if (label && label.innerHTML !== undefined) {\n // Tell the user what is wrong by highlighting the field with a different color background\n /// and update the error message display area to describe the actual error\n label.classList.toggle(\"InputInError\", false);\n }\n var updateElement = document.getElementById(errId);\n if (updateElement && updateElement.innerHTML !== undefined) {\n updateElement.classList.toggle('hidden', true);\n updateElement.innerHTML = \"\";\n }\n }\n }\n else {\n console.log(`Cannot find push button elements of group '${groupName}' or it does not support checkvalidation`);\n }\n }\n }\n else {\n console.log(\"Could not find any radio button group with the id of '\" + groupName + \"'\");\n }\n return isFieldValid;\n}",
"function CheckBoxValidation(Controlname,Fieldname)\n {\n var objfrm=document.getElementById(Controlname); \n var objFieldname=Fieldname;\t \t\n\t var flag;\n\t flag=false;\n\t\n\t var objValidator = new InputValidator();\n\t var objError \t = new ErrorAlert();\n if\n (\n \n objValidator.isCheckBoxValidation(objfrm,objValidator.Replace(objError.strchkboxchecked,\"<Field>\",objFieldname))\n \n )\n {\n\t \t objError = null\n\t\t objValidator = null\n\t\t flag=true\n }\n\n\t objError = null\n\t objValidator = null\n\t return flag\n }",
"function ValidateInputField(id, errId) {\n var isFieldValid = true;\n // see https://www.w3schools.com/js/js_validation_api.asp\n\n // Test the field based upon the id and if it fails, we set the isValidForm to false\n var testInputElement = document.getElementById(id);\n if (testInputElement && testInputElement.checkValidity() !== undefined) {\n if (testInputElement.checkValidity() == false) {\n // Tell the user what is wrong by highlighting the field with a different color background\n /// and update the error message display area to describe the actual error\n testInputElement.classList.toggle(\"InputInError\", true);\n var validationProblem = GetValidationMessage(id);\n var updateElement = document.getElementById(errId);\n if (updateElement && updateElement.innerHTML !== undefined) {\n updateElement.classList.toggle('hidden', false);\n updateElement.innerHTML = `<div>Please check the field indicated\n <p class='problem-description'>${validationProblem}</p></div>`;\n }\n isFieldValid = false;\n }\n else {\n // There is no error so we need to remove any background color that indicated the error\n // to show that the error has gone away, and we need to blank out the error message display area\n testInputElement.classList.toggle(\"InputInError\", false);\n var updateElement = document.getElementById(errId);\n if (updateElement && updateElement.innerHTML !== undefined) {\n updateElement.classList.toggle('hidden', true);\n updateElement.innerHTML = \"\";\n }\n }\n }\n else {\n console.log(`Element '${id}' cannot be found or doesn't support validation checking`);\n }\n\n return isFieldValid;\n}",
"function validateCheckBoxGrp(elem, minreq, maxreq){\n\tchecknum = 0;\n\tcheckmax = true;\n\tformObj = elem.form;\n\trequiredid = elem.id;\n\t\n\tfor (var i=0; i < (formObj.elements.length -1); i++) {\n\t\tif (formObj.elements[i].id == requiredid && formObj.elements[i].checked == true) {\n\t\t\tchecknum++;\n\t\t}\n\t}\n\t\t\n\tif (checknum > maxreq && maxreq > 0) {\n\t\tcheckmax = false;\n\t}\n\t\n\t//logic to determine if a field is checked...\n\tif (checknum < minreq || !checkmax) {\n\t\treturn false;\n\t}\n\treturn true;\n}",
"function ValidateGroup() {}",
"function validateCheckBoxesForRegisterForActivities() {\n\n let foundCheckedBox = false;\n\n // Create an errorSpan\n let errorSpan = $(\"<span>\");\n\n // Set the errorSpan id to checkBoxErrorSpan\n errorSpan.attr(\"id\", \"checkBoxErrorSpan\");\n\n // Set the text of the error span to At least one check box activity must be selected\n errorSpan.text(\"At least one check box activity must be selected\");\n\n // Set the css color attribute of the errorSpan to red\n errorSpan.css(\"color\", \"red\");\n\n // Loop through all the checkboxes\n for (let m = 0; m < $(\":checkbox\").length; m++) {\n\n if ($(\":checkbox\")[m].checked) {\n foundCheckedBox = true;\n break;\n }\n }\n\n if (!foundCheckedBox) {\n\n // Remove errorSpan if it exists\n $(\"#checkBoxErrorSpan\").remove();\n\n // Append the errorSpan in the activities field\n $(\".activities\").append(errorSpan);\n\n return false;\n }\n else {\n\n // At least one checkbox activity is selected, remove errorSpan\n $(\"#checkBoxErrorSpan\").remove();\n\n return true;\n }\n\n}",
"function validateFields(fieldsetId) {\r\n\tvar inputElements = document.querySelectorAll(\"#\" + fieldsetId + \" input\");\r\n\tvar selectElements = document.querySelectorAll(\"#\" + fieldsetId + \" select\" + \"[required]\");\r\n\tvar errorDiv = document.querySelectorAll(\"#\" + fieldsetId + \" .errorMessage\")[0];\r\n\tvar fieldsetValidity = true;\r\n\tvar elementCount = inputElements.length;\r\n\tvar currentElement;\r\n\ttry {\r\n\t\tfor (var i=0; i < elementCount; i++) {\r\n\t\t\tcurrentElement = inputElements[i];\r\n\t\t\tif (currentElement.value === \"\") {\r\n\t\t\t\tcurrentElement.style.background = \"rgb(255, 233, 233)\";\r\n\t\t\t\tcurrentElement.style.border = \"solid red 1px\";\r\n\t\t\t\tfieldsetValidity = false;\r\n\t\t\t} else {\r\n\t\t\t\tcurrentElement.style.background = \"white\";\r\n\t\t\t}\r\n\t\t}\r\n\t\telementCount = selectElements.length;\r\n\t\tfor (var i=0; i < elementCount; i++) {\r\n\t\t\tcurrentElement = selectElements[i];\r\n\t\t\tif (currentElement.selectedIndex === -1) {\r\n\t\t\t\tcurrentElement.style.border = \"1px solid red\";\r\n\t\t\t\tfieldsetValidity = false;\r\n\t\t\t} else {\r\n\t\t\t\tcurrentElement.style.border = \"\";\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (fieldsetValidity === false) {\r\n\t\t\t\tthrow \"Please complete all fields.\";\r\n\t\t} else {\r\n\t\t\terrorDiv.style.display = \"none\";\r\n\t\t\terrorDiv.innerHTML = \"\";\r\n\t\t}\r\n\t}\r\n\tcatch (msg) {\r\n\t\terrorDiv.style.display = \"block\";\r\n\t\terrorDiv.style.color = \"#FE0000\";\r\n\t\terrorDiv.style.padding = \"20px 0 0 15px\";\r\n\t\terrorDiv.innerHTML = msg;\r\n\t\tformValidity = false;\r\n\t}\r\n}",
"function ValidateAllControlsWithTables(iGroupID, aInputParams, iMsgManagerIndex, bRunValidation, bDisplayOverlay,\n fnOnSuccess, oOnSuccessParams, fnOnFailure, oOnFailureParams) {\n\n try {\n if (IsEmpty(iGroupID)) iGroupID = -1;\n if (IsEmpty(iMsgManagerIndex)) iMsgManagerIndex = -1;\n if (IsEmpty(bRunValidation)) bRunValidation = true;\n if (IsEmpty(bDisplayOverlay)) bDisplayOverlay = true;\n\n iGroupID = parseInt(iGroupID);\n iMsgManagerIndex = parseInt(iMsgManagerIndex);\n\n if (iGroupID > -1) {\n if (aCtrlGroups[iGroupID].sWorkMode != 'A' && aCtrlGroups[iGroupID].sWorkMode != 'W') {\n throw 'Error(JS): You cannot submit changes for group #' + iGroupID + ' because this group is still in the read-only mode.';\n }\n }\n else {\n for (var iGroupID2 in aCtrlGroups) {\n if (aCtrlGroups[iGroupID2].sWorkMode != 'A' && aCtrlGroups[iGroupID2].sWorkMode != 'W') {\n throw 'Error(JS): You cannot submit changes for group #' + iGroupID2 + ' because this group is still in the read-only mode.';\n }\n }\n }\n\n if (bRunValidation) {\n if (!ValidateAllControls(iGroupID, iMsgManagerIndex)) return false;\n }\n\n var oInfo;\n var sName, sValue;\n var aNames = [];\n var aInputParams2 = [];\n var aPKs = [];\n var counter = 0;\n var ipCounter = 0;\n var pkCounter = 0;\n var aGroups = {};\n\n if (IsArray(aInputParams)) {\n ipCounter = aInputParams.length;\n jQuery.each(aInputParams, function (i, val) {\n aInputParams2.push(val);\n });\n }\n\n var sSubmitHttpMethod = '';\n var sSubmitURL = '';\n\n if (iGroupID > -1) {\n sSubmitHttpMethod = aCtrlGroups[iGroupID].sSubmitHttpMethod;\n sSubmitURL = aCtrlGroups[iGroupID].sSubmitURL;\n }\n\n for (var index in aCtrls) {\n oInfo = aCtrls[index];\n\n if (!oInfo.bIsAJAXParam) {\n continue;\n }\n\n if (oInfo.sCtrlType == 'lbl') {\n continue;\n }\n\n if (!oInfo.bPK && iGroupID > -1 && oInfo.iGroupID != iGroupID) {\n continue;\n }\n\n if (IsEmpty(aCtrlGroups[oInfo.iGroupID].sSubmitHttpMethod)) {\n throw 'Error(JS): You cannot submit changes for group #' + oInfo.iGroupID + ' because it does not have the submit HTTP method.';\n }\n else if (IsEmpty(aCtrlGroups[oInfo.iGroupID].sSubmitURL)) {\n throw 'Error(JS): You cannot submit changes for group #' + oInfo.iGroupID + ' because it does not have the submit URL.';\n }\n\n if (IsEmpty(sSubmitHttpMethod)) sSubmitHttpMethod = aCtrlGroups[oInfo.iGroupID].sSubmitHttpMethod;\n if (IsEmpty(sSubmitURL)) sSubmitURL = aCtrlGroups[oInfo.iGroupID].sSubmitURL;\n\n if (iGroupID == -1) {\n if (sSubmitHttpMethod != aCtrlGroups[oInfo.iGroupID].sSubmitHttpMethod) {\n throw 'Error(JS): You cannot submit changes for fields from different groups at once because they do not share the same submit HTTP method.';\n }\n else if (sSubmitURL != aCtrlGroups[oInfo.iGroupID].sSubmitURL) {\n throw 'Error(JS): You cannot submit changes for fields from different groups at once because they do not share the same submit URL.';\n }\n }\n\n sName = oInfo.sCName;\n if (oInfo.sCtrlType == 'txt_auto') {\n if (!IsEmpty(oInfo.oOtherProp.sColumnNameValue)) {\n sName = oInfo.oOtherProp.sColumnNameValue;\n }\n }\n\n sValue = GetValue(oInfo.sClientID, oInfo.sCtrlType, oInfo);\n\n if (oInfo.bPK) {\n aPKs.push(sName);\n aInputParams2.push({ 'name': 'pkf' + pkCounter, 'value': sValue });\n ++pkCounter;\n }\n else {\n aNames.push(sName);\n aInputParams2.push({ 'name': 'f' + counter, 'value': sValue });\n ++counter;\n }\n\n aGroups[oInfo.iGroupID] = 1;\n }\n\n var oTable, nNodes, oElement, aRowData, iRowID, oCol, oRow, bIsValid, bExitFunction;\n var aTables = [], aTablePKs = [], aTableOtherFields = [];\n bExitFunction = false;\n\n for (var index in aDT) {\n oInfo = aDT[index];\n if (oInfo.bIsAjaxParam && oInfo.sType == \"jq-dt\") {\n oTable = oInfo.oTable;\n nNodes = oTable.fnGetNodes();\n\n aTablePKs = oInfo.sPKFields.split('|');\n aTableOtherFields = oInfo.sOtherFields.split('|');\n\n if (aTablePKs.length == 0) throw 'Error(JS): You can not submit data from the datatable (' + oInfo.sTableID + ') because it dosn\\'t have a primary key.';\n if (aTableOtherFields.length == 0) throw 'Error(JS): You can not submit data from the datatable (' + oInfo.sTableID + ') because it dosn\\'t have fields to update.';\n\n iRowID = 0;\n\n $.each(nNodes, function () {\n oRow = this;\n aRowData = GetJDataTableRow($('td:first-child', oRow), index);\n\n $.each(aTablePKs, function (i, cid) {\n aInputParams2.push({ 'name': 'tf_' + index + '_' + iRowID + '_' + cid, 'value': aRowData[cid] });\n });\n\n $.each(aTableOtherFields, function (i, cid) {\n if ($('.jt-ajax-param-' + cid, oRow).length > 0) {\n oCol = $('.jt-ajax-param-' + cid, oRow);\n\n if ($(oCol).hasClass('jt-ctrl-text')) {\n if (bRunValidation) {\n ValidateControl($(oCol), null);\n bIsValid = IsPageValid(iMsgManagerIndex);\n if (!bIsValid) {\n bExitFunction = true;\n return false;\n }\n }\n\n sValue = $(oCol).val();\n }\n else if ($(oCol).hasClass('jt-ctrl-ddl')) {\n if (bRunValidation) {\n ValidateControl($(oCol), null);\n bIsValid = IsPageValid(iMsgManagerIndex);\n if (!bIsValid) {\n bExitFunction = true;\n return;\n }\n }\n\n sValue = $(oCol).val();\n }\n else if ($(oCol).hasClass('jt-ctrl-chk')) {\n sValue = $(oCol).is(':checked');\n }\n\n aInputParams2.push({ 'name': 'tf_' + index + '_' + iRowID + '_' + cid, 'value': sValue });\n }\n });\n\n if (bExitFunction) return false;\n\n ++iRowID;\n });\n\n aTables.push(oInfo.sTableID + '&' + aTablePKs.join(':') + '&' + aTableOtherFields.join(':') + '&' + iRowID + '&' + index);\n }\n }\n\n if (bExitFunction) return false;\n\n if (aNames.length == 0 && aPKs.length == 0 && aTables.length == 0) throw 'Error(JS): There is no field marked as primary key. You should either mark a field as PK or pass in some input parameters that will serve as primary key.';\n\n return true;\n }\n catch (err) {\n alert(err);\n }\n}",
"function showControlGroupError(controlGroup, msg) {\n setControlGroupErrorMessage(controlGroup, msg);\n}",
"function validateCheckbox(field) {\n \n }",
"function clickedOK()\n{\n var labelValueArr = GC_CHECKBOXES.getAll();\n var ckboxGroupName = TF_GROUP_NAME.getValue();\n var canApplyMsg = \"\";\n \n canApplyMsg = checkForLabelsAndValues(labelValueArr);\n \n if (!canApplyMsg && !ckboxGroupName)\n canApplyMsg = dw.loadString(\"Commands/CheckboxGroup/NeedACheckboxGroupName\");\n else\n ckboxGroupName = dwscripts.entityNameEncode(ckboxGroupName);\n \n if (canApplyMsg)\n {\n alert(canApplyMsg);\n return;\n }\n \n var isTable = RG_LAYOUT.getSelectedIndex() == 1;\n \n // Do not allow the checked attribute to be set from the form object version\n // of the checkbox group.\n var selectValueEqualTo = \"\"; \n var insertionStr = createCheckboxGroupString(ckboxGroupName,isTable,selectValueEqualTo,labelValueArr);\n\n savePreferences(); // save layout choice, i.e. line break or table\n\n dw.getDocumentDOM().insertHTML(returnFormTag(insertionStr),false);\n window.close();\n\n}",
"function check_checkboxes() {\n if ($(\".activities > label > input:checked\").length === 0) {\n $('#checkboxError').html('<h3>You have not selected an activity. Please select an activity.<br></h3>');\n $('#checkboxError').css('color', 'red').show();\n $('.activities').css('border', 'solid red 3px').show();\n error_checkbox = true;\n }\n else {\n $('.activities').css('border', 'none').show();\n $('#checkboxError').css('color', 'red').hide();\n console.log(\"checkbox field is valid\");\n error_checkbox = false;\n };\n\n }",
"function checkboxFieldValidator(checkboxes) {\n let isSelected = false;\n for (let i = 0; i < checkboxes.length; i++) {\n // at least one box must be checked\n if (checkboxes[i].checked) {\n isSelected = true;\n break;\n }\n }\n if (!isSelected) {\n activities.classList.add('not-valid');\n activities.classList.remove('valid');\n activitiesHint.style.display = 'inline';\n return false;\n } else {\n activities.classList.add('valid');\n activities.classList.remove('not-valid');\n activitiesHint.style.removeProperty('display');\n return true;\n }\n}",
"function validateUgerGroupCreation(grpId, descr, apprLimit, tolrAmnt, error) {\n var errStr = 'Please enter ';\n $11(error).innerHTML = '';\n $11(error).style.color = \"red\";\n if ($11(grpId).value == 0) {\n errStr += 'GroupID, ';\n }\n if ($11(descr).value == 0) {\n errStr += 'Description, ';\n }\n if ($11(apprLimit).value == 0) {\n errStr += 'Approvl Limit, ';\n }\n if ($11(apprLimit).value != 0) {\n if (isNaN($11(apprLimit).value)) {\n errStr += 'valid Numeric values for Approval Limit, ';\n }\n }\n if ($11(tolrAmnt).value == 0) {\n errStr += 'Tolerance Amount, ';\n }\n if ($11(tolrAmnt).value != 0) {\n if (isNaN($11(tolrAmnt).value)) {\n errStr += 'valid Numeric values for Tolerance Amount, ';\n }\n }\n errStr = errStr.substring(0, errStr.length - 2);\n if (errStr.length > 13) {\n $11(error).innerHTML = errStr;\n $11(error).scrollIntoView();\n return false;\n }\n}",
"initControlGroups() {\n function checkSetValidity(controls) {\n if (controls.length <= 0) return false;\n\n const errorMessage = controls.some((control) => (control.input.checked)) ? '' : controls[0].el.dataset.controlGroupError;\n controls[0].input.setCustomValidity(errorMessage);\n }\n\n let controlGroups = {};\n\n // group controls by name\n this.controls.forEach((control) => {\n let controlGroup = control.controlGroup;\n if (controlGroup) {\n controlGroups[controlGroup] = controlGroups[controlGroup] || [];\n controlGroups[controlGroup].push(control);\n }\n });\n\n // set up validity check triggers\n Object.values(controlGroups).forEach((controls) => {\n const firstCheckbox = controls.length > 0 ? controls[0] : null;\n if (firstCheckbox) {\n controls.forEach((checkbox) => {\n checkbox.input.addEventListener('change', () => {\n checkSetValidity(controls);\n });\n });\n checkSetValidity(controls);\n }\n });\n }",
"function validateEducation(elem)\n{\n var errorChecker = 0;\n var status = 0;\n var message = document.querySelector(\"#educationErrField\");\n message.innerHTML = \"\";\n for (var i = 0; i < elem.length; i++)\n {\n if (elem[i].checked == true)\n {\n errorChecker++;\n }\n }\n if (errorChecker < 1)\n {\n status = 1;\n message.innerHTML = \"<mark>Please select your educational status</mark>\";\n }\n return status;\n}",
"function validateElementGroup(elem, emin, emax) {\n\tfillnum = 0;\n\tfillmax = true;\n\terrstr = '';\n\tdupeIdCount = inputIdCount(elem);\n\t//errstr += elem.id + ' = ' + dupeIdCount + '\\n';\n\n\tif (dupeIdCount > 1) {\n\t\tfor (var i=0; i < (formObj.elements.length -1); i++) {\n\t\t\tif (formObj.elements[i].id == elem.id) {\n\t\t\t\tmyelem = formObj.elements[i];\n\t\t\t\t//errstr += myelem.name + ' = ' + myelem.value + '\\n';\n\t\t\t\tif (validateBlank(myelem)) {\n\t\t\t\t\terrstr += validateFormat(myelem)\n\t\t\t\t\tfillnum++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (fillnum > emax && emax > 0) {\n\t\t\tfillmax = false;\n\t\t}\n\t\t\n\t\t//logic to determine if a field is checked...\n\t\tif (fillnum < emin || !fillmax) {\n\t\t errstr += '\\nYou must fill in at least ' + emin;\n\t\t if (emax > 0) {\n\t\t errstr += ' and no more than ' + emax;\n\t\t }\n\t\t errstr += ' value(s) for ' + elem.id + '.\\n';\n\t\t}\n\t\t\n\t}\n\telse {\n\t\tif(!validateBlank(elem)){\n\t\t errstr += \"\\n\" + elem.id + \" cannot be left blank.\\n\";\n\t\t}\n\t\telse {\n\t\t\terrstr += validateFormat(elem)\n\t\t}\n\t}\n\t\n\treturn errstr;\n}",
"function SetGroupMaskID(Grp1,Grp2,Grp3,Grp4)\n{\n if(Chkbx_Group1.Exists)\n { \n Chkbx_Group1.wState =Grp1\n Chkbx_Group2.wState =Grp2\n Chkbx_Group3.wState =Grp3\n Chkbx_Group4.Checked =Grp4\n if(Chkbx_Group1.wState==Grp1 && Chkbx_Group2.wState==Grp2 && Chkbx_Group3.wState==Grp3 && Chkbx_Group4.wState==Grp4)\n {\n Log.Message(\"Checked the Checkbox in Groups\")\n return true\n }\n else\n {\n Log.Message(\"Unable to Check the checkbox in Groups\")\n return false\n }\n }\n else\n {\n Log.Message(\"Unable to locate Group Mask ID box\")\n return false\n }\n}",
"function validateCheckBox(checkboxs, argStr) {\n\tvar args = argStr.split(\",\");\n\n\tvar val = null;\n\tfor(var i=0; i<checkboxs.length; i++) {\n\t\tif(checkboxs[i].checked) val = (val==null?\"\":\", \")+checkboxs[i].value;\n\t}\n\n\tvar emsg = \"\";\n\tif(val==null && args[1]=='required') emsg += \"กรุณาเลือก\";\n\n\tvar femsg = validateFunction(val, args, 2, checkboxs[0].name);\n\tif(femsg != null) emsg += (emsg!=\"\"?\", \":\"\")+femsg;\n\n\treturn emsg!=\"\"?(__emsg_with_name?\"\\\"\"+args[0]+\"\\\" \":\"\")+emsg:null;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function: createSheet Makes an API call to create a new spreadsheet to use. Also populates the first row with the columns 'Vidoe Name' and 'Video URL'. | function createSheet() {
var spreadsheetName = prompt("Enter file name", "Youtube Sounboard");
gapi.client.sheets.spreadsheets.create({
properties: {
title : spreadsheetName
},
'sheets' : [
{
data : [
{
startRow : 0,
startColumn : 0,
rowData : [
{
values : [
{
userEnteredValue : {
stringValue : "Video Name"
}
},
{
userEnteredValue : {
stringValue : "Video URL"
}
}
]
}
]
}
]
}
]
}).then(function(response) {
$("#retrievespreadsheetIdErrorCreate").hide();
var result = response.result;
//disable the create spreadsheet btn ??
var $item = $("<button>").text(result.properties.title + "(New)").addClass("list-group-item spreadSheetIDBtn").val(result.spreadsheetId);
$("#fileSelector").prepend($item);
}, function(response) {
$("#retrievespreadsheetIdErrorCreate").show();
$("#retrievespreadsheetIdErrorCreate").removeClass("hidden");
$("#retrievespreadsheetIdErrorCreateMessage").text(errorHandling(response));
});
} | [
"function createSpreadsheet() {\n window.gapi.client.sheets.spreadsheets\n .create({\n properties: {\n title: \"Shppd\"\n }\n })\n .then(response => console.log(response));\n}",
"function createSheet () {\n ss.insertSheet(name, index, options);\n\n // Apply pending Spreadsheet changes\n SpreadsheetApp.flush();\n }",
"function requestCreateSheet(track) {\n return gapi.client.request({\n path: PATH_CREATE,\n method: 'POST',\n body: createSheet(track)\n });\n}",
"function createSheet(name, folderId){\n var throughputHeader = [['Date (MM/DD/YYYY)','Cloud Worker','Use Case','Task Type','Tasks Completed','Task Duration',\n 'Notes','Average Task/Hr','Ramp Percentage','Target (Min) (Actual)','Target (Max) (Actual)',\n 'Target (Min) (After Ramp)','Target (Max) (After Ramp)','VC%']];\n var accuracyHeader = [['Date','#Task Reviewed','Task_Url (Optional)','Task Completed By','Task Type',\n '# Review Duration (hours)','Task Reviewed By','Accuracy','Min','Max','VC']];\n var overallThroughputHeader = [['Date','Email Address','Average VC %']];\n var overallAccuracyHeader = [['Date','Email Address','Average VC %']];\n var resource = {\n title : name,\n mimeType : MimeType.GOOGLE_SHEETS,\n parents : [{ id : folderId}]\n };\n var fileJson = Drive.Files.insert(resource);\n var file = SpreadsheetApp.openById(fileJson.id);\n file.getActiveSheet().setName(\"Throughput\");\n file.getActiveSheet().getRange(1, 1, 1, throughputHeader[0].length).setValues(throughputHeader).setFontWeight('bold');\n // file.getActiveSheet().getRange(1, file.getActiveSheet().getLastColumn()+1, 1, file.getActiveSheet().getMaxColumns())\n file.insertSheet().setName(\"Accuracy\");\n file.getActiveSheet().getRange(1, 1, 1, accuracyHeader[0].length).setValues(accuracyHeader).setFontWeight('bold');\n file.insertSheet().setName(\"Overall Throughput\");\n file.getActiveSheet().getRange(1, 1, 1, overallThroughputHeader[0].length).setValues(overallThroughputHeader).setFontWeight('bold');\n file.insertSheet().setName(\"Overall Accuracy\");\n file.getActiveSheet().getRange(1, 1, 1, overallAccuracyHeader[0].length).setValues(overallAccuracyHeader).setFontWeight('bold');\n return file.getUrl();\n}",
"function createRow() {\n\t//setInfoMessage(\"Creating new row.\");\n gapi.client.sheets.spreadsheets.values.append({\n spreadsheetId: SPREADSHEET_ID,\n range: \"Sheet1\",\n valueInputOption: \"USER_ENTERED\",\n values:\n [\n [\n $(\"#videoNameInput\").val(),\n $(\"#urlInput\").val()\n ]\n ]\n }).then(function(response) {\n\t $(\"#createEditModalError\").hide();\n closeModal();\n visualFeedback(\"Successfully created.\", true);\n\t\t$(\"#savedVideosInfo\").hide();\n //Create a new object in the collection and upated the table.\n //No need to make a new request.\n var results = response.result;\n var updatedRange = results.updates.updatedRange.match(/[0-9]+$/)[0];\n \n addSingleVideo($(\"#videoNameInput\").val(), $(\"#urlInput\").val(), updatedRange);\n \n populateTable();\n \n }, function(response) {\n //visualFeedback(\"Unsuccessfully created.\", false);\n $(\"#createEditModalError\").show();\n $(\"#createEditModalError\").removeClass(\"hidden\");\n $(\"#createEditModalErrorMessage\").text(errorHandling(response));\n });\n}",
"function setupSpreadsheet () {\n // Prepare header row\n var header = ['ID', 'Type', 'URL', 'Name', 'Description', 'Starred',\n 'Trashed', 'Sharable by Editors', 'Created', 'Modified', 'Size',\n 'Sharing Access', 'Sharing Permission', 'Owner', 'Viewers', 'Editors']\n // Create Spreadsheet\n var spreadsheetName = spreadsheetNameStart + dateString_()\n var spreadsheet = SpreadsheetApp.create(spreadsheetName, 2, header.length)\n // Add header row\n spreadsheet.appendRow(header)\n spreadsheet.setFrozenRows(1)\n // Duplicate sheet\n var sheetFolder = spreadsheet.getSheets()[0]\n var sheetFile = spreadsheet.insertSheet(1, {template: sheetFolder})\n // Name sheets\n sheetFolder.setName(sheetNameFolder)\n sheetFile.setName(sheetNameFile)\n // Return spreadsheet information\n return {\n done: true,\n id: spreadsheet.getId(),\n url: spreadsheet.getUrl()\n }\n}",
"function createSheet(sheetName) {\n var ss = SpreadsheetApp.getActiveSpreadsheet();\n var sheet = ss.getSheetByName(sheetName);\n \n if (!sheet) {\n return {sheet : ss.insertSheet(sheetName), created : true}; \n }\n \n return {sheet : sheet, created : false};\n}",
"async createSpreadsheet(title) {\n const resource = {\n properties: {\n title,\n }\n }\n try {\n const { data } = await this.sheets.spreadsheets.create({ resource });\n console.log(`Created new spreadsheet with ID: ${data.spreadsheetId} `);\n return data.spreadsheetId;\n } catch (err) {\n console.log(`error: ${err} `);\n return err;\n }\n }",
"function makeRecruitSheet(){\nvar sheetname = 'Recruits'\nvar ss = SpreadsheetApp.getActiveSpreadsheet(), newSheet;\nnewSheet = ss.insertSheet();\nnewSheet.setName(sheetname);\n}",
"function create_sheet() {\n var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();\n var sheet = spreadsheet.insertSheet('Project Plan');\n /* Create all of the headers first */\n /* Then set formulas, named ranges, and hide columns */\n var last_cell = _set_gantt_range(sheet, 43031, 43283);\n _set_days_remaining_values(sheet, last_cell);\n _set_gantt_chart_headers(sheet, last_cell);\n _hide_columns(sheet);\n _format_project_area(sheet);\n _set_frozen_rows_and_cols(sheet);\n _insert_images(sheet);\n format_category_names();\n}",
"function addSheet(auth, message, sheetName)\n{\n let requests = [];\n // Change the spreadsheet's title.\n requests.push({\n\n \"addSheet\": {\n \"properties\": {\n \"title\": sheetName,\n \"sheetType\": \"GRID\",\n \"gridProperties\": {\n \"rowCount\": 200,\n \"columnCount\": 200,\n \"hideGridlines\": false\n },\n \"hidden\": false,\n \"rightToLeft\": false\n }\n }\n\n });\n\n message.channel.send(\"Ok! Sheet \\\"\"+sheetName+\"\\\" created!\");\n\n sendRequest(auth, requests);\n}",
"createSheet () {\n let headers = [];\n for(let i in this.headers){\n headers.push(this.headers[i].name);\n }\n\n let sheetStx = {\n name: this.name,\n headers: headers,\n rows: this.rows\n }\n\n this.parent.sheets.push(sheetStx);\n }",
"function createSpread(noOfRows, spread) {\n\n\t// var spread = $(\"#createSheetDiv\").wijspread(\"spread\");\n\n\tspread.useWijmoTheme = true;\n\tspread.tabStripVisible(false);\n\tspread.showHorizontalScrollbar(false);\n\tspread.showVerticalScrollbar(false);\n\n\tvar sheet = spread.getActiveSheet();\n\tsheet.isPaintSuspended(true);\n\n\tsheet.setRowCount(noOfRows);\n\tsheet.setColumnCount(7);\n\tvar rc = sheet.getRowCount();\n\tvar cc = sheet.getColumnCount();\n\tvar cellType2 = new $.wijmo.wijspread.ComboBoxCellType();\n \tcellType2.items([\"GET\",\"POST\"]);\n\t\n\t/* set column header name */\n\tsheet.setValue(0, 0, \"Test Case ID\", $.wijmo.wijspread.SheetArea.colHeader);\n\tsheet.setValue(0, 1, \"Test Step\", $.wijmo.wijspread.SheetArea.colHeader);\n\tsheet.setValue(0, 2, \"Request URL\", $.wijmo.wijspread.SheetArea.colHeader);\n\tfor (var r = 0; r < rc; r++) \n \t{ \n\t sheet.setValue(0, 3, \"Type (GET/POST)\",\n\t $.wijmo.wijspread.SheetArea.colHeader,\n\t sheet.getCell(r, 3).cellType(cellType2)); \n\t} \n//\tsheet.setValue(0, 3, \"Type (GET/POST)\",$.wijmo.wijspread.SheetArea.colHeader);\n\tsheet.setValue(0, 4, \"Expected Assertion\",\n\t\t\t$.wijmo.wijspread.SheetArea.colHeader);\n\tsheet.setValue(0, 5, \"Expected Value\",\n\t\t\t$.wijmo.wijspread.SheetArea.colHeader);\n\tsheet.setValue(0, 6, \"Status\", $.wijmo.wijspread.SheetArea.colHeader);\n\t/* set column width */\n\tsheet.setColumnWidth(0, 100);\n\tsheet.setColumnWidth(1, 300);\n\tsheet.setColumnWidth(2, 200);\n\tsheet.setColumnWidth(3, 150);\n\tsheet.setColumnWidth(4, 150);\n\tsheet.setColumnWidth(5, 100);\n\tsheet.setColumnWidth(6, 100);\n\tvar filter = new $.wijmo.wijspread.HideRowFilter(\n\t\t\tnew $.wijmo.wijspread.Range(-1, 0, -1, 2));\n\tsheet.rowFilter(filter);\n\tfilter.setShowFilterButton(false);\n\tsheet.isPaintSuspended(false);\n}",
"function createSheet(sheetName, userId) {\n \tdb.Sheet.create({\n \t\tname: sheetName\n \t}).then(function(result) {\n\t \tconsole.log(\"sheet created named \" + sheetName);\n\t \tlet newSheetId = result.dataValues.id;\n\t\tconsole.log(\"new sheet id is \" + newSheetId);\n\n\t\tdb.UserSheet.create({\n\t\t\tuserId: userId,\n\t\t\tsheetId: newSheetId,\n\t\t\tuserIsCreator: true\n\t\t}).then(function(result) {\n\t\t\tconsole.log(\"usersheet entry added with new sheet id, user id, and user marked creator\")\n\t\t\tconsole.log(result.dataValues);\n\t\t}).catch(function (err) {\n\t\t\tconsole.log(err);\n\t\t});\n\n }).catch(function (err) {\n\t\tconsole.log(err);\n\t});\n}",
"function CreateSheet() {\r\n var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();\r\n var activeSpreadsheet = spreadsheet.getSheetByName(\"Main\");\r\n var data = activeSpreadsheet.getRange(\"A4:A\").getValues();\r\n \r\n /*\r\n ** Itterate through \"Main\" sheet to get project names\r\n ** and create a sheet with the same name.\r\n */\r\n var len = data.length\r\n for (var row = 0; row < len; row++) { \r\n var projectNames = data[row]; \r\n /*\r\n ** Check if a sheet has already been dedicated to a Project.\r\n ** Check if the project name is valid, ie. not the title.\r\n ** If it hasn't then create a dedicated sheet.\r\n */\r\n if ((spreadsheet.getSheetByName(projectNames) == null) && (projectNames != '')){ \r\n var yourNewSheet = spreadsheet.insertSheet();\r\n yourNewSheet.setName(projectNames);\r\n var sheet = spreadsheet.getSheetByName(projectNames);\r\n \r\n /*\r\n ** Layout of 'Template' and setting fonts.\r\n */\r\n sheet.setColumnWidth(1, 200);\r\n sheet.setColumnWidth(2, 200);\r\n sheet.setColumnWidth(3, 500);\r\n var cell = sheet.getRange(\"A1\").setFontWeight(\"bold\");\r\n cell.setValue(\"Software Releases\");\r\n var cell = sheet.getRange(\"B1\").setFontWeight(\"bold\");\r\n cell.setValue(\"Description\");\r\n var cell = sheet.getRange(\"C1\").setFontWeight(\"bold\");\r\n cell.setValue(\"Link\");\r\n var cell = sheet.getRange(\"A5\").setFontWeight(\"bold\");\r\n cell.setValue(\"Test Softwares\");\r\n var cell = sheet.getRange(\"A10\").setFontWeight(\"bold\");\r\n cell.setValue(\"Documentation Links\");\r\n var cell = sheet.getRange(\"A15\").setFontWeight(\"bold\");\r\n cell.setValue(\"Flashing / Programming\");\r\n } \r\n }\r\n}",
"function createSheet(){\n var ss = SpreadsheetApp.getActiveSpreadsheet();\n var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();\n var sheetname =[\"Burn-up\",\"Simulations\",\"Scratch\"];\n\n //set name for the first sheet\n sheets[0].setName(\"Data\");\n\n //creating new sheets\n for(var i = 1; i <= sheetname.length; i ++){\n //check if sheets already exist\n if(sheets[i] == null){\n //inserting new sheets\n ss.insertSheet(sheetname[i - 1], i);\n Logger.log(sheetname[i-1]);\n }\n\n }\n }",
"function newSheet() {\n // Get the active sheet and spreadsheet\n var ss = SpreadsheetApp.getActive();\n var s = ss.getActiveSheet();\n \n // Add a new sheet the the spread sheet based on a template.\n var templateSheet = ss.getSheetByName('templateSheet');\n ss.insertSheet(0, {template: templateSheet});\n \n // Get the list of sheet names.\n var sheets = ss.getSheets();\n \n // Name the new sheet the next year.\n s = ss.getActiveSheet();\n // If the last year is not a number ask for the new sheet name.\n // Else add one to the last year and make that the name.\n if(isNaN(sheets[1].getName())) {\n launchSheetBox();\n } else {\n s.setName(String(Number(sheets[1].getName()) + 1));\n }\n \n // Add title bar protection.\n var range = s.getRange('1:1');\n range.protect().setDescription('Title Bar');\n}",
"function makeSheet(parsedInput) {\n let name = parsedInput[1];\n let formulaArray = parsedInput[2];\n let array = convertFormulaArray(formulaArray);\n // console.log(\"array in makeSheet: \" + JSON.stringify(array));\n let sheet = new Spreadsheet(array);\n spreadsheets[name] = sheet;\n}",
"createSheet(sheetName) {\n if (sheetName == null)\n throw new Error(\"Sheet name not defined in Spreadsheet.createSheet\");\n this._sheets[sheetName] = new SheetGS(this._spreadsheet.insertSheet(sheetName));\n return this._sheets[sheetName];\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if a certain element is inside the root nav | function isElementInsideNav(el) {
const expandedLevel1El = rootEl.querySelector('[data-o-hierarchical-nav-level="1"] > [aria-expanded="true"]');
let expandedMegaDropdownEl;
let allLevel1Els;
if (expandedLevel1El) {
expandedMegaDropdownEl = getMegaDropdownEl(expandedLevel1El);
if (expandedMegaDropdownEl && expandedMegaDropdownEl.contains(el)) {
return true;
}
}
allLevel1Els = rootEl.querySelectorAll('[data-o-hierarchical-nav-level="1"] > li');
for (let c = 0, l = allLevel1Els.length; c < l; c++) {
if (allLevel1Els[c].contains(el)) {
return true;
}
}
return false;
} | [
"function isNavInMenu(list, elem) {\n var isChild = false;\n if (!list || !elem) {\n return false;\n } else if (elem == list) {\n return true;\n } else if (list.childNodes) {\n for (var i = 0; i < list.childNodes.length; i++) {\n var child = list.childNodes[i];\n if (child && (elem == child || isNavInMenu(child, elem))) {\n return true;\n }\n }\n }\n\n return false;\n} // isNavInMenu",
"function is_element_inside_menu(el) {\n\n while ((el = el.parentElement) !== null) {\n if (el.nodeType !== Node.ELEMENT_NODE) {\n continue;\n }\n if (el.isEqualNode(menu)) {\n return true;\n }\n }\n return false;\n\n }",
"function isBreadCrumb(o) {\n return !!o && o.parentNode === document.querySelector('#spin-nav');\n}",
"function isTopLevelEl(el) {\n\t\tif (!el) {\n\t\t\treturn false;\n\t\t}\n\t\tvar tn = el.prop('tagName');\n\t\ttn = tn ? tn.toLowerCase() : null;\n\t\treturn tn === 'html' || tn === 'head';\n\t}",
"contains(element) {\n return this.root.contains(element.root);\n }",
"function canTraverse() {\n\treturn pageData.breadcrumb != null;\n}",
"function hasActiveParent( elm ) {\n\t\t\t\t\t\t\t\t\t\tvar parentNode = elm.parentNode.parentNode;\n\t\t\t\t\t\t\t\t\t\tvar classList = parentNode.classList;\n\n\t\t\t\t\t\t\t\t\t\tif ( parentNode.tagName == \"LI\" && classList.contains( \"active\" ) ) {\n\t\t\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t\t\t}",
"function isNav () {\n\tpg = document.title;\n\t\n\tif (pg == 'Home' || pg == 'Resume' || pg == 'Favorite Sites' || pg == 'My Life' || pg == 'Friends') {\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}",
"function isAncestry(elem, parent) {\n while (elem) {\n if (elem === parent)\n return true;\n else\n elem = elem.parentNode;\n }\n return false;\n }",
"function hasParent(el) {\n\t\tif (el[0].nodeName === \"BODY\") {\n\t\t\t// The node passed to this function is the <body> element\n\t\t\treturn false;\n\t\t}\n\t\telse {\n\t\t\t// The node passed as an argument is not the <body> element\n\t\t\t// Get the classname of the parent node, or set to undefined\n\t\t\tvar selector = el[0].parentElement.className || undefined;\n\n\t\t\tif (selector) {\n\t\t\t\t// The current parent node has a class name\n\t\t\t\tif (selector === \"dropdown-menu\") {\n\t\t\t\t\t// The element the user is tabbing to is within a dropdown-menu\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// The parent element of this node does not have the dropdown-menu class\n\t\t\t\t\treturn hasParent($(el).parent());\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// The parent element of this node does not have a class\n\t\t\t\treturn hasParent($(el).parent());\n\t\t\t}\n\t\t}\n\t}",
"function isInPage (element) {\n if (element === document.body) return false;\n return document.body.contains(element);\n}",
"function isParentHighlited(element){\n\t\n\tvar level = $(element).attr('level').split(\"_\")[1];\n\tvar isParentHighlited = false;\n\tvar treeStartingLevel = 0;\n\t\n\tfor(var i = level ; i >= treeStartingLevel ; i--){\n\t\tisParentHighlited = $(element).closest(\"li[level='level_\"+ i + \"']\").children(\".jstree-search\").length > 0;\n\t\tif(isParentHighlited)\n\t\t\tbreak;\n\t}\n\treturn isParentHighlited;\n}",
"function hasActiveParent(elm) {\n\t\t\t\t\t\t\t\t\t\t\tvar parentNode = elm.parentNode.parentNode;\n\t\t\t\t\t\t\t\t\t\t\tvar classList = parentNode.classList;\n\t\n\t\t\t\t\t\t\t\t\t\t\tif (parentNode.tagName == \"LI\" && classList.contains(\"active\")) {\n\t\t\t\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t\t\t\t}",
"function shouldAppearInPrimaryNavBarMenu(item){// Items with children should always appear in the primary navbar menu.\nif(item.children){return true;}// Some nodes are otherwise important enough to always include in the primary navigation menu.\nswitch(navigationBarNodeKind(item)){case 245/* ClassDeclaration */:case 214/* ClassExpression */:case 248/* EnumDeclaration */:case 246/* InterfaceDeclaration */:case 249/* ModuleDeclaration */:case 290/* SourceFile */:case 247/* TypeAliasDeclaration */:case 322/* JSDocTypedefTag */:case 315/* JSDocCallbackTag */:return true;case 202/* ArrowFunction */:case 244/* FunctionDeclaration */:case 201/* FunctionExpression */:return isTopLevelFunctionDeclaration(item);default:return false;}function isTopLevelFunctionDeclaration(item){if(!item.node.body){return false;}switch(navigationBarNodeKind(item.parent)){case 250/* ModuleBlock */:case 290/* SourceFile */:case 161/* MethodDeclaration */:case 162/* Constructor */:return true;default:return false;}}}",
"function elementIsInContainer(container, element) {\n if (container[0] == window) {\n return $('body')[0].contains(element);\n } else {\n return container[0].contains(element);\n }\n }",
"function isNavSection(node) {\n if (!node || !node.item) {\n return false;\n }\n\n return (node.item.typeAlias === 'console:navSection') && (!node.item.isAppTab || node.item.depth > 2);\n }",
"function elemHasEnteredView(element){\n\n\t// Detect window top bound and offset\n\tvar viewTopOffset = $(window).scrollTop() + $(window).height();\n\n // Detect element top bound\n var elemTopOffset = $(element).offset().top;\n\n return (elemTopOffset <= viewTopOffset);\n}",
"function isParentNavItem() {\n var parentItem = service.getParentItem();\n\n if (!parentItem) {\n return false;\n } else {\n //return parentItem.state.name === 'folder'; // This is a little arbitrary. A better test would be to add the information to the breadcrumb.\n return true;\n }\n }",
"function check_if_in_view() {\n //get the window positions\n var window_height = $window.height();\n var window_top_position = $window.scrollTop();\n var window_bottom_position = (window_top_position + window_height); \n \n //checks to see if the highlight element is in view and then highlights the navbar button corresponding to it\n $.each($highlight_elements, function () {\n var h_element = $(this);\n //get the heights and position\n var h_element_height = h_element.outerHeight();\n var h_element_top = h_element.offset().top;\n var h_element_bottom = (h_element_height + h_element.position().top);\n //get the element id and format it to get the nav link id\n var h_button_id = \"#\" + h_element.attr('id') + \"-nav\";\n \n //if within view, adds the highlight active class to highlight the navbar button\n if ((h_element_bottom >= window_top_position) &&\n (h_element_top <= window_bottom_position)){\n //remove any existing highlight class\n $(\".highlight-active\").removeClass(\"highlight-active\");\n //then add to current\n $(h_button_id).addClass('highlight-active');\n } else {\n $(h_button_id).removeClass('highlight-active');\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the view to present the product. | function setProductInView() {
$scope.presentPercentageOff = $scope.product.percentage_off ? true : false;
$scope.presentOriginalPrice = $scope.product.original_price ? true : false;
$scope.changePercentageOff();
$scope.changeOriginalPrice();
fillOptionMenus();
setProductPhotos();
} | [
"renderProductView() {\n const productView = new ProductView({ collection: productCollection });\n }",
"viewProduct(product){\n this.props.selectProduct(product);\n this.setState({view: true,edit: false,mode: false});\n this.open();\n }",
"function ProductView() {\n this.productList = BB.DOM.PRODUCT_LIST;\n this.productListItem = BB.DOM.PRODUCT_LIST_ITEM;\n this.productModalEl = BB.DOM.PRODUCT_DETAIL_MODAL;\n this.productModalTemplate = BB.DOM.PRODUCT_DETAIL_MODAL_TEMPLATE;\n this.rerenderProducts = new BB.Observer(this);\n this.modalHasBeenTriggered = new BB.Observer(this);\n this.bindEvents();\n }",
"OnClick(products){\n console.log(\"product selected\")\n BuySdkManager.presentProductwithId(String(products.product_id));\n console.log(\"product view displayed succesfully\");\n }",
"function setView(view){\n if (window.currentView !== null && window.currentView != view){\n if (window.currentView == \"distribution\")\n switchFromDistributionToPerCapita();\n else\n switchFromPerCapitaToDistribution();\n }\n window.currentView = view;\n }",
"showView(view) {\n\t\tif (!view) {\n\t\t\tthis.region.empty();\n\t\t}\n\n\t\t// if an alternate view has been specified,\n\t\t// instantiate that, otherwise use the default view\n\t\tthis.view = view ? new view() : this.view\n\n\t\t// attach the view\n\t\tif (this.viewClass && this.regionName) {\n\t\t\tthis.region.show(this.view);\n\t\t}\n\t}",
"function setCurrentView(view)\n {\n if(view == VIEW_MODE_THUMBNAILS)\n {\n $('#perc-activated-templates').removeClass('perc-templates-detailed');\n _switchToThumbnailView();\n }\n else if(view == VIEW_MODE_CATALOG)\n {\n $('#perc-activated-templates').addClass('perc-templates-detailed');\n _switchToCatalogView();\n }\n }",
"async show({ params, view }) {\n try {\n const product = await Product.findOrFail(params.id);\n\n return view.render(\"products.detail\", {\n product: product.toJSON()\n });\n } catch (err) {\n return view.render(\"error.index\", {\n message: \"Esse produto não existe! :(\",\n back: \"products\",\n err\n });\n }\n }",
"function redirectToProductPage(productId, viewType){\n\twx.openProductSpecificView({\n\t productId: productId, // 商品id\n\t viewType: viewType // 0.默认值,普通商品详情页1.扫一扫商品详情页2.小店商品详情页\n\t});\n}",
"function oota_product_view(p_product_id)\n{\n\toota_request_async(oota_url_use+'product_view.json', 'product_id='+p_product_id, null);\n\treturn false;\n}",
"function displaySpecificView(view) {\n $(view).css('display', 'block');\n }",
"function viewProduct()\n{\n\twith (window.document.frmListProduct) {\n\t\twindow.location.href = 'productIndex.php';\n\t}\n}",
"navigateViewProductPage(e) {\n window.location = `/viewProducts`;\n }",
"function showProductPage(product){\n const imagesHTML = productImagesHTML(product);\n const infosHTML = productInfoHTML(product);\n\n $(\"#product-page .model-photos\").html(imagesHTML);\n $(\"#product-page #select\").html(infosHTML);\n\n showDrawer(\"product-page\");\n}",
"async create({ view }) {\n return view.render(\"products.form\", {\n editing: false\n });\n }",
"showView(view) {\n this.triggerMethod('before:show:view', view);\n this.getRegion('wrapRegion').show(view);\n this.triggerMethod('show:view', view);\n }",
"function setViewToPartido() {\n \tfindPartidoData();\n}",
"function setupView() {\n // set home buttone view point to initial extent\n var homeButton = new Home({\n view: view,\n viewpoint: new Viewpoint({\n targetGeometry: initialExtent\n })\n });\n view.ui.add(homeButton, \"top-left\");\n\n //expand widget\n editExpand = new Expand({\n expandIconClass: \"esri-icon-edit\",\n expandTooltip: \"Expand Edit\",\n expanded: false,\n view: view,\n content: editArea\n });\n view.ui.add(editExpand, \"top-right\");\n }",
"displayCartView() {\n this.isCartView = true;\n this.pageTitle = \"Your Cart\";\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle each command, and return relevant information to slack Return stats on all case filters from Desk | function status(res,type) {
let dataEntries = []
// Recursively call Desk until there are no more pages of results
let i = 1
function getOpenCases() {
desk.cases({
labels:['Priority publisher,SaaS Ads,Direct publisher,Community publisher,Home,Community commenter'],
status:['new,open'],
sort_field:'created_at',
sort_direction: 'asc',
per_page:100,
page:i
}, function(error, data) {
if (i <= Math.ceil(data.total_entries/100)) {
dataEntries = dataEntries.concat(data._embedded.entries)
i++
getOpenCases()
} else if (!data) {
error()
} else {
filterSend(dataEntries)
}
});
}
getOpenCases()
function getResolvedCases() {
desk.get('cases',{
labels:['Priority publisher,SaaS Ads,Direct publisher,Community publisher,Home,Community commenter'],
status:['resolved'],
sort_field:'created_at',
sort_direction: 'asc',
per_page:100
}, function(error, data) {
if (!data) {
error()
} else {
}
});
}
//getResolvedCases()
function filterSend(dataEntries) {
createStats(dataEntries)
slackSend()
}
// Filter the data into seprate objects that correspond to each Desk filter
function createStats(dataEntries) {
var priorityFilter = dataEntries.filter(function(caseObj){
return caseObj.labels.includes('Priority publisher') && !caseObj.labels.includes('SaaS Ads')
})
var saasFilter = dataEntries.filter(function(caseObj){
return caseObj.labels.includes('SaaS Ads') && !caseObj.labels.includes('Ad Content Report')
})
var directFilter = dataEntries.filter(function(caseObj){
return caseObj.labels.includes('Direct publisher') && !caseObj.labels.includes('Channel commenter') && !caseObj.labels.includes('SaaS Ads')
})
var communityFilter = dataEntries.filter(function(caseObj){
return caseObj.labels.includes('Community publisher') && !caseObj.labels.includes('Priority publisher') && !caseObj.labels.includes('SaaS Ads')
})
var channelFilter = dataEntries.filter(function(caseObj){
return caseObj.labels.includes('Home')
})
var commenterFilter = dataEntries.filter(function(caseObj){
return caseObj.labels.includes('Community commenter')
})
// New cases stats only for further segments
var priorityNew = priorityFilter.filter(function(caseObj){
return caseObj.status.includes('new')
})
var saasNew = saasFilter
.filter(function(caseObj){
return caseObj.status.includes('new')
})
var directNew = directFilter.filter(function(caseObj){
return caseObj.status.includes('new')
})
var communityNew = communityFilter.filter(function(caseObj){
return caseObj.status.includes('new')
})
var channelNew = channelFilter.filter(function(caseObj){
return caseObj.status.includes('new')
})
var commenterNew = commenterFilter.filter(function(caseObj){
return caseObj.status.includes('new')
})
// Open cases stats using complicated maths
var priorityOpen = priorityFilter.length - priorityNew.length
var saasOpen = saasFilter.length - saasNew.length
var directOpen = directFilter.length - directNew.length
var communityOpen = communityFilter.length - communityNew.length
var channelOpen = channelFilter.length - channelNew.length
var commenterOpen = commenterFilter.length - commenterNew.length
// Object so we can easily build the slack message
// Format: {"Filter Name": All cases, New cases, Open cases, "Needs attention" threshold for each filter}
stats = {
Priority:[priorityFilter.length,priorityNew.length,priorityOpen,10],
"Saas & Ads":[saasFilter.length,saasNew.length,saasOpen,30],
Direct:[directFilter.length,directNew.length,directOpen,30],
Community:[communityFilter.length,communityNew.length,communityOpen,30],
Channel:[channelFilter.length,channelNew.length,channelOpen,30],
Commenter:[commenterFilter.length,commenterNew.length,commenterOpen,60],
// Twitter: [dmCounter, dmCounter, dmCounter, 3],
}
}
// Build and send the message with data from each filter
function slackSend() {
var total = 0
var attachments = []
var statusColor
Object.keys(stats).map(function(objectKey, i) {
total += stats[objectKey][0]
if (stats[objectKey][0] > stats[objectKey][3]) {
statusColor = disqusRed
statusIcon = "🔥"
} else if (stats[objectKey][0] <= 5) {
statusColor = disqusGreen
statusIcon = ":partyporkchop:"
} else {
statusColor = disqusGreen
statusIcon = "🆒"
}
attachments.push({
"fallback": stats[objectKey][0] + " total" + stats[objectKey][1] + " new" + stats[objectKey][2] + " open",
"color": statusColor,
"title": statusIcon + " " + objectKey + ": " + stats[objectKey][0],
"text": stats[objectKey][1] + " new, " + stats[objectKey][2] + " open"
})
});
let statusMessage = {
"response_type": "in_channel",
"text": total + " total cases right now.",
"attachments": attachments
}
// depending on request origin, also send the response as webhook for daily notifications
if (type === 'notification') {
webhook({text:"Morning report incoming!"});
webhook(statusMessage);
}
res.send(statusMessage);
// TODO Write function that stores this data to database
//store(stats);
}
} | [
"function cases() {\n\tif (command === \"my-tweets\") {\n\t\tmyTweets();\n\t} else if (command === \"spotify-this-song\") {\n\t\tif (userInput){\n\t\tspotifySong();\n\t\t} else {\n\t\t\tuserInput = \"The Sign Ace of Base\";\n\t\t\tspotifySong();\n\t\t}\n\t} else if (command === \"movie-this\") {\n\t\tif (userInput){\n\t\t\tmovieThis();\n\t\t} else {\n\t\t\tuserInput = \"Mr. Nobody\"\n\t\t\tmovieThis();\n\t\t}\n\t} else if (command === \"do-what-it-says\") {\n\t\tdoWhatItSays();\n\t} else {\n\t\tconsole.log(\"Please enter one of the following required commands: my-tweets, spotify-this-song, movie-this or do-what-it-says.\");\n\t}\n}",
"advise()\n\t{\n\t\tlet tags = this.resultTagsForDomain( { inputObject: this.test_result.raw_response } );\n\n\t\tif( tags.length < 1 )\n\t\t{\n\t\t\tif( this.command == \"domain\" )\n\t\t\t{\n\t\t\t\tthis.severity = this.resultTagToSeverity( { resultTag: CW_Constants.RESULT_PASS } );\n\t\t\t\tthis.content = this.contentForSeverity( { severity: this.severity } );\n\t\t\t}\n\t\t\telse // http(s)-port commands\n\t\t\t{\n\t\t\t\t// The only PUNT condition is a response that takes too long. Without logic below, that will generate a NOTICE\n\t\t\t\tif( this.test_result.result == CW_Constants.RESULT_PUNT )\n\t\t\t\t{\n\t\t\t\t\t// TODO: Get config to see if we should notify\n\t\t\t\t}\n\n\t\t\t\tlet extraKey = null;\n\t\t\t\tif( (this.command == \"http-port\" || this.command == \"https-port\") &&\n\t\t\t\t\tthis.test_result.raw_response.raw_response == \"NO_RESPONSE\" )\n\t\t\t\t{\n\t\t\t\t\textraKey = this.test_result.raw_response.raw_response;\n\t\t\t\t}\n\t\n\t\t\t\tthis.severity = this.resultTagToSeverity( { resultTag: this.test_result.result } );\n\t\t\t\tthis.content = this.contentForSeverity( { severity: this.severity, extraInput: extraKey } );\n\t\t\t}\n\n\t\t}\n\t\telse // handle more complex responses and direct messages\n\t\t{\n\t\t\tthis.content = \"\";\n\t\t\ttags.forEach(\n\t\t\t\ttag =>\n\t\t\t\t{\n\t\t\t\t\tlet severity = this.resultTagToSeverity( { resultTag: tag.result_value, extraInput: tags } );\n\n\t\t\t\t\tif( severity > this.severity )\n\t\t\t\t\t{\n\t\t\t\t\t\tthis.severity = severity;\n\t\t\t\t\t\tthis.test_result.result = tag.result_value;\n\t\t\t\t\t}\n\n\t\t\t\t\tif( severity == CW_Constants.SEVERITY_DIRECT_MESSAGE && tags[0].message != undefined && tags[0].message.length > 0 )\n\t\t\t\t\t{\n\t\t\t\t\t\tthis.content += tags[0].message;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tthis.content += this.contentForSeverity( { severity: severity, extraInput: tag.intermediate_key } ) + \"\\n\";\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.result = tag.result_value;\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\t}",
"function slackSlashCommand(req, res, next) {\n if (req.body.command === \"/sally\") {\n const type = req.body.text.split(\" \")[0];\n console.log(\"Got request: \", req.body.text);\n let response;\n if (type === \"add\" || type === \"create\") {\n // CREATE NEW TODO\n response = addAttrib(req.body, \"todo\");\n } else if (type === \"finish\" || type === \"fin\" || type === \"done\") {\n // END NEW TODO\n const todoOpts = getTodoOpts(req.body.user_id);\n let response = {\n ...pickTaskToFinish,\n };\n response.attachments[0].blocks[0].accessory.options = todoOpts.fields;\n } else if (type === \"standup\") {\n // SEND STANDUP\n response = standup(req.body);\n //clean up finished and blockers\n db.delete(`/${req.body.user_id}/finished`);\n db.delete(`/${req.body.user_id}/blocker`);\n } else if (type === \"list\" || type === \"display\") {\n // LIST CURRENT TASKS\n response = display(req.body.user_id);\n } else if (type === \"blocker\") {\n // ADD BLOCKER\n response = addAttrib(req.body, \"blocker\", true);\n } else if (type === \"clear\") {\n // CLEAR ALL TODOS\n response = clearTodos(req.body.user_id);\n } else {\n // Help\n res.send(\n \"Use this command followed by `add <string>`, `blocker`, or `finish` to move tasks around. Use `list` or `standup` to view the current status. Note: `standup` removes finished tasks.\"\n );\n }\n res.json(response);\n } else {\n next();\n }\n}",
"function handleCommand(command, args, logData) {\n\n if (!command) {\n return console.log(\"Please enter a command and try again.\");\n }\n switch (command) {\n case 'concert-this':\n if (args.length === 0) {\n return console.log('No artist given');\n }\n getAPIResource(makeBandsInTownURL(args), bandsInTownResponse, args, logData);\n break;\n case 'spotify-this-song':\n if (args.length === 0) {\n args = \"The Sign\";\n }\n spotifyRequest(args, logData);\n break;\n case 'movie-this':\n if (args.length === 0) {\n args = 'Mr. Nobody';\n }\n getAPIResource(OMDBApiURL + args, OMDBResponse, args, logData);\n break;\n case 'do-what-it-says':\n\n // Read from file of previously used commands\n fs.readFile(textFilePath, 'utf8', function (err, response) {\n if (err) {\n return console.log(err);\n }\n // Get a random command\n const commandPoolStr = response;\n const commandPoolArr = commandPoolStr.split(';');\n const randomIndex = Math.floor(Math.random() * commandPoolArr.length);\n const newCommandAndArgs = commandPoolArr[randomIndex].split(',');\n\n const newCommand = newCommandAndArgs[0]\n let newArgs = newCommandAndArgs[1]\n\n // Remove double quotes (\"\") from string args\n newArgs = newArgs.slice(1, newArgs.length - 1)\n\n // Handle new command and args. Do not log to text file\n handleCommand(newCommand, newArgs, false);\n })\n break;\n case 'help':\n console.log('Available commands:\\n');\n console.log('concert-this <artist/band name here>');\n console.log('spotify-this-song <song name here>');\n console.log('movie-this <movie name here>');\n console.log('do-what-it-says');\n break;\n default:\n console.log('Unrecognized command.');\n }\n}",
"checkCommands(data) {\n\n\t\tif (/(PLEASE)/g.test(data) && /(WAKE)/g.test(data) && /(UP)/g.test(data)) {\n\t\t\tif(this.config.standByMethod === \"DPMS\")\n\t\t\t{exec(\"xset dpms force on\", null);}\n\t\t\tif(this.config.standByMethod === \"PI\") /////////// Turns on HDMI on Pi @sdetweil\n\t\t\t{exec(\"/opt/vc/bin/tvservice -p && sudo chvt 6 && sudo chvt 7\", null);}\n\t\t\tthis.hdmi = true;\n\n\t\t} else if (/(GO)/g.test(data) && /(TO)/g.test(data) && /(SLEEP)/g.test(data)) {\n\t\t\tif(this.config.standByMethod === \"DPMS\")\n\t\t\t{exec(\"xset dpms force off\", null);}\n\t\t\tif(this.config.standByMethod === \"PI\") /////////// Turns off HDMI on Pi @sdetweil\n\t\t\t{exec(\"/opt/vc/bin/tvservice -o\", null);}\n\t\t\tthis.hdmi = false;\n\n\t\t} else if (/(HIDE)/g.test(data) && /(MODULES)/g.test(data)) {\n\t\t\tthis.sendSocketNotification(\"HIDE_MODULES\");\n\n\t\t} else if (/(SHOW)/g.test(data) && /(MODULES)/g.test(data)) {\n\t\t\tthis.sendSocketNotification(\"SHOW_MODULES\");\n\n // Help screen made better by @cowboysdude\n\t\t} else if (/(HELP)/g.test(data)) {\n\t\t\tif (/(CLOSE)/g.test(data) || (this.help && !/(OPEN)/g.test(data))) {\n\t\t\t\tthis.sendSocketNotification(\"CLOSE_HELP\");\n\t\t\t\tthis.help = false;\n\t\t\t} else if (/(OPEN)/g.test(data) || (!this.help && !/(CLOSE)/g.test(data))) {\n\t\t\t\tthis.sendSocketNotification(\"OPEN_HELP\");\n\t\t\t\tthis.help = true;\n\t\t\t}\n\n\t\t\t////////////////// Toggle enhanced by @TheStigh /////////////\n\t\t\t////////////////\t\t\t Page 1 commands \t\t\t////////////////\n\t\t} else if (/(SHOW)/g.test(data) && /(PAGE)/g.test(data) && /(ONE)/g.test(data)) {\n\t\t\tthis.sendSocketNotification(\"HIDE_MODULES\");\n\t\t\tthis.sendSocketNotification(\"MODULE_STATUS\",{hide: [], show: this.config.pageOneModules, toggle:[]});\n\n\t\t} else if (/(HIDE)/g.test(data) && /(PAGE)/g.test(data) && /(ONE)/g.test(data)) {\n\t\t\tthis.sendSocketNotification(\"HIDE_MODULES\");\n\n\t\t\t////////////////\t\t\t Page 2 commands \t\t\t////////////////\n\t\t} else if (/(SHOW)/g.test(data) && /(PAGE)/g.test(data) && /(TWO)/g.test(data)) {\n\t\t\tthis.sendSocketNotification(\"HIDE_MODULES\");\n\t\t\tthis.sendSocketNotification(\"MODULE_STATUS\",{hide: [], show: this.config.pageTwoModules, toggle:[]});\n\n\t\t} else if (/(HIDE)/g.test(data) && /(PAGE)/g.test(data) && /(TWO)/g.test(data)) {\n\t\t\tthis.sendSocketNotification(\"HIDE_MODULES\");\n\n\t\t\t////////////////\t\t\t Page 3 commands \t\t\t////////////////\n\t\t} else if (/(SHOW)/g.test(data) && /(PAGE)/g.test(data) && /(THREE)/g.test(data)) {\n\t\t\tthis.sendSocketNotification(\"HIDE_MODULES\");\n\t\t\tthis.sendSocketNotification(\"MODULE_STATUS\",{hide: [], show: this.config.pageThreeModules, toggle:[]});\n\n\t\t} else if (/(HIDE)/g.test(data) && /(PAGE)/g.test(data) && /(THREE)/g.test(data)) {\n\t\t\tthis.sendSocketNotification(\"HIDE_MODULES\");\n\n\t\t\t////////////////\t\t\t Page 4 commands \t\t\t////////////////\n\t\t} else if (/(SHOW)/g.test(data) && /(PAGE)/g.test(data) && /(FOUR)/g.test(data)) {\n\t\t\tthis.sendSocketNotification(\"HIDE_MODULES\");\n\t\t\tthis.sendSocketNotification(\"MODULE_STATUS\",{hide: [], show: this.config.pageFourModules, toggle:[]});\n\n\t\t} else if (/(HIDE)/g.test(data) && /(PAGE)/g.test(data) && /(FOUR)/g.test(data)) {\n\t\t\tthis.sendSocketNotification(\"HIDE_MODULES\");\n\n\t\t\t////////////////\t\t\t Page 5 commands \t\t\t////////////////\n\t\t} else if (/(SHOW)/g.test(data) && /(PAGE)/g.test(data) && /(FIVE)/g.test(data)) {\n\t\t\tthis.sendSocketNotification(\"HIDE_MODULES\");\n\t\t\tthis.sendSocketNotification(\"MODULE_STATUS\",{hide: [], show: this.config.pageFiveModules, toggle:[]});\n\n\t\t} else if (/(HIDE)/g.test(data) && /(PAGE)/g.test(data) && /(FIVE)/g.test(data)) {\n\t\t\tthis.sendSocketNotification(\"HIDE_MODULES\");\n\n\t\t\t////////////////\t\t\t Page 6 commands \t\t\t////////////////\n\t\t} else if (/(SHOW)/g.test(data) && /(PAGE)/g.test(data) && /(SIX)/g.test(data)) {\n\t\t\tthis.sendSocketNotification(\"HIDE_MODULES\");\n\t\t\tthis.sendSocketNotification(\"MODULE_STATUS\",{hide: [], show: this.config.pageSixModules, toggle:[]});\n\n\t\t} else if (/(HIDE)/g.test(data) && /(PAGE)/g.test(data) && /(SIX)/g.test(data)) {\n\t\t\tthis.sendSocketNotification(\"HIDE_MODULES\");\n\n\t\t\t////////////////\t\t\t Page 7 commands \t\t\t////////////////\n\t\t} else if (/(SHOW)/g.test(data) && /(PAGE)/g.test(data) && /(SEVEN)/g.test(data)) {\n\t\t\tthis.sendSocketNotification(\"HIDE_MODULES\");\n\t\t\tthis.sendSocketNotification(\"MODULE_STATUS\",{hide: [], show: this.config.pageSevenModules, toggle:[]});\n\n\t\t} else if (/(HIDE)/g.test(data) && /(PAGE)/g.test(data) && /(SEVEN)/g.test(data)) {\n\t\t\tthis.sendSocketNotification(\"HIDE_MODULES\");\n\n\t\t\t////////////////\t\t\t Page 8 commands \t\t\t////////////////\n\t\t} else if (/(SHOW)/g.test(data) && /(PAGE)/g.test(data) && /(EIGHT)/g.test(data)) {\n\t\t\tthis.sendSocketNotification(\"HIDE_MODULES\");\n\t\t\tthis.sendSocketNotification(\"MODULE_STATUS\",{hide: [], show: this.config.pageEightModules, toggle:[]});\n\n\t\t} else if (/(HIDE)/g.test(data) && /(PAGE)/g.test(data) && /(EIGHT)/g.test(data)) {\n\t\t\tthis.sendSocketNotification(\"HIDE_MODULES\");\n\n\t\t\t////////////////\t\t\t Page 9 commands \t\t\t////////////////\n\t\t} else if (/(SHOW)/g.test(data) && /(PAGE)/g.test(data) && /(NINE)/g.test(data)) {\n\t\t\tthis.sendSocketNotification(\"HIDE_MODULES\");\n\t\t\tthis.sendSocketNotification(\"MODULE_STATUS\",{hide: [], show: this.config.pageNineModules, toggle:[]});\n\n\t\t} else if (/(HIDE)/g.test(data) && /(PAGE)/g.test(data) && /(NINE)/g.test(data)) {\n\t\t\tthis.sendSocketNotification(\"HIDE_MODULES\");\n\n\t\t\t////////////////\t\t\t Page 10 commands \t\t\t////////////////\n\t\t} else if (/(SHOW)/g.test(data) && /(PAGE)/g.test(data) && /(TEN)/g.test(data)) {\n\t\t\tthis.sendSocketNotification(\"HIDE_MODULES\");\n\t\t\tthis.sendSocketNotification(\"MODULE_STATUS\",{hide: [], show: this.config.pageTenModules, toggle:[]});\n\n\t\t} else if (/(HIDE)/g.test(data) && /(PAGE)/g.test(data) && /(TEN)/g.test(data)) {\n\t\t\tthis.sendSocketNotification(\"HIDE_MODULES\");\n\n\t\t} else {\n for (let row of importedWords.modOp){\n\n// These vars ARE used in the .test(data) below\n // refactored\n\t\t\t\tfirstWord = row[0];\n\t\t\t\tsecWord = row[1];\n\t\t\t\tthirdWord = row[2];\n\t\t\t\tfourthWord = row[3];\n\t\t\t\ttrueFalse = row[4];\n\t\t\t\tmodName = row[5];\n\t\t\t\tsendNoti = row[6];\n\n\t\t\t\tthis.firstWord = RegExp(firstWord);\n\t\t\t\tthis.secWord = RegExp(secWord);\n\t\t\t\tthis.thirdWord = RegExp(thirdWord);\n\t\t\t\tthis.fourthWord = RegExp(fourthWord);\n\t\t\t\tthis.trueFalse = trueFalse;\n\t\t\t\tthis.modName = modName;\n\t\t\t\tthis.sendNoti = sendNoti;\n\n\t\t\t\tif (this.firstWord.test(data) && this.secWord.test(data) && this.thirdWord.test(data) && this.fourthWord.test(data)) {\n\t\t\t\t\t//console.log(\">>> modName & sendNoti : \"+this.modName+\" \"+this.sendNoti);\n\t\t\t\t\tif (this.modName != \"\") {\n\t\t\t\t\t\tif (this.trueFalse === \"true\") {\n\t\t\t\t\t\t\tthis.sendSocketNotification(\"MODULE_STATUS\",{hide: [], show: [this.modName], toggle:[]});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tthis.sendSocketNotification(\"MODULE_STATUS\",{hide: [this.modName], show: [], toggle:[]});\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.sendSocketNotification(\"MODULE_UPDATE\",this.sendNoti);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"function botMsgActions(incoming, Discord) {\n const sendMsg = (msg) => {\n incoming.channel.send(msg)\n };\n\n return {\n sendAll(data) {\n const embed = new Discord.MessageEmbed()\n .setColor('#000000')\n .setTitle(`Coding Lab Techs`);\n\n data.forEach((counselor, counselorIndex) => {\n let zoomTokens = counselor[3].split('/');\n embed.addField(counselor[0], `*${counselor[2]}* | Zoom ID: ${zoomTokens[zoomTokens.length - 1]} | [Book Appointments Here](${counselor[5]})\\n${counselor[1]}`);\n });\n sendMsg(embed);\n },\n sendSkillMatched(data, inputSkill) {\n const matchedOnes = getter.skillMatchedCounselors(data, inputSkill);\n\n if (matchedOnes.length > 0) {\n const embed = new Discord.MessageEmbed()\n .setColor('#000000')\n .setTitle(`Following Lab Techs Know \\`${inputSkill}\\``);\n\n matchedOnes.forEach((counselor, counselorIndex) => {\n let zoomTokens = counselor[3].split('/');\n embed.addField(counselor[0], `*${counselor[2]}* | Zoom ID: ${zoomTokens[zoomTokens.length - 1]} | [Book Appointments Here](${counselor[5]})`);\n });\n \n sendMsg(embed);\n } else {\n sendMsg(\n `😅 Sorry! We have no ${inputSkill} experts at this time. Try an ITP resident or faculty member here: https://itp.nyu.edu/help/in-person-help/office-hours/`\n );\n }\n },\n };\n}",
"function runCommand(command, query) {\n //if command = spotify \n if (command === \"spotify-this-song\") {\n spotify.search({ type: 'track', query: query }).then(\n function (data) {\n // prints the artists, name, href, album using spotify\n console.log(data.tracks.items[0].name);\n console.log(data.tracks.items[0].artists);\n console.log(data.tracks.items[0].album);\n console.log(data.tracks.items[0].href);\n // Artist(s)\n //loop to print all the items in response\n // for (item of data.tracks.items) {\n // //console.log(item)\n // console.log(item.href);\n // console.log(item.name);\n // console.log(item.artists);\n // console.log(item.album);\n // }\n }\n , function (error) { console.log(error); });\n }\n //if command = movie....\n else if (command === \"movie-this\") {\n axios.get(queryUrl).then(function (response) {\n console.log(response.data.Title);\n console.log(response.data.Year);\n console.log(response.data.Director);\n console.log(response.data.Rated);\n console.log(response.data.Actors);\n console.log(response.data.Plot);\n console.log(response.data.Language);\n })\n\n .catch(function (error) {\n console.log(error);\n });\n }\n //if command = concert....\n else if (command === \"concert-this\") {\n axios.get(queryConcert).then(function (response) {\n // console.log(response);\n console.log(response.data[0].venue.name);\n console.log(moment(response.data[0].datetime).format(\"MM/DD/YYYY\"));\n console.log(response.data[0].venue.city);\n //console.log(response.data.venue);\n }).catch(function (error) {\n console.log(error);\n });\n }\n //if command = do-what-\n else if (command === 'do-what-it-says') {\n fs.readFile(\"random.txt\", \"utf8\", function (error, data) {\n if (error) {\n console.log(error);\n return;\n }\n var dataArray = data.split(\",\");\n runCommand(dataArray[0], dataArray[1]);\n })\n }\n}",
"function processTxtCommands() {\n var playerAction = \"txtCommand \\\"\" + txtCommand.value + \"\\\"\";\n // Convert string to lower case for analysis\n var txtCommandLowcase = txtCommand.value.toLowerCase();\n switch(txtCommandLowcase) {\n case \"w\": attemptGoWest(playerAction); break;\n case \"n\": attemptGoNorth(playerAction); break;\n case \"s\": attemptGoSouth(playerAction); break;\n case \"e\": attemptGoEast(playerAction); break;\n default: parsedTxtCommands();\n }\n }",
"function handleControl(event, context) {\n var state;\n var idx;\n var accessToken = event.payload.accessToken;\n var what = event.payload.appliance.additionalApplianceDetails.WhatAmI;\n var message_id = event.header.messageId;\n var switchtype = event.payload.appliance.additionalApplianceDetails.switchis;\n var applianceId = event.payload.appliance.applianceId;\n var maxDimLevel = event.payload.appliance.additionalApplianceDetails.maxDimLevel;\n\n var confirmation;\n var funcName;\n\n switch (what) {\n case \"light\":\n var switchtype = \"switch\";\n\n if (event.header.name == \"TurnOnRequest\") {\n confirmation = \"TurnOnConfirmation\";\n funcName = \"On\";\n }\n else if (event.header.name == \"TurnOffRequest\") {\n confirmation = \"TurnOffConfirmation\";\n funcName = \"Off\";\n }\n else if (event.header.name == \"SetPercentageRequest\") {\n dimLevel = event.payload.percentageState.value / ( 100 / maxDimLevel);\n confirmation = \"SetPercentageConfirmation\";\n switchtype = 'dimmable';\n funcName = dimLevel;\n }\n var headers = {\n namespace: 'Alexa.ConnectedHome.Control',\n name: confirmation,\n payloadVersion: '2',\n messageId: message_id\n };\n ctrlLights(switchtype,applianceId, funcName, function (callback) {\n var result = {\n header: headers,\n payload: callback\n };\n context.succeed(result);\n }); break;\n case \"blind\":\n var switchtype = \"switch\";\n\n if (event.header.name == \"TurnOnRequest\") {\n confirmation = \"TurnOnConfirmation\";\n funcName = \"Off\";\n }\n else if (event.header.name == \"TurnOffRequest\") {\n confirmation = \"TurnOffConfirmation\";\n funcName = \"On\";\n }\n var headers = {\n namespace: 'Alexa.ConnectedHome.Control',\n name: confirmation,\n payloadVersion: '2',\n messageId: message_id\n };\n ctrlLights(switchtype,applianceId, funcName, function (callback) {\n var result = {\n header: headers,\n payload: callback\n };\n context.succeed(result);\n }); break;\n case \"scene\":\n\n var AppID = parseInt(event.payload.appliance.applianceId) - 200;\n\n if (event.header.name == \"TurnOnRequest\") {\n confirmation = \"TurnOnConfirmation\";\n funcName = \"On\";\n }\n else if (event.header.name == \"TurnOffRequest\") {\n confirmation = \"TurnOffConfirmation\";\n funcName = \"Off\";\n }\n headers = {\n namespace: 'Alexa.ConnectedHome.Control',\n name: confirmation,\n payloadVersion: '2',\n messageId: message_id\n };\n ctrlScene(AppID, funcName, function (callback) {\n var result = {\n header: headers,\n payload: callback\n };\n context.succeed(result);\n }); break;\n case \"temp\":\n\n var temp = event.payload.targetTemperature.value;\n\n applianceId = event.payload.appliance.applianceId;\n\n if (event.header.name == \"SetTargetTemperatureRequest\") {\n confirmation = \"SetTargetTemperatureConfirmation\";\n //\tflVal = parseFloat(temp);\n }\n headers = {\n namespace: 'Alexa.ConnectedHome.Control',\n name: confirmation,\n payloadVersion: '2',\n messageId: message_id\n };\n ctrlTemp(applianceId, temp, function (callback) {\n var result = {\n header: headers,\n payload: callback\n };\n context.succeed(result);\n });\n break;\n\n default:\n log(\"error \",\"error - not hit a device type\");\n\n }\n}",
"_onCmd(cmd, tokens, client, self) {\n /* Note: called as a command; `this` refers to a command object */\n let t0 = tokens.length === 0 ? null : tokens[0];\n if (t0 === null || t0 === \"help\") {\n if (t0 === null) {\n Content.addHelpText(`Fanfare is ${self._on ? \"en\" : \"dis\"}abled`);\n }\n this.printUsage();\n Content.addHelpText(\"Add a number to cheerdemo to simulate that number of bits\");\n Content.addHelpText(\"Available arguments for subdemo:\");\n for (let kind of TwitchSubEvent.KINDS) {\n Content.addHelpLine(kind, `Demonstrate the ${kind} type of subscription`);\n }\n for (let plan of TwitchSubEvent.PLANS) {\n let name = TwitchSubEvent.PlanName(plan);\n Content.addHelpLine(plan, `Demonstrate a ${name} subscription`);\n }\n Content.addHelpText(`Default kind: ${TwitchSubEvent.SUB}`);\n Content.addHelpText(`Default plan: ${TwitchSubEvent.PLAN_TIER1}`);\n } else if (t0 === \"on\") {\n self._on = true;\n Content.addInfoText(\"Fanfare is now enabled\");\n } else if (t0 === \"off\") {\n self._on = false;\n Content.addInfoText(\"Fanfare is now disabled\");\n } else if (t0 === \"demo\") {\n self._onChatEvent(self._client, {bits: 1000}, true);\n self._onSubEvent(self._client, {\n kind: TwitchSubEvent.SUB,\n plan: TwitchSubEvent.PLAN_TIER1\n }, true);\n } else if (t0 === \"cheerdemo\") {\n let bits = 1000;\n if (tokens.length === 2 && Util.IsNumber(tokens[1])) {\n bits = Util.ParseNumber(tokens[1]);\n }\n self._onChatEvent(self._client, {bits: bits}, true);\n } else if (t0 === \"subdemo\") {\n let kind = TwitchSubEvent.SUB;\n let plan = TwitchSubEvent.PLAN_TIER1;\n if (tokens.length > 1) {\n for (let k of TwitchSubEvent.KINDS) {\n if (tokens.includes(k)) {\n kind = k;\n }\n }\n for (let p of TwitchSubEvent.PLANS) {\n if (tokens.includes(p)) {\n plan = p;\n }\n }\n }\n self._onSubEvent(self._client, {kind: kind, plan: plan}, true);\n } else {\n Content.addErrorText(`Fanfare: unknown argument ${t0}`);\n this.printUsage();\n }\n }",
"function handleCommand(e){\n let cmd = JSON.parse(e.data);\n let type = cmd.type;\n if(type === \"hi\") {\n //Hello command - register this user as part of the client\n handleCardHello(cmd);\n } else if(type === \"new-client\"){\n //A new client has announced its arrival\n handleNewClient(cmd);\n } else if(type === \"goodbye\"){\n //Goodbye command - deallocate this user resources\n handleCardGoodbye(cmd);\n } else if(type === \"update-triage\"){\n //A card has had its triage updated\n handleUpdateTriage(cmd);\n } else if(type === \"new-card\") {\n //A new card has been created\n handleNewCard(cmd);\n } else if(type === \"assign\"){\n handleAssign(cmd);\n }\n}",
"handleCommand(str) {\n if( typeof(str) == 'undefined') {\n return \"Nonexistant command string\"\n } if( str == \"\" ) {\n return \"Empty command string\"\n }\n let strarr = str.split(\" \")\n let rval = 0\n switch(strarr[0]){\n case \"PLACE\":\n let re = new RegExp(\"PLACE ([0-4])( |,)([0-4])( |,)(north|east|south|west)\")\n let ret = str.search(re)\n if( ret == -1) {\n return \"PLACE syntax is '/^PLACE [0-4](,| )[0-4](,| )(north|west|south|east)$/ e.g. PLACE 1 1 north\"\n }\n let arr = re.exec(str)\n rval = this.place(arr[1], arr[3], arr[5])\n switch(rval) {\n case 1:\n return \"Tried to place outside of boundaries\"\n case 0:\n return \"Successfully placed beefy\"\n default:\n return \"CRITFAIL: Unknown status code from this.place\"\n } \n case \"MOVE\":\n rval = this.move()\n switch(rval) {\n case 1:\n return \"Tried to drive beefy off the edge of the table\"\n case -1:\n return \"Beefy can't drive if he's not on the table yet\"\n case 0:\n return \"Beefy went for a drive\"\n default:\n return \"CRITFAIL: Unknown status code from this.move \" + rval\n }\n case \"LEFT\":\n rval = this.left()\n switch(rval) {\n case -1:\n return \"Beefy can't turn if he's not on the table yet\"\n case 0:\n return \"Turned beefy left\"\n default:\n return \"CRITFAIL: Unknown status code from this.left\"\n }\n case \"RIGHT\":\n rval = this.right()\n switch(rval) {\n case -1:\n return \"Beefy can't turn if he's not on the table yet\"\n case 0:\n return \"Turned beefy right\"\n default:\n return \"CRITFAIL: Unknown status code from this.right\"\n }\n case \"REPORT\":\n rval = this.report\n switch(rval) {\n case -1:\n return \"Beefy can't give a report if he's not on the table yet\"\n default:\n return rval;\n }\n default:\n return \"Unrecognized opcode, your options are PLACE, MOVE, LEFT, RIGHT, and REPORT. Check the docs for their syntax\"\n }\n\n }",
"function send(data){\n //Get and filter control units, devices, components that are matching the filters in the data parameter.\n //Then create commands that is to be sent to each matching control unit.\n var allCommands = [];\n\n if(data instanceof Array){\n for(var i = 0; i < data.length; i++){\n var filter = data[i].filter;\n var value = data[i].value;\n\n var controlUnits = ControlUnitFinder.find(filter); //Get all control units that matches the filter\n var commands = createCommands(controlUnits, filter, value); //Create commands that is to be sent to each matching control unit\n allCommands = allCommands.concat(commands);\n }\n }else{\n var filter = data.filter;\n var value = data.value;\n\n var controlUnits = ControlUnitFinder.find(filter); //Get all control units that matches the filter\n var commands = createCommands(controlUnits, filter, value); //Create commands that is to be sent to each matching control unit\n allCommands = allCommands.concat(commands);\n }\n\n //Group the commands by the same API key\n var apiGroups = groupByApiKey(allCommands);\n\n //Send the commands to each control unit\n for(var apiKey in apiGroups){\n var commands = apiGroups[apiKey];\n\n console.log('\\n----- Sending command to control unit ----------');\n printCommands(commands);\n\n Stream.get(apiKey).emit(commands); //Get the communication channel of the control unit and send the commands to it\n }\n }",
"function commandTranslate(command, input) {\n\tconsole.log('translate ' + command.str + input);\n\tif (command.str == 'category') {\n\t\tinput = input.replace(/\\s+/g, '').toLowerCase();\n\t\tconsole.log('cleaned input' + input);\n\t\treturn input;\n\t}\n\tif (command.str == 'sort') {\n\t\treturn Sort.action(input);\n\t}\n\tif (command.str == 'stop') {\n\t\tconsole.log('stop');\n\t\tStop.action(input);\n\t}\n\tif (command.str == 'start') {\n\t\tconsole.log('start');\n\t\tStart.action(input);\n\t}\n\tif (command.str == 'faster') {\n\t\tconsole.log('faster');\n\t\tFaster.action(input);\n\t}\n\tif (command.str == 'slower') {\n\t\tconsole.log('slower');\n\t\tSlower.action(input);\n\t}\n\tif (command.str == 'rate') {\n\t\tconsole.log('rate');\n\t\tRate.action(input);\n\t}\n\tif (command.str == 'help') {\n\t\tconsole.log('help');\n\t\tHelp.action(input);\n\t}\n\tif (command.str == 'location') {\n\t\tconsole.log('location action called');\n\t\treturn Location.action(input);\n\t}\n\tif (command.str == 'more') {\n\t\tconsole.log('more action called');\n\t\treturn More.action(input);\n\t}\n\tif (command.str == 'search') {\n\t\tconsole.log('search action called');\n\t\treturn Search.action(input);\n\t}\n\tif (command.str == 'call') {\n\t\tconsole.log('call action called');\n\t\treturn Call.action(input);\n\t}\t\t\t\t\t\t\t\n\telse {\n\t\treturn input;\n\t}\n\n}",
"function hit(){\n \n //multiple command arrays might be sent in the same push;\n //loop through them\n for(var i = 0; i < arguments.length; i++){\n \n var command = arguments[i];\n \n //if the last element of the command array is an object, it may be\n //a extensible configuration object telling us how to handle this\n //command\n if (command.length && typeof(command[command.length - 1]) == 'object') {\n \n var command_options = command[command.length - 1];\n \n //delay this command until next page load\n if (command_options['delayed']) {\n delayCommand(command);\n continue;\n }\n \n }\n \n //send the command to each registered engine\n for(var j = 0; j < engines.length; j++){\n engines[j].run(command);\n }\n \n }\n\n }",
"function processMessageCrusader(self, msg){\n switch (msg){\n case 0:\n break;\n case 1:\n self.status = 'searchAndAttack';\n break;\n case 16390:\n self.status = 'rally';\n //self.finalTarget = self.rallyTarget;\n break;\n case 16391:\n self.status = 'defend';\n //self.finalTarget = self.defendTarget;\n break;\n }\n}",
"function commandSwitch(cmd, arg) {\nswitch (cmd) {\n\n case 'concert-this':\n concertThis(arg);\n break;\n\n case 'spotify-this-song':\n spotifyThis(arg);\n break;\n\n case 'movie-this':\n movieThis(arg);\n break;\n\n case 'do-what-it-says':\n doWhatItSays();\n break;\n\n case \"commands\":\n console.log(\"\\nspotify-this-song\\nmovie-this\\ndo-what-it-says\");\n break;\n}\n}",
"function processHelp(bot, channelID) {\n const setMessage = \"To set a custom command (admins only), type `!set <command> <messsage>`. For example: `!set eat I eat dog food`\\n\\n\";\n const readMessage = \"To run a custom command, type `!<command>`. For example: `!eat`\\n\\n\";\n const allCommandsMessage = \"To see all custom commands type `!commands`\\n\\n\";\n const showAdminMessage = \"To see all KB Bot admins `!admins`\\n\\n\";\n const gvgRequestMessage = \"To request for GvG, type `!gvg-need`\\n\\n\";\n const gvgRemoveMeMessage = \"To remove yourself from the GvG list, type `!gvg-removeme`\\n\\n\";\n const gvgListMessage = \"To see list of players looking for GvG, type `!gvg-list`\\n\\n\";\n const gvgClearListMessage = \"To clear GvG list (admins only), type `!gvg-clear-list` or `!gvg-clear`\\n\\n\";\n const gvgRemoveSomeoneMessage = \"To remove someone from the GvG list (admins only), type `!gvg-remove name`\\n\\n\";\n const giveThanksMessage = \"To thank someone, type `!thank name`. To see ranking, `!top-thanks`\\n\\n\";\n\n bot.sendMessage({\n to: channelID,\n message: setMessage +\n readMessage +\n allCommandsMessage +\n showAdminMessage +\n gvgRequestMessage +\n gvgListMessage +\n gvgRemoveMeMessage +\n gvgClearListMessage +\n gvgRemoveSomeoneMessage +\n giveThanksMessage\n });\n}",
"ProcessWatchCommand() {\n if (this.commandParameters.length < 1)\n return;\n //get the channel id\n this.friendlyChannelName = this.message.content.substring(this.message.content.indexOf(' ') + 1);\n this.channelId = this.GetVoiceChannelIdByName(this.friendlyChannelName);\n\n //if the channel id was empty then the channel wasn't found, reply to the user and tell them they mistyped the channel\n if (this.channelId == '') {\n this.message.channel.send('Channel ' + this.friendlyChannelName + ' not found');\n return;\n } else {\n\n //hook to the join events for the given channel id\n this.client.on('voiceStateUpdate', (oldMember, newMember) => {\n this.ListenToChannel(oldMember, newMember);\n });\n\n //just display a message so the user knows they're being watched\n var msg = 'Watching the channel ' + this.friendlyChannelName + ' for joining users';\n this.ReplyToMessage(msg);\n this.audioPlayer.channelId = this.channelId;\n }\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate javascript code for routes | function routeCode(procedure) {
console.log("Generating route for", procedure.name);
var js = "";
function add(line) {
js += line + '\n';
}
add("var express = require(\"express\");");
add("/**");
add(" * @function " + procedure.name);
for (i = 0; i < procedure.parameters.length; i++) {
var temp = " * @param {" + procedure.parameters[i].type + "} " + procedure.parameters[i].name;
add(temp);
}
add(" */\n");
add("exports.router = function (connection) {");
add(" var router = express.Router();");
add(" router.post(\"/"+procedure.name+"\", function (req, res) {");
add(" connection.query(\"" + query(procedure.name, procedure.parameters) + "\", req.body, res);");
add(" });");
add(" return router;");
add("}");
return js;
} | [
"function routeCode(procedure) {\n\tvar js = \"\";\n\n\tfunction add(line) {\n\t\tjs += line + '\\n';\n\t}\n\n\tadd(\"var express = require(\\\"express\\\");\");\n\tadd(\"/**\");\n\tadd(\" * @function \" + procedure.name);\n\tfor (i = 0; i < procedure.parameters.length; i++) {\n\t\tvar temp = \" * @param {\" + procedure.parameters[i].type + \"} \" + procedure.parameters[i].name;\n\t\tadd(temp);\n\t}\n\tadd(\" */\\n\");\n\tadd(\"exports.router = function (connection) {\");\n\tadd(\"\tvar router = express.Router();\");\n\tadd(\"\trouter.post(\\\"/procedures/\" + procedure.name + \"\\\", function (req, res) {\");\n\tadd(\"\t\tconnection.query(\\\"\" + query(procedure.name, procedure.parameters) + \"\\\", req.body, res);\");\n\tadd(\"\t});\");\n\tadd(\"\treturn router;\");\n\tadd(\"}\");\n\n\treturn js;\n}",
"function RouteCompiler() {\n\n}",
"function _compileRouter()\n{\n var method = function(conttype)\t// method which handles requests for additional parts of page (js, css, images)\n {\t\t\t\t\t// http://example.com/%part_type%/%name%\n if(typeof(conttype) == 'string')// http://example.com/js/index.js - gets index.js from public dir (_public).\n {\n conttype = 'text/'+conttype;\n return function(req, res)\n {\n var fname = url.parse(req.url).pathname.split('/'); fname = fname[fname.length - 1];\n var folder = url.parse(req.url).pathname.split('/'); folder = folder[folder.length - 2];\n var fpath = path.join(_public,folder,fname);\n fs.exists(fpath, function(ex)\n {\n if(ex)\n {\n var stat = fs.statSync(fpath);\n var fd = fs.openSync(fpath, 'r');\n var buff = new Buffer(stat.size);\n fs.readSync(fd, buff, 0, buff.length, null);\n res.writeHead(200, {'Content-Type': conttype}); \n res.end(buff);\n }\n else\n {\n res.end();\n }\n }\n );\n \n }\n }\n }\n _router.handlers['css']={};\n _router.handlers[ 'js']={};\n _router.handlers['img']={};\n _router.handlers['css']['GET']=method('css');\n _router.handlers[ 'js']['GET']=method('javascript');\n _router.handlers['img']['GET']=method('')\n}",
"routes () {\n\n }",
"function genCode() {\n\n\t//login function implemented in login.js file\n\tlogin();\n\n\n\t//To start the server to visit the redirect url\n\tstart_server();\n\n}",
"function Route() {}",
"function Route(){}",
"function routingFn() {\n\n // Return the function that manages the routing\n // Ok being non-synchro\n return function (req, res, next) {\n\n // Default menus and blocks for each request\n // More of these can be added in modules, these are jsut the defaults\n res.menu = {\n admin:new calipso.menu('admin', 'weight', 'root', {\n cls:'admin'\n }),\n adminToolbar:new calipso.menu('adminToolbar', 'weight', 'root', {\n cls:'admin-toolbar toolbar'\n }),\n // TODO - Configurable!\n userToolbar:new calipso.menu('userToolbar', 'weight', 'root', {\n cls:'user-toolbar toolbar'\n }),\n primary:new calipso.menu('primary', 'name', 'root', {\n cls:'primary'\n }),\n secondary:new calipso.menu('secondary', 'name', 'root', {\n cls:'secondary'\n })\n };\n\n\n // Initialise our clientJS library linked to this request\n var Client = require('./client/Client');\n res.client = new Client();\n\n // Initialise helpers - first pass\n calipso.helpers.getDynamicHelpers(req, res, calipso);\n\n // Route the modules\n calipso.module.eventRouteModules(req, res, next);\n\n };\n\n}",
"function buildRouteJSON() {\n\t// Pull in Route Declarations as a string so import statements aren't attempted\n\tconst routesAsString = fs.readFileSync(path.resolve(__dirname, vuejsRouteFile), 'utf-8');\n\t// Clean out the arrow functions and imports used for code-splitting routes in vue\n\t// re-establish a js array from our cleaned string\n\tconst matchPaths = RegExp(/path:\\s'([^']*)'/g);\n\tlet myArray = [];\n\tconst paths = [];\n\t// eslint-disable-next-line\n\twhile ((myArray = matchPaths.exec(routesAsString)) !== null) {\n\t\tconst msg = `${myArray[0]}`;\n\t\tconst pathOnly = msg.replace(/(path:\\s)/, '');\n\t\tconst cleanString = pathOnly.replace(/'/g, '');\n\t\tif (cleanString !== '*' && cleanString !== '' && cleanString.indexOf('/') === 0) {\n\t\t\tpaths.push(cleanString);\n\t\t}\n\t}\n\t// add /static path and anything against it to allow initial calls for static assets\n\tpaths.push('/static/:any');\n\t// add paths for auth0 implementation\n\tpaths.push('/error');\n\tpaths.push('/ui-login');\n\tpaths.push('/ui-logout');\n\tpaths.push('/process-ssr-auth');\n\t// add path for time synchronization\n\tpaths.push('/timesync');\n\t// add paths for healthcheck\n\tpaths.push('/healthcheck');\n\t// add paths for sitemap\n\tpaths.push('/sitemaps/ui.xml');\n\n\treturn paths;\n}",
"initRoutes() {\n }",
"function routesFromFilejs(downloadJson, userRoutes) {\n var script = document.createElement('script');\n script.type = 'text/javascript';\n script.src = 'assets/data/routes-content.js';\n script.onload = function () {\n function donwloadJSON() {\n var data = \"data:text/json;charset=utf-8,\" + encodeURIComponent(JSON.stringify(routes));\n var elem = document.createElement('a');\n elem.setAttribute(\"href\", data);\n elem.setAttribute(\"download\", \"routes-content.json\");\n elem.click();\n }\n if (downloadJson) {\n donwloadJSON(); // export js routes to use as json, uncomment to use\n }\n var components = userRoutes(routes);\n RouteComponent.init(components)\n };\n document.getElementsByTagName('head')[0].appendChild(script);\n}",
"function getRoutes() {\n $.get('/api/subsegments', renderRouteList);\n }",
"function route(){\n\tlog(\"Info: route: start\");\n\tvar qs=getEnv()['QUERY_STRING'];\n\tvar filepath=getQueryVariable(qs,\"path\");\n\tfilepath=filepath==null?\"../res/html/index.html\":filepath;\n\trenderfile(filepath)\n\tlog(\"Info: route: end\");\n}",
"async registerEndpoints () {\n const routes = await this.getViewConstants()\n\n // Order parameterized url's so they can't replace already defined routes.\n // e.g. /something/:param/:param must not be routed before /something/whatever/:param\n routes.sort((a, b) => {\n const aCount = a.path.split(':').length\n const bCount = b.path.split(':').length\n return aCount - bCount\n })\n\n const writeFile = promisify(fs.writeFile)\n let routeOutput = `/**\n * Auto-generated routes from cubic view node. We can't\n * get them at runtime, so we need to save them like a config\n * file pre-build.\n */\n export default ${JSON.stringify(routes, null, 2)}\n `\n\n // Lazy cleanup for stringified functions\n /* eslint no-useless-escape: \"off\" */\n routeOutput = routeOutput.replace(/\"\\(\\) \\=\\>/g, '() =>').replace(/`\\)\"/g, '`)')\n\n // Save to file\n await writeFile(path.join(__dirname, '../vue/router/routes.js'), routeOutput)\n }",
"function code() {\n server.route({\n method: 'GET',\n path: '/foobar',\n handler(request, reply) {\n reply({foo: 'bar'});\n },\n config: {\n description: 'foobar sample route',\n tags: ['api']\n }\n });\n}",
"onRoutes(routes) {}",
"function generateCode(){\n\n}",
"function _pipeRoutesJsIntoRoutes(pluginOptions) {\n\n if (!pluginOptions.routes || pluginOptions.routes.length == 0) {\n return;\n }\n\n let controllerName;\n let controllerAction;\n let relatedController;\n let relatedAction;\n\n pluginOptions.routes.forEach((route) => {\n\n if (pluginOptions.hapiRoutes[route.path] && pluginOptions.hapiRoutes[route.path][\"method\"] === route.method) {\n throw new Error(`URL path ( ${route.path}|${pluginOptions.hapiRoutes[route.path][\"method\"]} defined more than one in routes.js`);\n }\n\n const config = route.config;\n if ((typeof config == \"string\" || config instanceof String) && config.indexOf(\"@\") > 0) {\n // config just contain handler.\n controllerName = config.split(\"@\")[0].trim();\n controllerAction = config.split(\"@\")[1].trim();\n\n relatedController = pluginOptions.controllers[controllerName];\n if (!relatedController) {\n throw new Error(\"Controller : ( \" + controllerName + \".js ) not found\");\n }\n\n relatedAction = relatedController[controllerAction];\n //// Plug & Play with /\n if (typeof relatedAction == \"function\") {\n relatedAction = {\n handler: relatedController[controllerAction]\n };\n }\n if (!relatedAction) {\n throw new Error(\"Controller action -> \" + controllerAction + \" : ( \" + controllerAction + \"@\" + controllerName + \" ) defined in routes.js not found in \" + controllerName);\n }\n\n // Controller and Action found added!\n pluginOptions.hapiRoutes[route.path + \"@\" + route.method] = {\n method: route.method,\n path: route.path || \"GET\",\n config: relatedAction\n };\n }\n else { // default blueprint if not contain `@`\n\n controllerName = config.trim();\n relatedController = pluginOptions.controllers[controllerName];\n\n if (!relatedController) {\n throw new Error(\"Controller : ( \" + controllerName + \".js ) not found defined in routes.js\");\n }\n\n Object.keys(BlueprintRoutes).forEach((blueprintRoute) => {\n\n const idParameter = controllerName.substr(0, controllerName.indexOf(\"_controller\")).toLocaleLowerCase();\n\n const path = route.path + BlueprintRoutes[blueprintRoute].path.replace(\"{id}\", \"{\" + idParameter + \"id}\");\n\n const method = BlueprintRoutes[blueprintRoute].method;\n\n if (route.except && route.except.indexOf(blueprintRoute) >= 0) {\n ;//do nothing\n }\n else if (!relatedController[blueprintRoute] && ((blueprintRoute === \"sorting\") || (blueprintRoute === \"sorted\") || (blueprintRoute === \"delete-info\") || (blueprintRoute === \"update-info\"))) {\n ;//do nothing\n }\n else if (!relatedController[blueprintRoute]) {\n console.log(\"Controller : ( \" + controllerName + \".js ) defined as a blueprint in routes.js but \" + blueprintRoute + \" not found in controller file\");\n }\n else {\n //// Plug & Play with /\n if (typeof relatedController[blueprintRoute] == \"function\") {\n relatedController[blueprintRoute] = {\n handler: relatedController[blueprintRoute]\n };\n }\n\n if (!relatedController[blueprintRoute].payload && Payload(blueprintRoute)) {\n relatedController[blueprintRoute].payload = Payload(blueprintRoute);\n }\n\n if (!relatedController[blueprintRoute].payload && Payload(blueprintRoute)) {\n relatedController[blueprintRoute].payload = Payload(blueprintRoute);\n }\n\n // Controller and Action found added!\n pluginOptions.hapiRoutes[path + \"@\" + method] = {\n method: method,\n path: path,\n config: relatedController[blueprintRoute]\n };\n }\n });\n }\n });\n}",
"routesCompile() {\n this.routeTree = {};\n var rSplit,\n part;\n for (var i = 0; i < this.numOfRoutes; i++) {\n rSplit = this.routesKeys[i].split('/');\n rSplit.splice(0, 1);\n this.mSetNode(this.routeTree, rSplit[0], rSplit, 0, this.dicRoutes[this.routesKeys[i]])\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
show or hide the dialogue name plates based on the current speaker indicated by the current text node | function UpdateNamePlates(speaker) {
switch (speaker) {
case "player":
namePlateLeftElement.style.visibility = "Visible";
namePlateRightElement.style.visibility = "Hidden";
break;
default:
// right name plate text also changes based on the speaker
if (speaker) {
namePlateRightElement.innerHTML = speaker
namePlateLeftElement.style.visibility = "Hidden";
namePlateRightElement.style.visibility = "Visible";
} else {
namePlateLeftElement.style.visibility = "Hidden";
namePlateRightElement.style.visibility = "Hidden";
};
};
} | [
"checkSpeaker() {\r\n this.leftNameText.alpha = 0.5;\r\n this.leftPortraitImage.alpha = 0.5;\r\n this.rightNameText.alpha = 0.5;\r\n this.rightPortraitImage.alpha = 0.5;\r\n if (this.currentChat.left) {\r\n if (this.currentChat.leftName) {\r\n this.leftNameText.visible = true;\r\n this.leftNameText.setText(` ${this.currentChat.leftName}: `);\r\n } else {\r\n this.leftNameText.visible = false;\r\n }\r\n if (this.currentChat.leftPortraitName) {\r\n this.leftPortraitImage.visible = true;\r\n this.leftPortraitImage.setTexture(this.currentChat.leftPortraitName);\r\n } else {\r\n this.leftPortraitImage.visible = false;\r\n }\r\n this.leftNameText.alpha = 1;\r\n this.leftPortraitImage.alpha = 1;\r\n }\r\n if (this.currentChat.right) {\r\n this.rightNameText.setText(` ${this.currentChat.rightName}: `);\r\n this.rightPortraitImage.setTexture(this.currentChat.rightPortraitName);\r\n this.rightNameText.visible = true;\r\n this.rightPortraitImage.visible = true;\r\n this.rightNameText.alpha = 1;\r\n this.rightPortraitImage.alpha = 1;\r\n }\r\n if (this.currentChat.leftExit) this.exitFromScene('left');\r\n if (this.currentChat.rightExit) this.exitFromScene('right');\r\n }",
"function tied(){\n $('.winningText').hide();\n $('.losingText').hide();\n $(\".tiedText\").show();\n $('.computerChoiceTextContainer').show();\n}",
"function displayPresentsText(phase){\n\n if(phase == 1){\n centerText(presentsText);\n presentsText.setText(\"RIKKOKIRI\", true);\n }\n if(phase == 2){\n presentsText.setText(\"RIKKOKIRI PRESENTS\", true);\n }\n\n}",
"function speakerName() {\n if (showBody == true) {\n fill(200, 200, 200);\n textFont(nameFont);\n textSize(30);\n text(whoSpeaks, 300, 440);\n\n if (whoSpeaks == \"Bai\") {\n\n image(bodyIcon, 20, 300, 280, 280);\n }\n\n }\n\n}",
"function Show_robot_speech(str, id, mode) {\n $speech_bubbles[id] = robot_speech_bubble(str);\n $speech_bubbles[id].slideDown();\n $speech_bubbles[id].attr(\"style\", \"display: block\");\n console.log(\"open bubble\" + id);\n }",
"function Show_robot_speech(str, id, mode) {\n $speech_bubbles[id] = robot_speech_bubble(str);\n $speech_bubbles[id].slideDown();\n $speech_bubbles[id].attr(\"style\", \"display: block\");\n console.log(\"open bubble\" + id);\n}",
"displayPortrait() {\n this.setSpeakerImage();\n if (currentSpeaker == this.name) {\n this.portrait.setVisible(true);\n fyvePortrait.setVisible(false);\n } else if (currentSpeaker == \"fyve\"){\n this.portrait.setVisible(false)\n fyvePortrait.setVisible(true);\n }\n }",
"function goodbyeSpeakerSequence() {\n $(\"#left-summed-image\").hide();\n $(\"#right-summed-image\").hide();\n $(\"#left-inboard-speaker\").hide();\n $(\"#left-outboard-speaker\").hide();\n $(\"#right-inboard-speaker\").hide();\n $(\"#right-outboard-speaker\").hide();\n $(\"#legend-speaker\").hide();\n}",
"displaySpeaker() {\n //will process if child class has set speaker to true\n if (this.scene.speaker) {\n // will process if fade in dialog has been toggled in child class\n if (this.scene.fadeIn) {\n //will process if the y position of textBox is not as high as its landing position (smaller or equal to)\n if (this.dialogBox.textBox.position.y <= this.dialogBox.textBox.landingPosition.y) {}\n //position changes until landing position is obtained;\n if (this.dialogBox.speaker.position.x > this.dialogBox.speaker.landingPosition.x) {\n this.dialogBox.speaker.position.x += this.dialogBox.speaker.slideInSpeed\n }\n }\n //If fadeIn is not toggled and that dialogBox isn't fading out (closing), make the speaker position the same as landing Position.\n else if (!this.scene.fadeIn && !this.dialogBox.closing) {\n this.dialogBox.speaker.position.x = this.dialogBox.speaker.landingPosition.x;\n this.dialogBox.speaker.position.y = this.dialogBox.speaker.landingPosition.y;\n }\n\n //If fadeOut was toggled in child class, and that dialog Box should be closing (true), make the speaker img go right\n if (this.scene.fadeOut && this.dialogBox.closing) {\n this.dialogBox.speaker.position.x += this.dialogBox.speaker.slideOutSpeed;\n }\n\n //===Brokenness filters ===\n //Define, if game is brokenness, the values of filter (flickering of images) applied\n\n if (this.brokenness.lvl1.on) //Only process if brokenness lvl 1 is true (if microaggression 1 was played);\n {\n //set employee filter's values to the corresponding level of brokenness' values;\n this.brokenness.employeeFilter.triggerThreshold = this.brokenness.lvl1.employeeFilter.triggerThreshold;\n this.brokenness.employeeFilter.timeApplied = this.brokenness.lvl1.employeeFilter.timeApplied;\n this.brokenness.employeeFilter.filterChangeInterval = this.brokenness.lvl1.employeeFilter.filterChangeInterval;\n }\n if (this.brokenness.lvl2.on) //overwrite lvl1 brokenness value if brokenness lvl2 is true;\n {\n this.brokenness.employeeFilter.triggerThreshold = this.brokenness.lvl2.employeeFilter.triggerThreshold;\n this.brokenness.employeeFilter.timeApplied = this.brokenness.lvl2.employeeFilter.timeApplied;\n this.brokenness.employeeFilter.filterChangeInterval = this.brokenness.lvl2.employeeFilter.filterChangeInterval\n }\n if (this.brokenness.lvl3.on) //overwrite lvl2 brokenness value if brokenness lvl3 is true;\n {\n this.brokenness.employeeFilter.triggerThreshold = this.brokenness.lvl3.employeeFilter.triggerThreshold;\n this.brokenness.employeeFilter.timeApplied = this.brokenness.lvl3.employeeFilter.timeApplied;\n this.brokenness.employeeFilter.filterChangeInterval = this.brokenness.lvl3.employeeFilter.filterChangeInterval\n }\n if (this.brokenness.lvl4.on) //overwrite lvl3 brokenness value if brokenness lvl2 is true;\n {\n this.brokenness.employeeFilter.triggerThreshold = this.brokenness.lvl4.employeeFilter.triggerThreshold;\n this.brokenness.employeeFilter.timeApplied = this.brokenness.lvl4.employeeFilter.timeApplied;\n this.brokenness.employeeFilter.filterChangeInterval = this.brokenness.lvl4.employeeFilter.filterChangeInterval;\n }\n\n if (this.brokenness.lvl5.on) //overwrite lvl4 brokenness value if brokenness lvl2 is true;\n {\n this.brokenness.employeeFilter.triggerThreshold = this.brokenness.lvl5.employeeFilter.triggerThreshold;\n this.brokenness.employeeFilter.timeApplied = this.brokenness.lvl5.employeeFilter.timeApplied;\n this.brokenness.employeeFilter.filterChangeInterval = this.brokenness.lvl5.employeeFilter.filterChangeInterval\n }\n\n let changeEmployeeFilter = random(); // let changeEmployeeFilter be a random number between 0 and 1\n if (changeEmployeeFilter < this.brokenness.employeeFilter.triggerThreshold) { //Process only if the random changeFilter is smaller than the established threshold\n if (!this.brokenness.employeeFilter.on) {\n this.brokenness.employeeFilter.on = true //turn filter on and setTimeout to turn it off in timeApplied amount of milliseconds\n setTimeout(() => {\n this.brokenness.employeeFilter.on = false\n }, this.brokenness.employeeFilter.timeApplied)\n }\n }\n\n if (this.brokenness.employeeFilter.on) //only process if employee Filter is true (if it has been toggled by the above if statement)\n {\n //Every filterChangeInterval amount of seconds, change the speaker image for a random filter of those available in the array (original image, neon, inverted)\n setTimeout(() => {\n this.dialogBox.speaker.img = random(this.employeeImgFilters)\n }, this.brokenness.employeeFilter.filterChangeInterval)\n }\n //else, reset the speaker image to its default image\n else {\n this.dialogBox.speaker.img = employeeImg\n }\n\n // display the speaker img in the position defined above (with fade in or not);\n push();\n imageMode(this.dialogBox.speaker.imageMode);\n image(\n this.dialogBox.speaker.img,\n this.dialogBox.speaker.position.x,\n this.dialogBox.speaker.position.y,\n this.dialogBox.speaker.size.width,\n this.dialogBox.speaker.size.height\n );\n pop();\n }\n }",
"function skills() {\n document.getElementById(\"aboutMeText\").style.display = \"none\"\n document.getElementById(\"aboutMeSkills\").style.display = \"block\"\n\n}",
"function showWordMeaning() {\n toggleElementVisibility(\"word-area-game-over\");\n toggleElementVisibility(\"word-area-in-play\");\n}",
"setDisplayText(char) {\n document.getElementById('display').innerHTML = SOUND_NAMES[char]\n }",
"function setupSpeechBubble(){\n\tdocument.getElementById(\"speechbubble\").style.visibility = \"visible\";\n\n}",
"function showTextScene(textNodeIndex) {\n // NODE INDEX = STRING; STRING = CORRESPONDING SCENE OBJECT ID; TEXT SCENE = CHOSEN SCENE FROM ARRAY\n const textScene = textScenes.find(\n (textScene) => textScene.id === textNodeIndex\n );\n textElement.innerText = textScene.text;\n showSceneSlide(textScene);\n // REMOVES HTML DOM OPTION BUTTONS\n \n \n while (optionButtonElement.firstChild) {\n optionButtonElement.removeChild(optionButtonElement.firstChild);\n }\n\n\n // @@ Creating button from TextScene.options.text\n //this builds on the showOption function \n textScene.options.forEach((option) => {\n if (showOption(option)) {\n const button = document.createElement(\"button\");\n button.innerText = option.text;\n button.classList.add(\"btn\");\n button.addEventListener(\"click\", () => selectOption(option));\n optionButtonElement.appendChild(button);\n }\n });\n}",
"function reveal_text() {\n reveal_by_class(\"hidden-text\", \"block\");\n}",
"function ChangeAdventureText(inputString) {\n if (inputString) {\n // setting the allCharactersRevealed boolean to false to indicate that there is text to reveal with the typewriter effect only if there is valid input string\n allCharactersRevealed = false;\n } else {\n return console.log(`Warning, there is no text for node ${currentTextNode.nodeId}!`);\n }\n // remove any old text span elements inside the adventure text container\n while (adventureTextContainerElement.firstChild) {\n adventureTextContainerElement.removeChild(adventureTextContainerElement.firstChild);\n };\n // show the skip button when the text is changed and hide any dialogue choices so that they cannot be selected before all the text is revealed\n skipButtonElement.style.visibility = \"Visible\";\n dialogueChoicesElement.style.visibility = \"Hidden\";\n // iterate through each word of the input string to include the entered player name if that word is _playerName\n let words = inputString.split(\" \");\n for (let i = 0; i < words.length; i++) {\n if (words[i] === \"_playerName\") {\n words[i] = _playerName;\n };\n };\n // the revivedString is the full input string now containing the player name instead of _playerName \n let revivedString = words.join(\" \");\n // set the array of span elements back to empty before adding the new hidden ones\n characterSpans = [];\n revivedString.split(\"\").forEach((character) => {\n let newSpan = document.createElement(\"span\");\n newSpan.innerHTML = character;\n newSpan.classList.add(\"hidden\");\n // change the text color based on the speaker to make it clear who is speaking at any time\n switch (currentTextNode.speaker) {\n case \"player\":\n newSpan.style.color = \"blue\";\n break;\n default:\n // if no speaker is set the color will be black\n if (currentTextNode.speaker) {\n newSpan.style.color = \"orange\";\n };\n break;\n };\n // add the newly created span element to the text container and the characterSpans array for use when revealing them with the RevealSpanCharacters function\n adventureTextContainerElement.appendChild(newSpan);\n characterSpans.push(newSpan);\n });\n}",
"function personal() {\n document.getElementById(\"aboutMeSkills\").style.display = \"none\"\n document.getElementById(\"aboutMeText\").style.display = \"block\"\n}",
"displayDialogText() {\n //If the box is not on its landing position, don't show the text\n if (this.dialogBox.textBox.position.y <= this.dialogBox.textBox.landingPosition.y) {\n this.dialogBox.textBox.fullTextDisplayed = true //Defines to true so buttons can appear (made that way to add a typewriter effect in the future)\n //display text\n push();\n textAlign(LEFT);\n textFont(this.dialogBox.textBox.font);\n textSize(this.dialogBox.textBox.textSize)\n fill(this.dialogBox.textBox.textFill.r, this.dialogBox.textBox.textFill.g, this.dialogBox.textBox.textFill.b);\n text(this.dialogBox.textBox.string, this.dialogBox.textBox.textPosition.x, this.dialogBox.textBox.textPosition.y, this.dialogBox.textBox.textPosition.x2, this.dialogBox.textBox.textPosition.y2);\n pop();\n }\n }",
"function displayTarget(){\n findTarget();\n if(isPlaying===true){\n $('#target-letter').text(\"'\" + targetLet + \"'\");\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Watch the value, mdbuffervalue, and mdmode attributes | function watchAttributes() {
attr.$observe('value', function(value) {
var percentValue = clamp(value);
element.attr('aria-valuenow', percentValue);
if (mode() != MODE_QUERY) animateIndicator(bar2, percentValue);
});
attr.$observe('mdBufferValue', function(value) {
animateIndicator(bar1, clamp(value));
});
attr.$observe('mdMode',function(mode){
if (lastMode) container.removeClass( lastMode );
switch( mode ) {
case MODE_QUERY:
case MODE_BUFFER:
case MODE_DETERMINATE:
case MODE_INDETERMINATE:
container.addClass( lastMode = "_md-mode-" + mode );
break;
default:
container.addClass( lastMode = "_md-mode-" + MODE_INDETERMINATE );
break;
}
});
} | [
"function watchAttributes() {\n attr.$observe('value', function(value) {\n var percentValue = clamp(value);\n element.attr('aria-valuenow', percentValue);\n\n if (mode() != MODE_QUERY) animateIndicator(bar2, percentValue);\n });\n\n attr.$observe('mdBufferValue', function(value) {\n animateIndicator(bar1, clamp(value));\n });\n\n attr.$observe('mdMode', function(mode) {\n switch (mode) {\n case MODE_QUERY:\n case MODE_BUFFER:\n case MODE_DETERMINATE:\n case MODE_INDETERMINATE:\n container.removeClass('ng-hide' + ' ' + lastMode);\n container.addClass(lastMode = \"md-mode-\" + mode);\n break;\n default:\n if (lastMode) container.removeClass(lastMode);\n container.addClass('ng-hide');\n lastMode = undefined;\n break;\n }\n });\n }",
"function watchAttributes() {\n attr.$observe('value', function(value) {\n var percentValue = clamp(value);\n element.attr('aria-valuenow', percentValue);\n\n if (mode() != MODE_QUERY) animateIndicator(bar2, percentValue);\n });\n\n attr.$observe('mdBufferValue', function(value) {\n animateIndicator(bar1, clamp(value));\n });\n\n attr.$observe('mdMode',function(mode){\n switch( mode ) {\n case MODE_QUERY:\n case MODE_BUFFER:\n case MODE_DETERMINATE:\n case MODE_INDETERMINATE:\n container.removeClass( 'ng-hide' + ' ' + lastMode );\n container.addClass( lastMode = \"md-mode-\" + mode );\n break;\n default:\n if (lastMode) container.removeClass( lastMode );\n container.addClass('ng-hide');\n lastMode = undefined;\n break;\n }\n });\n }",
"function watchAttributes() {\n attr.$observe('value', function(value) {\n var percentValue = clamp(value);\n element.attr('aria-valuenow', percentValue);\n\n if (mode() != MODE_QUERY) animateIndicator(bar2, percentValue);\n });\n\n attr.$observe('mdBufferValue', function(value) {\n animateIndicator(bar1, clamp(value));\n });\n\n attr.$observe('disabled', function(value) {\n if (value === true || value === false) {\n isDisabled = !!value;\n } else {\n isDisabled = angular.isDefined(value);\n }\n\n element.toggleClass(DISABLED_CLASS, isDisabled);\n container.toggleClass(lastMode, !isDisabled);\n });\n\n attr.$observe('mdMode', function(mode) {\n if (lastMode) container.removeClass(lastMode);\n\n switch (mode) {\n case MODE_QUERY:\n case MODE_BUFFER:\n case MODE_DETERMINATE:\n case MODE_INDETERMINATE:\n container.addClass(lastMode = \"md-mode-\" + mode);\n break;\n default:\n container.addClass(lastMode = \"md-mode-\" + MODE_INDETERMINATE);\n break;\n }\n });\n }",
"function watchAttributes() {\n attr.$observe('value', function(value) {\n var percentValue = clamp(value);\n element.attr('aria-valuenow', percentValue);\n\n if (mode() != MODE_QUERY) animateIndicator(bar2, percentValue);\n });\n\n attr.$observe('mdBufferValue', function(value) {\n animateIndicator(bar1, clamp(value));\n });\n\n attr.$observe('disabled', function(value) {\n if (value === true || value === false) {\n isDisabled = !!value;\n } else {\n isDisabled = angular.isDefined(value);\n }\n\n element.toggleClass(DISABLED_CLASS, isDisabled);\n container.toggleClass(lastMode, !isDisabled);\n });\n\n attr.$observe('mdMode', function(mode) {\n if (lastMode) container.removeClass( lastMode );\n\n switch( mode ) {\n case MODE_QUERY:\n case MODE_BUFFER:\n case MODE_DETERMINATE:\n case MODE_INDETERMINATE:\n container.addClass( lastMode = \"md-mode-\" + mode );\n break;\n default:\n container.addClass( lastMode = \"md-mode-\" + MODE_INDETERMINATE );\n break;\n }\n });\n }",
"function startWatchingForValueChange(target,targetInst){activeElement=target;activeElementInst=targetInst;activeElement.attachEvent('onpropertychange',handlePropertyChange);}",
"function initWatchVal() {} // 16439",
"set BufDirty(value) { this.native.BufDirty = value; }",
"function initWatchVal() {}",
"_addWatcher() {\n // `getterSetter` can be undefined when a non-input element is used\n if (!AutoNumericHelper.isUndefined(this.getterSetter)) {\n const { set: setter, get: getter } = this.getterSetter;\n Object.defineProperty(this.domElement, this.attributeToWatch, {\n configurable: true, // This is needed in some rare cases\n get : () => getter.call(this.domElement),\n set : val => {\n setter.call(this.domElement, val);\n // Only `set()` the value if the modification comes from an external source\n if (this.settings.watchExternalChanges && !this.internalModification) {\n this.set(val);\n }\n },\n });\n }\n\n //FIXME The code above fails for the `textContent` attribute since `this.getterSetter` is undefined when using `getOwnPropertyDescriptor()`\n /* //XXX The code below *almost* work for the textContent, but breaks some unit tests\n this.valueWatched = this.domElement[this.attributeToWatch];\n Object.defineProperty(this.domElement, this.attributeToWatch, {\n configurable: true, // This is needed in some rare cases\n get : () => this.valueWatched,\n set : val => {\n this.valueWatched = val;\n // Only `set()` the value if the modification comes from an external source\n if (this.settings.watchExternalChanges && !this.internalModification) {\n this.set(val);\n }\n },\n });\n */\n }",
"function watchAttributes() {\n\n // instance has no update method? => set default update method\n if ( !instance.update ) instance.update = ( key, value ) => {\n switch ( key ) {\n case 'ccm':\n case 'component':\n case 'config':\n case 'element':\n case 'id':\n case 'index':\n case 'init':\n case 'onfinish':\n case 'parent':\n case 'ready':\n case 'root':\n case 'start':\n case 'update':\n break;\n case 'key':\n if ( ccm.helper.regex( 'json' ).test( value ) ) value = ccm.helper.parse( value );\n if ( ccm.helper.isObject( value ) )\n for ( const key in value )\n if ( value.hasOwnProperty( key ) )\n switch ( key ) {\n case 'ccm':\n case 'component':\n case 'dependency':\n case 'parent':\n case 'id':\n case 'index':\n case 'element':\n case 'root':\n case 'init':\n case 'ready':\n case 'start':\n case 'update':\n case 'key':\n break;\n default:\n instance[ key ] = value[ key ]\n }\n instance.start();\n break;\n default:\n instance[ key ] = value;\n instance.start();\n }\n };\n\n // watch attributes\n const MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;\n const observer = new MutationObserver( mutations =>\n mutations.forEach( mutation => {\n if ( mutation.type !== 'attributes' ) return;\n const key = mutation.attributeName;\n const value = instance.root.parentNode.getAttribute( key );\n instance.update( key, value );\n } )\n );\n observer.observe( instance.root.parentNode, { attributes: true } );\n\n }",
"function watchAttr(attrs, selector, type, getValue) {\n var element = $(selector).get(0);\n if (element) {\n if (getValue == undefined) {\n getValue = function(el, attr) {return el.getAttribute(attr)};\n }\n var observer = new MutationObserver(function (mutations) {\n mutations.forEach(function(mutation) {\n post(type, getValue(mutation.target, mutation.attributeName));\n });\n });\n observers.push(observer);\n observer.observe(element, { attributes: true, attributeFilter: attrs.split(\" \") });\n post(type, getValue(element, attrs));//trigger once to initialize the info\n } else {\n console.error(\"element does not exist (did Google change their site?): \" + selector);\n }\n }",
"function watchAttr(attrs, selector, type, getValue) {\n var element = $(selector).get(0);\n if (element) {\n if (getValue === undefined) {\n getValue = function(el, attr) { return el.getAttribute(attr); };\n }\n var observer = new MutationObserver(function (mutations) {\n mutations.forEach(function(mutation) { post(type, getValue(mutation.target, mutation.attributeName)); });\n });\n observers.push(observer);\n observer.observe(element, { attributes: true, attributeFilter: attrs.split(\" \") });\n post(type, getValue(element, attrs));//trigger once to initialize the info\n } else {\n console.error(\"element does not exist (did Google change their site?): \" + selector);\n }\n }",
"function watchMedia() { // 5503\n for (var mediaName in $mdConstant.MEDIA) { // 5504\n $mdMedia(mediaName); // initialize // 5505\n $mdMedia.getQuery($mdConstant.MEDIA[mediaName]) // 5506\n .addListener(invalidateLayout); // 5507\n } // 5508\n return $mdMedia.watchResponsiveAttributes( // 5509\n ['md-cols', 'md-row-height'], attrs, layoutIfMediaMatch); // 5510\n } // 5511",
"evaluate() {\n console.log('evaluate方法:计算watcher的值,修改dirty为false表示计算过');\n this.value = this.get()\n this.dirty = false //表示取过值了\n }",
"watchChanges() {\n\t\tthis.element.addEventListener('input', debounce(() => {\n\t\t\tconst formData = this.getFormData();\n\t\t\tconst updatedCardData = this.formatFormData(formData);\n\t\t\tthis.saveCardData(updatedCardData);\n\t\t}, 500));\n\t}",
"function watchMedia() {\n for (var mediaName in $mdConstant.MEDIA) {\n $mdMedia(mediaName); // initialize\n $mdMedia.getQuery($mdConstant.MEDIA[mediaName])\n .addListener(invalidateLayout);\n }\n return $mdMedia.watchResponsiveAttributes(\n ['md-cols', 'md-row-height', 'md-gutter'], attrs, layoutIfMediaMatch);\n }",
"setFdstat(byteOffset, value, littleEndian = false) {\n /*\n * typedef struct __wasi_fdstat_t {\n * __wasi_filetype_t fs_filetype; u8\n * <pad> u8\n * __wasi_fdflags_t fs_flags; u16\n * <pad> u32\n * __wasi_rights_t fs_rights_base; u64\n * __wasi_rights_t fs_rights_inheriting; u64\n * } __wasi_fdstat_t;\n */\n this.setUint8(byteOffset, value.filetype, littleEndian);\n this.setUint16(byteOffset + 2, 0, littleEndian);\n this.setBigUint64(byteOffset + 8, value.rights_base, littleEndian);\n this.setBigUint64(byteOffset + 16, value.rights_inheriting, littleEndian);\n }",
"observe(metric, value, attributes = {}) {\n if (!isObservableInstrument(metric)) {\n return;\n }\n let map = this._buffer.get(metric);\n if (map == null) {\n map = new AttributeHashMap();\n this._buffer.set(metric, map);\n }\n if (metric._descriptor.valueType === metrics.ValueType.INT && !Number.isInteger(value)) {\n api.diag.warn(`INT value type cannot accept a floating-point value for ${metric._descriptor.name}, ignoring the fractional digits.`);\n value = Math.trunc(value);\n }\n map.set(attributes, value);\n }",
"attributeChangedCallback(attr, oldVal, newVal) {\n console.log('inside attributeChangedCallback', 'attr:', attr, 'oldVal:', oldVal, 'newVal:', newVal);\n if (attr === 'value') {\n this.value = newVal;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
concat links into one string with carrier returns | function concatLinks(links) {
var str=""; // string of links
for (var i=0; i<links.length; i++) {
if (i==0) {
str=links[i];
}
else {
str += '\n' + links[i];
}
}
return str;
} | [
"formatUrls(){\n urls = this._urls.map( (u) => { return 'url=' + \"'\" + u + \"'\"; });\n urls = urls.join(' or ');\n return urls;\n }",
"formatUris() {\n const { unescape } = Nullthrows(this.props.uriService);\n const uris = this.getUris().map(unescape);\n\n return uris.length > 1 ? \"\\n\" + uris.join(\"\\n\") + \"\\n\" : uris[0] + \" \";\n }",
"_build_link(){\n\n\t\tconst link_data = [\n\t\t\tthis.opts.link_version,\n\t\t\tthis.opts.link_random_data,\n\t\t\tbtoa(this.names.flat().join(\"/\") + \"|\" + this.mapping.join(\"/\"))\n\t\t].join(\".\")\n\n\t\treturn `${this.opts.link_root}${link_data}`\n\t}",
"function buildLink(link){\r\n\treturn $(\"#base_link\").val()+link;\r\n}",
"function buildlinks(props, separator) {\n var links = [];\n // start link\n links.push('<a href=\"https://www.google.com/maps/search/?api=1&query=' + encodeURIComponent(props.start) + '\" target=_blank>start</a>');\n \n // map link\n // display our own map?\n if (props.fileid) {\n var thislink = '<a href=\"' + rrrouteurl + '/' + props.id + '\" target=_blank>route</a>';\n links.push(thislink);\n // display configured url?\n } else if (props.map) {\n links.push('<a href=\"' + props.map + '\" target=_blank>route</a>');\n }\n\n // turns link\n if (props.fileid) {\n // rrturnsurl is defined in in wp-content/themes/steeps/js/runningroutes directory locally \n // configured runningroutes-config.js\n var thislink = '<a href=\"' + rrturnsurl + '/' + props.id + '\" target=_blank>turns</a>';\n links.push(thislink);\n }\n\n // join these all together\n return links.join(separator);\n}",
"generateLink() {\n return `\n <a href='https://en.wikipedia.org/wiki/${encodeURI(this.options[0])}' property='rdf:seeAlso'>\n ${this.options[0]}\n </a> \n `;\n }",
"function delicious2text(links, linkFormat, linkSeparator){\n var linkTexts = [];\n links.forEach(function(link){\n var linkText = linkFormat.replace(/%([\\w]+)/g, function(match, linkAttribute){\n return link[linkAttribute];\n });\n linkTexts.push(linkText);\n });\n return linkTexts.join(linkSeparator);\n}",
"function getLinkStringFromArray(linkArray)\n{\n var abilityLink = \"\";\n if (linkArray.length > 0)\n {\n \n for (var i = 0; i < linkArray.length; i++)\n {\n abilityLink = abilityLink + \"\\n\"+gGMTell + linkArray[i]; \n }\n }\n return abilityLink;\n}",
"getLinkedHTMLName() {\n if (this.hasEmbeddedHyperlinks()) {\n const taskName = this.getName()\n const orderedLinks = this.links.sort((a,b)=>{return a.compare(b)})\n let linkedName = \"<span>\"\n let currLen = 0\n for (let i = 0; i < this.links.length; i++) {\n curr = this.links[i]\n if (curr.isIndexed()) {\n if (curr.start > currLen) {\n linkedName += taskName.substring(currLen, curr.start)\n linkedName += '<a href=\"' + curr.url + '\">'\n linkedName += taskName.substring(curr.start, curr.end)\n linkedName += '</a>'\n currLen = curr.start\n } // if need to \"fill in\" from last link (also checks for overlap)\n } // if the link has indexes into the name\n } // for each link\n\n // add anything not linked from the name to the end and close out\n linkedName += taskName.substring(currLen)\n linkedName += \"</span>\"\n return linkedName\n }\n else {\n return null\n }\n }",
"function shortenUrls(str) {\r\n\treturn Autolinker.link(str, {\r\n\t\ttruncate: {length: 30},\r\n\t replaceFn : function( autolinker, match ) {\r\n\t switch( match.getType() ) {\r\n\t case 'url' :\r\n\t var tag = autolinker.getTagBuilder().build( match ); \r\n\t \t\treturn tag.innerHtml;\r\n\t }\r\n\t\t}\r\n\t});\r\n}",
"function linkify(str) {\r\n \tvar response = '';\r\n\t\tfor (var i=0;i<str.length;i++) {\r\n\t\t\tif (str.substring(i,i+7) == \"http://\" || str.substring(i,i+8) == \"https://\") {\r\n\t\t\t\tvar prefix = str.charAt(i-1);\r\n\t\t\t\tif (prefix === ';' && str.substring(i-4,i) === '<') { prefix = '<' } // special case for < \r\n\t\t\t\tvar ei = findURLendIndex(str, i+7, prefix);\r\n\t\t\t\tif (ei !== -1) {\r\n\t\t\t\t\tvar link = str.substring(i,ei);\r\n\t\t\t\t\tif (link.length > 10 &&\r\n\t\t\t\t\t\tlink.indexOf('\\n')===-1 && \r\n\t\t\t\t\t\tlink.indexOf(' ')===-1) {\r\n\t\t\t\t\t\tresponse+='<a href=\"'+link+'\">'+link+'</a>';\r\n\t\t\t\t\t\ti = ei-1; \r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t} \r\n\t\t\tresponse+=str.charAt(i);\r\n\t\t}\r\n\t\treturn response; \r\n\t}",
"function _links_add_base($m) {\n global $_links_add_base;\n //1 = attribute name 2 = quotation mark 3 = URL\n return $m[1] . '=' . $m[2] .\n ( preg_match( '#^(\\w{1,20}):#', $m[3], $protocol ) && in_array( $protocol[1], wp_allowed_protocols() ) ?\n $m[3] :\n path_join( $_links_add_base, $m[3] ) )\n . $m[2];\n }",
"function write_link(s,n_up,app_str)\r\n {\r\n var str01 = chop_first(s);\r\n var str02 = n_dir_up(str01,n_up);\r\n var link_str = str02 + app_str;\r\n return link_str;\r\n }",
"function render_url(text) {\n if (text.includes(\"http\")) {\n return \"<a href=\\\"\" + text + \"\\\" target=\\\"_blank\\\">Buy Here</a>\";\n } else {\n return text;\n }\n }",
"function links(container) {\n return (container.links || []).map(function(link){\n return {\n 'Fn::Join': [\n ' ',\n [\n '--link',\n {'Fn::Join': [':', [link, link]]}\n ]\n ]\n };\n });\n}",
"function formatLink(link, affiliateName) {\n return `<p><h3 style=\"white-space: pre-wrap;\"><strong>Buy now:</strong></h3></p><h3 style=\"white-space: pre-wrap;\"><a href=\"${link}\" target=\"_blank\">${affiliateName}</a></h3>`;\n}",
"obsidianLink() {\r\n var _a, _b;\r\n const escaped = this.path.replace(\"|\", \"\\\\|\");\r\n if (this.type == \"header\")\r\n return escaped + \"#\" + ((_a = this.subpath) === null || _a === void 0 ? void 0 : _a.replace(\"|\", \"\\\\|\"));\r\n if (this.type == \"block\")\r\n return escaped + \"#^\" + ((_b = this.subpath) === null || _b === void 0 ? void 0 : _b.replace(\"|\", \"\\\\|\"));\r\n else\r\n return escaped;\r\n }",
"function makeLink(s, types) {\n const matchedType = types.filter(aType => aType.name === s);\n const tString = ` \\`${s}\\``;\n if (matchedType.length === 1) {\n return `[${tString}](http://${ReferenceLink})`.replace(\n 'NAME',\n matchedType[0].name,\n );\n } else {\n return tString;\n }\n}",
"buildLink(original, target, caption, monospace) {\n let attributes = \"\";\n if (this.urlPrefix.test(target)) {\n attributes = ' class=\"external\"';\n }\n else {\n let reflection;\n if (this.reflection) {\n reflection = this.reflection.findReflectionByName(target);\n }\n else if (this.project) {\n reflection = this.project.findReflectionByName(target);\n }\n if (reflection && reflection.url) {\n if (this.urlPrefix.test(reflection.url)) {\n target = reflection.url;\n attributes = ' class=\"external\"';\n }\n else {\n target = this.getRelativeUrl(reflection.url);\n }\n }\n else {\n const fullName = (this.reflection ||\n this.project).getFullName();\n this.warnings.push(`In ${fullName}: ${original}`);\n return original;\n }\n }\n if (monospace) {\n caption = \"<code>\" + caption + \"</code>\";\n }\n return Util.format('<a href=\"%s\"%s>%s</a>', target, attributes, caption);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function takes the JSON from the previous function. It then gets out a lattitude or longitude. lat lng | function getLatLng(results){
//Output the results
console.log(results);
//Scroll down the array in the JSON. I ignore everything except the two lat long variables
var location = results["results"][0]["geometry"]["location"],
//Finds the lattitude value
lat = location["lat"],
//Finds the longitude value
lng = location["lng"]
//weatherRequest(lat, lng)
//Output the lat, long into the console for debugging 2
console.log(lat)
console.log(lng)
console.log("lat, lng. Above")
} | [
"function getLatLon(adres,lijst){\n\t$.getJSON(\"https://maps.googleapis.com/maps/api/geocode/json?address=\"+ adres+\"&key=AIzaSyA2hhwsyvOFvwf6YJABI74dDS8ccSyGvf8\", function(data) {\n\t\t$(data).each(function( index_pjct , value_pjct ) {\n\t\t\tif(value_pjct.status!=\"ZERO_RESULTS\"){\n\t\t\t\tcodeAddress(value_pjct.results[0].geometry.location,lijst);\n\t\t\t}\n\t\t});\n\t});\n}",
"function getLatLon(body){\n let lat = body.result.latitude;\n let lon = body.result.longitude;\n let coordinates = [lat, lon];\n return coordinates\n}",
"function pullLatLong (response) {\n lat = response.coord.lat; \n long = response.coord.lon; \n pullCompData (); \n\n }",
"function getLatLong() {\n var zipURL, xmlHttp, data, lat, long;\n zipURL = 'https://us-zipcode.api.smartystreets.com/lookup?auth-id=160203563654804&zipcode=23221';\n xmlHttp = new XMLHttpRequest();\n \n xmlHttp.onreadystatechange = function(callback) {\n if (this.readyState === 4 && this.status === 200) {\n callback(this.responseText);\n }\n }(process);\n xmlHttp.open(\"GET\", zipURL, true);\n xmlHttp.send();\n\n\n\n function process(result) {\n data = JSON.parse(result);\n console.log(data);\n lat = data[0].zipcodes[0].latitude;\n long = data[0].zipcodes[0].longitude;\n }\n\n console.log(\"Lat: \" + lat + \" Long: \" + long);\n}",
"async getLatLong() {\n this.spinner.style.display = 'block';\n const response = await fetch(\n `https://api.openweathermap.org/data/2.5/weather?q=${this.city}&appid=${this.key}`\n );\n\n const responseData = await response.json();\n\n return {\n responseData,\n };\n }",
"function convertGeoJsonCoordinates(coords)\n{\n\treturn new L.LatLng(-coords[1], coords[0], coords[2]);\n}",
"function getlatlng(cioc){\r\n\t\t latlong=[countries[cioc][5][0],countries[cioc][5][1]];\r\n\t\r\n}",
"function getLongLatFromPostcode(postCode, callback)\n{\n var longLatValue = {};\n var postcodesAPI = new postcodesIO();\n postcodesAPI.lookup(postCode, function (error, longLatValue) {\n if(error){\n log(\"getLongLatFromPostcode - postcodesAPI error = \" + error);\n return callback(error);\n }\n\n callback(null, longLatValue);\n });\n}",
"_extractLocation(project){\n\n let coords = project.location.loc.coordinates;\n let lat = coords[1];\n let lng = coords[0];\n\n return { lng, lat};\n\n }",
"function getLatLong(locSuburb, locState, locStateCode, locPC) {\n\n console.log(\"loading Open Cage data\");\n\n // my Open Cage Data API key\n var keyOpenCage = \"135d8af66fb04c9bac0092208a55e2a7\";\n\n // Open Cage Data API call\n var urlGeocode = \"https://api.opencagedata.com/geocode/v1/json?q=\" + locSuburb + \",\" + locState + \",\" + locPC + \"&key=\" + keyOpenCage;\n \n // make request to server using Open Cage API call\n $.getJSON(urlGeocode, function (locationData) {\n\n// console.log(locationData.results[0]);\n\n var locLat = locationData.results[0].bounds.southwest.lat;\n var locLong = locationData.results[0].bounds.southwest.lng;\n var currentLocation = locLat + \",\" + locLong;\n \n // append location to data to html\n $(\"#coords\").html(currentLocation);\n \n // call function to get temperature data from Dark Sky API\n getWeatherData(currentLocation);\n \n // call function to get suburb data from Wikipedia API\n getSuburbData(locSuburb, locState, locPC);\n \n // call function to get suburb profile data from Domain API\n getProfileData(locSuburb, locStateCode, locPC);\n \n // call function to get place data from ACTmapi API\n getPlaceData(locSuburb);\n\n }); // close getJSON urlGeocode\n\n} // close getLocationName function",
"function extractLatLong(aisData,binPayload,start) {\n aisData.longitude = extractLong(binPayload,start,28);\n aisData.latitude = extractLat(binPayload,start+28,27);\n}",
"getLatLong (location) {\n return new google.maps.LatLng(location.split(',')[0], location.split(',')[1]);\n }",
"function getLatLong(mapPoint) {\n\t\tvar pt = esri.geometry.webMercatorToGeographic(mapPoint);\n\t\tvar lt = pt.y.toFixed(6);\n\t\tvar lng = pt.x.toFixed(6);\n\t\treturn ([lt, lng]);\n\t\t\n\t}",
"toLocation(json) {\n let lat = json.location.lat\n let lon = json.location.lon\n if (this._searchParams.includes(',')) { // is this a lat,lon query?\n const parts = this._searchParams.split(',')\n lat = parseFloat(parts[0])\n lon = parseFloat(parts[1])\n }\n return new Location(lat, lon, json.location.name, json.location.region,\n json.location.country, json.location.tz_id, 0)\n }",
"convertFromGoogle(llobjs) {\n llobjs.forEach( function(llo) {\n if (typeof(llo.lat) != \"undefined\" && typeof(llo.lng) != \"undefined\") {\n llo.latitude = llo.lat();\n llo.longitude = llo.lng();\n }\n });\n }",
"function getGeoLocal() {\r\n}",
"getLongitude(){\r\n return this.location.longitude;\r\n }",
"async getCoordinates(){\r\n const query = encodeURIComponent(`${this.city}, ${this.state}`);\r\n const response = await fetch(`https://api.opencagedata.com/geocode/v1/json?q=${query}&key=${this.apiKey}&pretty=1`);\r\n\r\n const responseData = await response.json();\r\n return {\r\n lat: responseData.results[0].geometry.lat,\r\n lng: responseData.results[0].geometry.lng\r\n };\r\n }",
"function fetchDegreesLatLon(zip, rightleft) {\n $.ajax({\n url: 'https://api.openweathermap.org/data/2.5/weather?zip=' + zip + ',us&APPID=' + api_key,\n dataType: \"jsonp\",\n success: function (parsed_json) {\n //Kelvin to Fahrenheit\n function temp() {\n k = Math.floor(parsed_json.main.temp);\n f = (k * 9 / 5) - 459.67;\n return Math.round(f, 2);;\n }\n c_temp = temp();\n putDegrees(rightleft, c_temp);\n changeBackground(rightleft, c_temp);\n }\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write a sum method which will work properly when invoked using either syntax below. console.log(sum(2,3)); // Outputs 5 console.log(sum(2)(3)); // Outputs 5 | function sum()
{
if (arguments.length > 1)
{
var total = 0;
for (var i = 0; i < arguments.length; i++)
{
if (arguments[i] instanceof Function)
{
total += arguments[i]();
}
else
{
total += arguments[i];
}
}
return total;
}
else
{
var arg = arguments[0];
return function (num)
{
return sum(arg, num);
};
}
} | [
"function sum(...args) {\n let cur = args.reduce((p, c) => p + c)\n\n let fn = (...args2) => {\n cur = cur + args2.reduce((p, c) => p + c)\n return fn\n }\n\n fn.sumOf = () => cur\n\n return fn\n}",
"function sum(){\n var args = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments));\n return reduce(args, function(a,b){\n return a+b;\n })\n}",
"function runSumWithClosures() {\n console.log(sum(1)(2)); // 3\n console.log(sum(5)(-1)); // 4\n}",
"function sum(a, b) {\n return arguments.length > 1 ? a + b : function (b) {return a + b}\n}",
"function getTotal() {\n let args = Array.prototype.slice.call(arguments);\n\n if (args.length == 2) return args[0] + args[1];\n else if (args.length == 1) {\n return (num2) => {\n return args[0] + num2;\n };\n }\n}",
"function sum() {\n let argu = [...arguments];\n function fn(...arr) {\n argu = argu.concat(arr);\n return fn\n }\n fn.valueOf = function () {\n return argu.reduce((total, item) => {\n return total + item\n }, 0)\n }\n return fn\n}",
"function sum(num1, num2) {}",
"function sum() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args[i] = arguments[i];\n }\n if (args.length > 1)\n return args[0] + sum(...args.slice(1));\n else\n return args[0];\n}",
"function sum(num1, num2) {return num1 + num2}",
"function sum(){\n // YOUR CODE HERE\n var arr = Array.prototype.slice.call(arguments)\n return reduce(arr, function(a, v) {\n return a + v;\n }, 0);\n}",
"function squareAndSum(...args){\n const squares = args.map(arg => arg**2) \n return squares.reduce((prev, next) => prev + next)\n}",
"function sum(a,b){\n return multiply(a,b)+b\n}",
"function sum(...args) {\n //console.log(\"args\", args); // args [1,3]\n var total = args.reduce((acc, elem) => acc + elem, 0);\n console.log(total);\n}",
"function sum(first){\n return function (second){\n return first + second;\n }\n}",
"function sum(a, b) {\n let add = a + b;\n return add;\n}",
"function coolSum() {\n var args = Array.from(arguments).filter((elem) => typeof elem === 'number');\n return args.reduce((previous, current) => previous + current, 0);\n\n // return Array.from(arguments)\n // .filter((elem) => typeof elem === 'number')\n // .reduce((previous, current) => previous + current, 0);\n }",
"function calculateSum(a,b) //here are two argument/parameters given to calculateSum function\n{\n //sum of two numbers\n /* lekin sum karne ke kiye humko 2 no dene hoge jo ki hum waha dege */\n let sum = a + b;\n return sum; //return function value ko return kar deta hai jo usko call karega\n}",
"function sum(firstNum, secondNum) {\n return firstNum + secondNum;\n}",
"function sum(num1, num2) {\n return num1 + num2;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Embed the WAMI SWF and call the named callback function when loaded. | function embedWamiSWF(id, initfn) {
var flashVars = {
visible : false,
loadedCallback : initfn
};
var params = {
allowScriptAccess : "always"
};
if (supportsTransparency()) {
params.wmode = "transparent";
}
if (typeof console !== 'undefined') {
flashVars.console = true;
}
var version = '10.0.0';
document.getElementById(id).innerHTML = "WAMI requires Flash "
+ version
+ " or greater<br />https://get.adobe.com/flashplayer/";
// This is the minimum size due to the microphone security panel
Wami.swfobject.embedSWF(swfurl, id, 214, 137, version, null, flashVars,
params);
// Without this line, Firefox has a dotted outline of the flash
Wami.swfobject.createCSS("#" + id, "outline:none");
} | [
"function defaultLoader(flash, embedCallback) {\n\n document.body.appendChild(flash);\n embedCallback();\n\n\n}",
"function embedWamiSWF(id, initfn) {\n var flashVars = {\n visible : false,\n loadedCallback : initfn\n }\n\n var params = {\n allowScriptAccess : \"always\"\n }\n\n if (supportsTransparency()) {\n params.wmode = \"transparent\";\n }\n\n if (typeof console !== 'undefined') {\n flashVars.console = true;\n }\n\n var version = '10.0.0';\n document.getElementById(id).innerHTML = \"WAMI requires Flash \"\n + version\n + \" or greater<br />https://get.adobe.com/flashplayer/\";\n\n // This is the minimum size due to the microphone security panel\n Wami.swfobject.embedSWF(_options.swfUrl, id, 214, 137, version, null,\n flashVars, params);\n\n // Without this line, Firefox has a dotted outline of the flash\n Wami.swfobject.createCSS(\"#\" + id, \"outline:none\");\n }",
"function onSWFLoad( e ) {\n\t\t\t\t// TODO - appropriate error handling\n\t\t\t\tif (!e.success) {\n\t\t\t\t\tconsole.error('Audio recorder > Flash plug-in <object> DOM creation failed');\n\t\t\t\t} else {\n\t\t\t\t\t_flash = e.ref;\n\t\t\t\t\t_$flash = $( _flash );\n\t\t\t\t}\n\t\t\t}",
"function embedWamiSWF(id, initfn) {\n var flashVars = {\n visible: false,\n loadedCallback: initfn\n };\n\n var params = {\n allowScriptAccess: \"always\"\n };\n\n if (supportsTransparency()) {\n params.wmode = \"transparent\";\n }\n\n if (typeof console !== 'undefined') {\n flashVars.console = true;\n }\n\n var version = '10.0.0';\n document.getElementById(id).innerHTML = \"WAMI requires Flash \"\n + version\n + \" or greater<br />https://get.adobe.com/flashplayer/\";\n\n // The minimum size for the security panel is 214 by 137....but Flash does not scale with the browser zoom level.\n // So, we must determine the zoom level and then scale this accordinglu. If the security dialogue\n // is partially blocked the user won't be able to interact with it (part of Flash's clickjacking protection)\n // Flash is pain is Flash\n // Note: detecting browser zoom level is hard and the below isn't perfect. Something better is needed to\n // detect zoom level consistently. Wami.swf itself could be updated to detect this.\n\n // try a couple things to get zoom level and use the most conservative\n var zoom_level_checks = [\n window.outerWidth / window.innerWidth,\n document.documentElement.offsetHeight / window.innerHeight];\n if (window.jQuery) {\n zoom_level_checks.push(document.width / jQuery(document).width());\n }\n\n // Get the smallest (most conservative) of these values;\n var browser_zoom_level = Math.min.apply(null,\n // filter for sane values\n zoom_level_checks.filter(function (n) { return n > 0 && n < 10; })\n );\n var scale_factor = 1.0 / browser_zoom_level;\n var flash_width = 214 * scale_factor + 1;\n var flash_height = 137 * scale_factor + 1;\n\n Wami.swfobject.embedSWF(_options.swfUrl, id, flash_width, flash_height, version, null,\n flashVars, params);\n\n // Without this line, Firefox has a dotted outline of the flash\n Wami.swfobject.createCSS(\"#\" + id, \"outline:none\");\n }",
"function loadFlashButton()\r\n {\r\n logDebug(\"loadFlashButton\") ;\r\n return partial(initFlashButton) ;\r\n }",
"function delegateWamiAPI() {\n var recorder = document.getElementById(_options.id);\n\n function delegate(name) {\n Wami[name] = function () {\n if (!(name in recorder) && console && console.error) {\n console.error(\"Attempting to call a flash function that doesn't exist. An error has occured in the Flash object.\");\n }\n return recorder[name].apply(recorder, arguments);\n };\n }\n delegate('startPlaying');\n delegate('stopPlaying');\n delegate('startRecording');\n delegate('stopRecording');\n delegate('startListening');\n delegate('stopListening');\n delegate('getRecordingLevel');\n delegate('getPlayingLevel');\n delegate('setSettings');\n\n // Append extra information about whether mic settings are sticky\n Wami.getSettings = function () {\n var settings = recorder.getSettings();\n settings.microphone.remembered = Wami._remembered;\n return settings;\n };\n\n Wami.showSecurity = function (panel, startfn, finishedfn, failfn) {\n // Flash must be on top for this.\n var container = document.getElementById(_options.cid);\n\n var augmentedfn = Wami.nameCallback(function () {\n checkRemembered(finishedfn);\n container.style.cssText = \"position: absolute;\";\n });\n\n container.style.cssText = \"position: absolute; z-index: 99999\";\n\n recorder.showSecurity(panel, startfn, augmentedfn, failfn);\n };\n\n Wami.show = function () {\n if (!supportsTransparency()) {\n recorder.style.visibility = \"visible\";\n }\n };\n\n Wami.hide = function () {\n // Hiding flash in all the browsers is tricky. Please read:\n // https://code.google.com/archive/p/wami-recorder/wikis/Quirks.wiki\n if (!supportsTransparency()) {\n recorder.style.visibility = \"hidden\";\n }\n };\n\n // If we already have permissions, they were previously 'remembered'\n Wami._remembered = recorder.getSettings().microphone.granted;\n\n if (_options.onLoaded) {\n _options.onLoaded();\n }\n\n if (!_options.noSecurityCheck) {\n checkSecurity();\n }\n }",
"function AddMap(id, configfile, width, heigth, params, applicationPath, culture, isReadyCallback) {\r\n\r\n try {\r\n\r\n var flashvarsdetails = {};\r\n var attributes = {};\r\n\r\n flashvarsdetails[\"urlprefix\"] = GetBasePath(applicationPath);\r\n flashvarsdetails[\"configfile\"] = GetBasePath(applicationPath) + configfile;\r\n flashvarsdetails[\"locale\"] = culture;\r\n flashvarsdetails[\"divid\"] = id;\r\n\r\n if (isReadyCallback != null) {\r\n flashvarsdetails[\"callbackfunction\"] = escape(isReadyCallback.toString());\r\n }\r\n\r\n\r\n swfobject.embedSWF(GetBasePath(applicationPath) + \"index.swf\",\r\n id,\r\n width,\r\n heigth,\r\n \"9.0.0\",\r\n \"playerProductInstall.swf\",\r\n flashvarsdetails,\r\n params,\r\n attributes);\r\n }\r\n catch (err) {\r\n }\r\n \r\n}",
"function archiveLoadedHandler(event){\n\tmyArchive = event.archives[0];\n\tif(flag_widget == false) {\n\t\tstartPlayback();\n\t}\n}",
"function addSwf(domain){\n // the differentiating query argument is needed in Flash9 to avoid a caching issue where LocalConnection would throw an error.\n var url = config.swf + \"?host=\" + config.isHost;\n var id = \"easyXDM_swf_\" + Math.floor(Math.random() * 10000);\n\n // prepare the init function that will fire once the swf is ready\n easyXDM.Fn.set(\"flash_loaded\" + domain.replace(/[\\-.]/g, \"_\"), function(){\n easyXDM.stack.FlashTransport[domain].swf = swf = swfContainer.firstChild;\n var queue = easyXDM.stack.FlashTransport[domain].queue;\n for (var i = 0; i < queue.length; i++) {\n queue[i]();\n }\n queue.length = 0;\n });\n\n if (config.swfContainer) {\n swfContainer = (typeof config.swfContainer == \"string\") ? document.getElementById(config.swfContainer) : config.swfContainer;\n }\n else {\n // create the container that will hold the swf\n swfContainer = document.createElement('div');\n\n // http://bugs.adobe.com/jira/browse/FP-4796\n // http://tech.groups.yahoo.com/group/flexcoders/message/162365\n // https://groups.google.com/forum/#!topic/easyxdm/mJZJhWagoLc\n apply(swfContainer.style, HAS_FLASH_THROTTLED_BUG && config.swfNoThrottle ? {\n height: \"20px\",\n width: \"20px\",\n position: \"fixed\",\n right: 0,\n top: 0\n } : {\n height: \"1px\",\n width: \"1px\",\n position: \"absolute\",\n overflow: \"hidden\",\n right: 0,\n top: 0\n });\n document.body.appendChild(swfContainer);\n }\n\n // create the object/embed\n var flashVars = \"callback=flash_loaded\" + encodeURIComponent(domain.replace(/[\\-.]/g, \"_\"))\n + \"&proto=\" + global.location.protocol\n + \"&domain=\" + encodeURIComponent(getDomainName(global.location.href))\n + \"&port=\" + encodeURIComponent(getPort(global.location.href))\n + \"&ns=\" + encodeURIComponent(namespace);\n swfContainer.innerHTML = \"<object height='20' width='20' type='application/x-shockwave-flash' id='\" + id + \"' data='\" + url + \"'>\" +\n \"<param name='allowScriptAccess' value='always'></param>\" +\n \"<param name='wmode' value='transparent'>\" +\n \"<param name='movie' value='\" +\n url +\n \"'></param>\" +\n \"<param name='flashvars' value='\" +\n flashVars +\n \"'></param>\" +\n \"<embed type='application/x-shockwave-flash' FlashVars='\" +\n flashVars +\n \"' allowScriptAccess='always' wmode='transparent' src='\" +\n url +\n \"' height='1' width='1'></embed>\" +\n \"</object>\";\n }",
"function showExpressInstall(att,par,replaceElemIdStr,callbackFn){var obj=getElementById(replaceElemIdStr);if(\n//Ensure that replaceElemIdStr is really a string and not an element\nreplaceElemIdStr=getId(replaceElemIdStr),isExpressInstallActive=!0,storedCallbackFn=callbackFn||null,storedCallbackObj={success:!1,id:replaceElemIdStr},obj){\"OBJECT\"===obj.nodeName.toUpperCase()?(// static publishing\nstoredFbContent=abstractFbContent(obj),storedFbContentId=null):(// dynamic publishing\nstoredFbContent=obj,storedFbContentId=replaceElemIdStr),att.id=EXPRESS_INSTALL_ID,(typeof att.width===UNDEF||!/%$/.test(att.width)&&toInt(att.width)<310)&&(att.width=\"310\"),(typeof att.height===UNDEF||!/%$/.test(att.height)&&toInt(att.height)<137)&&(att.height=\"137\");var pt=ua.ie?\"ActiveX\":\"PlugIn\",fv=\"MMredirectURL=\"+encodeURIComponent(win.location.toString().replace(/&/g,\"%26\"))+\"&MMplayerType=\"+pt+\"&MMdoctitle=\"+encodeURIComponent(doc.title.slice(0,47)+\" - Flash Player Installation\");\n// IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it,\n// because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work\nif(typeof par.flashvars!==UNDEF?par.flashvars+=\"&\"+fv:par.flashvars=fv,ua.ie&&4!=obj.readyState){var newObj=createElement(\"div\");replaceElemIdStr+=\"SWFObjectNew\",newObj.setAttribute(\"id\",replaceElemIdStr),obj.parentNode.insertBefore(newObj,obj),// insert placeholder div that will be replaced by the object element that loads expressinstall.swf\nobj.style.display=\"none\",removeSWF(obj)}createSWF(att,par,replaceElemIdStr)}}",
"function addSwf(domain){\r\n // the differentiating query argument is needed in Flash9 to avoid a caching issue where LocalConnection would throw an error.\r\n var url = config.swf + \"?host=\" + config.isHost;\r\n var id = \"easyXDM_swf_\" + Math.floor(Math.random() * 10000);\r\n \r\n // prepare the init function that will fire once the swf is ready\r\n easyXDM.Fn.set(\"flash_loaded\" + domain.replace(/[\\-.]/g, \"_\"), function(){\r\n easyXDM.stack.FlashTransport[domain].swf = swf = swfContainer.firstChild;\r\n var queue = easyXDM.stack.FlashTransport[domain].queue;\r\n for (var i = 0; i < queue.length; i++) {\r\n queue[i]();\r\n }\r\n queue.length = 0;\r\n });\r\n \r\n if (config.swfContainer) {\r\n swfContainer = (typeof config.swfContainer == \"string\") ? document.getElementById(config.swfContainer) : config.swfContainer;\r\n }\r\n else {\r\n // create the container that will hold the swf\r\n swfContainer = document.createElement('div');\r\n \r\n // http://bugs.adobe.com/jira/browse/FP-4796\r\n // http://tech.groups.yahoo.com/group/flexcoders/message/162365\r\n // https://groups.google.com/forum/#!topic/easyxdm/mJZJhWagoLc\r\n apply(swfContainer.style, HAS_FLASH_THROTTLED_BUG && config.swfNoThrottle ? {\r\n height: \"20px\",\r\n width: \"20px\",\r\n position: \"fixed\",\r\n right: 0,\r\n top: 0\r\n } : {\r\n height: \"1px\",\r\n width: \"1px\",\r\n position: \"absolute\",\r\n overflow: \"hidden\",\r\n right: 0,\r\n top: 0\r\n });\r\n document.body.appendChild(swfContainer);\r\n }\r\n \r\n // create the object/embed\r\n var flashVars = \"callback=flash_loaded\" + domain.replace(/[\\-.]/g, \"_\") + \"&proto=\" + global.location.protocol + \"&domain=\" + getDomainName(global.location.href) + \"&port=\" + getPort(global.location.href) + \"&ns=\" + namespace;\r\n swfContainer.innerHTML = \"<object height='20' width='20' type='application/x-shockwave-flash' id='\" + id + \"' data='\" + url + \"'>\" +\r\n \"<param name='allowScriptAccess' value='always'></param>\" +\r\n \"<param name='wmode' value='transparent'>\" +\r\n \"<param name='movie' value='\" +\r\n url +\r\n \"'></param>\" +\r\n \"<param name='flashvars' value='\" +\r\n flashVars +\r\n \"'></param>\" +\r\n \"<embed type='application/x-shockwave-flash' FlashVars='\" +\r\n flashVars +\r\n \"' allowScriptAccess='always' wmode='transparent' src='\" +\r\n url +\r\n \"' height='1' width='1'></embed>\" +\r\n \"</object>\";\r\n }",
"function _initFlashPlayer() {\n if (Drupal.microsite.installed != true) {\n setTimeout(function(){\n _initFlashPlayer();\n }, 500);\n } else {\n Drupal.microsite.initFlashPlayer();\n }\n }",
"loadPlugin(name, cb) {\n const src = _params.pluginCdnTemplate.replace(\n '[name]',\n name\n );\n loadScript(src, { async: false }, (err, plugin) => {\n if (err) {\n // eslint-disable-next-line no-console\n return console.error(\n `WaveSurfer plugin ${name} not found at ${src}`\n );\n }\n cb(window.WaveSurfer[name]);\n });\n }",
"function addSwf(domain){\r\n // the differentiating query argument is needed in Flash9 to avoid a caching issue where LocalConnection would throw an error.\r\n var url = config.swf + \"?host=\" + config.isHost;\r\n var id = \"easyXDM_swf_\" + Math.floor(Math.random() * 10000);\r\n \r\n // prepare the init function that will fire once the swf is ready\r\n easyXDM.Fn.set(\"flash_loaded\" + domain.replace(/[\\-.]/g, \"_\"), function(){\r\n easyXDM.stack.FlashTransport[domain].swf = swf = swfContainer.firstChild;\r\n var queue = easyXDM.stack.FlashTransport[domain].queue;\r\n for (var i = 0; i < queue.length; i++) {\r\n queue[i]();\r\n }\r\n queue.length = 0;\r\n });\r\n \r\n if (config.swfContainer) {\r\n swfContainer = (typeof config.swfContainer == \"string\") ? document.getElementById(config.swfContainer) : config.swfContainer;\r\n }\r\n else {\r\n // create the container that will hold the swf\r\n swfContainer = document.createElement('div');\r\n \r\n // http://bugs.adobe.com/jira/browse/FP-4796\r\n // http://tech.groups.yahoo.com/group/flexcoders/message/162365\r\n // https://groups.google.com/forum/#!topic/easyxdm/mJZJhWagoLc\r\n apply(swfContainer.style, HAS_FLASH_THROTTLED_BUG && config.swfNoThrottle ? {\r\n height: \"20px\",\r\n width: \"20px\",\r\n position: \"fixed\",\r\n right: 0,\r\n top: 0\r\n } : {\r\n height: \"1px\",\r\n width: \"1px\",\r\n position: \"absolute\",\r\n overflow: \"hidden\",\r\n right: 0,\r\n top: 0\r\n });\r\n document.body.appendChild(swfContainer);\r\n }\r\n \r\n // create the object/embed\r\n var flashVars = \"callback=flash_loaded\" + encodeURIComponent(domain.replace(/[\\-.]/g, \"_\"))\r\n + \"&proto=\" + global.location.protocol\r\n + \"&domain=\" + encodeURIComponent(getDomainName(global.location.href))\r\n + \"&port=\" + encodeURIComponent(getPort(global.location.href))\r\n + \"&ns=\" + encodeURIComponent(namespace);\r\n swfContainer.innerHTML = \"<object height='20' width='20' type='application/x-shockwave-flash' id='\" + id + \"' data='\" + url + \"'>\" +\r\n \"<param name='allowScriptAccess' value='always'></param>\" +\r\n \"<param name='wmode' value='transparent'>\" +\r\n \"<param name='movie' value='\" +\r\n url +\r\n \"'></param>\" +\r\n \"<param name='flashvars' value='\" +\r\n flashVars +\r\n \"'></param>\" +\r\n \"<embed type='application/x-shockwave-flash' FlashVars='\" +\r\n flashVars +\r\n \"' allowScriptAccess='always' wmode='transparent' src='\" +\r\n url +\r\n \"' height='1' width='1'></embed>\" +\r\n \"</object>\";\r\n }",
"function addSwf(domain){\n // the differentiating query argument is needed in Flash9 to avoid a caching issue where LocalConnection would throw an error.\n var url = config.swf + \"?host=\" + config.isHost;\n var id = \"easyXDM_swf_\" + Math.floor(Math.random() * 10000);\n \n // prepare the init function that will fire once the swf is ready\n easyXDM.Fn.set(\"flash_loaded\" + domain.replace(/[\\-.]/g, \"_\"), function(){\n easyXDM.stack.FlashTransport[domain].swf = swf = swfContainer.firstChild;\n var queue = easyXDM.stack.FlashTransport[domain].queue;\n for (var i = 0; i < queue.length; i++) {\n queue[i]();\n }\n queue.length = 0;\n });\n \n if (config.swfContainer) {\n swfContainer = (typeof config.swfContainer == \"string\") ? document.getElementById(config.swfContainer) : config.swfContainer;\n }\n else {\n // create the container that will hold the swf\n swfContainer = document.createElement('div');\n \n // http://bugs.adobe.com/jira/browse/FP-4796\n // http://tech.groups.yahoo.com/group/flexcoders/message/162365\n // https://groups.google.com/forum/#!topic/easyxdm/mJZJhWagoLc\n apply(swfContainer.style, HAS_FLASH_THROTTLED_BUG && config.swfNoThrottle ? {\n height: \"20px\",\n width: \"20px\",\n position: \"fixed\",\n right: 0,\n top: 0\n } : {\n height: \"1px\",\n width: \"1px\",\n position: \"absolute\",\n overflow: \"hidden\",\n right: 0,\n top: 0\n });\n document.body.appendChild(swfContainer);\n }\n \n // create the object/embed\n var flashVars = \"callback=flash_loaded\" + domain.replace(/[\\-.]/g, \"_\") + \"&proto=\" + global.location.protocol + \"&domain=\" + getDomainName(global.location.href) + \"&port=\" + getPort(global.location.href) + \"&ns=\" + namespace;\n swfContainer.innerHTML = \"<object height='20' width='20' type='application/x-shockwave-flash' id='\" + id + \"' data='\" + url + \"'>\" +\n \"<param name='allowScriptAccess' value='always'></param>\" +\n \"<param name='wmode' value='transparent'>\" +\n \"<param name='movie' value='\" +\n url +\n \"'></param>\" +\n \"<param name='flashvars' value='\" +\n flashVars +\n \"'></param>\" +\n \"<embed type='application/x-shockwave-flash' FlashVars='\" +\n flashVars +\n \"' allowScriptAccess='always' wmode='transparent' src='\" +\n url +\n \"' height='1' width='1'></embed>\" +\n \"</object>\";\n }",
"function initFacebookJS(){\n\t\t\t\tFB.Bootstrap.requireFeatures([\"Connect\"], function() {\n\t\t\t\t\tFB.Connect.requireSession(function(exception) {\n\t\t\t\t\t\t//define your flashVars\n\t\t\t\t\t\t//Pull out the current session data from Facebook\n\t\t\t\t\t\tvar sessionData = FB.Facebook.apiClient.get_session();\n\t\t\t\t\t\tvar flashvars = {as_swf_name:\"flashContent\", session_key:sessionData.session_key, secret:sessionData.secret};\n\t\t\t\t\t\t//locate movie and call initFacebookFlash callback in there\n\t\t\t\t\t\tthisMovie(flashvars.as_swf_name).initFacebookFlash(flashvars);\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t}",
"function addOnloadHook(f) {\n addLoadEvent(f);\n}",
"function startUpPlayer()\n{\n var flvPlayerFileURL= dwscripts.filePathToLocalURL(dw.getConfigurationPath()\n + dwscripts.FILE_SEP + \"Commands\"\n + dwscripts.FILE_SEP + \"FLVFileLoader.swf\");\n\n\tif(swfloader && !bFlashInit)\n\t{\n\t\tbFlashInit = true;\n\t\tswfloader.loadMovie(flvPlayerFileURL);\n\t}\n}",
"function addOnload(fn) {\n if (isDef(w.addEventListener)) {\n w.addEventListener(\"load\", fn, false);\n } else if (isDef(d.addEventListener)) {\n d.addEventListener(\"load\", fn, false);\n } else if (isDef(w.attachEvent)) {\n w.attachEvent(\"onload\", fn);\n //TODO: swfobject also keeps references to the listeners to detach them on onload\n // to avoid memory leaks ...\n } else if (typeof w.onload == \"function\") {\n var fnOld = w.onload;\n w.onload = function() {\n fnOld();\n fn();\n };\n } else {\n w.onload = fn;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
handleMouseMove, setups up the mouse events for the canvas, this calculates the delta for the mouse dragging the grid on the canvas | function handleMouseMove(e) {
// only do this code if the mouse is being dragged
if (!isDown) {
return
}
// tell the browser we're handling this event
e.preventDefault()
e.stopPropagation()
// get the current mouse position
mouseX = parseInt(e.clientX - offsetX)
mouseY = parseInt(e.clientY - offsetY)
// dx & dy are the distance the mouse has moved since
// the last mousemove event
var dx = mouseX - startX
var dy = mouseY - startY
// reset the vars for next mousemove
startX = mouseX
startY = mouseY
start_x = start_x + dx //netPanningX
start_y = start_y + dy //netPanningY
recalc()
} | [
"function drag(e){ //function called from nonogramMakerCanvas.js file\n\t//deal with horizontal shifting\n\tvar prev_xOffset = xOffset;\n\txOffset += e.movementX;\n\t\n\t\t//update display\n\tif(e.movementX > 0){\n\t\tvar pic = ctx.getImageData(0,0,window.innerWidth-e.movementX,window.innerHeight);\n\t\tctx.clearRect(0,0,canvas.width,canvas.height);\n\t\tctx.putImageData(pic,e.movementX,0);\n\t\tdrawGridlines(\"lightblue\",{xMin:0, xMax:e.movementX, yMin:0, yMax:canvas.height});\n\t} else if(e.movementX < 0){\n\t\tvar pic = ctx.getImageData(-e.movementX,0,window.innerWidth+e.movementX,window.innerHeight);\n\t\tctx.clearRect(0,0,canvas.width,canvas.height);\n\t\tctx.putImageData(pic,0,0);\n\t\tdrawGridlines(\"lightblue\",{xMin:canvas.width+e.movementX, xMax:canvas.width, yMin:0, yMax:canvas.height});\n\t} //if e.movementX === 0, don't need to do anything\n\t\n\t\n\t\n\t\n\t//deal with vertical shifting\n\tvar prev_yOffset = yOffset;\n\tyOffset += e.movementY;\n\t\n\t\t//update display\n\tif(e.movementY > 0){\n\t\tvar pic = ctx.getImageData(0,0,window.innerWidth,window.innerHeight-e.movementY);\n\t\tctx.clearRect(0,0,canvas.width,canvas.height);\n\t\tctx.putImageData(pic,0,e.movementY);\n\t\tdrawGridlines(\"lightblue\",{xMin:0, xMax:canvas.width, yMin:0, yMax:e.movementY});\n\t} else if(e.movementY < 0){\n\t\tvar pic = ctx.getImageData(0,-e.movementY,window.innerWidth,window.innerHeight+e.movementY);\n\t\tctx.clearRect(0,0,canvas.width,canvas.height);\n\t\tctx.putImageData(pic,0,0);\n\t\tdrawGridlines(\"lightblue\",{xMin:0, xMax:canvas.width, yMin:canvas.height+e.movementY, yMax:canvas.height});\n\t} //if e.movementY === 0, don't need to do anything\n\t\n\t\n\t\n\t//draw all squares - function found in utilities.js\n\tctx.fillStyle = \"black\";\n\tdrawData(minX,minY);\n\t\n}",
"function handleMouseMove(evt)\r\n{\r\n var mousePos = getMousePos(canvas, evt); //Returns tuple of mouse pos on canvas (x,y)\r\n mouse.x = Math.floor(mousePos.x/30); //find associated X-tile\r\n mouse.y = Math.floor(mousePos.y/30); //find associated Y-tile\r\n}",
"function canvasMouseMoveEv(event) {}",
"function handleMove(evt){\n\n g_mouseX = evt.clientX - g_canvas.offsetLeft; \n g_mouseY = evt.clientY - g_canvas.offsetTop;\n\n //Tower follows the mouse\n if(tower != null){\n\n if (g_mouseX < Arena.WIDTH){\n var pos = Arena.posToIndex(g_mouseX,g_mouseY)\n var newPos = Arena.indexToPos(pos.row,pos.column)\n\n g_mouseX = newPos.x;\n g_mouseY = newPos.y;\n }\n tower.setPos(g_mouseX,g_mouseY)\n tower.render(g_ctx);\n }\n}",
"function bindMouseMove() {\r\n canvas.addEventListener('mousemove', function(e) {\r\n mousePos = getMousePos(e);\r\n });\r\n }",
"function mouseDragged(){\n\toffsetX -= (pmouseX - mouseX) * 0.5;\n\toffsetY -= (pmouseY - mouseY) * 0.5;\n\n\tgrid.offsetY = offsetY;\n\tgrid.offsetX = offsetX;\n\n //Update offsets for every model\n for (let i = 0; i < models.length; i++)\n models[i].setOffsets(offsetX, offsetY);\n}",
"function handleMouseMove(e) {\n\t\tnowMouseX = e.pageX;\n\t\tdeltaPos = (nowMouseX - prevMouseX) / scrubber.width();\n targetPos = Math.max(0, Math.min(1, curPos + deltaPos));\n\t}",
"function canvasMouseMove(e) {\n\tif (!mouseIsDown) return;\t\t// Do nothing if not pressing down on mouse\n\tmousePosition = getCursorPosition(e);\n}",
"onCanvasMouseMove(event) {\n const { viewer } = this.state;\n\n viewer.raiseEvent('mouse-move', event);\n }",
"function gridsMouseMove(event) {\n if (mouseClicked && !solving) {\n var borderOffset = 5;\n var resizedOffSet = Math.floor((this.clientWidth / initWidth) * offSet);\n var resizedBlockSize = Math.floor((this.clientWidth - (resizedOffSet * 2)) / dimensions);\n var xDown = event.layerX - (borderOffset + resizedOffSet);\n var yDown = event.layerY - (borderOffset + resizedOffSet);\n var xDex = Math.floor(xDown / resizedBlockSize);\n var yDex = Math.floor(yDown / resizedBlockSize);\n for (var i = 0; i < curCanvases.length; ++i) {\n curVal = curCanvases[i];\n if (xDex >= 0 && xDex < dimensions && yDex >= 0 && yDex < dimensions) {\n if (fillOrRemove) {\n curVal.ctx.fillStyle = \"brown\";\n curVal.ctx.strokeStyle = \"blue\";\n curVal.backArray[xDex][yDex] = 1;\n curVal.ctx.fillRect((xDex * blockSize) + offSet, (yDex * blockSize) + offSet, blockSize, blockSize);\n curVal.ctx.strokeRect((xDex * blockSize) + offSet, (yDex * blockSize) + offSet, blockSize, blockSize);\n } else {\n curVal.ctx.fillStyle = \"white\";\n curVal.ctx.strokeStyle = \"blue\";\n curVal.backArray[xDex][yDex] = 0;\n curVal.ctx.fillRect((xDex * blockSize) + offSet, (yDex * blockSize) + offSet, blockSize, blockSize);\n curVal.ctx.strokeRect((xDex * blockSize) + offSet, (yDex * blockSize) + offSet, blockSize, blockSize);\n }\n }\n }\n }\n }",
"updateMouseMoveEvents() {\n this.updateEventsContainer('mouse-move');\n }",
"function canvasMouseMove(e) {\n\tblockus.setMousePosition(getCursorPosition(e));\n}",
"function onMouseMoveCanvas(e) {\n\tvar pointer = canvas.getPointer(e.e, true);\n var original_x = parseInt(pointer.x); // parseInt(pointer.x - 330);\n var original_y = parseInt(pointer.y); // parseInt(pointer.y - 22);\n jQuery(\".g-ruler-widget.horizontal .mouse-marker\").css(\"left\", original_x);\n jQuery(\".g-ruler-widget.vertical .mouse-marker\").css(\"top\", original_y);\n}",
"function mouseMove_handler( event )\n\t\t{\n\t\t\t_mouseX = event.pageX;\n\t\t\t_mouseY = event.pageY;\n\t\t}",
"handleMouseMove(event){\n if(this.selectedCard){\n var clickPos = EventManager.getMousePosition(event);\n this.selectedCard.pos[0] += clickPos[0] - this.prevMousePos[0];\n this.selectedCard.pos[1] += clickPos[1] - this.prevMousePos[1];\n Game.getInstance().update();\n this.prevMousePos = clickPos;\n }\n }",
"function onMouseMove(event) {\n\tif (dragging) {\n\t\tboard.translate(event.pageX - lastX, event.pageY - lastY);\n\t\tlastX = event.pageX;\n\t\tlastY = event.pageY\n\t}\n}",
"function updateMousePos(event) {\n mousePos.x = event.clientX - canvas.offsetLeft;\n mousePos.y = event.clientY - canvas.offsetTop;\n\n if (mousePos.x < 0) mousePos.x = 0;\n if (mousePos.y < 0) mousePos.y = 0;\n\n if (mousePos.x >= canvas.width) mousePos.x = canvas.width - 1;\n if (mousePos.y >= canvas.height) mousePos.y = canvas.height - 1;\n}",
"function enableMouseMove() {\n // Add event listener for mouse move events to the canvas\n canvas.addEventListener(\"mousemove\", function (evt) {\n triggerMouseEvent(evt, canvas, connectedGame.mouseMoveEvent);\n }, false);\n }",
"function onPointerMove(e) {\n if (pointerActive) {\n e.preventDefault();\n var pixelX = e.clientX;\n var pixelY = e.clientY;\n _deltaX = startX - pixelX;\n _deltaY = startY - pixelY; // SCROLL THE GRID\n\n handleScrollDelta(_deltaX, _deltaY); // RESET START X AND Y\n\n startX = pixelX;\n startY = pixelY;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create error message when doing an empty search | function errorMessageForEmptySearch() {
spinner.style.display = "block";
let errorMessageIfInputIsEmpty = `
<div class="errorMessageEmptySearch"><p>You have to write a title to be able to search</p></div>`
movieInformation.innerHTML = errorMessageIfInputIsEmpty
} | [
"function displayError() {\n alert(\"search term can not be empty!\");\n }",
"function displayError() {\n alert(\"search term can not be empty!\")\n }",
"function emptyMessage() {\n const list = $(results);\n if (!list.children().length) {\n list.append(`<li class=\"countries__searched__item\">No results for \"${search.val().trim()}\"</li>`);\n }\n }",
"function handleSearchErrorMessage(){\n\t\tvar message = \"\";\n\n\t\t//affichage du message commun\n\t\tif(selectMatiere && selectNiveau){\n\t\t\thideMessage();\n\t\t}else if(!selectMatiere && selectNiveau){\n\t\t\tmessage = \"Veuillez d'abord choisir une matière\";\n\t\t}else if(selectMatiere && !selectNiveau){\n\t\t\tmessage = \"Veuillez d'abord choisir un niveau\";\n\t\t}else{\n\t\t\tmessage = \"Veuillez d'abord choisir un niveau et une matière\";\n\t\t}\n\n\t\tif(message != \"\"){\n\t\t\tshowMessage(message);\n\t\t}\n\n\t}",
"function handleSearchNotFound() {\n displayErrorView(\"No toys found that match the filters and the search string '\"\n + id(\"search-term\").value.trim() + \"', please try again.\");\n }",
"renderError() {\n const template = this.renderTemplate('error', null, 'error');\n return (template ||\n html `\n <div class=\"message-parent\">\n <div label=\"search-error-text\" aria-label=\"We didn't find any matches.\" class=\"search-error-text\">\n ${this.strings.noResultsFound}\n </div>\n </div>\n `);\n }",
"function noResultTemplate(query) {\n return `<div class=\"search__empty\">\n ${icons.noResult}</br>\n No results have been found for <span>${query}</span>.</br>\n Please rephrase your query!\n </div>`;\n }",
"function renderNoResultsError() {\n console.warn(\"BEAUTIFUL IB RESULTS: %s\", \"no results found\");\n\n //get the element within the template which will contain the subjects\n const subject_list = document.querySelector(\".subject-list\");\n //get the error template element\n const template = document.querySelector(\"#template_error\");\n\n //create a clone of the error\n let clone = template.content.cloneNode(true);\n\n //change the error message\n clone.querySelector(\".subject\").textContent = `Oh no, we couldn't find the results!`;\n\n //render the subject\n subject_list.append(clone);\n }",
"function resetErrMsg(){\n\t\tself.errorMessage('');\n\t\tself.searchTerm('');\n\t}",
"function createSearchError(description) {\n return embedUtil.createMessage(\"Search Error\", description, \"exclamation mark\", true);\n}",
"function processNoResults() {\n const divSearchContainer = document.getElementsByClassName('search-container')[0];\n if (document.getElementsByClassName('search-error').length === 0) {\n divError = createAppendElement(divSearchContainer, 'search-error', 'DIV');\n divError.innerHTML = '<p>Your search found no results</p>';\n }\n createEmployeeCards(employees);\n }",
"emptyText() {\n \n if (this.loading) {\n return this.loadingText || 'Loading';\n } else {\n if (this.remote && this.query === '' && this.options.length === 0) return false;\n if (this.filterable && this.options.length > 0 && this.filteredOptionsCount === 0) { \n return this.noMatchText || 'No matches';\n }\n if (this.options.length === 0) {\n return this.noDataText || 'No Data';\n }\n }\n return null;\n }",
"function showSearchError() {\n toggleSearchMessage(true, \"An error occurred during your search.\");\n searchFieldElem.setAttribute(\"showSpinner\", false);\n }",
"renderError() {\n if(!this.state.validInput) {\n return(\n <div>\n <Alert severity=\"error\">Invalid input detected, please do not use '%, :, or &' and provide a search term.</Alert>\n <br />\n </div>\n );\n }\n }",
"function searchErrorCallback() {\n outputTextArea.value = \"error in search().\";\n }",
"function errorCallback(data) {\n 'use strict';\n if (film !== '') {\n\n console.log('error: \\n' + data);\n $('#results').text('Error searching. ' + JSON.parse(data).status_message);\n }\n }",
"getEmptyLabel(searchString) {\n if (searchString.length > 0) {\n return nls_1.localize('noResultsMatching', \"No results matching\");\n }\n return nls_1.localize('noResultsFound2', \"No results found\");\n }",
"function showErrorMessage() {\n const errorMessage = document.querySelector(\".error--message\");\n errorMessage.innerHTML = `<h1>No Matches for: ${searchInput.value}</h1>`;\n errorMessage.style.display = `inline-block`;\n}",
"function setNotFoundMessages() {\n $(\"#search-results-heading\").text(\"No recipes found, please change search criteria.\");\n $(\"#results\").text(\"\");\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle the start/end value constraining to 0..180, etc... | function clean_start_end_value(value){
// In case we pass in a number
value = value.toString();
let changed = false;
let new_value;
if(value == ''){
// Check if empty string
new_value = 0;
changed = true;
}else if(value.charAt(0) == '0'){
// Remove leading zeroes
new_value = parseInt(value,10);
changed = true;
}else{
// Check if we exceed the limits for the start or end value
new_value = parseInt(value,10);
if(new_value > 180){
new_value = 180;
changed = true;
}else if(new_value < 0){
new_value = 0;
changed = true;
}
}
if(changed){
return new_value;
}else{
return false;
}
} | [
"function suppliedBounds(start, end, step) {\n\n}",
"function setBounds() {\n // The value was found\n if (focus === value) {\n // Gray out all values\n max = -1;\n playing = false;\n }\n else if (focus < value) min = focus + 1;\n else max = focus - 1;\n}",
"function checkBoundaries(value) {\n if (value < options.lowerBound*10)\n return options.lowerBound*10;\n else if (value > options.upperBound*10)\n return options.upperBound*10;\n else\n return value;\n }",
"function checkBoundaries(value) {\n\t\tif (value < options.lowerBound*10)\n\t\t\treturn options.lowerBound*10;\n\t\telse if (value > options.upperBound*10)\n\t\t\treturn options.upperBound*10;\n\t\telse\n\t\t\treturn value;\n\t}",
"function validateStartEnd(start,end){return!!start&&!!end&&start.isValid&&end.isValid&&start<=end;}",
"function prepare_range_of_coordinates()\n\t\t{\n\t\t\tfull_range = create_range_of_coordinates(0, options.width, 0, options.height);\n\t\t}",
"limits() {\n var keys = Object.keys(this.data);\n var min = parseInt(this.data[keys[0]]); // ignoring case of empty list for conciseness\n var max = parseInt(this.data[keys[0]]);\n var i;\n for (i = 1; i < keys.length; i++) {\n var value = parseInt(this.data[keys[i]]);\n if (value < min) min = value;\n if (value > max) max = value;\n }\n this.yMin =min - Math.round(min/4);\n if(this.yMin <= 0)\n this.yMin=0;\n this.yMax = max + Math.round(max/4);\n\n }",
"function AutomatableRangedValue() {}",
"function valueInRange (start, value, finish) {\n\t return (start <= value) && (value <= finish);\n\t}",
"adjustRange() {\r\n\t\tthis.min = parseFloat(this.minObj.value);\r\n\t\tthis.max = parseFloat(this.maxObj.value);\r\n\t\tthis.adjustValue();\r\n\t}",
"constructor(startRadians = 0, endRadians = 0) { this._radians0 = startRadians; this._radians1 = endRadians; }",
"function displayCustomRange(id)\n{\n var newStart = document.getElementById(\"startIdx\").value;\n var newEnd = document.getElementById(\"endIdx\").value;\n if (newStart>0 && newEnd<650)\n {\n start = parseInt(newStart);\n end = parseInt(newEnd);\n drawChart();\n }\n else\n {\n alert(\"Invalid inputs. Chart not redrawn.\");\n }\n}",
"function validate(minlat, maxlong , minlat ,maxlat){\n if(Number.isFinite( minlat) && Number.isFinite( maxlong) && Number.isFinite(minlong) && Number.isFinite( maxlat) ){ \n if(minlat >maxlat || minlong>maxlong){\n alert('min value can not be bigger then this damn max value')\n return false\n }\n else{\n if(minlat<-180 ||maxlong>180 ||minlong<-180 ||maxlong>180){\n alert('values ranged only from -180 ')\n return false\n }\n else {\n return true\n }\n }\n }\n else{\n alert('please fill all this fucken fields with numbers')\n return false\n }\n}",
"function valueInRange(start, value, finish) {\n return start <= value && value <= finish;\n}",
"_checkEndValue() {\n var v = this._calcStepRounded(this.endValue);\n if(v >= this.value && v <= this.max) {\n this.set('endValue', v);\n } else {\n var m = this._calcStepRounded(this.max);\n this.set('endValue', m);\n }\n }",
"function valueInRange (start, value, finish) {\n return (start <= value) && (value <= finish);\n}",
"map(value, startRangeLower, startRangeHigher, targetRangeLower, targetRangeHigher)\n {\n let startSpan = startRangeHigher - startRangeLower;\n let targetSpan = targetRangeHigher - targetRangeLower;\n return (((value - startRangeLower) / startSpan) * targetSpan) + targetRangeLower;\n }",
"function Range() {\n\tthis._value = 0;\n\tthis._minimum = 0;\n\tthis._maximum = 100;\n\tthis._extent = 0;\n\t\n\tthis._isChanging = false;\n}",
"range(val, spec) {\n return isNullOrUndefined(val) || val >= spec.minValue && val <= spec.maxValue;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
funcao que valida o cep | function validateCep(cep)
{
//valida se o cep foi preenchido
if(cep == "" || cep.length < 8)
{
// adicionas os li a lista de erros
$("#listaErrosLightBox").append("<li> Erro de Preenchimento </li>");
$("#listaErrosLightBox").append("<li> É necessário o preenchimento do campo CEP </li>");
// chama a funcao que mostrar os erro no lightbox
showErrorColorBox();
return false;
}
// valida se o cep possui apenas numero
validaCep = "" + cep.match("[0-9]+");
//valida se o cep foi preenchido
if(validaCep.length < 8)
{
// adicionas os li a lista de erros
$("#listaErrosLightBox").append("<li> Erro de Preenchimento </li>");
$("#listaErrosLightBox").append("<li> Campo CEP preenchimento incorretamente </li>");
// chama a funcao que mostrar os erro no lightbox
showErrorColorBox();
return false;
}
return true;
} | [
"function MascaraCep(cep) {\n if (mascaraInteiro(cep) == false) {\n event.returnValue = false;\n }\n return formataCampo(cep, '00.000-000', event);\n}",
"function MascaraCep(cep)\n{\t\t\n if(mascaraInteiro(cep)==false)\n {\t\t\n event.returnValue = false;\t\n }\t\t\n return formataCampo(cep, '00.000-000', event);\n}",
"function validazioneFormDest_gestione_profilo_utente() {\n var nome_cognome = document.getElementById(\"nome_cognome\");\n var indirizzo = document.getElementById(\"indirizzo\");\n var civico = document.getElementById(\"civico\");\n var cap = document.getElementById(\"cap\");\n var tel = document.getElementById(\"tel\");\n\n var risNomeCognome = checkNomeCognome(nome_cognome);\n var risIndirizzo = checkAlfanumericoESpazi(indirizzo);\n var risCivico = checkCivico(civico);\n var risCAP = checkCAP(cap);\n var risTel = checkSoloNumerieDim(tel);\n\n if(!risNomeCognome){\n mostraErrore(nome_cognome, \"Il nome deve contenere solo lettere e non contenere meno di due caratteri\");\n }\n if(!risIndirizzo){\n mostraErrore(indirizzo,\"L'indirizzo non deve contenere caratteri speciali\");\n }\n if(!risCivico){\n mostraErrore(civico,\"Il numero civico deve essere del formato corretto (e.g. 4, 4b, 4-b o 4/1)\");\n }\n if(!risCAP){\n mostraErrore(cap,\"Non hai inserito un CAP del comune di Padova\");\n }\n if(!risTel){\n mostraErrore(tel,\"Non hai inserito un numero telefonico valido\");\n }\n return risNomeCognome && risIndirizzo && risCivico && risCAP && risTel;\n\n}",
"function MascaraCep(cep) {\n if (mascaraInteiro(cep) == false) {\n event.returnValue = false;\n }\n return formataCampo(cep, '00000-000', event);\n}",
"function MascaraCep(cep) {\n if (mascaraInteiro(cep) === false) {\n event.returnValue = false;\n }\n return formataCampo(cep, '00.000-000', event);\n}",
"function MascaraCep(cep){\r\n if(mascaraInteiro(cep)==false){\r\n event.returnValue = false;\r\n }\r\n return formataCampo(cep, '00.000-000', event);\r\n }",
"function MascaraCep(cep){\n if(mascaraInteiro(cep)==false){\n event.returnValue = false;\n } \n return formataCampo(cep, '00000-000', event);\n}",
"function MascaraCep(cep) {\n if (mascaraInteiro(cep) == false) {\n event.returnValue = false;\n }\n return formataCampo(cep, '00000-000', event);\n }",
"function validacao() {\n \n var erro = false;\n if(inNome.value.indexOf(\" \") == -1) {\n alert(\"Preencha o nome corretamente\")\n erro = true;\n }\n if(inCpf.value.lenght != 11) {\n alert(\"Preencha o CPF corretamente\")\n erro = true;\n }\n\n}",
"function valida_comentario(p_nombre,p_correo,p_asunto)\r\n{\r\n\tif(vacio(p_nombre)&& vacio (p_correo)&& vacio(p_asunto))\r\n\t{\r\n\t\tif(valida_correo(p_correo))\r\n\t\t{\r\n\t\t\treturn true\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\talert(\"por favor escribir correo valido\");\r\n\t\t\treturn false\r\n\t\t}\r\n\t}\r\n\talert(\"por favor llenar los campos\");\r\n\treturn false\r\n}",
"function ValidarCPF(Objcpf) {\n var cpf = Objcpf.value;\n exp = /\\.|\\-/g\n cpf = cpf.toString().replace(exp, \"\");\n var digitoDigitado = eval(cpf.charAt(9) + cpf.charAt(10));\n var soma1 = 0, soma2 = 0;\n var vlr = 11;\n\n for (i = 0; i < 9; i++) {\n soma1 += eval(cpf.charAt(i) * (vlr - 1));\n soma2 += eval(cpf.charAt(i) * vlr);\n vlr--;\n }\n soma1 = (((soma1 * 10) % 11) == 10 ? 0 : ((soma1 * 10) % 11));\n soma2 = (((soma2 + (2 * soma1)) * 10) % 11);\n\n var digitoGerado = (soma1 * 10) + soma2;\n if (digitoGerado != digitoDigitado) {\n $('input#cpf').parent().find('span').remove();\n\n $('input#cpf').addClass('has-error');\n\t\t$('input#cpf').after('<strong><span class=\"aviso col-sm-12\">Insira um CPF válido!</span></strong>');\n\t\tdocument.form1.cpf.focus();\n } else {\n $('input#cpf').removeClass('has-error');\n $('input#cpf').parent().find('span').remove();\n\n }\n\n\n}",
"function valida_cpf(cpf){\n erro = new String; \n if (cpf.value.length === 11){ \n cpf.value = cpf.value.replace('.', ''); \n cpf.value = cpf.value.replace('.', ''); \n cpf.value = cpf.value.replace('-', ''); \n var nonNumbers = /\\D/; \n if (nonNumbers.test(cpf.value)){ \n erro = \"A verificacao de CPF suporta apenas números!\"; \n }else{ \n if (cpf.value === \"00000000000\" || cpf.value === \"11111111111\" || cpf.value === \"22222222222\" || \n cpf.value === \"33333333333\" || cpf.value === \"44444444444\" || cpf.value === \"55555555555\" || \n cpf.value === \"66666666666\" || cpf.value === \"77777777777\" || cpf.value === \"88888888888\" || \n cpf.value === \"99999999999\") { \n erro = \"Número de CPF inválido\"; \n } \n var a = []; \n var b = new Number; \n var c = 11; \n for (i=0; i<11; i++){ \n a[i] = cpf.value.charAt(i); \n if (i < 9) b += (a[i] * --c); \n } \n if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x } \n b = 0; \n c = 11; \n for (y=0; y<10; y++) b += (a[y] * c--); \n if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; } \n if ((cpf.value.charAt(9) !== a[9]) || (cpf.value.charAt(10) !== a[10])) { \n erro = \"Número de CPF inválido\"; \n } \n } \n }else { \n if(cpf.value.length === 0) \n return false; \n else \n erro = \"Número de CPF inválido\"; \n } \n if (erro.length > 0) { \n alert(erro); \n cpf.focus(); \n return false; \n } \n return true;\n}",
"function ValidaCPF(cpf) {\r\n\r\n //Criando os campos para armezar cada dígito do CPF\r\n let num1 = parseInt(cpf.substring(0, 1));\r\n let num2 = parseInt(cpf.substring(1, 2));\r\n let num3 = parseInt(cpf.substring(2, 3));\r\n let num4 = parseInt(cpf.substring(4, 5));\r\n let num5 = parseInt(cpf.substring(5, 6));\r\n let num6 = parseInt(cpf.substring(6, 7));\r\n let num7 = parseInt(cpf.substring(8, 9));\r\n let num8 = parseInt(cpf.substring(9, 10));\r\n let num9 = parseInt(cpf.substring(10, 11));\r\n let num10 = parseInt(cpf.substring(12, 13));\r\n let num11 = parseInt(cpf.substring(13, 14));\r\n\r\n //Verificação para CPF inválidos com valores iguais\r\n if (num1 === num2 && num2 === num3 && num3 === num4\r\n && num4 === num5 && num5 === num6 && num6 === num7\r\n && num7 === num8 && num8 === num9 && num9 === num10\r\n && num10 === num11) {\r\n return false;\r\n } else {\r\n\r\n //Calculo para Verificar se o 1º dígito após o '-' é igual\r\n\r\n let soma1 = (num1 * 10) + (num2 * 9) + (num3 * 8) + (num4 * 7) + (num5 * 6) + (num6 * 5) + (num7 * 4) + (num8 * 3) + (num9 * 2);\r\n\r\n let resto1 = (soma1 * 10) % 11;\r\n\r\n //Calculo para Verificar se o 2º dígito após o '-' é igual\r\n\r\n let soma2 = (num1 * 11) + (num2 * 10) + (num3 * 9) + (num4 * 8) + (num5 * 7) + (num6 * 6) + (num7 * 5) + (num8 * 4) + (num9 * 3) + (num10 * 2);\r\n\r\n let resto2 = (soma2 * 10) % 11;\r\n\r\n //Verificação dos 2 dígitos\r\n\r\n if (resto1 === num10 && resto2 === num11) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }\r\n}",
"function validaced(){\n \n\n \n /**\n * Algoritmo para validar cedulas de Ecuador\n * @Author : Victor Diaz De La Gasca.\n * @Fecha : Quito, 15 de Marzo del 2013 \n * @Email : vicmandlagasca@gmail.com\n * @Pasos del algoritmo\n * 1.- Se debe validar que tenga 10 numeros\n * 2.- Se extrae los dos primero digitos de la izquierda y compruebo que existan las regiones\n * 3.- Extraigo el ultimo digito de la cedula\n * 4.- Extraigo Todos los pares y los sumo\n * 5.- Extraigo Los impares los multiplico x 2 si el numero resultante es mayor a 9 le restamos 9 al resultante\n * 6.- Extraigo el primer Digito de la suma (sumaPares + sumaImpares)\n * 7.- Conseguimos la decena inmediata del digito extraido del paso 6 (digito + 1) * 10\n * 8.- restamos la decena inmediata - suma / si la suma nos resulta 10, el decimo digito es cero\n * 9.- Paso 9 Comparamos el digito resultante con el ultimo digito de la cedula si son iguales todo OK sino existe error. \n */\n\n var cedula = document.getElementById('cedula').value;\n\n //Preguntamos si la cedula consta de 10 digitos\n if(cedula.length == 10){\n \n //Obtenemos el digito de la region que sonlos dos primeros digitos\n var digito_region = cedula.substring(0,2);\n \n //Pregunto si la region existe ecuador se divide en 24 regiones\n if( digito_region >= 1 && digito_region <=24 ){\n \n // Extraigo el ultimo digito\n var ultimo_digito = cedula.substring(9,10);\n\n //Agrupo todos los pares y los sumo\n var pares = parseInt(cedula.substring(1,2)) + parseInt(cedula.substring(3,4)) + parseInt(cedula.substring(5,6)) + parseInt(cedula.substring(7,8));\n\n //Agrupo los impares, los multiplico por un factor de 2, si la resultante es > que 9 le restamos el 9 a la resultante\n var numero1 = cedula.substring(0,1);\n var numero1 = (numero1 * 2);\n if( numero1 > 9 ){ var numero1 = (numero1 - 9); }\n\n var numero3 = cedula.substring(2,3);\n var numero3 = (numero3 * 2);\n if( numero3 > 9 ){ var numero3 = (numero3 - 9); }\n\n var numero5 = cedula.substring(4,5);\n var numero5 = (numero5 * 2);\n if( numero5 > 9 ){ var numero5 = (numero5 - 9); }\n\n var numero7 = cedula.substring(6,7);\n var numero7 = (numero7 * 2);\n if( numero7 > 9 ){ var numero7 = (numero7 - 9); }\n\n var numero9 = cedula.substring(8,9);\n var numero9 = (numero9 * 2);\n if( numero9 > 9 ){ var numero9 = (numero9 - 9); }\n\n var impares = numero1 + numero3 + numero5 + numero7 + numero9;\n\n //Suma total\n var suma_total = (pares + impares);\n\n //extraemos el primero digito\n var primer_digito_suma = String(suma_total).substring(0,1);\n\n //Obtenemos la decena inmediata\n var decena = (parseInt(primer_digito_suma) + 1) * 10;\n\n //Obtenemos la resta de la decena inmediata - la suma_total esto nos da el digito validador\n var digito_validador = decena - suma_total;\n\n //Si el digito validador es = a 10 toma el valor de 0\n if(digito_validador == 10)\n var digito_validador = 0;\n\n //Validamos que el digito validador sea igual al de la cedula\n if(digito_validador == ultimo_digito){\n console.log('la cedula:' + cedula + ' es correcta');\n }else{\n document.getElementById('cedula').value=\"\";\n console.log('la cedula:' + cedula + ' es incorrecta');\n }\n \n }else{\n // imprimimos en consola si la region no pertenece\n document.getElementById('cedula').value = \"Este formato no es válido\";\n /*alert(\"ced no es ecuatoriana\");*/\n /*console.log('Esta cedula no pertenece a ninguna region');*/\n }\n }else{\n //imprimimos en consola si la cedula tiene mas o menos de 10 digitos\n document.getElementById('cedula').value = \"\";\n /*alert(\"Formato incprrecto\");*/\n /*console.log('Esta cedula tiene menos de 10 Digitos');*/\n } \n \n}",
"function formValidation_isInvalidCep1( cep1 ){\t\t\n var invalidCep1 = ['11111','22222','33333','44444','55555','66666','77777','88888','99999','12345'];\n for( var i=0; i < invalidCep1.length; ++i ){\n if( cep1 == invalidCep1[i] ) return true;\n }\n return false;\n}",
"function ValidaCPF(){\n\n\t\tvar cpf = $( \"#cpf\" ).val();\n\t\texp = /\\.|\\-/g\n\t\tcpf = cpf.toString().replace( exp, \"\" );\n\t\tvar digitoDigitado = eval(cpf.charAt(9)+cpf.charAt(10));\n\t\tvar soma1=0, soma2=0;\n\t\tvar vlr =11;\n\n\t\tfor(i=0;i<9;i++){\n\t\t\tsoma1+=eval(cpf.charAt(i)*(vlr-1));\n\t\t\tsoma2+=eval(cpf.charAt(i)*vlr);\n\t\t\tvlr--;\n\t\t}\n\n\t\tsoma1 = (((soma1*10)%11)==10 ? 0:((soma1*10)%11));\n\t\tsoma2=(((soma2+(2*soma1))*10)%11);\n\n\t\tvar digitoGerado=(soma1*10)+soma2;\n\n\t\tif(digitoGerado!=digitoDigitado){\n\t\t\tmensagemValidacao('cpf', 'O CPF não é válido!', true)\n\t\t\tcamposAValidar = true;\n\t\t} else {\n\t\t\tmensagemValidacao('cpf', '', false)\n\t\t}\n\t}",
"function validarEspacioVacio(inputId) \n{\t \n\t CAF.model(inputId).addValidator(function(id,value) {\t\t\n\t\treturn (/\\s/.test(value) ? \"No puede contener espacios en blanco.\" : \"\");\n\t});\t\t\n}",
"function validarCupom(){\n\tvar cupom = document.getElementById(\"cupom\").value;\n\t\n\tif(cupom == \"\"){\n\t\talert(\"Informe o cupom!!\");\n\t\treturn false;\n\t}\n\treturn true;\n}",
"function validaPaciente(paciente){\n\n var erros = [];\n //FUNÇÃO VALIDA ESTAÕ NO ARQUIVO CALCULA-IMC.JS\n if (validaPeso(paciente.peso)!=true){\n erros.push(\"Peso é inválido\")\n }\n if (validaAltura(paciente.altura)!=true){\n erros.push(\"Altura é invalida\")\n }\n if (!validaNome(paciente.nome)){\n erros.push(\"Paciente sem nome\")\n }\n if (!validaGordura(paciente.gordura)){\n erros.push(\"Gordura Inválida\")\n }\n return erros\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET hero by id. Will 404 if id not found | getHero(id) {
const url = `${this.heroesUrl}/${id}`;
return this.http.get(url).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_4__["tap"])(_ => this.log(`fetched hero id=${id}`)), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_4__["catchError"])(this.handleError(`getHero id=${id}`)));
} | [
"getHero(id) {\n const url = `${this.heroesUrl}/${id}`;\n return this.http.get(url).pipe(operators_1.tap(_ => this.log(`fetched hero id=${id}`)), operators_1.catchError(this.handleError(`getHero id=${id}`)));\n }",
"getHero(id) {\n const url = `${this.heroesUrl}/hero/${id}`;\n return this.http.get(url).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"tap\"])(_ => this.log(`fetched hero id=${id}`)), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"catchError\"])(this.handleError(`getHero id=${id}`)));\n }",
"getHero(id) {\n const url = `${this.heroesUrl}/${id}`;\n return this.http.get(url).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_2__.tap)(_ => this.log(`fetched hero id=${id}`)), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.catchError)(this.handleError(`getHero id=${id}`)));\n }",
"getHeroNo404(id) {\n const url = `${this.heroesUrl}/?id=${id}`;\n return this.http.get(url)\n .pipe(operators_1.map(heroes => heroes[0]), // returns a {0|1} element array\n operators_1.tap(h => {\n const outcome = h ? `fetched` : `did not find`;\n this.log(`${outcome} hero id=${id}`);\n }), operators_1.catchError(this.handleError(`getHero id=${id}`)));\n }",
"async function fetchSuperHeroData(id) {\n const url = Common.apiUrl;\n\n try {\n const data = await Common.apiRequest(`${url}/${id}`);\n\n if (data.success) {\n renderSuperHeroDetails(data.data);\n } else {\n renderSuperHeroDetails(null);\n }\n } catch (error) {\n console.log('error', error);\n renderSuperHeroDetails(null);\n }\n }",
"function getHero( heroID ) { \n\t\tvar key = \"hero\" + (heroID + 1)\n\n\t\tif( _heroes[key] != undefined ) { \n\t\t\treturn _heroes[key]; \n\t\t}\t\t\n\t}",
"getPokemon(id) {\n return this.apiHandler.get(`pokemon/${id}/`);\n }",
"async function fetchSuperHeroInformation(id){\n const url= Common.apiUrl+id;\n try{\n const allinfo= await Common.apiRequest(`${url}`);\n //console.log(info);\n if(allinfo.success){\n SuperheroInformation(allinfo.data);\n }else{\n SuperheroInformation(null);\n }\n }catch(err){\n console.log('Error!! Cannot Find This SuperHero',err);\n SuperheroInformation(null);\n }\n\n }",
"async function serachById(id){ \n try{\n const superhero = await fetch(`https://superheroapi.com/api.php/${tokenId}/${id}`);\n const data = await superhero.json();\n if(data.response===\"success\")\n renderSuperhero(data); \n else \n renderResult([{name: \"No Results found\"}]);\n }\n catch(error){\n console.log(error);\n }\n }",
"async function deleteHero(id) {\n // Set Fetch API Options\n const options = {\n method: 'Delete',\n headers: { 'Content-Type': 'application/json' },\n };\n\n // Fetch, url & options (delete hero by ID)\n const del = await fetch(`http://localhost:3000/heroes/${id}`, options);\n // If promise \"OK\" is true, if else, promise OK is a status returned by the server\n return del.ok\n ? console.log(`Hero with ID '${id}' successfully deleted!`)\n : console.log(`Error, hero with ID '${id}' does not exist`);\n }",
"deleteHero(id) {\n const url = `${this.heroesUrl}/hero/${id}`;\n return this.http.delete(url, this.httpOptions).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"tap\"])(_ => this.log(`deleted hero id=${id}`)), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"catchError\"])(this.handleError('deleteHero')));\n }",
"deleteHero(id) {\n const url = `${this.heroesUrl}/${id}`;\n return this.http.delete(url, this.httpOptions).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_2__.tap)(_ => this.log(`deleted hero id=${id}`)), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.catchError)(this.handleError('deleteHero')));\n }",
"getHeroes() {\n return this.http.get(this.heroesUrl)\n .pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_2__.tap)(_ => this.log('fetched heroes')), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.catchError)(this.handleError('getHeroes', [])));\n }",
"function getHeroID(){\n const urlparams = new URLSearchParams(window.location.search);\n return urlparams.get('id');\n }",
"function getHeroFromForm(id) {\n\tvar select = document.getElementById(id);\n\tdrawHeroInfo(select[select.selectedIndex].value);\n}",
"getHeroes() {\n return this.http.get(this.heroesUrl)\n .pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_4__[\"tap\"])(_ => this.log('fetched heroes')), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_4__[\"catchError\"])(this.handleError('getHeroes', [])));\n }",
"getHeroes() {\n return this.http.get(this.heroesUrl)\n .pipe(operators_1.tap(heroes => this.log('fetched heroes')), operators_1.catchError(this.handleError('getHeroes', [])));\n }",
"getOne(callback, id, options) {\n\t\t\trequest(callback, {\n\t\t\t\tregion: options.region,\n\t\t\t\tcache: {\n\t\t\t\t\tenabled: options.cache !== undefined ? options.cache : true,\n\t\t\t\t\tregion: options.region,\n\t\t\t\t\tidentifier: \"champion/\" + id,\n\t\t\t\t\texpires: cacheTimes.VERY_LONG\n\t\t\t\t},\n\t\t\t\tpath: \"/lol/v3/champion/${id}\",\n\t\t\t\tpathParameters: {\n\t\t\t\t\tregion: options.region,\n\t\t\t\t\tid\n\t\t\t\t}\n\t\t\t});\n\t\t}",
"getProdHero(product_id) {\n return axios\n .get(API_URL + product_id + \"/hero\", {\n headers: authHeader(),\n })\n .then((response) => {\n return response;\n })\n .catch((err) => {\n return err;\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function for transition to repositories page | function goToRepos() {
var params = {
userName: $stateParams.userName,
basic: $stateParams.basic,
id: $stateParams.id,
token: $stateParams.token
};
console.log('Go back to repositories.');
$state.go('repositories', params);
} | [
"handleRepoNav() {\n if (this.userData.repo.edges === null\n || this.userData.repo.edges === undefined\n || this.userData.repo.edges.length === 0) {\n const emptyPrompt = `${this.userData.userLogin} has no public repositories.`;\n const pushEmpty = StackActions.push('Empty', { emptyPrompt });\n this.navigation.dispatch(pushEmpty);\n } else {\n const pushRepo = StackActions.push('Repo',\n { repo: this.userData.repo.edges, user: this.userData.userLogin });\n this.navigation.dispatch(pushRepo);\n }\n }",
"function repoClick(click_flag){\n\tif (click_flag){\n\t\twindow.history.pushState({page : 'repo'}, 'repoPage', '#repo')\n\t}\n\tremoveHome();\n\twipeWholePage();\n\n\tcreateDiv(\"contentItems\", \"text\")\n\tcreateInputBox(\"Input\", \"contentItems\");\n\tcreateButton(\"List Repos\", \"accessFunction()\", \"bn\", \"contentItems\");\n\tcreateButton(\"Go Home\", \"goHome(true)\", \"h\", \"contentItems\");\n\n\treturn;\n}",
"function showProject (user, repository) {\n \n w2ui.panelLayout.content('right', '<p>Fetching repository details...</p>');\n w2ui.panelLayout.show('right');\n\n octo.repos(user, repository).fetch().then(function(data) {\n console.log(data);\n var description = data.description;\n description = (description !== null && description !== '' ?\n '<p>' + description + '</p>': '<p>No description available.</p>');\n \n var created = timeSince(data.createdAt);\n var fork = data.fork;\n var isPrivate = data.private;\n var parentRepo = fork ? data.parent : false;\n var owner = data.owner.login;\n var repoIcon = '<i class=\"fa fa-github\"></i> ';\n if (fork) repoIcon = '<i class=\"fa fa-code-fork\"></i> ';\n if (isPrivate) repoIcon = '<i class=\"fa fa-eye-slash\"></i> ';\n if (owner !== config.user) repoIcon = '<img class=\"avatar-large\" src=\"' +\n data.owner.avatarUrl +'\"/> ';\n var history = '<p>Created ' + created + ' by ' + owner + '.</p>';\n if (parentRepo) history = '<p>Forked from ' + parentRepo.fullName + ' ' +\n created + ', by ' + owner + '.</p>';\n \n var editButton = '<div id=\"editbutton\" class=\"pressable\" ' +\n 'style=\"display: none; margin-bottom: 0;\" ' +\n 'onclick=\"openProject(' + \"'\" + owner + \"','\" + repository + \n \"', 'getbranchfromselection'\" + ')\">' +\n '<h2><i class=\"fa fa-pencil\" aria-hidden=\"true\"></i> Edit </h2></div>';\n \n var cardFront = '<div class=\"card-front\"><i class=\"fa fa-2x fa-gear repo-config\" ' + \n 'onclick=\"$(this).parent().parent().toggleClass(' + \"'flipped'\" + ')\"></i>' + \n '<div class=\"repo-blurb\"><h1>' + repoIcon + repository + '</h1>' +\n description + history + '</div>' + editButton + '<div id=\"branch-list\">' + \n '<p>Fetching branches ...</p></div></div>';\n \n var cardBack = '<div class=\"card-back\"><i class=\"fa fa-2x fa-share repo-config\" ' + \n 'onclick=\"$(this).parent().parent().toggleClass(' + \"'flipped'\" + ')\"></i>' + \n '<div class=\"repo-blurb\"><h1>Options</h1><p>Add collaborator</p></div>' +\n '</div>';\n \n var projectHTML = '<div class=\"card-container\"><div class=\"card\">' + \n cardFront + cardBack + '</div></div>';\n \n w2ui.panelLayout.content('right', projectHTML);\n \n octo.repos(user, repository).branches.fetch().then(function(results) {\n console.log(results);\n var branches = [];\n for (var i = 0; i< results.items.length; i++) {\n branches.push (results.items[i].name);\n }\n $(\"#branch-list\").html('<select class=\"branch-selector\"><option>' + \n branches.join('</option><option>') +\n '</option><option>New branch...</option></select>');\n // Allow edit\n $('#editbutton').show();\n // Default to master branch, if it exists\n if (branches.indexOf('master')>-1) $('#branch-list select').val('master');\n updateLayout();\n });\n \n });\n}",
"function jump2Repo(){\n window.location.assign('https://github.com/bfalchuk/bfalchuk.github.io');\n}",
"function updateRepositories(repos_url) {\n fetch(repos_url)\n .then(response => response.json())\n .then(json => {\n let repo_heading = document.createElement('h2');\n repo_heading.textContent = 'Repositories';\n repositories.appendChild(repo_heading);\n let div = document.createElement('div');\n div.classList.add('layout');\n repositories.appendChild(div);\n for(let i=0; i< json.length; i++) {\n let div_ = document.createElement('div');\n let repo_name = document.createElement('h3');\n let description = document.createElement('p');\n let repo_link = document.createElement('a'); \n\n repo_name.textContent = json[i]['name'];\n \n repo_link.appendChild(repo_name);\n repo_link.href = json[i]['html_url'];\n repo_link.target = '_blank';\n div_.appendChild(repo_link);\n\n description.textContent = json[i]['description'];\n div_.appendChild(description);\n\n \n\n div.appendChild(div_);\n } \n })\n }",
"function handleDashboard() {\n history.push('/repositories')\n }",
"function loadRepoView(){\n ermsRepoService.registerObserverCallback(repoViewObserver);\n ermsRepoService.setProfile(decodeURIComponent($stateParams.profileName), decodeURIComponent($stateParams.mapName));\n rvc.profileName = ermsRepoService.profile;\n rvc.repositoryRoot = ermsRepoService.repositoryRoot;\n rvc.mapName = ermsRepoService.mapName;\n //load the root view for the repository\n _getRootView(rvc.profileName);\n //Re-initialise the export feature by clearing the export basket and re-initialising the profile and mapping params\n //ermsExportService.clearBasket();\n ermsExportService.initExportParams(ermsRepoService.profile, ermsRepoService.mapName);\n\n }",
"function retrieveGitDetails(event) {\n var repoDetailContainer = $(this).siblings().find('.repo-details');\n //clear the repo details\n repoDetailContainer.html(\"\").toggleClass('hide')\n //add all repo details\n var repoDetails = event.data.repoDetails;\n // var language = $('<p>').text(\"Language: \" + repoDetails.language);\n var language = $('<p>').html(\"<span class='bold'>Language: </span>\" + repoDetails.language);\n var description = $('<p>').html(\"<span class='bold'>Description:</span> \" + repoDetails.description);\n var url = $('<a>', {\n href: repoDetails.url,\n target: '_blank'\n }).html('Check out this repo')\n var user = repoDetails.user;\n //get followers\n $.ajax({\n type: \"GET\",\n url: githubURL + 'users/' + user + '/followers'\n }).done(function(data) {\n var followerStr = \"\";\n\n if (data.length > 0) {\n data.forEach(function(follower) {\n followerStr += follower.login + \" | \"\n })\n } else {\n followerStr = \"none\";\n }\n var followerStr = $('<p>').html(\"<span class='bold'>Followers: </span>\" + followerStr)\n repoDetailContainer.append(language, description, followerStr, url);\n })\n }",
"function processrepoPage(url){\n request(url,cb);\n function cb(err, resp, html){\n if(err){\n console.log(err);\n }else{\n getRepoLink(html);\n }\n }\n}",
"function repositoryClick() {\n const repUrl = repLink + input.value;\n getJson(repUrl).then((data) => {\n const repositoryName = createAndAppend(\"h1\", container, data.full_name);\n repositoryName.setAttribute(\"id\", \"repositoryName\");\n const repositoryUrl = createAndAppend(\"a\", container, \"Link Of Repository: \" + data.html_url);\n repositoryUrl.setAttribute(\"id\", \"repositoryUrl\");\n repositoryUrl.setAttribute(\"href\", data.html_url);\n repositoryUrl.setAttribute(\"target\", \"_blank\");\n const contributor= createAndAppend(\"h2\", container, \"Contributors\");\n contributor.setAttribute(\"id\", \"contributors\");\n const contributorsList = createAndAppend(\"ul\", container);\n // nested Json to get contributors from the parent Json file\n getJson(data.contributors_url).then((newData) => {\n for (let i = 0; i < newData.length; i++) {\n const li = createAndAppend(\"li\", contributorsList);\n contributorsList.setAttribute(\"id\", \"contributorListLi\");\n const a = createAndAppend(\"a\", li,\"<hr>\" + \"User Name: \" + newData[i].login + \"<br><br>\");\n a.setAttribute(\"href\", newData[i].html_url);\n a.setAttribute(\"target\", \"_blank\");\n a.setAttribute(\"id\", \"userLoginLink\");\n const userAvatar = createAndAppend(\"img\", li);\n userAvatar.setAttribute(\"src\", newData[i].avatar_url + \"<hr>\");\n userAvatar.setAttribute(\"id\", \"userAvatar\");\n }\n })\n })\n }",
"_onRepositoryChanged() {\n const repository = this.model.get('repository');\n\n if (repository === null) {\n /*\n * A repository is no longer selected. The user either chose\n * the File Attachments Only entry or hit the \"< Repositories\"\n * link on mobile.\n *\n * If on mobile, we're going to add a small delay (slightly longer\n * than the animation time) before removing any views, so that\n * they don't disappear during animation.\n */\n this._$newReviewRequestContainer\n .removeClass('js-repository-selected');\n\n if (this.inMobileMode) {\n _.delay(this._removeCommitViews.bind(this), 400);\n } else {\n this._removeCommitViews();\n }\n } else {\n /*\n * The user has selected a repository. Begin placing new views\n * based on the repository's capabilities.\n */\n this._$newReviewRequestContainer\n .addClass('js-repository-selected');\n\n this._removeCommitViews();\n\n if (repository.get('filesOnly')) {\n this._preCommitView = new FilesOnlyPreCommitView({\n model: new FilesOnlyPreCommitModel({\n repository: repository\n })\n });\n } else {\n this._preCommitView = new RB.PreCommitView({\n model: new RB.UploadDiffModel({\n repository: repository\n })\n });\n\n if (repository.get('supportsPostCommit')) {\n this._postCommitView = new RB.PostCommitView({\n model: new RB.PostCommitModel({\n repository: repository\n }),\n $scrollContainer: this._$content,\n });\n }\n }\n\n this._$hint.hide();\n this._$content.append(this._preCommitView.render().el);\n\n if (this._postCommitView) {\n this._$content.append(this._postCommitView.render().el);\n }\n }\n }",
"function showRepoOverview(repo) {\n var item;\n item = '<li>';\n item += '<span class=\"name\"><a href=\"' + repo.html_url + '\">' + repo.name + '</a></span>';\n item += ' · <span class=\"time\"><a href=\"' + repo.html_url + '/commits\">' + prettyDate(repo.pushed_at) + '</a></span>';\n item += '</li>';\n\n $(item).appendTo(\"#updated-repos\");\n }",
"function displayRepos(username, repos, repoButton){\n let reposList = document.getElementById(\"repos-list\")\n if (repoButton.innerText === \"Show Repos\"){\n repoButton.innerText = \"Hide Repos\"\n for (var i = 0; i < 10 && i < repos.length; i++){\n const repo = repos[i]\n console.log(repo)\n let repoName = repo.name\n let result = repoName.link(`https://github.com/${username}/${repoName}`)\n let li = document.createElement(\"li\")\n li.innerHTML = result\n result.target = \"_blank\"\n reposList.appendChild(li)\n }\n }\n else if (repoButton.innerText === \"Hide Repos\") {\n repoButton.innerText = \"Show Repos\"\n while (reposList.firstChild){\n reposList.removeChild(reposList.firstChild);\n }\n }\n}",
"function repoViewObserver(){\n rvc.breadcrumbs = ermsRepoService.breadcrumbs;\n rvc.repo = ermsRepoService.repoItems;\n }",
"function selectRepo(e) {\n e.stopPropagation();\n \n var picked = e.currentTarget.children[0].innerHTML.split(' / ');\n \n selectedRepo = picked[1];\n \n // console.log(picked); // diag\n populateMenu(repos);\n \n // Call HitApi module's public .getEvents() method\n HitApi.getEvents(picked[0], picked[1]);\n \n // retract repo list\n DOM.$listContainer\n .addClass('hidden');\n }",
"function displayRepos(repos, searchTerm){\n // check to see if there are any repos for the username\n if(repos.length === 0){\n // if none found, display message and then return to beginning of function\n repoContainerEl.textContent = \"No repositories found for\" + nameInputEl.value.trim();\n return;\n }\n // clear old content from repoContainerEl search list \n repoContainerEl.textContent = \"\";\n // will display repoSearchTerm text value\n repoSearchTerm.textContent = searchTerm;\n // console.log(repos);\n // console.log(searchTerm);\n\n // loop over repos\n for (var i = 0; i<repos.length; i++){\n // format repo name getting 'owner.login' and 'name' from each index in array \n var repoName = repos[i].owner.login + \"/\" + repos[i].name;\n // create a container for each repo\n var repoEl = document.createElement('a');\n // create class for repoEl\n repoEl.classList = \"list-item flex-row justify-space-between align-center\";\n // create href to link to single-repo.html passing in repoName as query\n repoEl.setAttribute(\"href\", \"./single-repo.html?repo=\" + repoName);\n // create a span element to hold repository name\n var titleEl = document.createElement('span');\n //add repoName variable from above into titleEl <span>\n titleEl.textContent = repoName;\n // append to container\n repoEl.appendChild(titleEl);\n // create status element for issues \n var statusEl = document.createElement('span');\n // create class for statusEl\n statusEl.classList = \"flex-row align-center\";\n // check if current repo has issues\n if (repos[i].open_issues_count>0){\n statusEl.innerHTML = \"<i class='fas fa-times status-icon icon-danger'></i>\" + repos[i].open_issues_count + \" issue(s)\";\n }else{\n statusEl.innerHTML = \"<i class='fas fa-check-square status-icon icon-success'></i>\";\n }\n \n // append to container\n repoEl.appendChild(statusEl);\n // append container to DOM repoContainerEl is empty <div id=\"repos-container\"> \n repoContainerEl.appendChild(repoEl);\n}\n}",
"handleViewRepo(repo) {\n this.setState({\n viewRepo: true,\n selectedRepo: repo\n })\n }",
"function repos() {\n document.getElementById(\"numberOfRepos\").innerHTML = \"\";\n\n if (reposData.length == 0) {\n document.getElementById(\"numberOfRepos\").innerHTML =\n gitData.login + \" has no repositories\";\n endLoader();\n }\n if (reposData.length > 0) {\n for (var i = 0; i < reposData.length; i++) {\n document.getElementById(\"numberOfRepos\").innerHTML = \"\";\n document.getElementById(\"numberOfRepos\").innerHTML =\n gitData.login + \" has \" + gitData.public_repos + \" repositories\";\n\n var containerDiv = document.createElement(\"div\");\n\n var nameDiv = document.createElement(\"div\");\n var a = document.createElement(\"a\");\n a.setAttribute(\"href\", reposData[i].svn_url);\n a.setAttribute(\"target\", \"_blank\");\n a.innerHTML = reposData[i].name;\n\n nameDiv.appendChild(a);\n nameDiv.setAttribute(\"class\", \"repoName\");\n\n var logoDiv = document.createElement(\"div\");\n var node2 = document.createTextNode(reposData[i].stargazers_count);\n var img = document.createElement(\"img\");\n img.setAttribute(\"class\", \"starPic\");\n img.setAttribute(\"src\", \"../media/star2.png\");\n logoDiv.appendChild(node2);\n logoDiv.appendChild(img);\n logoDiv.setAttribute(\"class\", \"repoIcons\");\n\n var node3 = document.createTextNode(reposData[i].forks_count);\n var img = document.createElement(\"img\");\n img.setAttribute(\"class\", \"forkPic\");\n img.setAttribute(\"src\", \"../media/gitFork.svg\");\n img.setAttribute(\"alt\", \"forkPic\");\n logoDiv.appendChild(node3);\n logoDiv.appendChild(img);\n logoDiv.setAttribute(\"class\", \"repoIcons\");\n\n containerDiv.appendChild(nameDiv);\n containerDiv.appendChild(logoDiv);\n document.getElementById(\"reposName\").appendChild(containerDiv);\n containerDiv.setAttribute(\"class\", \"repo flex flexBetween\");\n\n endLoader();\n }\n }\n}",
"function repoFetch(){\n\t\t$('#repo-fetch').on('click', function(e) {\n\t\t\te.preventDefault();\n\n\t\t\t$.ajax({\n\t\t\t\t\turl: 'https://api.github.com/users/alex-b-ly/repos',\n\t\t\t\t\ttype: 'GET',\n\t\t\t\t\tsuccess: function(repo){\n\t\t\t\t\t\tfor(var i=0; i<repo.length; i++){\n\t\t\t\t\t\t\tvar repoName = repoNameBuilder(repo[i]);\n\t\t\t\t\t\t\t$('.repo-list').append(repoName);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t},\n\t\t\t\t\terror: function(jqXHR, textStatus, errorThrown){\n\t\t\t\t\t\talert('Not available presently.');\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tfunction repoNameBuilder(repoList){\n\t\t\t\t\tvar repoCreate = $('<a>');\n\t\t\t\t\tvar repoCommits = repoList.url += \"/commits\";\n\t\t\t\t\trepoCreate.attr('href', repoCommits);\n\t\t\t\t\trepoCreate.addClass('col-xs-12').addClass('text-center').addClass('repo-name');\n\t\t\t\t\trepoCreate.text(repoList.name);\n\n\t\t\t\t\treturn repoCreate;\n\t\t\t\t}\t\n\n\t\t\t$(this).fadeOut(500, function() {\n\t\t\t\t$('.repo-title').fadeIn(800);\n\t\t\t\t$('.repo-instructions').fadeIn(800);\t\t\t\n\t\t\t\t$('.repo-list').fadeIn(1200);\n\t\t\t});\n\t\t});\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Address object constructor. Constructor parameters: arg string representation or another address object Members: address IPv6 address (8 16 bit numbers) null, if invalid prefix prefix length in bits type 4 for IPv4, 6 for IPv6, 0 for invalid | function Address(arg) {
this.clear();
if (typeof arg == "string") {
this.fromString(arg);
} else if (typeof arg == "object" && arg.constructor.name == "Address") {
this.address = arg.address.slice();
this.prefix = arg.prefix;
this.type = arg.type;
} else {
throw "constructor not implemented";
}
} | [
"static fromString(str) {\n if (!(0, account_1.isValidAddress)(str)) {\n throw new Error('Invalid address');\n }\n return new Address((0, bytes_1.toBuffer)(str));\n }",
"function expandIPv6Address(address) {\n var fullAddress = \"\";\n var expandedAddress = \"\";\n var validGroupCount = 8;\n var validGroupSize = 4;\n\n var ipv4 = \"\";\n var extractIpv4 = /([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})/;\n var validateIpv4 = /((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})/;\n\n // look for embedded ipv4\n if(validateIpv4.test(address))\n {\n groups = address.match(extractIpv4);\n for(var i=1; i<groups.length; i++)\n {\n ipv4 += (\"00\" + (parseInt(groups[i], 10).toString(16)) ).slice(-2) + ( i==2 ? \":\" : \"\" );\n }\n address = address.replace(extractIpv4, ipv4);\n }\n\n if(address.indexOf(\"::\") == -1) // All eight groups are present.\n fullAddress = address;\n else // Consecutive groups of zeroes have been collapsed with \"::\".\n {\n var sides = address.split(\"::\");\n var groupsPresent = 0;\n for(var i=0; i<sides.length; i++)\n {\n groupsPresent += sides[i].split(\":\").length;\n }\n fullAddress += sides[0] + \":\";\n for(var i=0; i<validGroupCount-groupsPresent; i++)\n {\n fullAddress += \"0000:\";\n }\n fullAddress += sides[1];\n }\n var groups = fullAddress.split(\":\");\n for(var i=0; i<validGroupCount; i++)\n {\n while(groups[i].length < validGroupSize)\n {\n groups[i] = \"0\" + groups[i];\n }\n expandedAddress += (i!=validGroupCount-1) ? groups[i] + \":\" : groups[i];\n }\n return expandedAddress;\n}",
"static parseAddress(addressStr) {\n const [channelAddr, msgId] = addressStr.split(\":\");\n return new node_1.Address(node_1.ChannelAddress.parse(channelAddr), node_1.MsgId.parse(msgId));\n }",
"function ipv6WithMask (address, required) {\n var reg = /^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\\b((25[0-5])|(1\\d{2})|(2[0-4]\\d)|(\\d{1,2}))\\b)\\.){3}(\\b((25[0-5])|(1\\d{2})|(2[0-4]\\d)|(\\d{1,2}))\\b))|(([0-9A-Fa-f]{1,4}:){0,5}:((\\b((25[0-5])|(1\\d{2})|(2[0-4]\\d)|(\\d{1,2}))\\b)\\.){3}(\\b((25[0-5])|(1\\d{2})|(2[0-4]\\d)|(\\d{1,2}))\\b))|(::([0-9A-Fa-f]{1,4}:){0,5}((\\b((25[0-5])|(1\\d{2})|(2[0-4]\\d)|(\\d{1,2}))\\b)\\.){3}(\\b((25[0-5])|(1\\d{2})|(2[0-4]\\d)|(\\d{1,2}))\\b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))$/;\n if (address.indexOf('/') != -1) {\n var addressList = address.split('/');\n var ip = addressList[0];\n var len = parseInt(addressList[1]);\n return addressList.length == 2 && (len >= 0 && len <= 128) && reg.test(ip);\n }\n return required ? false : reg.test(address);\n}",
"function normalizeIpV6Address(str) {\n\tvar arr = str.split(\"/\");\n\tvar ipv6Str = trim(arr[0]);\n\n\tvar prefixStr = \"\";\n\tif (arr.length == 2)\n\t\tprefixStr = trim(arr[1]);\n\n\tvar doubleColonSplitArr = ipv6Str.split(\"::\");\n\tvar retIpV6Str = \"\";\n\tif (doubleColonSplitArr.length > 1) {\n\t\t// if the length is more than 1 it means :: was there\n\t\t//\n\t\t// Since there can only be a single instance of :: we assume a pre and post str.\n\t\tvar preDoubleColonStr = doubleColonSplitArr[0];\n\t\tvar postDoubleColonStr = doubleColonSplitArr[1];\n\n\t\tvar preDoubleColonSingleColonCount = numOccurrencesInStr(preDoubleColonStr, \":\");\n\t\tvar postDoubleColonSingleColonCount = numOccurrencesInStr(postDoubleColonStr, \":\");\n\n\t\tvar numPreFields;\n\t\tif (preDoubleColonStr.length > 0)\n\t\t\tnumPreFields = preDoubleColonSingleColonCount + 1; // if there are 3 : it means a:b:c:d i.e. 4 fields\n\t\telse\n\t\t\tnumPreFields = 0;\n\n\t\tvar numPostFields;\n\t\tif (postDoubleColonStr.length > 0)\n\t\t\tnumPostFields = postDoubleColonSingleColonCount + 1;\n\t\telse\n\t\t\tnumPostFields = 0;\n\n\t\tvar numFieldsToFill = 8 - (numPreFields+numPostFields);\n\t\tvar strToFill = \"\";\n\t\tif (numFieldsToFill > 0) {\n\t\t\t// it should always be > 0, if there were eight fields then there would not be a :: and so we would not be here.\n\t\t\t// this is just an extra check\n\t\t\tfor(var i=0; i<numFieldsToFill; i++) {\n\t\t\t\tif (i > 0)\n\t\t\t\t\tstrToFill += \":\";\n\t\t\t\tstrToFill += \"0\";\n\t\t\t}\n\t\t}\n\n\t\tif (preDoubleColonStr.length > 0) {\n\t\t\tretIpV6Str += preDoubleColonStr;\n\t\t}\n\n\t\tif (strToFill.length > 0) {\n\t\t\tif (retIpV6Str.length > 0)\n\t\t\t\tretIpV6Str += \":\";\n\n\t\t\tretIpV6Str += strToFill;\n\t\t}\n\n\t\tif (postDoubleColonStr.length > 0) {\n\t\t\tif (retIpV6Str.length > 0)\n\t\t\t\tretIpV6Str += \":\";\n\n\t\t\tretIpV6Str += postDoubleColonStr;\n\t\t}\n\n\t} else {\n\t\t// no ::, not in compressed form and so we just return the original string\n\t\tretIpV6Str = ipv6Str;\n\t}\n\n\tif (prefixStr.length > 0)\n\t\treturn retIpV6Str + \"/\" + prefixStr;\n\telse\n\t\treturn retIpV6Str;\n\n}",
"static fromTrytes(address) {\r\n if (!objectHelper_1.ObjectHelper.isType(address, trytes_1.Trytes)) {\r\n throw new dataError_1.DataError(\"The address should be a valid Trytes object\");\r\n }\r\n const trytesString = address.toString();\r\n if (trytesString.length !== Address.LENGTH && trytesString.length !== Address.LENGTH_WITH_CHECKSUM) {\r\n throw new dataError_1.DataError(`The address should either be ${Address.LENGTH} or ${Address.LENGTH_WITH_CHECKSUM} characters in length`, { length: trytesString.length });\r\n }\r\n const addressTrytes = trytesString.substr(0, Address.LENGTH);\r\n let checksumTrytes;\r\n if (trytesString.length === Address.LENGTH_WITH_CHECKSUM) {\r\n checksumTrytes = trytesString.substr(Address.LENGTH);\r\n }\r\n return new Address(addressTrytes, checksumTrytes);\r\n }",
"function IPAddress$getValidIPv6(address) {\n debug$assertValidString(address);\n // string doesn't match the most general REGEX for IPv6 addresses\n if (!isString(address) || !address.match(IPv6_REGEX)) {\n return;\n }\n\n // deal with address that has the last two hextets in IPv4 form\n var parts = address.split(':');\n if (parts[parts.length - 1].indexOf('.') !== -1) {\n var converted = IPAddress$dottedQuadNotation(parts[parts.length - 1]);\n var tmp = parts.pop();\n parts.push(converted[0]);\n parts.push(converted[1]);\n address = parts.join(':');\n }\n\n // deal with compressed notation for '0000' hextets\n // there can be only one occurence of '::'\n var splitDoubleColon = address.split('::');\n if (splitDoubleColon.length > 2 ||\n (splitDoubleColon.length === 1 && parts.length !== 8)) {\n return;\n }\n\n var ipArr;\n // expand compressed hextets\n if (splitDoubleColon.length > 1) {\n ipArr = IPAddress$expandZeros(splitDoubleColon);\n } else {\n ipArr = parts;\n }\n\n // not enough hextets\n var numHextets = ipArr.length;\n if (numHextets !== 8) {\n return;\n }\n\n // values should be withing [0, 65535]\n while (numHextets--) {\n var hexVal = parseInt(ipArr[numHextets], 16);\n if (!isUInt(hexVal, 0, MAX_UINT16)) {\n return;\n }\n }\n\n // address was fully expanded to the colon notation\n return ipArr.join(':');\n}",
"function Address(addressIn, maskIn) {\n //The Address object will hold all the info abput the input address\n\n //First step is to test the inputs and throw an error if they are not valid\n isAddressValid(addressIn);\n this.decimalAddress = addressIn\n this.binaryAddress = stringToBinary(addressIn)\n\n isMaskValid(addressIn, maskIn);\n this.binaryMask = stringToBinary(maskIn)\n this.cidrMask = convertDecimalMaskToCIDR(maskIn)\n\n this.networkClass = getNetworkInfo(this.decimalAddress, this.cidrMask).networkClass\n this.publicOrPrivate = getNetworkInfo(this.decimalAddress, this.cidrMask).publicOrPrivate\n this.nshBits = getSignificantBits(this.decimalAddress, this.cidrMask)\n\n this.subnetMagicNumber = getSubnetMagicNumber(this.cidrMask)\n this.networks = generateSubnetIDs(this.decimalAddress, this.cidrMask)\n this.network = getSubnetOfAddress(this.decimalAddress, this.cidrMask).network\n this.addressType = getSubnetOfAddress(this.decimalAddress, this.cidrMask).addressType\n}",
"function Addr() {\n this._fields = [0, 0, 0, 0, 0, 0, 0, 0];\n this._attrs = {};\n}",
"function make_address(request, prefix) {\n var addr = request.slot(prefix+\"_street\");\n if (request.slot(prefix+\"_city\"))\n addr += \" \" + request.slot(prefix+\"_city\");\n if (request.slot(prefix+\"_state\"))\n addr += \" \" + request.slot(prefix+\"_state\");\n return addr;\n}",
"function createAddress(pubKey, prefix) {\r\n\t// Create buffer\r\n\tif(pubKey.length !=20) {\r\n\t\t// 2 - Perform SHA-256 hashing on the public key \r\n\t\tvar pubKeyHash256 = bitcoinjs.crypto.sha256(pubKey);\r\n\t\r\n\t\t// 3 - Perform RIPEMD-160 hashing on the result of SHA-256 \r\n\t\tvar pubkeyRipemd160 = bitcoinjs.crypto.ripemd160(pubKeyHash256);\r\n\t}\r\n\telse {\r\n\t\tvar pubkeyRipemd160 = pubKey\r\n\t}\r\n\t// 4 - Add version byte in front of RIPEMD-160 hash\r\n\tvar mainNetParam=new Buffer ([prefix]);\r\n\tvar pubkeyAddParam = Buffer.concat([mainNetParam, pubkeyRipemd160]);\r\n\t\r\n\t// 5-8 Base58Check encoding\r\n\tvar address= bs58check.encode(pubkeyAddParam);\r\n\treturn address;\r\n}",
"function isValidIPv6Address(ipStr) {\n\t var validateIPv4Address = __webpack_require__(323).validateIPv4Address\n\t\n\t // We need to have at least one ':'\n\t if (ipStr.indexOf(':') == -1) {\n\t return false\n\t }\n\t\n\t // We can only have one '::' shortener\n\t if (String_count(ipStr, '::') > 1) {\n\t return false\n\t }\n\t\n\t // '::' should be encompassed by start, digits or end\n\t if (ipStr.indexOf(':::') != -1) {\n\t return false\n\t }\n\t\n\t // A single colon can neither start nor end an address\n\t if ((ipStr.charAt(0) == ':' && ipStr.charAt(1) != ':') ||\n\t (ipStr.charAt(ipStr.length - 1) == ':' &&\n\t ipStr.charAt(ipStr.length - 2) != ':')) {\n\t return false\n\t }\n\t\n\t // We can never have more than 7 ':' (1::2:3:4:5:6:7:8 is invalid)\n\t if (String_count(ipStr, ':') > 7) {\n\t return false\n\t }\n\t\n\t // If we have no concatenation, we need to have 8 fields with 7 ':'\n\t if (ipStr.indexOf('::') == -1 && String_count(ipStr, ':') != 7) {\n\t // We might have an IPv4 mapped address\n\t if (String_count(ipStr, '.') != 3) {\n\t return false\n\t }\n\t }\n\t\n\t ipStr = _explodeShorthandIPstring(ipStr)\n\t\n\t // Now that we have that all squared away, let's check that each of the\n\t // hextets are between 0x0 and 0xFFFF.\n\t var hextets = ipStr.split(':')\n\t for (var i = 0, l = hextets.length, hextet; i < l; i++) {\n\t hextet = hextets[i]\n\t if (String_count(hextet, '.') == 3) {\n\t // If we have an IPv4 mapped address, the IPv4 portion has to\n\t // be at the end of the IPv6 portion.\n\t if (ipStr.split(':').pop() != hextet) {\n\t return false\n\t }\n\t try {\n\t validateIPv4Address(hextet)\n\t }\n\t catch (e) {\n\t if (!(e instanceof ValidationError)) {\n\t throw e\n\t }\n\t return false\n\t }\n\t }\n\t else {\n\t if (!hexRE.test(hextet)) {\n\t return false\n\t }\n\t var intValue = parseInt(hextet, 16)\n\t if (isNaN(intValue) || intValue < 0x0 || intValue > 0xFFFF) {\n\t return false\n\t }\n\t }\n\t }\n\t\n\t return true\n\t}",
"function parseAddress(str, hn)\n{\n if(typeof str !== \"string\")\n {\n warn(\"invalid address\", str);\n return {};\n }\n var parts = str.split(\",\");\n if(!dhash.isSHA1(parts[0]))\n {\n warn(\"invalid address hashname part\", str);\n return {};\n }\n var ret = hn || {}; // update existing or create new\n ret.hashname = parts[0];\n ret.ip = parts[1];\n ret.port = parseInt(parts[2]);\n ret.address = str;\n ret.hash = new dhash.Hash(null, parts[0]);\n return ret;\n}",
"function BvmAddr(value) {\n _classCallCheck(this, BvmAddr);\n\n _defineProperty(this, \"_bn\", void 0);\n\n if (typeof value === 'string') {\n // hexadecimal number\n if (value.startsWith('0x')) {\n this._bn = new BN$1(value.substring(2), 16);\n } else {\n // assume base 58 encoding by default\n var newstr = transform(value);\n this._bn = new BN$1(bs58.decode(newstr));\n }\n } else {\n this._bn = new BN$1(value);\n }\n\n if (this._bn.byteLength() > 32) {\n throw new Error(\"Invalid bvm address input\");\n }\n }",
"function prefixToNetMask(prefixLen) {\n var prefix = Math.pow(2,prefixLen) - 1;\n var binaryString = prefix.toString(2);\n for(var i=binaryString.length;i<32;i++) {\n binaryString += '0';\n }\n return v4.Address.fromHex(parseInt(binaryString,2).toString(16)).address;\n}",
"function isLegalIPv6Address(aHostName) {\n if (!aHostName) {\n return null;\n }\n\n // Break the IP address down into individual components.\n let ipComponents = aHostName.toLowerCase().split(\":\");\n\n // Make sure there are at least 3 components.\n if (ipComponents.length < 3) {\n return null;\n }\n\n let ipLength = ipComponents.length - 1;\n\n // Take care if the last part is written in decimal using dots as separators.\n let lastPart = isLegalIPv4Address(ipComponents[ipLength], false);\n if (lastPart) {\n let lastPartComponents = lastPart.split(\".\");\n // Convert it into standard IPv6 components.\n ipComponents[ipLength] = (\n (lastPartComponents[0] << 8) |\n lastPartComponents[1]\n ).toString(16);\n ipComponents[ipLength + 1] = (\n (lastPartComponents[2] << 8) |\n lastPartComponents[3]\n ).toString(16);\n }\n\n // Make sure that there is only one empty component.\n let emptyIndex;\n for (let i = 1; i < ipComponents.length - 1; i++) {\n if (ipComponents[i] == \"\") {\n // If we already found an empty component return null.\n if (emptyIndex) {\n return null;\n }\n\n emptyIndex = i;\n }\n }\n\n // If we found an empty component, extend it.\n if (emptyIndex) {\n ipComponents[emptyIndex] = 0;\n\n // Add components so we have a total of 8.\n for (let count = ipComponents.length; count < 8; count++) {\n ipComponents.splice(emptyIndex, 0, 0);\n }\n }\n\n // Make sure there are 8 components.\n if (ipComponents.length != 8) {\n return null;\n }\n\n // Format all components to 4 character hex value.\n for (let i = 0; i < ipComponents.length; i++) {\n if (ipComponents[i] == \"\") {\n ipComponents[i] = 0;\n }\n\n // Make sure the component is a number and it isn't larger than 0xffff.\n if (/^[0-9a-f]{1,4}$/.test(ipComponents[i])) {\n ipComponents[i] = parseInt(ipComponents[i], 16);\n if (isNaN(ipComponents[i]) || ipComponents[i] > 0xffff) {\n return null;\n }\n } else {\n return null;\n }\n\n // Pad the component with 0:s.\n ipComponents[i] = (\"0000\" + ipComponents[i].toString(16)).substr(-4);\n }\n\n // TODO: support Zone indices in Link-local addresses? Currently they are rejected.\n // http://en.wikipedia.org/wiki/IPv6_address#Link-local_addresses_and_zone_indices\n\n let hostName = ipComponents.join(\":\");\n // Treat 0000:0000:0000:0000:0000:0000:0000:0000 as an invalid IPv6 address.\n return hostName != \"0000:0000:0000:0000:0000:0000:0000:0000\"\n ? hostName\n : null;\n}",
"function best(address) {\n // based on:\n // Javascript to test an IPv6 address for proper format, and to\n // present the \"best text representation\" according to IETF Draft RFC at\n // http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04\n // 8 Feb 2010 Rich Brown, Dartware, LLC\n // Please feel free to use this code as long as you provide a link to\n // http://www.intermapper.com\n // http://intermapper.com/support/tools/IPV6-Validator.aspx\n // http://download.dartware.com/thirdparty/ipv6validator.js\n\n var _address = address.toLowerCase();\n var segments = _address.split(':');\n var length = segments.length;\n var total = 8;\n\n // trim colons (:: or ::a:b:c… or …a:b:c::)\n if (segments[0] === '' && segments[1] === '' && segments[2] === '') {\n // must have been ::\n // remove first two items\n segments.shift();\n segments.shift();\n } else if (segments[0] === '' && segments[1] === '') {\n // must have been ::xxxx\n // remove the first item\n segments.shift();\n } else if (segments[length - 1] === '' && segments[length - 2] === '') {\n // must have been xxxx::\n segments.pop();\n }\n\n length = segments.length;\n\n // adjust total segments for IPv4 trailer\n if (segments[length - 1].indexOf('.') !== -1) {\n // found a \".\" which means IPv4\n total = 7;\n }\n\n // fill empty segments them with \"0000\"\n var pos;\n for (pos = 0; pos < length; pos++) {\n if (segments[pos] === '') {\n break;\n }\n }\n\n if (pos < total) {\n segments.splice(pos, 1, '0000');\n while (segments.length < total) {\n segments.splice(pos, 0, '0000');\n }\n\n length = segments.length;\n }\n\n // strip leading zeros\n var _segments;\n for (var i = 0; i < total; i++) {\n _segments = segments[i].split(\"\");\n for (var j = 0; j < 3 ; j++) {\n if (_segments[0] === '0' && _segments.length > 1) {\n _segments.splice(0,1);\n } else {\n break;\n }\n }\n\n segments[i] = _segments.join(\"\");\n }\n\n // find longest sequence of zeroes and coalesce them into one segment\n var best = -1;\n var _best = 0;\n var _current = 0;\n var current = -1;\n var inzeroes = false;\n // i; already declared\n\n for (i = 0; i < total; i++) {\n if (inzeroes) {\n if (segments[i] === '0') {\n _current += 1;\n } else {\n inzeroes = false;\n if (_current > _best) {\n best = current;\n _best = _current;\n }\n }\n } else {\n if (segments[i] == '0') {\n inzeroes = true;\n current = i;\n _current = 1;\n }\n }\n }\n\n if (_current > _best) {\n best = current;\n _best = _current;\n }\n\n if (_best > 1) {\n segments.splice(best, _best, \"\");\n }\n\n length = segments.length;\n\n // assemble remaining segments\n var result = '';\n if (segments[0] === '') {\n beststr = \":\";\n }\n\n for (i = 0; i < length; i++) {\n result += segments[i];\n if (i === length - 1) {\n break;\n }\n\n result += ':';\n }\n\n if (segments[length - 1] === '') {\n result += \":\";\n }\n\n return result;\n}",
"function isAddress(str) {\n\treturn str.match(/^[a-f0-9]{76}$/) !== null;\n}",
"function formatAddress(acc) {\n return T_Address.canonicalize(acc); // TODO: typing\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cancel or submit form in dialog | function cancel(form) {
$mdDialog.cancel();
} | [
"function cancelHAForm() {\n setForm();\n hideHAForm();\n}",
"function cancel(form) {\n $mdDialog.cancel();\n }",
"function submitCancelHandler()\n{\n\tvar bGoback=true;\n\t\n\tif(defined(CONTENTS.List.getCancelConfirmMessage))\n\t\tif(CONTENTS.List.contentsChanged())\n \t\t\tif(!confirmDialog(CONTENTS.List.getCancelConfirmMessage()))\n \t\t\t\tbGoback=false;\n\tif(bGoback)\n \t\ttop.goBack();\t\t\n}",
"function cancel() {\n modalInstance.close();\n }",
"function cancelForm(e) {\n e.preventDefault();\n return false;\n}",
"cancelForm() {\n const { id } = this.state;\n const body = { id, abort: true };\n this.submitForm(body);\n }",
"function onCancel(){\n\tView.getOpenerView().closeDialog();\t\t\n}",
"function cancel_submit(win) {\n\t\twin.close( );\n\t}",
"function cancel_submit(win)\n{\n win.close();\n}",
"function evhan_cancel_button(ev) {\n ev.preventDefault();\n if (!is_open)\n return false;\n\n if (confirming) {\n confirming = false;\n set_caption(null, false);\n var fel = $('#'+dialog_el_id+'_infield');\n fel.prop('disabled', false);\n var butel = $('#'+dialog_el_id+'_accept');\n butel.prop('disabled', false);\n butel.text('Save');\n return false;\n }\n\n var callback = dialog_callback;\n //GlkOte.log('### cancel');\n dialog_close();\n if (callback)\n callback(null);\n\n return false;\n}",
"function handleCancel() {\n console.log(\"Handling cancel overlay...\");\n form.empty();\n closeOverlay();\n }",
"async submitCancel () {\n // this will be the page.cancelSubmit button (evt.currentTarget)\n const page = this.page\n const order = this.order\n const req = {\n orderID: order.id,\n pw: page.cancelPass.value\n }\n page.cancelPass.value = ''\n const loaded = app().loading(page.cancelForm)\n const res = await postJSON('/api/cancel', req)\n loaded()\n if (!app().checkResponse(res)) return\n page.status.textContent = intl.prep(intl.ID_CANCELING)\n Doc.hide(page.forms)\n order.cancelling = true\n }",
"function updateCancel() {\n transaccion.resetForm();\n }",
"function btnCancel_onClick() {\n\t\t\tSP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.Cancel);\n\t\t}",
"function cancel() {\n logger.warning('Confirm Modal: Cancel/Dismiss');\n $modalInstance.dismiss();\n }",
"function AjaxDialogCancel(event, ui) {\n $(this).dialog(\"close\");\n}",
"function cancelarform()\n{\n\tlimpiar();\n\tmostrarform(false);\n}",
"function cancelNewEvent() {\n $('#AddEventDetails').dialog(\"close\");\n clearNewEventForm();\n}",
"async submitCancel () {\n // this will be the page.cancelSubmit button (evt.currentTarget)\n const page = this.page\n const order = this.order\n const req = {\n orderID: order.id,\n pw: page.cancelPass.value\n }\n page.cancelPass.value = ''\n app.loading(page.cancelForm)\n var res = await postJSON('/api/cancel', req)\n app.loaded()\n if (!app.checkResponse(res)) return\n page.status.textContent = 'cancelling'\n Doc.hide(page.forms)\n order.cancelling = true\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prevents the user from copying or pasting the text in the Fnn Textboxes This is done so that they have to physically type the fnn in twice. They can't copy/paste it | function FnnTextboxKeyHandler(objEvent)
{
// keyCode 37 is the left key
if (objEvent.shiftKey && objEvent.keyCode == 37)
{
// The user is trying to select text by pressing shift-left
// Jog the cursor left one character
objEvent.target.selectionEnd = objEvent.target.selectionStart = objEvent.target.selectionStart -1;
objEvent.preventDefault();
}
else if (objEvent.ctrlKey || objEvent.keyCode == 45)
{
objEvent.preventDefault();
}
else
{
return true;
}
} | [
"function fnNoQuotes(obj)\n{\n\tobj.onpaste=function () {event.returnValue=false; obj.value=trim_quotes(window.clipboardData.getData('Text'));};\n\tobj.onkeypress=function () {return filtrar_teclas(event,\"'\\\"\",true);};\n}",
"function preventNonNumPaste(e,textboxid) {\r\n\r\n\te.preventDefault();\r\n\tvar pastedText = '';\r\n\r\n// Internet Explorer\r\n\tif (window.clipboardData && window.clipboardData.getData) {\r\n\t\tpastedText = window.clipboardData.getData('Text');\r\n\t}\r\n\r\n//Other Browsers\r\n\telse if (e.clipboardData && e.clipboardData.getData) {\r\n\t\tpastedText = e.clipboardData.getData('text/plain');\r\n\t}\r\n\r\n//Regex for replacing special characters and alphabets with nothing\r\n\tvar regexCutStr;\r\n\tif (textboxid == \"phone\"){\r\n\t\tregexCutStr = pastedText.replace(/[^0-9]+/g, '');\r\n\t} else if(textboxid == \"dob\"){\r\n\t\tregexCutStr = pastedText.replace(/[^0-9\\/]+/g, '');\r\n\t}\r\n//Length of textbox\r\n\tstrLength = document.getElementById(textboxid).value.length;\r\n\r\n//To be pasted string is cut to remaining length\r\n\tremainingLength = 10 - strLength;\r\n\tvar contentCutToTen = regexCutStr.substring(0, remainingLength);\r\n\tdocument.getElementById(textboxid).value += contentCutToTen;\r\n\r\n}",
"function NonAddableFieldTextChanged(e) {\n\tchangeValueOfNonAddableField(userDataInArrays, clickedTextField.id, clickedTextField.text);\t// editProfileHelper.js\n}",
"function preventNonAlphabetPaste(e,textboxid) {\r\n\r\n\te.preventDefault();\r\n\tvar pastedText = '';\r\n\r\n// Internet Explorer\r\n\tif (window.clipboardData && window.clipboardData.getData) {\r\n\t\tpastedText = window.clipboardData.getData('Text');\r\n\t}\r\n\r\n//Other Browsers\r\n\telse if (e.clipboardData && e.clipboardData.getData) {\r\n\t\tpastedText = e.clipboardData.getData('text/plain');\r\n\t}\r\n\r\n//Regex for replacing special characters and alphabets with nothing \r\n\tvar regexCutStr = pastedText.replace(/[^A-Za-z\\.]+/g, '');\r\n\r\n//Length of textbox\r\n\tstrLength = document.getElementById(textboxid).value.length;\r\n\r\n//To be pasted string is cut to remaining length\r\n\tremainingLength = 15 - strLength;\r\n\tvar contentCutToFifteen = regexCutStr.substring(0, remainingLength);\r\n\tdocument.getElementById(textboxid).value += contentCutToFifteen;\r\n\r\n\tvar str = document.getElementById(textboxid).value;\r\n//Running the function capitalize with the value to be replaced\r\n\tcapitalize(textboxid,str);\r\n\r\n}",
"function restrictInput(textarea) {\n textarea.on('input', function() {\n var c = this.selectionStart,\n r = /[^a-z0-9'.,- ]/gi,\n v = $(this).val();\n if(r.test(v)) {\n $(this).val(v.replace(r, ''));\n c--;\n }\n this.setSelectionRange(c, c);\n });\n}",
"function allowMessages() {\n that.textInput.disabled = false;\n // restore original text\n if (savedTextValue !== null) {\n that.textInput.value = savedTextValue;\n savedTextValue = null;\n }\n }",
"function TextAreaOnly(e)\n{\n var unicode = e.charCode? e.charCode : e.keyCode\n // allow backspace 8, tab 9, enter, space 32, ! 33, end 35, home 36, left arrow 37, ampersand 38, single quote 39, right arrow 39,\n // ( 40, ) 41, comma 44, dash 45, full stop 46, del 46, / 47, colon 58, semicolon 59, question mark 63, underscore 95\n var charOK = [8,9,13,32,33,35,36,37,38,39,40,41,44,45,46,47,58,59,63,95];\n var aok = $.inArray(unicode, charOK);\n // not an approved char & also not numbers, capital & small letters\n if (aok<0) // only test further if not an approved char\n if (unicode<48 || (unicode>57 && unicode<65) || (unicode>90 && unicode<97) || unicode>122)\n return false; // disable key press\n}",
"function handlePaste(field, evt)\r\n{\r\n\tif (isIE) {\r\n\t\tevent.returnValue = false;\r\n\r\n\t\tvar text = window.clipboardData.getData(\"Text\");\r\n\t\tfield.value = importPartialToMask(field, text);\r\n\t}\r\n}",
"function disablePaste(id){\r$('#'+id).bind(\"cut copy paste\",function(e) {\r e.preventDefault();\r });\r}",
"function warnInvalid (theField, desField, s, f)\r\n{ if (f) theField.focus();\r\n if (theField.type == \"text\") {\r\n theField.select()\r\n }\r\n if (desField.length == 0) {\r\n alert(pPrompt + s)\r\n statBar(pPrompt + s)\r\n }else{\r\n alert(pPrompt + s + '\\n\\nPara el campo \"' + desField + '\"')\r\n statBar(pPrompt + s + ' Para el campo \"' + desField + '\"')\r\n }\r\n return false\r\n}",
"function UnbInsertText(what, replace)\r\n{\r\n\tif (replace == null) replace = 0;\r\n\t\r\n// changes for pragmaMx\r\n\tif (openerdoc) {\r\n\t\tcurdoc = openerdoc;\r\n\t} else {\r\n\t\tcurdoc = document;\r\n\t}\r\n// end changes for pragmaMx\r\n\r\n\tif (textbox.createTextRange)\r\n\t{\r\n\t\ttextbox.focus();\r\n\t\tcurdoc.selection.createRange().duplicate().text = what;\r\n\t\ttextbox.focus();\r\n\t}\r\n\telse if (textbox.selectionStart >= 0)\r\n\t{\r\n\t\t// Mozilla without selected text\r\n\t\tvar start_selection = textbox.selectionStart;\r\n\t\tvar end_selection = textbox.selectionEnd;\r\n\t\tvar scroll_top = textbox.scrollTop;\r\n\t\tvar scroll_left = textbox.scrollLeft;\r\n\r\n\t\t// fetch everything from start of text area to selection start\r\n\t\tvar start = textbox.value.substring(0, start_selection - replace);\r\n\t\t// fetch everything from end of selection to end of text area\r\n\t\tvar end = textbox.value.substring(end_selection, textbox.textLength);\r\n\r\n\t\ttextbox.value = start + what + end;\r\n\r\n\t\ttextbox.selectionStart = textbox.selectionEnd = start_selection - replace + what.length;\r\n\t\ttextbox.focus();\r\n\t\ttextbox.scrollTop = scroll_top;\r\n\t\ttextbox.scrollLeft = scroll_left;\r\n\t}\r\n\telse\r\n\t{\r\n\t\ttextbox.value += what;\r\n\t\ttextbox.focus();\r\n\t}\r\n// changes for pragmaMx\r\n\tif (openerdoc) {\r\n\t\twindow.focus();\r\n\t}\r\n// end changes for pragmaMx\r\n}",
"function inputWatermarks() {\n\t$('input, textarea').bind('keydown, keyup', function() {\n\t\tif($(this).val() != '') {\n\t\t\t$(this).prev('label').hide(0);\n\t\t} else {\n\t\t\t$(this).prev('label').show(0);\n\t\t}\n\t});\n}",
"skipAlways(e) {\n const kdCode = this.kdCode;\n const which = this.which;\n const ctrlKey = this.ctrlKey;\n const cmdKey = this.cmdKey;\n\n // catch the ctrl up on ctrl-v\n const shiftKey = this.shiftKey;\n if (((ctrlKey || cmdKey) && e.type === 'keyup' && !isUndefined(this.valuePartsBeforePaste)) || (shiftKey && kdCode === keyCode.Insert)) {\n this.checkPaste();\n return false;\n }\n\n // skip Fx keys, windows keys, other special keys\n if ((kdCode >= keyCode.F1 && kdCode <= keyCode.F12) ||\n (kdCode >= keyCode.Windows && kdCode <= keyCode.RightClick) ||\n (kdCode >= keyCode.Tab && kdCode < keyCode.Space) ||\n (kdCode < keyCode.Backspace &&\n (which === 0 || which === kdCode)) ||\n kdCode === keyCode.NumLock ||\n kdCode === keyCode.ScrollLock ||\n kdCode === keyCode.Insert ||\n kdCode === keyCode.Command) {\n return true;\n }\n\n // if select all (a)\n if ((ctrlKey || cmdKey) && kdCode === keyCode.a) {\n if (this.settings.sNumber) {\n e.preventDefault();\n const valueLen = this.that.value.length;\n const aSignLen = this.settings.aSign.length;\n const negLen = (!contains(this.that.value, '-'))?0:1;\n const aSuffixLen = this.settings.aSuffix.length;\n const pSign = this.settings.pSign;\n const pNeg = this.settings.pNeg;\n\n let start;\n if (pSign === 's') {\n start = 0;\n } else {\n start = (pNeg === 'l' && negLen === 1 && aSignLen > 0)?aSignLen + 1:aSignLen;\n }\n\n let end;\n if (pSign === 'p') {\n end = valueLen - aSuffixLen;\n } else {\n switch (pNeg) {\n case 'l':\n end = valueLen - (aSuffixLen + aSignLen);\n break;\n case 'r':\n end = (aSignLen > 0)?valueLen - (aSignLen + negLen + aSuffixLen):valueLen - (aSignLen + aSuffixLen);\n break;\n default :\n end = valueLen - (aSignLen + aSuffixLen);\n }\n }\n\n setElementSelection(this.that, start, end);\n }\n return true;\n }\n\n // if copy (c)\n if ((ctrlKey || cmdKey) && (kdCode === keyCode.c || kdCode === keyCode.v || kdCode === keyCode.x)) {\n if (e.type === 'keydown') {\n this.expandSelectionOnSign();\n }\n\n // try to prevent wrong paste\n if (kdCode === keyCode.v || kdCode === keyCode.Insert) {\n if (e.type === 'keydown' || e.type === 'keypress') {\n if (isUndefined(this.valuePartsBeforePaste)) {\n this.valuePartsBeforePaste = this.getBeforeAfter();\n }\n } else {\n this.checkPaste();\n }\n }\n return e.type === 'keydown' || e.type === 'keypress' || kdCode === keyCode.c;\n }\n\n if (ctrlKey || cmdKey) {\n return true;\n }\n\n // jump over thousand separator\n if (kdCode === keyCode.LeftArrow || kdCode === keyCode.RightArrow) {\n const aSep = this.settingsClone.aSep;\n const aDec = this.settingsClone.aDec;\n const startJump = this.selection.start;\n const value = this.that.value;\n if (e.type === 'keydown' && !this.shiftKey) {\n if (kdCode === keyCode.LeftArrow && (value.charAt(startJump - 2) === aSep || value.charAt(startJump - 2) === aDec)) {\n this.setPosition(startJump - 1);\n } else if (kdCode === keyCode.RightArrow && (value.charAt(startJump + 1) === aSep || value.charAt(startJump + 1) === aDec)) {\n this.setPosition(startJump + 1);\n }\n }\n return true;\n }\n\n return kdCode >= keyCode.PageDown && kdCode <= keyCode.DownArrow;\n }",
"function cleanPaste( event ){\n\t\tif (event.clipboardData && event.clipboardData.getData) {\n\t\t\tevent.preventDefault();\n\t\t\tvar html = autoLink( event.clipboardData.getData('text/plain') );\n\t\t\tdocument.execCommand('insertHTML', false, html);\n\t\t}\n\t}",
"function preventInputEe(event) {\n if (event.which === 69 || event.which === 101) {\n event.preventDefault();\n }\n}",
"function disallowModify(obj) {\r\n var msg;\r\n var dofocus;\r\n if (arguments.length>1) { msg = arguments[1]; }\r\n if (arguments.length>2) { dofocus = arguments[2]; } else { dofocus=false; }\r\n if (getInputValue(obj) != getInputDefaultValue(obj)) {\r\n if (!isBlank(msg)) {\r\n alert(msg);\r\n }\r\n if (dofocus) {\r\n obj.select();\r\n obj.focus();\r\n }\r\n setInputValue(obj,getInputDefaultValue(obj));\r\n return true;\r\n }\r\n return false;\r\n }",
"handlePaste(event) {\n event.preventDefault();\n }",
"function acceptText(text) {\n if (typeof text === 'undefined') { text = \"\"; }\n \n globalTextEntry.style.display = \"initial\";\n globalTextEntry.value = text;\n}",
"function textAreaPlaceholder(e) {\n let code = e.keyCode || e.which;\n\n if (placeholder_toggle && /^.$/.test(e.key)) {\n placeholder_toggle = false;\n chat_text_area_placeholder.setAttribute(\"style\", \"display: none;\");\n\n } else if (!placeholder_toggle && (code == 8 || e.key == \"Backspace\") && chat_text_area.innerText.length < 2) {\n placeholder_toggle = true;\n chat_text_area_placeholder.removeAttribute(\"style\");\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
para llenar la tabla con los datos de programas | function llenar_tabla_programas(){
$.ajax({
url: 'data/programas/app.php',
type: 'post',
data: {llenar_tabla_programas:'asjkef'},
success: function (data) {
$('#tbt_programas tbody').html(data);
}
});
} | [
"function inicializar_tablas() {\n /* Inicializacion de la tabla de tipos de platillos activos\n Elementos de la tabla:\n l - length changing input control\n f - El buscador\n t - La tabla\n i - Table information summary\n p - Paginacion\n r - processing display element\n */\n $('#tplatillos-activos').DataTable({\n responsive: true, // tabla responsiva\n dom: '<\"top\">rt<\"bottom\"lp>', // ubicacion de los elementos\n language: { // Lenguaje de la tabla\n url: \"//cdn.datatables.net/plug-ins/1.10.19/i18n/Spanish.json\"\n }\n });\n\n // Inicializacion de la tabla de tipos de platillos activos\n $('#tplatillos-inactivos').DataTable({\n responsive: true, // tabla responsiva\n dom: '<\"top\">rt<\"bottom\"lp>', // ubicacion de los elementos\n language: { // Lenguaje de la tabla\n url: \"//cdn.datatables.net/plug-ins/1.10.19/i18n/Spanish.json\"\n }\n });\n}",
"function logicaPrograma() {\n crearTabla(5, 5);\n colorearCasilla(10);\n colorearTabla();\n manejadorEventos();\n}",
"function getColumnTable(tabla){\n columns = {\n \"beneficiarios\" : [\n {\"column\":\"tipoDocumento_abr\", \"label\":\"Tipo documento\"},\n {\"column\":\"numeroDocumento\", \"label\":\"Número documento\"}, \n {\"column\":\"nombre_completo\", \"label\":\"Nombre beneficiario\"},\n {\"column\":\"fechaNacimiento\", \"label\":\"Fecha nacimiento\"},\n {\"column\":\"direccion\", \"label\":\"Dirección\"},\n {\"column\":\"accion\", \"label\":\"Acción\"}\n ],\n \"beneficiarios_prod\" : [\n {\"column\":\"aplica\", \"label\":\"\"},\n {\"column\":\"tipoDocumento_abr\", \"label\":\"Tipo documento\"},\n {\"column\":\"numeroDocumento\", \"label\":\"Numero documento\"}, \n {\"column\":\"nombre_completo\", \"label\":\"Nombre beneficiario\"},\n {\"column\":\"fechaNacimiento\", \"label\":\"Fecha nacimiento\"},\n {\"column\":\"direccion\", \"label\":\"Dirección\"},\n {\"column\":\"tarifa\", \"label\":\"Tarifa mensual\", \"format\":\"miles\"}\n ],\n \"programacion\" : [\n {\"column\":\"fechahora\", \"label\":\"Fecha y hora\"},\n {\"column\":\"comando\", \"label\":\"Comando\"},\n {\"column\":\"accion\", \"label\":\"Acciones\"}\n ],\n \"1\" : [\n {\"column\":\"identificacion\", \"label\":\"Identificación\"},\n {\"column\":\"nombre\", \"label\":\"Nombre\"}, \n {\"column\":\"telefono\", \"label\":\"Teléfono\"},\n {\"column\":\"email\", \"label\":\"Correo eléctronico\"},\n {\"column\":\"direccion\", \"label\":\"Dirección\"}, \n {\"column\":\"login\", \"label\":\"Login\"}, \n {\"column\":\"rol\", \"label\":\"rol\"},\n {\"column\":\"estado\", \"label\":\"Estado\"},\n {\"column\":\"editar\", \"label\":\"Editar\"},\n {\"column\":\"activar\", \"label\":\"Activar\"},\n {\"column\":\"eliminar\", \"label\":\"Desactivar\"} \n ], \n \"2\" : [\n {\"column\":\"identificacion\", \"label\":\"Nit\"},\n {\"column\":\"nombre\", \"label\":\"Nombre\"},\n {\"column\":\"telefono\", \"label\":\"Teléfono\"},\n {\"column\":\"email\", \"label\":\"Correo eléctronico\"},\n {\"column\":\"direccion\", \"label\":\"Dirección\"}, \n {\"column\":\"login\", \"label\":\"Login\"},\n {\"column\":\"rol\", \"label\":\"rol\"}, \n {\"column\":\"estado\", \"label\":\"Estado\"},\n {\"column\":\"editar\", \"label\":\"Editar\"}, \n {\"column\":\"activar\", \"label\":\"Activar\"},\n {\"column\":\"eliminar\", \"label\":\"Desactivar\"} \n ],\n \"pedido\" : [\n {\"column\":\"cancelar\", \"label\":\"Accion\"}, \n {\"column\":\"codigo\", \"label\":\"Codigo\"},\n {\"column\":\"nombre\", \"label\":\"Nombre\"},\n {\"column\":\"valor\", \"label\":\"Valor\", \"format\":\"miles\"},\n {\"column\":\"cantidad\", \"label\":\"Cantidad\", \"format\":\"numero\"},\n {\"column\":\"subtotal\", \"label\":\"Subtotal\", \"format\":\"miles\"},\n {\"column\":\"impuesto\", \"label\":\"Impuesto\", \"format\":\"miles\"},\n {\"column\":\"descuento\", \"label\":\"Descuento\", \"format\":\"miles\"},\n {\"column\":\"promo_nombre\", \"label\":\"Promoción\"},\n {\"column\":\"promo_descuento\", \"label\":\"Descuento promoción\", \"format\":\"miles\"},\n {\"column\":\"total\", \"label\":\"Total\", \"format\":\"miles\"}\n ],\n \"gestion_pedidos\" : [\n {\"column\":\"codigo\", \"label\":\"Codigo\"},\n {\"column\":\"usuario_nombre\", \"label\":\"Usuario\"},\n {\"column\":\"subtotal\", \"label\":\"Subtotal\", \"format\":\"miles\"},\n {\"column\":\"impuesto\", \"label\":\"Impuesto\", \"format\":\"miles\"},\n {\"column\":\"descuento\", \"label\":\"Descuento\", \"format\":\"miles\"},\n {\"column\":\"promo_descuento\", \"label\":\"Promoción\", \"format\":\"miles\"},\n {\"column\":\"total\", \"label\":\"Total\", \"format\":\"miles\"},\n {\"column\":\"detalle\", \"label\":\"Detalle\"},\n {\"column\":\"confirmar\", \"label\":\"Confirmar\"},\n {\"column\":\"cancelar\", \"label\":\"Cancelar\"}\n ],\n \"promo_producto\":[\n {\"column\":\"cod_producto\", \"label\":\"Codigo\"},\n {\"column\":\"nom_producto\", \"label\":\"Nombre\"},\n {\"column\":\"valor_descuento\", \"label\":\"Descuento\"},\n {\"column\":\"dia_aplica\", \"label\":\"Día\"},\n {\"column\":\"hora_inicial\", \"label\":\"Hora inicio\"},\n {\"column\":\"hora_final\", \"label\":\"Hora fin\"},\n {\"column\":\"descripcion\", \"label\":\"Descripcion\"} \n ],\n \"factura_venta\":[\n {\"column\":\"codigo\", \"label\":\"Codigo\"},\n {\"column\":\"nombre_usuario\", \"label\":\"Nombre Usuario\"},\n {\"column\":\"impuesto\", \"label\":\"Impuesto\", \"format\":\"miles\"},\n {\"column\":\"descuento\", \"label\":\"Descuento\", \"format\":\"miles\"},\n {\"column\":\"promocion\", \"label\":\"Promocion\", \"format\":\"miles\"},\n {\"column\":\"subtotal\", \"label\":\"Sub total\", \"format\":\"miles\"},\n {\"column\":\"total\", \"label\":\"Total\", \"format\":\"miles\"},\n {\"column\":\"fecha_creacion\", \"label\":\"Fecha creación\"} \n ],\n \"beneficiarios_cotiza\" : [ \n {\"column\":\"tipoNroId\", \"label\":\"Identificación\"},\n {\"column\":\"nombre_completo\", \"label\":\"Nombre beneficiario\"},\n {\"column\":\"des_parentesco\", \"label\":\"Parantesco\"},\n {\"column\":\"soporte_eps\", \"label\":\"Soporte EPS\"},\n {\"column\":\"salud\", \"label\":\"Declaración de salud\"},\n {\"column\":\"nombreProducto\", \"label\":\"Producto\"}\n ],\n \"beneficiarios_cotiza2\" : [ \n {\"column\":\"tipoNroId\", \"label\":\"Identificación\"},\n {\"column\":\"nombre_completo\", \"label\":\"Nombre beneficiario\"},\n {\"column\":\"des_parentesco\", \"label\":\"Parantesco\"},\n {\"column\":\"soporte_eps\", \"label\":\"Soporte EPS\"}, \n {\"column\":\"nombreProducto\", \"label\":\"Producto\"}\n ],\n \"realizar_pago\" : [\n {\"column\":\"producto\", \"label\":\"Producto\"},\n {\"column\":\"afiliados\", \"label\":\"Afiliados\"}, \n {\"column\":\"tarifa\", \"label\":\"Tarifa mensual\", \"format\":\"miles\"}\n ],\n \"beneficiarios_contrato\" : [\n {\"column\":\"tipoDocumento_abr\", \"label\":\"Tipo de identificación\"},\n {\"column\":\"numeroDocumento\", \"label\":\"Número de identificación\"}, \n {\"column\":\"nombre_completo\", \"label\":\"Nombre beneficiario\"},\n {\"column\":\"telefono\", \"label\":\"Teléfono\"},\n {\"column\":\"correo\", \"label\":\"Correo electrónico\"},\n {\"column\":\"tarifaProducto\", \"label\":\"Tarifa mensual\"}\n ],\n \"Contactos\" : [\n {\"column\":\"lugar\", \"label\":\"Lugar\"},\n {\"column\":\"telefono\", \"label\":\"Número de Telefono\"},\n {\"column\":\"lugar2\", \"label\":\"Lugar\"},\n {\"column\":\"telefono2\", \"label\":\"Número de Telefono\"}\n ]\n };\n\n return columns[tabla];\n \n}",
"function crearTabla(datos = [], selListaPor = \"\") {\n\t\n\tconst fi = \"<tr>\";\n\tconst fc = \"</tr>\";\n\tconst di = \"<td>\";\n\tconst dc = \"</td>\";\n\tlet filasHtml = \"\";\n\t\n\tswitch (selListaPor) {\n\t\tcase selVistaListarUsuarios:\n\t\t\tlet us = [UsuarioCtrl.getModelo()];\n\t\t\tus = datos;\n\t\t\tfor (const u of us) {\n\t\t\t\tfilasHtml += fi;\n\t\t\t\tfilasHtml += `${di} ${u.cedula} ${dc}`;\n\t\t\t\tfilasHtml += `${di} ${u.nombre} ${dc}`;\n\t\t\t\tfilasHtml += `${di} ${u.email} ${dc}`;\n\t\t\t\tfilasHtml += `${di} ${u.usuario} ${dc}`;\n\t\t\t\tfilasHtml += `${di} ${u.password} ${dc}`;\n\t\t\t\tfilasHtml += fc;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase selVistaListarClientes:\n\t\t\tlet cs = [ClienteCtrl.getModelo()];\n\t\t\tcs = datos;\n\t\t\tfor (const c of cs) {\n\t\t\t\tfilasHtml += fi;\n\t\t\t\tfilasHtml += `${di} ${c.cedula} ${dc}`;\n\t\t\t\tfilasHtml += `${di} ${c.nombre} ${dc}`;\n\t\t\t\tfilasHtml += `${di} ${c.email} ${dc}`;\n\t\t\t\tfilasHtml += `${di} ${c.direccion} ${dc}`;\n\t\t\t\tfilasHtml += `${di} ${c.telefono} ${dc}`;\n\t\t\t\tfilasHtml += fc;\t\t\t\t\n\t\t\t}\t\t\t\t\n\t\t\tbreak;\t\n\n\t\tcase selVistaListarVentaClientes:\n\t\t\tlet vcs = [ClienteCtrl.getModelo()];\n\t\t\tvcs = datos;\n\t\t\tlet sumaTotalVentas = 0;\n\t\t\t\n\t\t\tfor (const vc of vcs) {\n\t\t\t\t//carcular total ventas\n\t\t\t\tconst tv = vc.ventas.reduce((ac, v)=> {\n\t\t\t\t\treturn ac + v.valorVenta;\n\t\t\t\t}, 0)\n\n\t\t\t\tfilasHtml += fi;\n\t\t\t\tfilasHtml += `${di} ${vc.cedula} ${dc}`;\n\t\t\t\tfilasHtml += `${di} ${vc.nombre} ${dc}`;\n\t\t\t\tfilasHtml += `${di} ${tv} ${dc}`;\n\t\t\t\tfilasHtml += fc;\n\t\t\t\t\n\t\t\t\tsumaTotalVentas += tv;\n\t\t\t}\n\t\t\tfilasHtml += fi;\n\t\t\tfilasHtml += `${di} Total Ventas ${dc}`;\n\t\t\tfilasHtml += `<td colspan=\"2\"> ${sumaTotalVentas} ${dc}`\n\t\t\tfilasHtml += fc;\n\t\t\tbreak;\t\n\t\t\t\n\t\tcase selVistaListarProveedores:\n\t\t\tlet ps = [ProveedorCtrl.getModelo()];\n\t\t\tps = datos;\n\t\t\tfor (const p of ps) {\n\t\t\t\tfilasHtml += fi;\n\t\t\t\tfilasHtml += `${di} ${p.nit} ${dc}`;\n\t\t\t\tfilasHtml += `${di} ${p.nombre} ${dc}`;\n\t\t\t\tfilasHtml += `${di} ${p.ciudad} ${dc}`;\n\t\t\t\tfilasHtml += `${di} ${p.direccion} ${dc}`;\n\t\t\t\tfilasHtml += `${di} ${p.telefono} ${dc}`;\n\t\t\t\tfilasHtml += fc;\t\t\t\t\n\t\t\t}\t\t\t\t\n\t\t\tbreak;\t\t\t\n\t\t\t\n\t\tcase selVistaListarProductos:\n\t\t\tlet pts = [ProductoCtrl.getModelo()];\n\t\t\tpts = datos;\n\t\t\tfor (const p of pts) {\n\t\t\t\tfilasHtml += fi;\n\t\t\t\tfilasHtml += `${di} ${p.codigo} ${dc}`;\n\t\t\t\tfilasHtml += `${di} ${p.nombre} ${dc}`;\n\t\t\t\tfilasHtml += `${di} ${p.precioCompra} ${dc}`;\n\t\t\t\tfilasHtml += `${di} ${p.ivacompra} ${dc}`;\n\t\t\t\tfilasHtml += `${di} ${p.precioVenta} ${dc}`;\n\t\t\t\tfilasHtml += fc;\t\t\t\t\n\t\t\t}\t\t\t\t\n\t\t\tbreak;\t\n\t\t\t\n\t\tcase selVistaListarVentas:\n\t\t\tlet vs = [VentaCtrl.getModelo()];\n\t\t\tvs = datos;\n\t\t\tfor (const v of vs) {\n\t\t\t\tfilasHtml += fi;\n\t\t\t\tfilasHtml += `${di} ${v.codigo} ${dc}`;\n\t\t\t\tfilasHtml += `${di} ${v.valorVenta} ${dc}`;\n\t\t\t\tfilasHtml += `${di} ${v.ivaVenta} ${dc}`;\n\t\t\t\tfilasHtml += `${di} ${v.totalVenta} ${dc}`;\n\t\t\t\tfilasHtml += fc;\t\t\t\t\n\t\t\t}\t\t\t\t\n\t\t\tbreak;\t\t\t\t\n\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\t$(`${selListaPor} table tbody`).html(filasHtml);\n}",
"function remplirTableau() {\r\n tabIsEmpty = false;\r\n tbody.empty();\r\n var html = \"\";\r\n data.forEach(function (element) {\r\n html = '<tr>' +\r\n '<th>' + element.order + '</th>' +\r\n '<td>' + element.activity + '</td>' +\r\n '<td>' + element.manager + '</td>' +\r\n '<td>' + element.numofsub + '</td>' +\r\n '</tr>';\r\n tbody.append(html);\r\n });\r\n }",
"criarTabela() {\n // deleta a tabela\n while (this.tabela.hasChildNodes()) {\n this.tabela.removeChild(this.tabela.firstChild)\n }\n // criação da tabela e dados\n // cria o cabeçalho da tabela\n let tHeader = this.tabela.createTHead()\n let hRow = tHeader.insertRow()\n hRow.insertCell(0).innerHTML = 'Mês'\n hRow.insertCell(1).innerHTML = 'Dinheiro aplicado'\n hRow.insertCell(2).innerHTML = 'Juros'\n hRow.insertCell(3).innerHTML = 'Total'\n // cria e insere os dados na tabela\n let investido = this.investido\n let total = this.investido\n let mes = 0\n for (let index = 0; index < this.periodo; index++) {\n // calcula o valor investido\n investido += this.aporte\n // calcula o valor total\n total += this.aporte\n total *= this.juros\n // aumenta o valor de mês\n mes++\n // insere os dados na tabela\n // .toLocalString = ajusta o valor para a moeda BRL\n let row = this.tabela.insertRow()\n row.insertCell(0).innerHTML = mes\n row.insertCell(1).innerHTML = investido.toLocaleString('pt-BR', {\n style: 'currency',\n currency: 'BRL'\n })\n row.insertCell(2).innerHTML = (total - investido).toLocaleString('pt-BR', {\n style: 'currency',\n currency: 'BRL'\n })\n row.insertCell(3).innerHTML = total.toLocaleString('pt-BR', {\n style: 'currency',\n currency: 'BRL'\n })\n }\n }",
"function getColumnTable(tabla){\ncolumns = {\n \"permisos_campo_rol\" : [\n {\"column\":\"nom_tabla\", \"label\":\"Tabla\"},\n {\"column\":\"nom_campo\", \"label\":\"Campo\"}, \n {\"column\":\"ch_estado\", \"label\":'Estado <br><input type=\"checkbox\" id=\"chcAll\">', \"attribs\":'class=\"center_th\"', \"attribs_head\":'class=\"center_th\"'}\n ],\n \"observacion_persona\" : [\n {\"column\":\"documento_ovp\", \"label\":\"Documento\"},\n {\"column\":\"nombre_ovp\", \"label\":\"Nombre\"},\n {\"column\":\"cargo_ovp\", \"label\":\"Cargo\"},\n {\"column\":\"quitar\", \"label\":'Quitar'}\n ],\n \"reporte_terreno\": [\n {\"column\":\"predial_terreno\", \"label\":\"No. Predial\"},\n {\"column\":\"nombre_proyecto\", \"label\":\"Nombre Proyecto\"},\n {\"column\":\"codigonal\", \"label\":\"Código Nacional\"},\n {\"column\":\"calidad_bien\", \"label\":\"Calidad del Bien\"},\n {\"column\":\"direccion_oficial\", \"label\":\"Dirección Oficial\"},\n {\"column\":\"tipo_bien\", \"label\":\"Tipo de Bien\"},\n {\"column\":\"barrio\", \"label\":\"Barrio\"},\n {\"column\":\"comuna\", \"label\":\"Comuna\"},\n {\"column\":\"n_folio\", \"label\":\"No. Folio\"},\n {\"column\":\"modo_adquisicion\", \"label\":\"Modo Adquisición\"},\n {\"column\":\"dependencia\", \"label\":\"Organismo\"},\n {\"column\":\"nombrecomun_p\", \"label\":\"Nombre Común\"},\n {\"column\":\"tipo_documento\", \"label\":\"Tipo de Documento\"},\n {\"column\":\"numero_documento\", \"label\":\"Número de Documento\"},\n {\"column\":\"fecha_doc\", \"label\":\"Fecha Documento\"},\n {\"column\":\"notaria_doc\", \"label\":\"Notaría\"},\n {\"column\":\"area_cesion\", \"label\":\"Área Cesión\"},\n {\"column\":\"area_actual\", \"label\":\"Área Actual\"},\n {\"column\":\"area_sicat\", \"label\":\"Área Sicat\"},\n {\"column\":\"area_terreno\", \"label\":\"Área en SAP\"}\n ]\n };\n\n return columns[tabla];\n\n}",
"function buildTable(data) {\n //Vamos a crear un elemento html \"table\" y lo almacenaramos en una funcion table.\n var table = document.createElement(\"table\");\n //Agregamos la tabla de Boostrap.\n table.setAttribute('class', 'table');\n //En la variable fields vamos a almacenar los Keys de data (Tarea, Status, Finalizada, Eliminar).\n var fields = Object.keys(data[0]);\n //Creamos una variable headRow donde le asignaremos un elemento HTML tr\n var headRow = document.createElement(\"tr\");\n //Vamos a recorrer en un ciclo todos los elementos que esten en fields y los almacenaremos en una variable field.\n fields.forEach(function(field) {\n //Vamos a crear una celda TH en la variable headCell\n var headCell = document.createElement(\"th\");\n headCell.setAttribute('scope', 'col');\n //A la celda le asisgnaremos un textNode con la informacion que tenga field (Tarea, Status, Finalizada, Eliminar);\n headCell.appendChild(document.createTextNode(field));\n //A headRow le asignaremos un nodo hijo con la informacion de headCell\n headRow.appendChild(headCell);\n });\n\n //Finalmente a table le asignaremos un nodo hijo que sera headRow y con esto crearemos la primer parte de la tabla.\n //La parte donde vienen los nombres de las variables (Tarea, Status, Finalizada, Eliminar)\n table.appendChild(headRow);\n\n //Recorreremos cada elemento que hay dentro de data que son objetos en este caso y le pondremos un index\n //para saber en que elemento estamos.\n data.forEach(function(object, index) {\n //Crearemos una variable row que sea igual a un elemento HTML tr\n var row = document.createElement(\"tr\");\n //En la variable fields vamos a almacenar los Keys de data (Tarea, Status, Finalizada, Eliminar).\n fields.forEach(function(field) {\n if (field == undefined) {\n field = \"vacio\";\n }\n //Crearemos una variable cell que sea igual a un elemento HTML td\n var cell = document.createElement(\"td\");\n //Vamos a verificar que si el valor de alguna celda es igual a \"En Progreso\" entonces reemplazaremos\n //Ese String y lo convertiremos a un boton\n if (object[field] === \"En Progreso\" && object[field] !== undefined) {\n //Creamos una variable completeButton que sea igual a un nodoHijo de cell que contenga un elemento\n //HTML de tipo Input\n //Con esto sustituimos en cell el texto que tenia por un Input.\n var completeButton = cell.appendChild(document.createElement(\"input\"));\n completeButton.setAttribute('class', 'button2');\n //A completeButton le asiganmos los atributos type = submit para el formato como boton y el value\n //= a Completar.\n completeButton.type = \"submit\", completeButton.value = \"Completar\";\n //Ponemos el boton dentro de la celda.\n row.appendChild(cell);\n //Le agregamos un eventListener que se active al click del boton y que llame a la funcion updateRegister\n //y le envie el nombre de la tarea que tenga ese boton asignado.\n completeButton.addEventListener(\"click\", function() {\n updateRegister(object[fields[0]]);\n });\n //Vamos a verificar que si el valor de alguna celda es igual a \"Eliminar\" entonces reemplazaremos\n //Ese String y lo convertiremos a un boton\n } else if (object[field] === \"Eliminar\" && object[field] != undefined) {\n //Creamos una variable completeButton que sea igual a un nodoHijo de cell que contenga un elemento\n //HTML de tipo Input\n //Con esto sustituimos en cell el texto que tenia por un Input.\n var completeButton = cell.appendChild(document.createElement(\"input\"));\n completeButton.setAttribute('class', 'button2');\n //A completeButton le asiganmos los atributos type = submit para el formato como boton y el value\n //= a Completar.\n completeButton.type = \"submit\", completeButton.value = \"Eliminar\";\n //Ponemos el boton dentro de la celda.\n row.appendChild(cell);\n //Le agregamos un eventListener que se active al click del boton y que llame a la funcion deleteRegister\n //y le envie el nombre de la tarea que tenga ese boton asignado.\n completeButton.addEventListener(\"click\", function() {\n console.log(object[fields[0]]);\n deleteRegister(object[fields[0]], \"Finalizada\");\n });\n } else if (object[field] != undefined) {\n //Si no se cumple ninguna condicion anterior unicamente insertaremos el texto con la informacion.\n //No se crearan ningun boton.\n cell.appendChild(document.createTextNode(object[field]));\n row.appendChild(cell);\n }\n });\n //Finalmente a tabla le asiganeremos otro nodoHijo que contenga toda la informacion de row.\n table.appendChild(row);\n });\n //Retornamos la tabla creada.\n return table;\n}",
"function reinicializaTabela() {\n primeiraLinhaImpressao = 0;\n limpaTabela();\n}",
"function gettable (){ // query to connect all the table to show all the data.\n connection.query(`SELECT e.id, e.first_name, e.last_name, emprole.title, emprole.salary, department.dptname AS department,\n concat(m.first_name, ' ', m.last_name) AS manager FROM employee AS e LEFT JOIN employee AS m ON e.manager_id = m.id \n INNER JOIN emprole ON e.role_id = emprole.id INNER JOIN department ON emprole.dept_id = department.id`,\n (err, res) => {\n if (err) throw err;\n console.log(consoletable.getTable(res))\n initialize();\n });\n}",
"function addTable(){\n alienData.forEach(aliens =>{\n\t\t// Creating the rows for each line\n var row = tbody.append(\"tr\");\n\t\t// Creating the cells and appending values \n columns.forEach(column => {\n\t\t\t// Formating the entries for City, State and Country to show them in upper case\n if(column ==\"city\" || column ==\"state\" ||column == \"country\"){\n row.append(\"td\").text(aliens[column].toUpperCase());\n }\n\t\t\t // Append the shape, duration and comment values\n else row.append(\"td\").text(aliens[column]); \n })\n })\n}",
"function generarTablaEj (){\r\n buscarEjXNivDocEntrega();\r\n document.querySelector(\"#divEjalumnos\").innerHTML = `<table id=\"tabEjAlumno\" border='2px' style='background-color: #FA047F; position: relative;'>\r\n <th>Título</th><th>Docente</th><th>Nivel</th>`;\r\n for(let iterador = 0; iterador<= ejerciciosAMostrar.length-1; iterador ++){\r\n document.querySelector(\"#tabEjAlumno\").innerHTML += `<tr id=\"${iterador}\" class=\"filaEjercicioAlumno\"> <td style=\"padding: 10px\"> ${ejerciciosAMostrar[iterador].titulo} </td> <td style=\"padding: 10px\"> ${ejerciciosAMostrar[iterador].Docente.nombre} </td><td style=\"padding: 10px\"> ${ejerciciosAMostrar[iterador].nivel} </td> </tr>`;\r\n }\r\n addEventsTablaEj();\r\n}",
"function inicializarTablero() {\n console.log( tablero );\n for (i = 0; i < tablero.columnas; i++) { //Recorremos las columnas\n tablero.celdas[i] = [];\n for (j = 0; j < tablero.filas; j++) { //Recorremos las filas\n tablero.celdas[i][j] = '(' + i + ',' + j + ')';//Guardamos la posicion de la columna y la fila dentro del array\n }\n }\n}",
"crearTablero() {\n // Número de parejas necesario de cada tipo para rellenar el tablero\n let nParejas = ((this.n * this.m) / 2) / this.tipos.length;\n\n for (let j = 0; j < this.tipos.length; j++) {\n for (let i = 0; i < nParejas; i++) {\n this.crearPareja(this.tipos[j]);\n }\n }\n }",
"function listarEstudiantes() {\n\n //agrega por DOM la fila de cabecera\n var table = document.getElementById(\"estudiantes\")\n table.innerHTML = \"\";//Limpia la tabla\n var row1 = document.createElement(\"tr\");\n var col1 = document.createElement(\"th\");\n var texto1 = document.createTextNode(\"Código\");\n var col2 = document.createElement(\"th\");\n var texto2 = document.createTextNode(\"Nombre\");\n var col3 = document.createElement(\"th\");\n var texto3 = document.createTextNode(\"Nota\");\n \n //agrega los textos\n col1.appendChild(texto1); \n col2.appendChild(texto2); \n col3.appendChild(texto3); \n //agrega las columnas a la fila\n row1.appendChild(col1);\n row1.appendChild(col2);\n row1.appendChild(col3);\n table.appendChild(row1);\n //agrega la fila a la tabla\n table.appendChild(row1);\n table.appendChild(row1);\n var resultado = \"\";\n\n estudiantesJson.sort(OrdenarNombreAscendente);\n \n for (var i = 0; i < estudiantesJson.length; i++) {\n resultado += \" <tr><td>\" + estudiantesJson[i].codigo + \"</td> \" + \"<td>\" + estudiantesJson[i].nombre + \"</td>\" + \"<td>\" + estudiantesJson[i].nota + \"</td></tr>\";\n }\n table.innerHTML += resultado;\n\n}",
"function loadTableDataa(tableName) {\n\tgenerarTablaGlobal(tableName, getTableData(tableName));\n}",
"function load_table_schema(table) {\n let en_schema = ['ID', 'Title', 'Creator', 'Scientific Name', 'Description', 'Publisher', 'Date', 'Relation', 'Source', 'Language'];\n let ar_schema = ['الهوية', 'العنوان', 'الموضوع', 'الوصف', 'المصدر', 'الحق', 'التاريخ'];\n let schema = lang ? en_schema : ar_schema;\n let head = table.createTHead();\n head.innerHTML = \"\";\n let row = head.insertRow(0);\n for (let i = 0; i < schema.length; i++) {\n row.innerHTML += '<th>' + schema[i] + '</th>';\n }\n}",
"function load_table_schema(table){\n let en_schema = ['ID','Title','Creator','Scientific Name','Description','Publisher','Date','Source','Language'];\n let ar_schema = ['الهوية','العنوان', 'الموضوع', 'الوصف', 'المصدر', 'الحق', 'التاريخ'];\n let schema = lang?en_schema:ar_schema;\n let head = table.createTHead();\n head.innerHTML = \"\";\n let row = head.insertRow(0);\n for(let i = 0; i < schema.length; i++){\n row.innerHTML += '<th>' + schema[i] + '</th>';\n } \n}",
"function vypis_tabulky_turnaj()\n{\n for(var i=0; i<aktualny_turnaj_pocet_skupin;i++)\n {\n var tabulka=ziskaj_tabulku_podla_zapasov();\n zorad_tabulku_podla_bodov(tabulka);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Filter collections list (creates new block) | function filterCollectionsBlock(block, callback, keepEmptyCategories = false) {
const result = {
type: 'collections-list',
showCategories: block.showCategories,
collections: collections.filterCollections(block.collections, callback, keepEmptyCategories),
};
return result;
} | [
"function makeBlockLists() {\n\tblockList.eachCategory((cat)=> {\n\t\tvar $list = $('#list_'+cat);\n\t\t$list.html('');\n\t\tblockList.eachId(cat, (cat, sid)=>{\n\t\t\t$list.append('<option>'+sid+'</option>');\n\t\t});\n\t});\n\tupdateInUse();\n}",
"getCollectionsBlock() {\n\t if (this.loading || this.error !== '') {\n\t return null;\n\t }\n\t const blocks = this.render();\n\t return blocks !== null && blocks.collections !== null\n\t ? objects.cloneObject(blocks.collections)\n\t : null;\n\t }",
"function applyCollectionsFilter(block, filter, filters$1) {\n\t const keyword = filter.keyword.trim();\n\t const hasFilters = filters$1 !== null && filters$1.filterType === 'categories';\n\t const filtersList = filters$1;\n\t if (keyword === '') {\n\t // Empty\n\t if (hasFilters) {\n\t // Enable all filters\n\t filters.enableFilters(filtersList, true);\n\t }\n\t return block;\n\t }\n\t // Disable all filters, will re-enable them again during filter process\n\t const activeCategories = {};\n\t if (hasFilters) {\n\t filters.enableFilters(filtersList, false);\n\t }\n\t // Filter collections block\n\t return filterCollectionsBlock(block, (item, category) => {\n\t for (let i = filterKeys.length - 1; i >= 0; i--) {\n\t // Get key\n\t const key = filterKeys[i];\n\t if (item[key] === void 0) {\n\t continue;\n\t }\n\t // Test value\n\t if (objects.match(item[key], keyword)) {\n\t // Enable category in category filters\n\t if (hasFilters) {\n\t if (activeCategories[category] !== true) {\n\t activeCategories[category] = true;\n\t if (filtersList.filters[category] !== void 0) {\n\t filtersList.filters[category].disabled = false;\n\t }\n\t }\n\t }\n\t return true;\n\t }\n\t }\n\t return false;\n\t }, false);\n\t}",
"getCollectionsBlock() {\n\t if (this.loading || this.error !== '') {\n\t return null;\n\t }\n\t const blocks = this.render();\n\t return blocks !== null && blocks.collections !== null\n\t ? blocks.collections\n\t : null;\n\t }",
"function createNewCollection() {\n var fake = {\n avatarURL: \"\",\n description: \"\",\n id: -1,\n isActive: true,\n isDefaultCollection: false,\n paradata: { comments: [], dislikes: 0, following: 0, iDislikeThis: false, iLikeThis: false, likes: 0 },\n title: \"\"\n };\n var found = false;\n for(i in libraryData.collections){\n if(libraryData.collections[i].id == -1){\n libraryData.collections[i] = fake;\n pickLibCol(libraryData.collections[i]);\n found = true;\n break;\n }\n }\n if(!found){ \n libraryData.collections.push(fake);\n pickLibCol(libraryData.collections[libraryData.collections.length - 1]);\n }\n}",
"filter(callback) {\n\n // return limited collection\n return new Todos( { todos: this._data.todos.filter(callback) } );\n }",
"function createFilters() {\n\n}",
"function initBlacklistedItems(collection) {\n\tlogTrace('invoking initBlacklistedItems($)', collection);\n\n\tconst itemTypes = [\n\t\t'categories',\n\t\t'channels',\n\t\t'tags'\n\t];\n\n\tif (typeof collection !== 'object') {\n\n\t\tcollection = {};\n\t}\n\n\tconst itemTypesLength = itemTypes.length;\n\tfor (let i = 0; i < itemTypesLength; i++) {\n\n\t\tlet itemType = itemTypes[i];\n\n\t\tif (collection[itemType] === undefined) {\n\n\t\t\tcollection[itemType] = {};\n\t\t}\n\t}\n\n\treturn collection;\n}",
"function newBlockGroup() { \n listAll = listAll.concat(blockGroup.list) \n for (let i = 0; i < blockGroup.list.length; i++) {\n blockGroup.cells[blockGroup.list[i].getPosition()].style.boxShadow = 'none';\n } \n \n if (sideBar.gameOverCheck()){\n sideBar.gameOver(); \n return;\n }\n \n blockGroup = new BlockGroup();\n blockGroup.collapse(); \n}",
"function _createCollection(blockClass, models, views){ \n var ret = [], \n models = models || [], \n views = views || [], \n len = (models.length > views.length)? models.length: views.length; \n\n //pair them x times where x is the maximum length\n _.times(len, function(index){ \n var ob = {}; \n ob.blockClass = blockClass; \n\n //set model and view\n if(model = models[index]) ob.model = model; \n else if(model = models[0]) ob.model = model; //repeat model[0] if necessary to complete the array \n\n if(view = views[index]) ob.view = view; \n else if(view = views[0]) ob.view = view; \n ret.push(ob); \n }); \n return ret; \n }",
"function addBlock(itemset, items, name){\n var block = {};\n block.type = name;\n block.recMath = false;\n block.minSummonerLevel = -1;\n block.maxSummonerLevel = -1;\n block.showIfSummonerSpell = \"\";\n block.hideIfSummonerSpell = \"\";\n block.items = [];\n items.filter(unique).forEach(function(item){\n var entry = {};\n entry.id = item + \"\";\n entry.count = 1;\n //add item to block if the item exists\n if(builder.items[item] != undefined){\n block.items.push(entry);\n }\n })\n itemset.blocks.push(block);\n }",
"filter(type) {\n return this.blocks.filter((x) => { return x.type == type; });\n }",
"function initBlacklistedItems(collection) {\n\tlogTrace('invoking initBlacklistedItems($)', collection);\n\n\tconst itemTypes = [\n\t\t'games',\n\t\t'communities',\n\t\t'creative',\n\t\t'channels'\n\t];\n\n\tif (typeof collection !== 'object') {\n\n\t\tcollection = {};\n\t}\n\n\tconst itemTypesLength = itemTypes.length;\n\tfor (let i = 0; i < itemTypesLength; i++) {\n\n\t\tlet itemType = itemTypes[i];\n\n\t\tif (collection[itemType] === undefined) {\n\n\t\t\tcollection[itemType] = {};\n\t\t}\n\t}\n\n\treturn collection;\n}",
"filterBlockList () {\n let self = this;\n \n self.plannedEffortList = self.chart.data.efforts.filter((effort) => {\n return effort.usageCount > 0\n });\n \n self.unplannedEffortList = self.chart.data.efforts.filter((effort) => {\n return effort.usageCount < 1\n });\n }",
"function createCollections() {\n return {};\n}",
"async indexFilters(entry, block, view) {\n if (!this.options.indexFilters)\n return;\n\n const hash = block.hash();\n\n const prevBasic = await this.getCFHeader(\n Buffer.from(block.prevBlock, 'hex'),\n FILTERS.REGULAR\n );\n const prevExt = await this.getCFHeader(\n Buffer.from(block.prevBlock, 'hex'),\n FILTERS.EXTENDED\n );\n\n let basicRaw;\n const b = this.db.batch();\n const basic = GCSFilter.fromBlock(block);\n if (basic.data.length > 0)\n basicRaw = basic.toRaw();\n b.put(layout.g.build(hash), basicRaw);\n b.put(layout.G.build(hash), basic.header(prevBasic));\n\n let extRaw;\n const ext = GCSFilter.fromExtended(block);\n if (ext.data.length > 0)\n extRaw = ext.toRaw();\n b.put(layout.x.build(hash), extRaw);\n b.put(layout.X.build(hash), ext.header(prevExt));\n\n await b.write();\n }",
"function newFilterBlock(filter) {\n\tvar output = \"\";\n\tvar buttonId = \"clear-\" + filter.identifier;\n\n\toutput += \"<div id=\\\"\" + filter.identifier + \"\\\" class=\\\"filter-block inner-content-segment\\\">\";\n\toutput += \"<h2>\" + filter.displayName + \"</h2>\";\n\toutput += \"<p>\" + filter.displayValue + \"</p>\";\n\toutput += \"<input id=\\\"\" + buttonId + \"\\\" class=\\\"button filter-clear-button\\\" type=\\\"submit\\\" value=\\\"Clear\\\">\";\n\toutput += \"</div>\";\n\n\treturn output;\n}",
"function getBlockByUserCreated(userId) {\n return db('lists as l')\n // .join('twitter_users as tu', 'tu.twitter_id', \"l.twitter_id\")\n .where('l.twitter_id', userId)\n .where('is_block_list', true)\n}",
"initCollectionBanlist() {\n this.col.banlist = this.prepareCollection('banlist', { unique: ['address'] });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function: objArc creates an arc (a linestring with n segments) Parameters: center center point radius radius of the arc alpha starting angle (in Grad) omega ending angle (in Grad) segments number of segments for drawing the arc flag true : create arc feature from center to start to endpoint to center false : create arc feature from start to endpoint Returns: an array with four features, if flag=true arc feature (from Linestring) the startpoint (from Point) the endpoint (from Point) the chord (from LineString) | function objArc(center, radius, alpha, omega, segments, flag)
{
var pointList=[];
if(flag)
pointList.push(new ol.geom.Point(center.x, center.y));
var dAngle= segments+1;
for(var i=0;i<dAngle;i++)
{
var Angle = alpha - (alpha-omega)*i/(dAngle-1);
var x = center.x + radius*Math.cos(Angle*Math.PI/180);
var y = center.y + radius*Math.sin(Angle*Math.PI/180);
var point = new ol.geom.Point(x, y);
pointList.push(point);
}
if(flag)
pointList.push(new ol.geom.Point(center.x, center.y));
var ftArc = new ol.Feature.Vector(new ol.geom.LineString(pointList));
if(flag)
{
var ftArcPt0 = new ol.Feature.Vector(pointList[1]);
var ftArcPt1 = new ol.Feature.Vector(pointList[pointList.length-2]);
var ftArcSehne = new ol.Feature.Vector(new ol.geom.LineString([pointList[1], pointList[pointList.length-2]]));
var arrArc = [ftArc, ftArcPt0, ftArcPt1, ftArcSehne];
}
else
var arrArc = [ftArc];
return(arrArc);
} | [
"createArc() {\n var n = 20;\n var startPoint = this.start[0] - this.center[0];\n var endPoint = this.end[0] - this.center[0];\n var startAngle = Math.acos(startPoint/this.radius);\n var endAngle = Math.acos(endPoint/this.radius);\n var dtheta = (endAngle - startAngle)/n;\n var theta = startAngle;\n var x1, y1;\n var arcPoints = [];\n var cn = 0;\n while (cn <= n) { //while the start point is not at the end point\n x1 = this.center[0] + this.radius * Math.cos(theta);\n y1 = this.center[1] + this.radius * Math.sin(theta);\n arcPoints.push( {x: x1, y: y1} );\n theta += dtheta;\n cn += 1;\n }\n this.arc = arcPoints;\n return arcPoints;\n }",
"function generateArc(p1, center, endAngleDeg, maxSegmentLength) {\n\tconst points = [];\n\tconst radius = findDistance(p1, center);\n\tconst endAngle = endAngleDeg / 180 * Math.PI;\n\tlet startAngle = findAngle(center, p1);\n\twhile (startAngle > endAngle) startAngle -= Math.PI * 2;\n\n\tconst segmentInRadians = 1 / 180 * Math.PI * 2;\n\tconst angleDiff = endAngle - startAngle;\n\tconst numSegments = Math.ceil(angleDiff / segmentInRadians);\n\n\tfor (let i = 1; i < numSegments; i++) {\n\t\tconst f = i / numSegments;\n\t\tpoints.push(getPointOnCircle(center, radius, startAngle + f * angleDiff));\n\t}\n\n\treturn points;\n}",
"PathArcTo(centre, radius, a_min, a_max, num_segments = 0) { this.native.PathArcTo(centre, radius, a_min, a_max, num_segments); }",
"function Arc(\n centroidx,\n centroidy,\n radius,\n radstart,\n radend,\n arcID,\n Case,\n fx,\n fy,\n groupID,\n color,\n endpoint1x,\n endpoint1y,\n endpoint2x,\n endpoint2y,\n line1ID,\n line2ID\n) {\n this.centroidx = centroidx;\n this.centroidy = centroidy;\n this.radius = radius;\n this.radstart = radstart;\n this.radend = radend;\n this.arcID = arcID;\n this.Case = Case;\n this.fx = fx;\n this.fy = fy;\n this.groupID = groupID;\n this.color = color;\n this.endpoint1x = endpoint1x;\n this.endpoint1y = endpoint1y;\n this.endpoint2x = endpoint2x;\n this.endpoint2y = endpoint2y;\n this.line1ID = line1ID;\n this.line2ID = line2ID;\n this.midpointX = 0; //Gets set in createnewfilletdim\n this.midpointY = 0; //Gets set in createnewfilletdim\n\n this.drawarc = function (color) {\n c.beginPath();\n c.arc(\n this.centroidx,\n this.centroidy,\n this.radius,\n this.radstart,\n this.radend\n );\n c.lineWidth = 2;\n c.strokeStyle = color;\n c.stroke();\n };\n}",
"function instantiateArc (obj, layers, options) {\n // expected values\n let lthk = obj['lthk']\n let pptx = obj['pptx']\n let ppty = obj['ppty']\n // let pptz = obj['pptz']\n let swid = obj['swid']\n let ang0 = obj['ang0'] // start angle\n let ang1 = obj['ang1'] // end angle\n // FIXME need to determine resolution from object/layer/variables\n let res = CSG.defaultResolution2D\n\n // conversion\n if (lthk === 0.0) {\n // convert to 2D object\n return CSG.Path2D.arc({center: [pptx, ppty], radius: swid, startangle: ang0, endangle: ang1, resolution: res})\n }\n // FIXME how to represent 3D arc?\n return CSG.Path2D.arc({center: [pptx, ppty], radius: swid, startangle: ang0, endangle: ang1, resolution: res})\n}",
"computeGeometry() {\n var pointList=[];\n var segments = 100;\n pointList.push(this.center);\n var dAngle= segments+1;\n for(var i=0;i<dAngle;i++)\n {\n var Angle = this.alpha - (this.alpha-this.omega)*i/(dAngle-1);\n var x = this.center[0] + this.radius*Math.cos(Angle*Math.PI/180);\n var y = this.center[1] + this.radius*Math.sin(Angle*Math.PI/180);\n var point = [x, y];\n if (this.center.length > 2) {\n var fovV = (this.omega - this.alpha) * Math.PI / 180;\n var fovH = 2 * Math.atan(Math.tan(fovV/2.0)/this.aspectRatio);\n var z = this.center[2] + (this.radius * Math.tan(fovH));\n point.push(z);\n }\n pointList.push(point);\n }\n pointList.push(this.center);\n var ftArc = new Polygon([pointList]);\n var ftArcPt0 = new Point(pointList[1]);\n var ftArcPt1 = new Point(pointList[pointList.length-2]);\n var ftArcSehne = new LineString([pointList[1], pointList[pointList.length-2]]);\n\n var arrArc = [ftArc, ftArcPt0, ftArcPt1, ftArcSehne];\n this.fullGeometry = arrArc;\n this.geometry = ftArc;\n }",
"function arc(props) {\n\tconst { start, radius, end, largeArc, sweep, rotation } = props;\n\t\n\treturn 'M' + start.left + ',' + start.top +\n\t\t' A' + radius.x + ',' + radius.y +\n\t\t' ' + (rotation || '0') +\n\t\t(largeArc ? ' 1' : ' 0') +\n\t\t(sweep ? ' 1 ' : ' 0 ') +\n\t\tend.left + ',' + end.top;\n}",
"function arcToBeziers(angleStart, angleExtent) {\n var numSegments = Math.ceil(Math.abs(angleExtent) / 90.0);\n\n var angleIncrement = (angleExtent / numSegments);\n\n // The length of each control point vector is given by the following formula.\n var controlLength = 4.0 / 3.0 * Math.sin(angleIncrement / 2.0) / (1.0 + Math.cos(angleIncrement / 2.0));\n\n var commands = [];\n\n for (var i = 0; i < numSegments; i++) {\n var cmd = { command: 'curveTo', code: 'C' };\n var angle = angleStart + i * angleIncrement;\n // Calculate the control vector at this angle\n var dx = Math.cos(angle);\n var dy = Math.sin(angle);\n // First control point\n cmd.x1 = (dx - controlLength * dy);\n cmd.y1 = (dy + controlLength * dx);\n // Second control point\n angle += angleIncrement;\n dx = Math.cos(angle);\n dy = Math.sin(angle);\n cmd.x2 = (dx + controlLength * dy);\n cmd.y2 = (dy - controlLength * dx);\n // Endpoint of bezier\n cmd.x = dx;\n cmd.y = dy;\n commands.push(cmd);\n }\n return commands;\n}",
"parseArcCommand(path, rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, start, end) {\n x_axis_rotation = x_axis_rotation * Math.PI / 180;\n\n // Ensure radii are positive\n rx = Math.abs(rx);\n ry = Math.abs(ry);\n\n // Compute (x1′, y1′)\n let dx2 = (start.x - end.x) / 2.0;\n let dy2 = (start.y - end.y) / 2.0;\n let x1p = Math.cos(x_axis_rotation) * dx2 + Math.sin(x_axis_rotation) * dy2;\n let y1p = - Math.sin(x_axis_rotation) * dx2 + Math.cos(x_axis_rotation) * dy2;\n\n // Compute (cx′, cy′)\n let rxs = rx * rx;\n let rys = ry * ry;\n let x1ps = x1p * x1p;\n let y1ps = y1p * y1p;\n\n // Ensure radii are large enough\n let cr = x1ps / rxs + y1ps / rys;\n\n if (cr > 1) {\n // scale up rx,ry equally so cr == 1\n let s = Math.sqrt(cr);\n rx = s * rx;\n ry = s * ry;\n rxs = rx * rx;\n rys = ry * ry;\n }\n\n let dq = (rxs * y1ps + rys * x1ps);\n let pq = (rxs * rys - dq) / dq;\n let q = Math.sqrt(Math.max(0, pq));\n if (large_arc_flag === sweep_flag) q = - q;\n let cxp = q * rx * y1p / ry;\n let cyp = - q * ry * x1p / rx;\n\n // Step 3: Compute (cx, cy) from (cx′, cy′)\n let cx = Math.cos(x_axis_rotation) * cxp - Math.sin(x_axis_rotation) * cyp + (start.x + end.x) / 2;\n let cy = Math.sin(x_axis_rotation) * cxp + Math.cos(x_axis_rotation) * cyp + (start.y + end.y) / 2;\n\n // Step 4: Compute θ1 and Δθ\n let theta = this.svgAngle(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry);\n let delta = this.svgAngle((x1p - cxp) / rx, (y1p - cyp) / ry, (- x1p - cxp) / rx, (- y1p - cyp) / ry) % (Math.PI * 2);\n\n path.currentPath.absellipse(cx, cy, rx, ry, theta, theta + delta, sweep_flag === 0, x_axis_rotation);\n }",
"function calcArc(center, r) {\n\tvar waypoints = [];\n\tfor (var i = 0; i < 50; i++) {\n\t\tvar x = center.x + Math.cos(Math.PI * i / 50) * r;\n\t\tvar y = center.y + Math.sin(Math.PI * i / 50) * r;\n\t\twaypoints.push({x:x, y:y});\n\t}\n\treturn waypoints;\n}",
"function createArcShape(center, v1, v3, iRadius, oRadius, rotation, theta, isClockwise) {\n\n\tvar shape = new THREE.Shape();\n\tshape.moveTo(v1.x, v1.y);\n\tshape.absarc(center.x, center.y, iRadius, rotation, rotation + theta, isClockwise);\n\tshape.lineTo(v3.x, v3.y);\n\tshape.absarc(center.x, center.y, oRadius, rotation + theta, rotation, !isClockwise);\n\t//shape.lineTo(v1.x, v1.y);\t\t// if add this line, road#515 geometry#2 lane#-2 won't draw, same error happens to road#517 do not know why\n\t\n\treturn shape;\n}",
"PathArcToFast(centre, radius, a_min_of_12, a_max_of_12) { this.native.PathArcToFast(centre, radius, a_min_of_12, a_max_of_12); }",
"function parseArcCommand( path, rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, start, end ) {\n\n\t\t\tx_axis_rotation = x_axis_rotation * Math.PI / 180;\n\n\t\t\t// Ensure radii are positive\n\t\t\trx = Math.abs( rx );\n\t\t\try = Math.abs( ry );\n\n\t\t\t// Compute (x1′, y1′)\n\t\t\tvar dx2 = ( start.x - end.x ) / 2.0;\n\t\t\tvar dy2 = ( start.y - end.y ) / 2.0;\n\t\t\tvar x1p = Math.cos( x_axis_rotation ) * dx2 + Math.sin( x_axis_rotation ) * dy2;\n\t\t\tvar y1p = - Math.sin( x_axis_rotation ) * dx2 + Math.cos( x_axis_rotation ) * dy2;\n\n\t\t\t// Compute (cx′, cy′)\n\t\t\tvar rxs = rx * rx;\n\t\t\tvar rys = ry * ry;\n\t\t\tvar x1ps = x1p * x1p;\n\t\t\tvar y1ps = y1p * y1p;\n\n\t\t\t// Ensure radii are large enough\n\t\t\tvar cr = x1ps / rxs + y1ps / rys;\n\n\t\t\tif ( cr > 1 ) {\n\n\t\t\t\t// scale up rx,ry equally so cr == 1\n\t\t\t\tvar s = Math.sqrt( cr );\n\t\t\t\trx = s * rx;\n\t\t\t\try = s * ry;\n\t\t\t\trxs = rx * rx;\n\t\t\t\trys = ry * ry;\n\n\t\t\t}\n\n\t\t\tvar dq = ( rxs * y1ps + rys * x1ps );\n\t\t\tvar pq = ( rxs * rys - dq ) / dq;\n\t\t\tvar q = Math.sqrt( Math.max( 0, pq ) );\n\t\t\tif ( large_arc_flag === sweep_flag ) q = - q;\n\t\t\tvar cxp = q * rx * y1p / ry;\n\t\t\tvar cyp = - q * ry * x1p / rx;\n\n\t\t\t// Step 3: Compute (cx, cy) from (cx′, cy′)\n\t\t\tvar cx = Math.cos( x_axis_rotation ) * cxp - Math.sin( x_axis_rotation ) * cyp + ( start.x + end.x ) / 2;\n\t\t\tvar cy = Math.sin( x_axis_rotation ) * cxp + Math.cos( x_axis_rotation ) * cyp + ( start.y + end.y ) / 2;\n\n\t\t\t// Step 4: Compute θ1 and Δθ\n\t\t\tvar theta = svgAngle( 1, 0, ( x1p - cxp ) / rx, ( y1p - cyp ) / ry );\n\t\t\tvar delta = svgAngle( ( x1p - cxp ) / rx, ( y1p - cyp ) / ry, ( - x1p - cxp ) / rx, ( - y1p - cyp ) / ry ) % ( Math.PI * 2 );\n\n\t\t\tpath.currentPath.absellipse( cx, cy, rx, ry, theta, theta + delta, sweep_flag === 0, x_axis_rotation );\n\n\t\t}",
"function arc(cx, cy, rx, ry, rot, largeArc, sweep, endx, endy) {\n let arc = document.createElementNS(Svg.svgNS, \"path\");\n arc.setAttribute(\"d\", `\n M ${cx},${cy}\n a ${rx},${ry} ${rot} ${(largeArc ? 1 : 0)},${(sweep ? 1 : 0)} ${endx},${endy}\n `);\n return arc;\n }",
"arc(x, y, radius, startAngle, endAngle, anticlockwise = false) {\n const entired = Math.abs(endAngle - startAngle) >= 2 * Math.PI;\n if (Math.abs(startAngle) > 2 * Math.PI) startAngle = startAngle % (2 * Math.PI);\n if (startAngle < 0) startAngle = 2 * Math.PI + startAngle;\n if (Math.abs(endAngle) > 2 * Math.PI) endAngle = endAngle % (2 * Math.PI);\n if (endAngle < 0) endAngle = 2 * Math.PI + endAngle;\n\n if (entired) {\n endAngle = startAngle + 2 * Math.PI;\n } else {\n if (anticlockwise) {\n [startAngle, endAngle] = [endAngle, startAngle];\n }\n\n if (endAngle < startAngle) {\n endAngle = endAngle + 2 * Math.PI;\n }\n }\n\n let angle = endAngle - startAngle;\n let r = 0;\n const PI_2 = Math.PI / 2; // approximate the arc by a Bezier curve.\n\n const k0 = 4 * (Math.sqrt(2) - 1) / 3; // 0.55228474983...\n\n const tm0 = new _TransferMatrix2D__WEBPACK_IMPORTED_MODULE_5__[\"TransferMatrix2D\"]().translate(x, y).scale(radius, radius);\n let points = []; // tslint:disable-next-line:ban-comma-operator\n\n for (; PI_2 < angle; r += PI_2, angle -= PI_2) {\n const tm = tm0.rotate(startAngle + r);\n if (points.length === 0) points.push(tm.transfer(new _TransferMatrix2D__WEBPACK_IMPORTED_MODULE_5__[\"Point2D\"](1, 0)));\n points.push(tm.transfer(new _TransferMatrix2D__WEBPACK_IMPORTED_MODULE_5__[\"Point2D\"](1, k0)));\n points.push(tm.transfer(new _TransferMatrix2D__WEBPACK_IMPORTED_MODULE_5__[\"Point2D\"](k0, 1)));\n points.push(tm.transfer(new _TransferMatrix2D__WEBPACK_IMPORTED_MODULE_5__[\"Point2D\"](0, 1)));\n }\n\n const k1 = 4 * Math.tan(angle / 4) / 3;\n {\n const tm = tm0.rotate(startAngle + r);\n if (points.length === 0) points.push(tm.transfer(new _TransferMatrix2D__WEBPACK_IMPORTED_MODULE_5__[\"Point2D\"](1, 0)));\n points.push(tm.transfer(new _TransferMatrix2D__WEBPACK_IMPORTED_MODULE_5__[\"Point2D\"](1, k1)));\n points.push(tm.transfer(new _TransferMatrix2D__WEBPACK_IMPORTED_MODULE_5__[\"Point2D\"](Math.cos(angle) + k1 * Math.sin(angle), Math.sin(angle) - k1 * Math.cos(angle))));\n points.push(tm.transfer(new _TransferMatrix2D__WEBPACK_IMPORTED_MODULE_5__[\"Point2D\"](Math.cos(angle), Math.sin(angle))));\n }\n if (anticlockwise) points = points.reverse();\n const p = points[points.length - 1];\n points = points.map(pt => this.ctm.transfer(pt));\n this.subpath.push(this.subpathIsEmptyOrClosed ? \"M\" : \"L\", points.shift(), \"C\");\n this.subpath.push(...points);\n this.currentPoint = this.subpath[this.subpath.length - 1];\n this.currentPointOnCtm = p;\n }",
"dispatchArcArc(cpA, extendA, cpB, extendB, reversed) {\n // Arc: X = C + cU + sV\n // Line: contains points A0,A1\n // Arc point colinear with line if det (A0, A1, X) = 0\n // with homogeneous xyw points and vectors.\n // With equational X: det (A0, A1, C) + c det (A0, A1,U) + s det (A0, A1, V) = 0.\n // solve for theta.\n // evaluate points.\n // project back to line.\n let matrixA;\n let matrixB;\n if (this._worldToLocalPerspective) {\n const dataA = cpA.toTransformedPoint4d(this._worldToLocalPerspective);\n const dataB = cpB.toTransformedPoint4d(this._worldToLocalPerspective);\n matrixA = Matrix3d_1.Matrix3d.createColumnsXYW(dataA.vector0, dataA.vector0.w, dataA.vector90, dataA.vector90.w, dataA.center, dataA.center.w);\n matrixB = Matrix3d_1.Matrix3d.createColumnsXYW(dataB.vector0, dataB.vector0.w, dataB.vector90, dataA.vector90.w, dataB.center, dataB.center.w);\n }\n else {\n const dataA = cpA.toTransformedVectors(this._worldToLocalAffine);\n const dataB = cpB.toTransformedVectors(this._worldToLocalAffine);\n matrixA = Matrix3d_1.Matrix3d.createColumnsXYW(dataA.vector0, 0, dataA.vector90, 0, dataA.center, 1);\n matrixB = Matrix3d_1.Matrix3d.createColumnsXYW(dataB.vector0, 0, dataB.vector90, 0, dataB.center, 1);\n }\n const conditionA = matrixA.conditionNumber();\n const conditionB = matrixB.conditionNumber();\n if (conditionA > conditionB)\n this.dispatchArcArc_thisOrder(cpA, matrixA, extendA, cpB, matrixB, extendB, reversed);\n else\n this.dispatchArcArc_thisOrder(cpB, matrixB, extendB, cpA, matrixA, extendA, !reversed);\n }",
"function ArcCollection() {\nvar _xx, _yy, // coordinates data\n _ii, _nn, // indexes, sizes\n _zz, _zlimit = 0, // simplification\n _bb, _allBounds, // bounding boxes\n _arcIter, _filteredArcIter; // path iterators\n\nif (arguments.length == 1) {\ninitLegacyArcs(arguments[0]); // want to phase this out\n} else if (arguments.length == 3) {\ninitXYData.apply(this, arguments);\n} else {\nerror(\"ArcCollection() Invalid arguments\");\n}\n\nfunction initLegacyArcs(arcs) {\nvar xx = [], yy = [];\nvar nn = arcs.map(function(points) {\n var n = points ? points.length : 0;\n for (var i=0; i<n; i++) {\n xx.push(points[i][0]);\n yy.push(points[i][1]);\n }\n return n;\n});\ninitXYData(nn, xx, yy);\n}\n\nfunction initXYData(nn, xx, yy) {\nvar size = nn.length;\nif (nn instanceof Array) nn = new Uint32Array(nn);\nif (xx instanceof Array) xx = new Float64Array(xx);\nif (yy instanceof Array) yy = new Float64Array(yy);\n_xx = xx;\n_yy = yy;\n_nn = nn;\n_zz = null;\n_filteredArcIter = null;\n\n// generate array of starting idxs of each arc\n_ii = new Uint32Array(size);\nfor (var idx = 0, j=0; j<size; j++) {\n _ii[j] = idx;\n idx += nn[j];\n}\n\nif (idx != _xx.length || _xx.length != _yy.length) {\n error(\"ArcCollection#initXYData() Counting error\");\n}\n\ninitBounds();\n// Pre-allocate some path iterators for repeated use.\n_arcIter = new ArcIter(_xx, _yy);\nreturn this;\n}\n\nfunction initZData(zz) {\nif (!zz) {\n _zz = null;\n _filteredArcIter = null;\n} else {\n if (zz.length != _xx.length) error(\"ArcCollection#initZData() mismatched arrays\");\n if (zz instanceof Array) zz = new Float64Array(zz);\n _zz = zz;\n _filteredArcIter = new FilteredArcIter(_xx, _yy, _zz);\n}\n}\n\nfunction initBounds() {\nvar data = calcArcBounds(_xx, _yy, _nn);\n_bb = data.bb;\n_allBounds = data.bounds;\n}\n\nfunction calcArcBounds(xx, yy, nn) {\nvar numArcs = nn.length,\n bb = new Float64Array(numArcs * 4),\n bounds = new Bounds(),\n arcOffs = 0,\n arcLen,\n j, b;\nfor (var i=0; i<numArcs; i++) {\n arcLen = nn[i];\n if (arcLen > 0) {\n j = i * 4;\n b = MapShaper.calcArcBounds(xx, yy, arcOffs, arcLen);\n bb[j++] = b[0];\n bb[j++] = b[1];\n bb[j++] = b[2];\n bb[j] = b[3];\n arcOffs += arcLen;\n bounds.mergeBounds(b);\n }\n}\nreturn {\n bb: bb,\n bounds: bounds\n};\n}\n\nthis.updateVertexData = function(nn, xx, yy, zz) {\ninitXYData(nn, xx, yy);\ninitZData(zz || null);\n};\n\n// Give access to raw data arrays...\nthis.getVertexData = function() {\nreturn {\n xx: _xx,\n yy: _yy,\n zz: _zz,\n bb: _bb,\n nn: _nn,\n ii: _ii\n};\n};\n\nthis.getCopy = function() {\nvar copy = new ArcCollection(new Int32Array(_nn), new Float64Array(_xx),\n new Float64Array(_yy));\nif (_zz) copy.setThresholds(new Float64Array(_zz));\nreturn copy;\n};\n\nfunction getFilteredPointCount() {\nvar zz = _zz, z = _zlimit;\nif (!zz || !z) return this.getPointCount();\nvar count = 0;\nfor (var i=0, n = zz.length; i<n; i++) {\n if (zz[i] >= z) count++;\n}\nreturn count;\n}\n\nfunction getFilteredVertexData() {\nvar len2 = getFilteredPointCount();\nvar arcCount = _nn.length;\nvar xx2 = new Float64Array(len2),\n yy2 = new Float64Array(len2),\n zz2 = new Float64Array(len2),\n nn2 = new Int32Array(arcCount),\n i=0, i2 = 0,\n n, n2;\n\nfor (var arcId=0; arcId < arcCount; arcId++) {\n n2 = 0;\n n = _nn[arcId];\n for (var end = i+n; i < end; i++) {\n if (_zz[i] >= _zlimit) {\n xx2[i2] = _xx[i];\n yy2[i2] = _yy[i];\n zz2[i2] = _zz[i];\n i2++;\n n2++;\n }\n }\n if (n2 < 2) error(\"Collapsed arc\"); // endpoints should be z == Infinity\n nn2[arcId] = n2;\n}\nreturn {\n xx: xx2,\n yy: yy2,\n zz: zz2,\n nn: nn2\n};\n}\n\nthis.getFilteredCopy = function() {\nif (!_zz || _zlimit === 0) return this.getCopy();\nvar data = getFilteredVertexData();\nvar copy = new ArcCollection(data.nn, data.xx, data.yy);\ncopy.setThresholds(data.zz);\nreturn copy;\n};\n\n// Return arcs as arrays of [x, y] points (intended for testing).\nthis.toArray = function() {\nvar arr = [];\nthis.forEach(function(iter) {\n var arc = [];\n while (iter.hasNext()) {\n arc.push([iter.x, iter.y]);\n }\n arr.push(arc);\n});\nreturn arr;\n};\n\nthis.toString = function() {\nreturn JSON.stringify(this.toArray());\n};\n\n// Snap coordinates to a grid of @quanta locations on both axes\n// This may snap nearby points to the same coordinates.\n// Consider a cleanup pass to remove dupes, make sure collapsed arcs are\n// removed on export.\n//\nthis.quantize = function(quanta) {\nvar bb1 = this.getBounds(),\n bb2 = new Bounds(0, 0, quanta-1, quanta-1),\n transform = bb1.getTransform(bb2),\n inverse = transform.invert();\n\nthis.applyTransform(transform, true);\nthis.applyTransform(inverse);\n};\n\n// Return average segment length (with simplification)\nthis.getAvgSegment = function() {\nvar sum = 0, count = 0;\nthis.forEachSegment(function(i, j, xx, yy) {\n var dx = xx[i] - xx[j],\n dy = yy[i] - yy[j];\n sum += Math.sqrt(dx * dx + dy * dy);\n count++;\n});\nreturn sum / count || 0;\n};\n\n// Return average magnitudes of dx, dy (with simplification)\nthis.getAvgSegment2 = function() {\nvar dx = 0, dy = 0, count = 0;\nthis.forEachSegment(function(i, j, xx, yy) {\n dx += Math.abs(xx[i] - xx[j]);\n dy += Math.abs(yy[i] - yy[j]);\n count++;\n});\nreturn [dx / count || 0, dy / count || 0];\n};\n\nthis.forEachArcSegment = function(arcId, cb) {\nvar fw = arcId >= 0,\n absId = fw ? arcId : ~arcId,\n zlim = this.getRetainedInterval(),\n n = _nn[absId],\n i = fw ? _ii[absId] : _ii[absId] + n - 1,\n step = fw ? 1 : -1,\n count = 0,\n prev;\n\nfor (var j = 0; j < n; j++, i += step) {\n if (zlim === 0 || _zz[i] >= zlim) {\n if (count > 0) {\n cb(prev, i, _xx, _yy);\n }\n prev = i;\n count++;\n }\n}\n};\n\nthis.forEachSegment = function(cb) {\nfor (var i=0, n=this.size(); i<n; i++) {\n this.forEachArcSegment(i, cb);\n}\n};\n\n// Apply a linear transform to the data, with or without rounding.\n//\nthis.applyTransform = function(t, round) {\nvar xx = _xx, yy = _yy, x, y;\nif (round && typeof round != 'function') {\n round = Math.round;\n}\nif (!t) {\n t = new Transform(); // null transform\n}\nfor (var i=0, n=xx.length; i<n; i++) {\n x = xx[i] * t.mx + t.bx;\n y = yy[i] * t.my + t.by;\n if (round) {\n x = round(x);\n y = round(y);\n }\n xx[i] = x;\n yy[i] = y;\n}\ninitBounds();\n};\n\n// Return an ArcIter object for each path in the dataset\n//\nthis.forEach = function(cb) {\nfor (var i=0, n=this.size(); i<n; i++) {\n cb(this.getArcIter(i), i);\n}\n};\n\n// Iterate over arcs with access to low-level data\n//\nthis.forEach2 = function(cb) {\nfor (var arcId=0, n=this.size(); arcId<n; arcId++) {\n cb(_ii[arcId], _nn[arcId], _xx, _yy, _zz, arcId);\n}\n};\n\nthis.forEach3 = function(cb) {\nvar start, end, xx, yy, zz;\nfor (var arcId=0, n=this.size(); arcId<n; arcId++) {\n start = _ii[arcId];\n end = start + _nn[arcId];\n xx = _xx.subarray(start, end);\n yy = _yy.subarray(start, end);\n if (_zz) zz = _zz.subarray(start, end);\n cb(xx, yy, zz, arcId);\n}\n};\n\n// Remove arcs that don't pass a filter test and re-index arcs\n// Return array mapping original arc ids to re-indexed ids. If arr[n] == -1\n// then arc n was removed. arr[n] == m indicates that the arc at n was\n// moved to index m.\n// Return null if no arcs were re-indexed (and no arcs were removed)\n//\nthis.filter = function(cb) {\nvar map = new Int32Array(this.size()),\n goodArcs = 0,\n goodPoints = 0;\nfor (var i=0, n=this.size(); i<n; i++) {\n if (cb(this.getArcIter(i), i)) {\n map[i] = goodArcs++;\n goodPoints += _nn[i];\n } else {\n map[i] = -1;\n }\n}\nif (goodArcs === this.size()) {\n return null;\n} else {\n condenseArcs(map);\n if (goodArcs === 0) {\n // no remaining arcs\n }\n return map;\n}\n};\n\nfunction condenseArcs(map) {\nvar goodPoints = 0,\n goodArcs = 0,\n copyElements = MapShaper.copyElements,\n k, arcLen;\nfor (var i=0, n=map.length; i<n; i++) {\n k = map[i];\n arcLen = _nn[i];\n if (k > -1) {\n copyElements(_xx, _ii[i], _xx, goodPoints, arcLen);\n copyElements(_yy, _ii[i], _yy, goodPoints, arcLen);\n if (_zz) copyElements(_zz, _ii[i], _zz, goodPoints, arcLen);\n _nn[k] = arcLen;\n goodPoints += arcLen;\n goodArcs++;\n }\n}\n\ninitXYData(_nn.subarray(0, goodArcs), _xx.subarray(0, goodPoints),\n _yy.subarray(0, goodPoints));\nif (_zz) initZData(_zz.subarray(0, goodPoints));\n}\n\nthis.dedupCoords = function() {\nvar arcId = 0, i = 0, i2 = 0,\n arcCount = this.size(),\n zz = _zz,\n arcLen, arcLen2;\nwhile (arcId < arcCount) {\n arcLen = _nn[arcId];\n arcLen2 = MapShaper.dedupArcCoords(i, i2, arcLen, _xx, _yy, zz);\n _nn[arcId] = arcLen2;\n i += arcLen;\n i2 += arcLen2;\n arcId++;\n}\nif (i > i2) {\n initXYData(_nn, _xx.subarray(0, i2), _yy.subarray(0, i2));\n if (zz) initZData(zz.subarray(0, i2));\n}\nreturn i - i2;\n};\n\nthis.getVertex = function(arcId, nth) {\nvar i = this.indexOfVertex(arcId, nth);\nreturn {\n x: _xx[i],\n y: _yy[i]\n};\n};\n\nthis.indexOfVertex = function(arcId, nth) {\nvar absId = arcId < 0 ? ~arcId : arcId,\n len = _nn[absId];\nif (nth < 0) nth = len + nth;\nif (absId != arcId) nth = len - nth - 1;\nif (nth < 0 || nth >= len) error(\"[ArcCollection] out-of-range vertex id\");\nreturn _ii[absId] + nth;\n};\n\n// Test whether the vertex at index @idx is the endpoint of an arc\nthis.pointIsEndpoint = function(idx) {\nvar ii = _ii,\n nn = _nn;\nfor (var j=0, n=ii.length; j<n; j++) {\n if (idx === ii[j] || idx === ii[j] + nn[j] - 1) return true;\n}\nreturn false;\n};\n\n// Tests if arc endpoints have same x, y coords\n// (arc may still have collapsed);\nthis.arcIsClosed = function(arcId) {\nvar i = this.indexOfVertex(arcId, 0),\n j = this.indexOfVertex(arcId, -1);\nreturn i != j && _xx[i] == _xx[j] && _yy[i] == _yy[j];\n};\n\n// Tests if first and last segments mirror each other\n// A 3-vertex arc with same endpoints tests true\nthis.arcIsLollipop = function(arcId) {\nvar len = this.getArcLength(arcId),\n i, j;\nif (len <= 2 || !this.arcIsClosed(arcId)) return false;\ni = this.indexOfVertex(arcId, 1);\nj = this.indexOfVertex(arcId, -2);\nreturn _xx[i] == _xx[j] && _yy[i] == _yy[j];\n};\n\nthis.arcIsDegenerate = function(arcId) {\nvar iter = this.getArcIter(arcId);\nvar i = 0,\n x, y;\nwhile (iter.hasNext()) {\n if (i > 0) {\n if (x != iter.x || y != iter.y) return false;\n }\n x = iter.x;\n y = iter.y;\n i++;\n}\nreturn true;\n};\n\nthis.getArcLength = function(arcId) {\nreturn _nn[absArcId(arcId)];\n};\n\nthis.getArcIter = function(arcId) {\nvar fw = arcId >= 0,\n i = fw ? arcId : ~arcId,\n iter = _zz && _zlimit ? _filteredArcIter : _arcIter;\nif (i >= _nn.length) {\n error(\"#getArcId() out-of-range arc id:\", arcId);\n}\nreturn iter.init(_ii[i], _nn[i], fw, _zlimit);\n};\n\nthis.getShapeIter = function(ids) {\nreturn new ShapeIter(this).init(ids);\n};\n\n// Add simplification data to the dataset\n// @thresholds is either a single typed array or an array of arrays of removal thresholds for each arc;\n//\nthis.setThresholds = function(thresholds) {\nvar n = this.getPointCount(),\n zz = null;\nif (!thresholds) {\n // nop\n} else if (thresholds.length == n) {\n zz = thresholds;\n} else if (thresholds.length == this.size()) {\n zz = flattenThresholds(thresholds, n);\n} else {\n error(\"Invalid threshold data\");\n}\ninitZData(zz);\nreturn this;\n};\n\nfunction flattenThresholds(arr, n) {\nvar zz = new Float64Array(n),\n i = 0;\narr.forEach(function(arr) {\n for (var j=0, n=arr.length; j<n; i++, j++) {\n zz[i] = arr[j];\n }\n});\nif (i != n) error(\"Mismatched thresholds\");\nreturn zz;\n}\n\n// bake in current simplification level, if any\nthis.flatten = function() {\nif (_zlimit > 0) {\n var data = getFilteredVertexData();\n this.updateVertexData(data.nn, data.xx, data.yy);\n _zlimit = 0;\n} else {\n _zz = null;\n}\n};\n\nthis.getRetainedInterval = function() {\nreturn _zlimit;\n};\n\nthis.setRetainedInterval = function(z) {\n_zlimit = z;\nreturn this;\n};\n\nthis.getRetainedPct = function() {\nreturn this.getPctByThreshold(_zlimit);\n};\n\nthis.setRetainedPct = function(pct) {\nif (pct >= 1) {\n _zlimit = 0;\n} else {\n _zlimit = this.getThresholdByPct(pct);\n _zlimit = MapShaper.clampIntervalByPct(_zlimit, pct);\n}\nreturn this;\n};\n\n// Return array of z-values that can be removed for simplification\n//\nthis.getRemovableThresholds = function(nth) {\nif (!_zz) error(\"[arcs] Missing simplification data.\");\nvar skip = nth | 1,\n arr = new Float64Array(Math.ceil(_zz.length / skip)),\n z;\nfor (var i=0, j=0, n=this.getPointCount(); i<n; i+=skip) {\n z = _zz[i];\n if (z != Infinity) {\n arr[j++] = z;\n }\n}\nreturn arr.subarray(0, j);\n};\n\nthis.getArcThresholds = function(arcId) {\nif (!(arcId >= 0 && arcId < this.size())) {\n error(\"[arcs] Invalid arc id:\", arcId);\n}\nvar start = _ii[arcId],\n end = start + _nn[arcId];\nreturn _zz.subarray(start, end);\n};\n\nthis.getPctByThreshold = function(val) {\nvar arr, rank, pct;\nif (val > 0) {\n arr = this.getRemovableThresholds();\n rank = utils.findRankByValue(arr, val);\n pct = arr.length > 0 ? 1 - (rank - 1) / arr.length : 1;\n} else {\n pct = 1;\n}\nreturn pct;\n};\n\nthis.getThresholdByPct = function(pct) {\nvar tmp = this.getRemovableThresholds(),\n rank, z;\nif (tmp.length === 0) { // No removable points\n rank = 0;\n} else {\n rank = Math.floor((1 - pct) * (tmp.length + 2));\n}\n\nif (rank <= 0) {\n z = 0;\n} else if (rank > tmp.length) {\n z = Infinity;\n} else {\n z = utils.findValueByRank(tmp, rank);\n}\nreturn z;\n};\n\nthis.arcIntersectsBBox = function(i, b1) {\nvar b2 = _bb,\n j = i * 4;\nreturn b2[j] <= b1[2] && b2[j+2] >= b1[0] && b2[j+3] >= b1[1] && b2[j+1] <= b1[3];\n};\n\nthis.arcIsContained = function(i, b1) {\nvar b2 = _bb,\n j = i * 4;\nreturn b2[j] >= b1[0] && b2[j+2] <= b1[2] && b2[j+1] >= b1[1] && b2[j+3] <= b1[3];\n};\n\nthis.arcIsSmaller = function(i, units) {\nvar bb = _bb,\n j = i * 4;\nreturn bb[j+2] - bb[j] < units && bb[j+3] - bb[j+1] < units;\n};\n\n// TODO: allow datasets in lat-lng coord range to be flagged as planar\nthis.isPlanar = function() {\nreturn !MapShaper.probablyDecimalDegreeBounds(this.getBounds());\n};\n\nthis.size = function() {\nreturn _ii && _ii.length || 0;\n};\n\nthis.getPointCount = function() {\nreturn _xx && _xx.length || 0;\n};\n\nthis.getBounds = function() {\n\nreturn _allBounds;\n};\n\nthis.getSimpleShapeBounds = function(arcIds, bounds) {\nbounds = bounds || new Bounds();\nfor (var i=0, n=arcIds.length; i<n; i++) {\n this.mergeArcBounds(arcIds[i], bounds);\n}\nreturn bounds;\n};\n\nthis.getSimpleShapeBounds2 = function(arcIds, arr) {\nvar bbox = arr || [],\n bb = _bb,\n id = absArcId(arcIds[0]) * 4;\nbbox[0] = bb[id];\nbbox[1] = bb[++id];\nbbox[2] = bb[++id];\nbbox[3] = bb[++id];\nfor (var i=1, n=arcIds.length; i<n; i++) {\n id = absArcId(arcIds[i]) * 4;\n if (bb[id] < bbox[0]) bbox[0] = bb[id];\n if (bb[++id] < bbox[1]) bbox[1] = bb[id];\n if (bb[++id] > bbox[2]) bbox[2] = bb[id];\n if (bb[++id] > bbox[3]) bbox[3] = bb[id];\n}\nreturn bbox;\n};\n\nthis.getMultiShapeBounds = function(shapeIds, bounds) {\nbounds = bounds || new Bounds();\nif (shapeIds) { // handle null shapes\n for (var i=0, n=shapeIds.length; i<n; i++) {\n this.getSimpleShapeBounds(shapeIds[i], bounds);\n }\n}\nreturn bounds;\n};\n\nthis.mergeArcBounds = function(arcId, bounds) {\nif (arcId < 0) arcId = ~arcId;\nvar offs = arcId * 4;\nbounds.mergeBounds(_bb[offs], _bb[offs+1], _bb[offs+2], _bb[offs+3]);\n};\n}",
"function drawArc(e1,e2,a,k,num_arc, coordonnees, first, p){\n\n var x = 155+(a-1)*230,\n y= 140+(4-e1)*50-(e2-e1)*25,\n h = 2+(e2-e1)*50, x1, x2, x3, x4,y1, y2, y3, y4;\n\n if (first){\n first = false;\n\n if (k%2==0){\n\n if (e2<e1){\n coordonnees[num_arc][0] = x-30+50*((k+1)/2)+(e1-e2-1)*15;\n coordonnees[num_arc][1] = y;\n }\n else {\n coordonnees[num_arc][0] = x-30-50*((k+1)/2)-(e1-e2-1)*15;\n coordonnees[num_arc][1] = y;\n }\n }\n\n\n else {\n\n if (e2>=e1){\n coordonnees[num_arc][0] = x+50*((k+1)/2)+(e2-e1-1)*15;\n coordonnees[num_arc][1] = y ;\n }\n\n else {\n coordonnees[num_arc][0] = x-55-50*(k+1)/2-(e2-e1-1)*15+30;\n coordonnees[num_arc][1] = y ;\n }\n }\n var arc_div = document.createElement('div');\n arc_div.className = \"arc\";\n arc_div.id = num_arc;\n document.body.appendChild(arc_div);\n arc_div.onmousedown = function(evt) {\n dragged = true;\n xi = num_arc; xj = 0;\n yi = num_arc; yj = 1;\n }\n\n }\n\n\n if (k%2==0){\n\n if (e2<e1){\n x1 = x4 = x;\n y1 = y+26+(e1-e2-1)*25;\n y4 = y-26-(e1-e2-1)*25;\n line(x,y-h/2, x+8,y-h/2-8);\n line(x,y-h/2, x+8,y-h/2+8);\n noFill();\n bezier(x1, y1, coordonnees[num_arc][0], coordonnees[num_arc][1]+(e1-e2-1)*25+20, coordonnees[num_arc][0], coordonnees[num_arc][1]-(e1-e2-1)*25-20, x4, y4);\n xx = bezierPoint(x1, coordonnees[num_arc][0], coordonnees[num_arc][0], x4, 1/2);\n yy = bezierPoint(y1, coordonnees[num_arc][1]+(e1-e2-1)*25+20, coordonnees[num_arc][1]-(e1-e2-1)*25-20, y4, 1/2);\n }\n else {\n x1 = x4 = x-30;\n y1 = y+24+(e2-e1-1)*25;\n y4 = y-26-(e2-e1-1)*25;\n line(x-38,y-h/2-9, x-30,y-h/2-1);\n line(x-38,y-h/2+7, x-30,y-h/2-1);\n noFill();\n bezier(x1, y1, coordonnees[num_arc][0]-30, coordonnees[num_arc][1]+(e2-e1-1)*25+20, coordonnees[num_arc][0]-30,coordonnees[num_arc][1]-(e2-e1-1)*25-20, x4, y4);\n xx = bezierPoint(x1, coordonnees[num_arc][0]-30, coordonnees[num_arc][0]-30, x4, 1/2);\n yy = bezierPoint(y1, coordonnees[num_arc][1]+(e2-e1-1)*25+20, coordonnees[num_arc][1]-(e2-e1-1)*25-20, y4, 1/2);\n }\n }\n\n else {\n\n if (e2>=e1){\n x1 = x4 = x;\n y1 = y+26+(e2-e1-1)*25;\n y4 = y-26-(e2-e1-1)*25;\n line(x,y-h/2, x+8,y-h/2-8);\n line(x,y-h/2, x+8,y-h/2+8);\n noFill();\n bezier(x1, y1, coordonnees[num_arc][0], coordonnees[num_arc][1]+(e2-e1-1)*25+20, coordonnees[num_arc][0], coordonnees[num_arc][1]-(e2-e1-1)*25-20, x4, y4);\n xx = bezierPoint(x1, coordonnees[num_arc][0], coordonnees[num_arc][0], x4, 1/2);\n yy = bezierPoint(y1, coordonnees[num_arc][1]+(e2-e1-1)*25+20, coordonnees[num_arc][1]-(e2-e1-1)*25-20, y4, 1/2);\n }\n else {\n x1 = x4 = x-30;\n x2 = x3 = x-55-50*(k+1)/2-(e2-e1-1)*15;\n y1 = y+24+(e1-e2-1)*25;\n y4 = y-26-(e1-e2-1)*25;\n line(x-38,y-h/2-9, x-30,y-h/2-1);\n line(x-38,y-h/2+7, x-30,y-h/2-1);\n noFill();\n bezier(x1, y1, coordonnees[num_arc][0]-30, coordonnees[num_arc][1]+(e1-e2-1)*25+20, coordonnees[num_arc][0]-30,coordonnees[num_arc][1]-(e1-e2-1)*25-20, x4, y4);\n xx = bezierPoint(x1, coordonnees[num_arc][0]-30, coordonnees[num_arc][0]-30, x4, 1/2);\n yy = bezierPoint(y1, coordonnees[num_arc][1]+(e1-e2-1)*25+20, coordonnees[num_arc][1]-(e1-e2-1)*25-20, y4, 1/2);\n }\n }\n divs[num_arc].style.top = yy + \"px\";\n divs[num_arc].style.left = xx + \"px\";\n fill(255);\n ellipse(xx, yy, 5,5);\n\n}",
"function translateArc (obj, layers, options) {\n// expected values\n let lthk = obj['lthk']\n let pptx = obj['pptx']\n let ppty = obj['ppty']\n let pptz = obj['pptz']\n let swid = obj['swid']\n let ang0 = obj['ang0'] // start angle\n let ang1 = obj['ang1'] // end angle\n let name = obj['name']\n\n // convert to 2D object\n if (lthk === 0.0) {\n // FIXME need to determine resolution from object/layer/variables\n let res = CSG.defaultResolution2D\n let script = ` let ${name} = CSG.Path2D.arc({center: [${pptx},${ppty}],radius: ${swid},startangle: ${ang0},endangle: ${ang1}, resolution: ${res}})\n`\n obj['script'] = script\n addToLayer(obj, layers)\n return\n }\n // FIXME how to represent 3D arc?\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check left diagonal winner combination | function checkDiagonalFromLeftToRight(){
for (let i = 0; i < gameSize; i++) {
let array = [i + 1];
let iCounter = gameSize - 1 - i;
for (let j = 0; j < i + 1; j++ ) {
array[j] = gameField[iCounter][j];
iCounter++;
}
if (isContaineWinCombination(array, "X")) {
printWinner();
return true;
}
if (isContaineWinCombination(array, "0")) {
printWinner();
return true;
}
}
for (let i = 0; i < gameSize; i++) {
let array = [i + 1];
let iCounter = gameSize - 1 - i;
for (let j = 0; j < i + 1; j++ ) {
array[j] = gameField[j][iCounter];
iCounter++;
}
if (isContaineWinCombination(array, "X")) {
printWinner();
return true;
}
if (isContaineWinCombination(array, "0")) {
printWinner();
return true;
}
}
return false;
} | [
"function diagonalCheck(player){\n\t\tvar diag1 = []; \n\t\tvar diag2= [];\n\t\tfor (var i=0; i<cellStates.length; i++) {\n\t\t\tdiag1.push(cellStates[i][i]);\n\t\t}\n\t\tif (diag1.every(arraySameValue)) {\n\t\t\thandleWinner();\n\t\t\treturn;\n\t\t}\n\t\tfor (var j=0; j<cellStates.length; j++) {\n\t\t\tdiag2.push(cellStates[j][2-j]);\n\t\t}\n\t\tif (diag2.every(arraySameValue)) {\n\t\t\thandleWinner();\n\t\t\treturn;\n\t\t}\n\t}",
"function checkBoard() {\n var winner, empty = false;\n // check board\n for (var i = 0; i < 3; i++) {\n // horizontally\n if (cell(i, 0).v !== '-' && cell(i, 0).v == cell(i, 1).v && cell(i, 1).v == cell(i, 2).v) {\n winner = cell(i, 0).v;\n // marking winning row\n getRow(i).map(c => {c.w = true;});\n }\n \t// vertically\n if (cell(0, i).v !== '-' && cell(0, i).v == cell(1, i).v && cell(1, i).v == cell(2, i).v) {\n winner = cell(0, i).v;\n // marking winning column\n getCols(i).map(c => {c.w = true;});\n }\n if (winner) {\n \tbreak;\n }\n }\n\n // diagonally\n if (cell(0, 0).v !== '-' && cell(0, 0).v == cell(1, 1).v && cell(1, 1).v == cell(2, 2).v) {\n winner = cell(0, 0).v;\n // marking winning diagonal\n [cell(0, 0), cell(1, 1), cell(2, 2)].map(c => {c.w = true;});\n } else if (cell(0, 2).v !== '-' && cell(0, 2).v == cell(1, 1).v && cell(1, 1).v == cell(2, 0).v) {\n winner = cell(0, 2).v;\n // marking winning diagonal\n [cell(0, 2), cell(1, 1), cell(2, 0)].map(c => {c.w = true;});\n }\n\n\t\t// check for any empty cell\n for (var i = 0; i < 3; i++) {\n for (var j = 0; j < 3; j++) {\n if (cell(i, j).v === '-') {\n \tempty = true;\n \tbreak;\n }\n }\n if (empty) {\n \tbreak;\n }\n }\n\t\tif (!empty && !winner) {\n\t\t\t// the board is full and nobody wins.\n\t\t\twinner = \"Nobody\";\n\t\t}\n\n if (winner) {\n $scope.winner = winner;\n }\n }",
"_checkDiag() {\n let cells = [this.get(0,0), this.get(1,1), this.get(2,2)];\n let winner = this._is_same_player(cells);\n if (winner) { return winner; }\n\n cells = [this.get(0,2), this.get(1,1), this.get(2,0)];\n winner = this._is_same_player(cells);\n if (winner) { return winner; }\n\n return null;\n }",
"function diagonalWin() {\n for (var i = 0; i < diagonalCombinations.length; i++) {\n if (JSON.stringify(diagonalCombinations[i]) === JSON.stringify(rowCombinations[0])) {\n player = '1';\n\n return [true, player];\n } else if (JSON.stringify(diagonalCombinations[i]) === JSON.stringify(rowCombinations[1])) {\n player = '2';\n\n return [true, player];\n } else\n {\n continue;\n }\n }\n}",
"diagWin() {\n let idxDiag1 = [[0, 0], [1, 1], [2, 2]];\n let idxDiag2 = [[2, 0],[1, 1],[0, 2]];\n let diag1 = [];\n idxDiag1.forEach((pos) => diag1.push(this.grid[pos[0]][pos[1]]));\n let diag2 = [];\n idxDiag2.forEach((pos) => diag2.push(this.grid[pos[0]][pos[1]]));\n if (diag1.every( el => el === diag1[0])) {\n this.winningSymble = diag1[0];\n return true;\n }\n if (diag2.every( el => el === diag2[0])){\n this.winningSymble = diag2[0];\n return true;\n }\n return false;\n }",
"function winning_diagonal_down(player) {\n\tfor (var i = 0; i < size; i++) \n\t\tif(grid[i][i] != player)\n\t\t\treturn false;\n\treturn true;\n}",
"function check_diagonals() {\n var ltr = game_state[0][0] + game_state[1][1] + game_state[2][2];\n var rtl = game_state[0][2] + game_state[1][1] + game_state[2][0];\n switch (ltr) {\n case 3:\n win_game('Player 1');\n break;\n case -3:\n win_game('Computer');\n break;\n }\n switch (rtl) {\n case 3:\n win_game('Player 1');\n break;\n case -3:\n win_game('Computer');\n break;\n }\n}",
"function checkDiagonalWin() {\n\tfor (var col = 0; col <5; col++) {\n\t\tfor (var row = 0; row < 7; row++) {\n\t\t\tif (colorMatchCheck(getColor(row,col), getColor(row+1,col+1), getColor(row+2,col+2), getColor(row+3,col+3))) {\n\t\t\t\tconsole.log('diag');\n\t\t\t\treportWin(row,col);\n\t\t\t\treturn true;\n\t\t\t} else if (colorMatchCheck(getColor(row,col), getColor(row-1,col-1), getColor(row-2,col-2), getColor(row-3,col-3))){\n\t\t\t\tconsole.log('diag');\n\t\t\t\treportWin(row,col);\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n}",
"function winning_diagonal_up(player) {\n\tfor (var i = 0,j = size-1; i < size,j >= 0; i++,j--)\n\t\t\tif(grid[i][j] != player)\n\t\t\t\treturn false;\n\treturn true;\n\n}",
"findWinnerInDiagonals() {\n const dirSE = [1, 1];\n const dirNE = [-1, 1];\n const topLeftCorner = [0, 0];\n const bottomLeftCorner = [this.board.length - 1, 0];\n let winner = this.checkDiagonals(topLeftCorner, dirSE);\n if (winner === \"none\") {\n winner = this.checkDiagonals(bottomLeftCorner, dirNE);\n }\n return winner;\n }",
"checkForWinner(row, col) {\n const playerID = this.turn.id;\n let counter = 0; // number of same color checkers in the row so far\n let rowIndex; // row index to check\n let colIndex; // col index to check\n \n // checks for vertical win\n for (let i = 0; i < 7; i++) {\n rowIndex = row - 3 + i;\n if (rowIndex < 0 || rowIndex > this.board.rows - 1) continue;\n if (this.board.check(rowIndex, col, playerID)) {\n counter++;\n if (counter === 4) return true; // if there is a winner, return true\n } else counter = 0;\n }\n \n // checks for horizontal win\n counter = 0; // restart counter\n for (let i = 0; i < 7; i++) {\n colIndex = col - 3 + i;\n if (colIndex < 0 || colIndex > this.board.cols - 1) continue;\n if (this.board.check(row, colIndex, playerID)) {\n counter++;\n if (counter === 4) return true;\n } else counter = 0;\n }\n \n // checks for rising (/) diagonal win\n counter = 0;\n for (let i = 0; i < 7; i++) {\n rowIndex = row + 3 - i;\n colIndex = col - 3 + i;\n if (rowIndex < 0 || rowIndex > this.board.rows - 1 || colIndex < 0 || colIndex > this.board.cols - 1) continue;\n if (this.board.check(rowIndex, colIndex, playerID)) {\n counter++;\n if (counter === 4) return true;\n } else counter = 0;\n }\n \n // checks for falling (\\) diagonal win \n counter = 0; \n for (let i = 0; i < 7; i++) {\n rowIndex = row - 3 + i;\n colIndex = col - 3 + i;\n if (rowIndex < 0 || rowIndex > this.board.rows - 1 || colIndex < 0 || colIndex > this.board.cols - 1) continue;\n if (this.board.check(rowIndex, colIndex, playerID)) {\n counter++;\n if (counter === 4) return true;\n } else counter = 0;\n }\n \n return false; // if no winner yet, return false\n }",
"function diagonalWinCheck() {\n for(var col =0;col<5;col++) {\n for(var row=0;row<7;row++) {\n if(colorMatchCheck(returnColor(row,col),returnColor(row+1,col+1),returnColor(row+2,col+2))) {\n console.log(\"diagonal\");\n reportWin(row,col);\n return true;\n }else if(colorMatchCheck(returnColor(row,col), returnColor(row-1,col+1),returnColor(row-2,col+2))) {\n console.log(\"diagonal\");\n reportWin(row,col);\n return true;\n }else {\n continue;\n }\n }\n }\n}",
"__checkDiagonals(){\n\t\treturn (this.board[0][0] == this.board[1][1] && this.board[1][1] == this.board[2][2] && this.board[0][0]) ||\n\t\t\t\t(this.board[0][2] == this.board[1][1] && this.board[1][1] == this.board[2][0] && this.board[0][2])\n\t}",
"function checkDiagonialDown() {\n // loop through the rows\n for (var row = 0; row <= rowCount - connect; row++) {\n // loop through the columns\n for (var col = 0; col <= colCount - connect; col++) {\n // checking for 4 diagonial top down\n if (board[row][col] != 0 &&\n board[row][col] === board[row+1][col+1] &&\n board[row][col] === board[row+2][col+2] &&\n board[row][col] === board[row+3][col+3]) {\n winner = board[row][col];\n return board[row][col];\n }\n }\n }\n}",
"checkDiagonalLeft(row, col) {\n let cell = this.state.cells\n let changePlayer = this.state.player ? 2 : 1\n\n while (row < 5 && col > 0) {\n row++\n col--\n }\n\n while (row >= 3 && col <= 3) {\n if (cell[row][col] === changePlayer &&\n cell[row - 1][col + 1] === changePlayer &&\n cell[row - 2][col + 2] === changePlayer &&\n cell[row - 3][col + 3] === changePlayer) {\n return 1\n }\n row--\n col++\n }\n return 0\n }",
"function diagonalWin() {\n\n //if one diagonal win returns true\n if(board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != ' ' ){\n return true;\n }\n //if other diagonal win returns true\n else if( board[2][0] == board[1][1] && board[1][1] == board[0][2] && board[2][0] != ' '){\n return true;\n }\n\n}",
"function checkDiagonialUp() {\n // loop through the rows\n for (var row = rowCount - 1; row >= rowCount - connect; row--) {\n // loop through the columns\n for (var col = 0; col <= colCount - connect; col++) {\n // checking for 4 diagonial up\n if (board[row][col] != 0 &&\n board[row][col] === board[row-1][col+1] &&\n board[row][col] === board[row-2][col+2] &&\n board[row][col] === board[row-3][col+3]) {\n winner = board[row][col];\n return board[row][col];\n }\n }\n }\n}",
"checkDiagonalRight(){\n for (let r = 3; r < 6; r++) {\n for (let c = 0; c < 4; c++) {\n if (this.board[r][c]){\n if (this.board[r][c] === this.board[r - 1][c + 1] &&\n this.board[r][c] === this.board[r - 2][c + 2] &&\n this.board[r][c] === this.board[r - 3][c + 3])\n {\n return this.board;\n }\n }\n }\n }\n }",
"function _checkMoves() {\n\t\t\n\t\t// iterate through the rows\n\t\tfor(row = 0; row < _rows; row++) {\n\t\t\t\n\t\t\t// iterate through the cols\n\t\t\tfor (col = 0; col < _cols; col++) {\n\t\t\t\t\n\t\t\t\t// check top and bottom\n\t\t\t\tif(row - 1 >= 0 && typeof _board[row - 1][col] !== \"undefined\"\n\t\t\t\t && row + 1 < _rows && typeof _board[row + 1][col] !== \"undefined\"){\n\t\t\t\t\t\n\t\t\t\t\tif(_board[row - 1][col] === _board[row][col] && _board[row + 1][col] === _board[row][col]) {\n\t\t\t\t\t\t_winnerFound = true;\n\t\t\t\t\t\t_winner = _board[row][col];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// check left and right\n\t\t\t\tif(col - 1 >= 0 && typeof _board[row][col - 1] !== \"undefined\"\n\t\t\t\t && col + 1 < _cols && typeof _board[row][col + 1] !== \"undefined\"){\n\t\t\t\t\t\n\t\t\t\t\tif(_board[row][col - 1] === _board[row][col] && _board[row][col + 1] === _board[row][col]) {\n\t\t\t\t\t\t_winnerFound = true;\n\t\t\t\t\t\t_winner = _board[row][col];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// check diagonals\n\t\t\t\tif(col - 1 >= 0 && col + 1 < _cols && row - 1 >= 0 && row + 1 < _rows){\n\n\t\t\t\t\tif(typeof _board[row - 1][col - 1] !== \"undefined\"\n\t\t\t\t\t && typeof _board[row + 1][col + 1] !== \"undefined\"\n\t\t\t\t\t && _board[row - 1][col - 1] === _board[row][col] \n\t\t\t\t\t && _board[row + 1][col + 1] === _board[row][col]) {\n\t\t\t\t\t\t_winnerFound = true;\n\t\t\t\t\t\t_winner = _board[row][col];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else if(typeof _board[row - 1][col + 1] !== \"undefined\"\n\t\t\t\t\t && typeof _board[row + 1][col - 1] !== \"undefined\"\n\t\t\t\t\t && _board[row - 1][col + 1] === _board[row][col] \n\t\t\t\t\t\t&& _board[row + 1][col - 1] === _board[row][col]) {\n\t\t\t\t\t\t_winnerFound = true;\n\t\t\t\t\t\t_winner = _board[row][col];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t// if winner was found, then break out of loop\n\t\t\tif(_winnerFound) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Triggered when a file is selected via the media picker. | function onMediaFileSelected(event) {
event.preventDefault();
var file = event.target.files[0];
// Clear the selection in the file picker input.
imageFormElement.reset();
// Check if the file is an image.
if (!file.type.match('image.*')) {
var data = {
message: 'You can only share images',
timeout: 2000
};
signInSnackbarElement.MaterialSnackbar.showSnackbar(data);
return;
}
// Check if the user is signed-in
if (checkSignedInWithMessage()) {
saveImageMessage(file);
}
} | [
"function onMediaFileSelected(event) {\n event.preventDefault();\n var file = event.target.files[0];\n\n\n // Clear the selection in the file picker input.\n imageFormElement.reset();\n\n // Check if the file is an image.\n if (!file.type.match('image.*')) {\n var data = {\n message: 'You can only share images',\n timeout: 2000\n };\n //signInSnackbarElement.MaterialSnackbar.showSnackbar(data);\n return;\n }\n // Check if the user is signed-in\n if (checkSignedInWithMessage()) {\n //console.log(\"File: \"+JSON.stringify(file));\n saveImageMessage(file);\n }\n}",
"function onMediaFileSelected(event) {\n event.preventDefault();\n var file = event.target.files[0];\n\n // Clear the selection in the file picker input.\n imageFormElement1.reset();\n\n // Check if the file is an image.\n if (!file.type.match('image.*')) {\n var data = {\n message: 'You can only share images',\n timeout: 2000\n };\n signInSnackbarElement1.MaterialSnackbar.showSnackbar(data);\n return;\n }\n // Check if the user is signed-in\n if (checkSignedInWithMessage()) {\n saveImageMessage(file);\n }\n}",
"function onMediaFileSelected(event) {\n event.preventDefault();\n var file = event.target.files[0];\n\n // Clear the selection in the file picker input.\n imageFormElement.reset();\n\n // Check if the file is an image.\n if (!file.type.match('image.*')) {\n var data = {\n message: 'You can only share images',\n timeout: 2000\n };\n signInSnackbarElement.MaterialSnackbar.showSnackbar(data);\n return;\n }\n // Check if the user is signed-in\n if (checkSignedInWithMessage()) {\n saveImageMessage(file);\n }\n}",
"function on_file_selected() {\n\n // if the user canceled, just return.\n if ( $('#fcu')[0].files.length == 0 ){\n return;\n }\n\n // update the display label with the file name\n $('#fcuLabel').text($('#fcu')[0].files[0].name);\n\n // upload the file and start the audio processing\n upload_audio();\n}",
"function onMediaFileSelected(event) {\n event.preventDefault();\n var file = event.target.files[0];\n\n // Clear the selection in the file picker input.\n imageFormElement.reset();\n\n // Check if the file is an image.\n if (!file.type.match(\"image.*\")) {\n var data = {\n message: \"You can only share images\",\n timeout: 2000\n };\n signInSnackbarElement.MaterialSnackbar.showSnackbar(data);\n return;\n }\n // Check if the user is signed-in\n if (checkSignedInWithMessage()) {\n saveImageMessage(file);\n }\n}",
"function fileSelectedHandler(event) {\n console.log(\"file selected: \" + event.target.files[0]);\n setThumbnail(event.target.files[0]);\n }",
"function file_selected(ev) {\n var files = ev.target.files;\n if (files.length != 1) {\n alert(\"You can only upload one file at a time.\");\n return;\n }\n set_file(files[0]);\n }",
"function selectFile() {\n\n // This pops up a \"file picker\" that allows user to select an object from their device.\n // It appears to only allow for images on current Firefox OS devices, even though the\n // Simulator allows audio and contact files to be selected. Not sure why.\n var activity = new MozActivity({\n name: \"pick\",\n data: {\n type: [\"image/png\", \"image/jpg\", \"image/jpeg\", \"audio/mpeg\", \"audio/mp4\", \"audio/ogg\", \"video/mp4\", \"video/3gpp\", \"application/pdf\" ]\n
}\n });\n\n activity.onsuccess = function () {\n uploadFile(this.result.blob);\n };\n \n // Display an alert if we cancel the file picker operation.\n pick.onerror = function () {\n alert(\"No file selected.\");\n };\n}",
"function handleFileSelect() {\n var picture = document.getElementById('picture_input').files.item(0);\n displayPicturePreview(picture);\n }",
"function onSendFileBtnClick() {\n app.external.pickSingleFile(onFilePicked, onFilePickError);\n }",
"function handleFileUploadChange(e) {\n // selectedFile that will keep track of whatever file a user has input via the Choose File button\n selectedFile = e.target.files[0];\n}",
"function selectFile() {\r\n $(\"#select-file\").click();\r\n}",
"function setSelectFileEvent() {\n $(document).on('selectFile', function (eventObject, value) {\n if (value.isMultiple) {\n fileSelect.prop('multiple', 'multiple');\n }\n else {\n fileSelect.removeProp('multiple');\n }\n fileSelect.click();\n fileSelect.off('change');\n fileSelect.one('change', function (eventObject) {\n var target = eventObject.target;\n var files = target.files;\n value.callback(files);\n showProperty(selectedTree);\n });\n });\n }",
"function fileChoose(e) {\n\t\n\tdocument.getElementById(\"uploadFile\").click();\n}",
"function handleFileSelect(evt) \n{\n //console.log('file uploaded'); //debugg\n file = evt.target.files[0]; // FileList object\n}",
"function handleFileSelected(file) {\n const uploadButton = document.getElementById('upload-button')\n selectedFile = file\n if (file == null) {\n uploadButton.disabled = true\n return\n }\n updatePreviewImages(file)\n uploadButton.disabled = false\n}",
"function chosenMedia(e) {\n if (e.outVal != undefined && e.outVal != null) {\n var media = e.outVal;\n $(currentMediaPicker).find(\".fileId\").val(media.id);\n $(currentMediaPicker).find(\".fileType\").val(media.type);\n $(currentMediaPicker).find(\".filePath\").val(media.path);\n $(currentMediaPicker).find(\".chosenMediaItem > span\").text(media.name);\n if (media.isPreviewable) {\n if (media.isImage) {\n $(currentMediaPicker).find(\"img.preview\").attr(\"src\", media.path);\n $(currentMediaPicker).find(\"img.preview\").show();\n $(currentMediaPicker).find(\"img.playButton\").hide();\n }\n else {\n $(currentMediaPicker).find(\"img.preview\").hide();\n $(currentMediaPicker).find(\"img.playButton\").show();\n }\n }\n else {\n $(currentMediaPicker).find(\"img.preview\").hide();\n $(currentMediaPicker).find(\"img.playButton\").hide();\n }\n }\n}",
"function handlePictureSelect() {\n searchElement(\"modal-file\").click();\n }",
"function onClickFile(fileItem) {\n // Try to detect file type\n var ext = fileItem.split('.').pop().toLowerCase();\n if(ext == 'mp4') {\n displayPanoVideo(fileItem);\n } else if (ext == \"jpg\" || ext == \"jpeg\" || ext == \"png\") {\n displayPanoPhoto(fileItem);\n }\n updateListHighlight(lastSelection, \"normal\");\n updateListHighlight(fileItem, \"highlight\");\n lastSelection = fileItem;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
updates the task running status according to the current queue | updateTaskRunning() {
this.taskRunning = !this.isEmpty;
} | [
"updateTaskToDone(taskId) {\n this.getTask(taskId).status = \"Done\";\n }",
"function updateTaskStatus() {\n let foundNextTask = false;\n\n vm.tasks.forEach(task => {\n // Set isForbidden\n task.isForbidden = !task.non_admin_may_edit && User.isNonAdmin();\n\n // Hide controls if hidden from non-admins\n task.isDataHidden = task.data_admin_only_visible && User.isNonAdmin();\n\n // Set isCurrentTask\n task.isCurrent = false;\n\n const isCurrent =\n !foundNextTask && task.status === 'incomplete' && !task.isForbidden;\n\n if (isCurrent) {\n task.isCurrent = true;\n vm.nextTaskUid = task.uid;\n\n foundNextTask = true;\n }\n });\n }",
"statusJob() {\n if (task) {\n if ((task.status = 'scheduled')) {\n return count;\n }\n }\n return -1;\n }",
"function checkTaskStatus() {\r\n if ( task.status === 'QUEUED' || task.status === 'RUNNING' || task.status === 'NEW' ) {\r\n ProgressStatusService.getSubmittedTask( task.taskId, {\r\n callback : function onSuccess( submittedTask ) {\r\n if ( submittedTask === null ) {\r\n task.status = 'UNKNOWN';\r\n task.fireEvent( 'synchronization-error', \"Task not found on the server.\" );\r\n Ext.Msg.alert( \"synchronization-error\" );\r\n return;\r\n }\r\n\r\n sync( submittedTask ); // copy state from the server to ObservableSubmittedTask\r\n\r\n Ext.defer( checkTaskStatus, 3000 ); // check again after delay\r\n\r\n },\r\n errorHandler : function onFailure( error ) {\r\n // can't get updates from the server.\r\n // stop checking for updates.\r\n task.status = 'UNKNOWN';\r\n task.fireEvent( 'synchronization-error', error );\r\n Ext.Msg.alert( \"synchronization-error\" );\r\n }\r\n } );\r\n }\r\n }",
"function updateStatus() {\n if (utils.isEmptyVal(vm.status)) {\n notificationService.error(\"Please select status\");\n return;\n }\n var taskDetails = {};\n var ids = utils.isEmptyVal(vm.taskIds) ? '' : _.pluck(vm.taskIds, 'intake_task_id');\n var taskid = ids.toString();\n taskDetails.status = utils.isEmptyVal(vm.status) ? '' : vm.status;\n taskDetails.percentage_complete = utils.isEmptyVal(vm.status) ? '' : (vm.status == 'Completed') ? '100' : (vm.status == 'Not Started') ? '0' : (vm.status == 'In Progress') ? '25' : '0';\n intakeTasksDatalayer.taskStatus(taskDetails, taskid)\n .then(function (response) {\n if (response == true) {\n notificationService.success('Task status updated successfully.');\n getAllTasks();\n vm.taskIds = [];\n vm.status = [];\n } else {\n notificationService.error('Unable to update status.');\n }\n\n }, function (error) {\n notificationService.error('Unable to update status.');\n });\n }",
"function update_queue_status_txt() {\n \n $('#queue_status').html(get_queue_count() + \" items queued.\");\n \n}",
"statusCheck(){\n console.log(`\\nTaskQueue length is ${this.taskQueue.length} !!`);\n let index = 0; //taking index separately, cause Map.prototype.forEach doesn't provide index by itself\n this.workers.forEach((status)=>{\n console.log(`Worker ${index} is ${status}`);\n index++;\n });\n }",
"function taskStatusSync() {\n var taskListId = getTaskListId(TASK_LIST_NAME);\n var optionalArgs = {maxResults: 100,showHidden: true};\n var tasks = Tasks.Tasks.list(taskListId,optionalArgs);\n if (tasks.items) {\n for (var i = 0; i < tasks.items.length; i++) {\n var task = tasks.items[i];\n if (task.status == 'completed') {\n var firstLine = task.notes.split(\"\\n\")[0];\n var habiticaId = firstLine.trim();\n Logger.log(\"Completed task ID sent to Habitica: \" + habiticaId)\n scoreHabititcaTask(habiticaId);\n }\n }\n } else {\n Logger.log('No tasks found.');\n }\n}",
"function processQueue() {\n if(taskQueue.length === 0) {\n return;\n }\n\t// pull first task off the queue and run it.\n let task = taskQueue.shift();\t\n console.log('Running task. runId: ' + task.runId + ' - cluster: '+ task.CLUSTER_NAME);\n\tcurrentTasks.unshift(task);\n\ttaskExecute(task);\n}",
"function updateStatus() {\n if (utils.isEmptyVal(vm.status)) {\n notificationService.error(\"Please select status\");\n return;\n }\n var taskDetails = {};\n taskDetails.taskid = utils.isEmptyVal(vm.taskIds) ? '' : _.pluck(vm.taskIds, 'task_id');\n taskDetails.status = utils.isEmptyVal(vm.status) ? '' : vm.status;\n taskDetails.percentage_complete = utils.isEmptyVal(vm.status) ? '' : (vm.status == 'Completed') ? '100' : (vm.status == 'Not Started') ? '0' : (vm.status == 'In Progress') ? '25' : '';\n tasksDatalayer.taskStatus(taskDetails)\n .then(function (response) {\n if (response == true) {\n notificationService.success('Task status updated successfully.');\n vm.taskIds = [];\n vm.status = [];\n init();\n } else {\n notificationService.error('Unable to update status.');\n }\n }, function (error) {\n notificationService.error('Unable to update status.');\n });\n }",
"function changeTaskStatus(taskId, target) {\n if (tasks[taskId]) {\n let task = tasks[taskId];\n let oldStatus = task.status;\n\n if (\n target === \"completed\" &&\n task.completed === false &&\n members[task.worker]\n ) {\n if (!members[currentUser].isChild) {\n projects[currentProject].points += 1;\n projectpointAdded(currentProject);\n task.completed = true;\n task.status = target;\n taskUpdated();\n } else if (currentProject > 2) {\n projects[currentProject].points += 1;\n projectpointAdded(currentProject);\n task.completed = true;\n task.status = target;\n } else {\n task.status = oldStatus;\n taskUpdated();\n alert(\"Kun voksne kan godkjenne oppgaver\");\n }\n } else {\n task.status = target;\n taskUpdated();\n }\n }\n}",
"run() {\n this.updateStatus_(JobStatus.RUNNING);\n }",
"_runQueue() {\n let running = this.runningCount;\n\n while (++running <= this.maxConcurrency) {\n const index = this._getNextIndex(Object.keys(this.pending), this.type);\n\n if (index === -1) {\n break;\n }\n\n const queueItem = this.pending[index];\n\n this.running[index] = queueItem;\n this.runningCount++;\n\n delete this.pending[index];\n this.pendingCount--;\n\n queueItem.run();\n }\n }",
"processQueue() {\n if (!this.pendingTasksQueue.isEmpty()) {\n const worker = this.pickWorker();\n\n if (worker) {\n this.dispatchTaskTo(worker);\n }\n }\n\n this.checkShutdown();\n }",
"onChangeStatusTaskOnServer(taskData) {\r\n console.log('Status changed');\r\n let result = this.tasks.find((a) => a.key == taskData.taskId);\r\n let position = this.tasks.indexOf(result);\r\n this.tasks[position].enableTask();\r\n this.changeStatus(position, taskData.isDone);\r\n this.tasks[position].isWaiting = false;\r\n }",
"handleTaskStatusChange(taskId) {\r\n const tasks = this.state.tasks.map(task => {\r\n if (task.id === taskId) {\r\n task.done = !task.done;\r\n }\r\n return task;\r\n });\r\n this.setState({\r\n tasks: tasks\r\n });\r\n }",
"function updateProcessQueueStatus( p, cb ) {\n\n log.i( p.pdf + ' Step 6 - Update PDF process Queue entry to next status as Mailing done ' );\n audit.updatePdfQueueStatus( p.dbc, p.pdf, p.row[ 2 ], p.hostname, p.statusTo, function( err, result ) {\n if ( err ) {\n return cb( err )\n } else {\n return cb( null )\n }\n }); \n \n}",
"function check_running() {\n db.Task.find({status: \"running\"}).exec(function(err, tasks) {\n if(err) throw err;\n logger.info(\"check_running:\"+tasks.length);\n //logger.info(\"check_running :: loaded \"+tasks.length+\" running tasks\");\n //process synchronously so that I don't accidentally overwrap with next check\n async.eachSeries(tasks, function(task, next) {\n logger.info(\"check_running \"+task._id);\n\n db.Resource.findById(task.resource_id, function(err, resource) {\n if(err) return next(err);\n if(!resource) return next(new Error(\"can't find such resource:\"+task.resource_id));\n common.get_ssh_connection(resource, function(err, conn) {\n var taskdir = common.gettaskdir(task.instance_id, task._id, resource);\n //TODO - not all service provides bin.status.. how will this handle that?\n logger.debug(\"cd \"+taskdir+\" && ./_status.sh\");\n conn.exec(\"cd \"+taskdir+\" && ./_status.sh\", {}, function(err, stream) {\n if(err) return next(err);\n var out = \"\";\n stream.on('close', function(code, signal) {\n switch(code) {\n case 0: //still running\n next();\n break;\n case 1: //finished\n load_products(task, taskdir, conn, function(err) {\n if(err) {\n common.progress(task.progress_key, {status: 'failed', msg: err.toString()});\n task.status = \"failed\";\n task.status_msg = err;\n task.save(next);\n return;\n }\n common.progress(task.progress_key, {status: 'finished', msg: 'Service Completed'});\n task.status = \"finished\";\n task.status_msg = \"Service completed successfully\";\n task.finish_date = new Date();\n task.save(next);\n });\n break;\n case 2: //failed\n common.progress(task.progress_key, {status: 'failed', msg: 'Service failed'});\n task.status = \"failed\"; \n task.status_msg = out;\n task.save(next);\n break; \n default:\n //TODO - should I mark it as failed? or.. 3 strikes and out rule?\n logger.error(\"unknown return code:\"+code+\" returned from _status.sh\");\n next();\n }\n })\n .on('data', function(data) {\n logger.info(data.toString());\n out += data.toString();\n }).stderr.on('data', function(data) {\n logger.error(data.toString());\n out += data.toString();\n });\n });\n });\n });\n }, function(err) {\n if(err) {\n logger.error(err);\n }\n \n //all done for this round - schedule for next\n setTimeout(check_running, 1000*10); //check job status every few minutes\n });\n });\n}",
"get currentRunningTask() {\r\n return this.tasks[this.currentTaskIndex];\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
list all internal timetable | function listalltimetable(req, res) {
internalSchema.find({}, { _id: 0, semester: 1, dateTimeSub: 1 }, function (err, internalsemester) {
res.send(internalsemester);
});
} | [
"function TablesList() {}",
"function getAllTimeEntries(callback) {\n var timeEntries = [];\n var timeEntryStore = this.db.transaction(\"time_entry\", \"readonly\").objectStore(\"time_entry\");\n timeEntryStore.openCursor().onsuccess = function(event) {\n var cursor = event.target.result;\n\n if (cursor) {\n timeEntries.push(cursor.value);\n cursor.continue();\n }\n else {\n callback(timeEntries);\n }\n }\n }",
"function Timetable() {\n return [{ \"day\":\"Monday\", \"9am\":\"\", \"10am\":\"\", \"11am\":\"\", \"12pm\":\"\", \"1pm\":\"\", \"2pm\":\"\", \"3pm\":\"\", \"4pm\":\"\" }, { \"day\":\"Tuesday\", \"9am\":\"\", \"10am\":\"\", \"11am\":\"\", \"12pm\":\"\", \"1pm\":\"\", \"2pm\":\"\", \"3pm\":\"\", \"4pm\":\"\" }, { \"day\":\"Wednesday\", \"9am\":\"\", \"10am\":\"\", \"11am\":\"\", \"12pm\":\"\", \"1pm\":\"\", \"2pm\":\"\", \"3pm\":\"\", \"4pm\":\"\" }, { \"day\":\"Thursday\", \"9am\":\"\", \"10am\":\"\", \"11am\":\"\", \"12pm\":\"\", \"1pm\":\"\", \"2pm\":\"\", \"3pm\":\"\", \"4pm\":\"\" }, { \"day\":\"Friday\", \"9am\":\"\", \"10am\":\"\", \"11am\":\"\", \"12pm\":\"\", \"1pm\":\"\", \"2pm\":\"\", \"3pm\":\"\", \"4pm\":\"\" }];\n}",
"allTimeHighs() {\n return this.getAllTimeHighsV1()\n .catch((err) => {\n console.error(\"Error in 'allTimeHigh' method of nomics module\\n\" + err);\n throw new Error(err);\n });\n }",
"async list() {\n const checks = await this.api.getChecks();\n const tms = await this.api.getTms();\n\n const listTable = new Table({\n head: ['Type', 'ID', 'Name', 'Status'],\n });\n\n _.forEach(checks, (check) => {\n listTable.push(['check', check.id, check.name, check.status]);\n });\n\n _.forEach(tms, (tm) => {\n listTable.push(['tm', tm.id, tm.name, tm.status]);\n });\n\n this.logger.info(`\\n${listTable.toString()}\\n`);\n }",
"function checkLiveInTimetable(casterName, timetable) {\n if(typeof timetable === 'undefined') return undefined; \n var result = [];\n var k = 0;\n for(var i=0; i < timetable.size; i++) {\n let timeslot = timetable.get(i);\n if(casterName.localeCompare(timeslot.casterName) == 0) {\n result[k] = timeslot;\n k++;\n }\n }\n return result;\n}",
"function createEmptyTimetable(){\n var timetable = new Timetable();\n timetable.setScope(9, 21);\n \n timetable.addLocations(['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY']);\n \n return timetable;\n}",
"getAll () {\n\t\treturn Object.values(this.times)\n\t\t\t.filter(modeTime => modeTime) // remove nulls\n\t\t\t.sort((a, b) => a.compareTo(b))\n\t}",
"async function getPossibleTimeslots() {\n const timeslotDetails = await db.any(`select * from ${Tables.timeslot} ;`);\n return _.map(timeslotDetails, timeslot => new Timeslot(timeslot));\n}",
"function makeTimetable() {\n renderer.draw('.timetable'); // any css selector\n\n\n // Call database and get classes\n getData();\n}",
"function timeCookieTable() {\n}",
"function getTimeEntries() {\n\t\t\t\ttime.getTime().then(function(results) {\n\t\t\t\t\tvm.timeentries = results;\n\t\t\t\t\tconsole.log(vm.timeentries);\n\t\t\t\t}, function(error) {\n\t\t\t\t\tconsole.log(error);\n\t\t\t\t});\n\t\t\t}",
"function overview() {\n var eventsDB = Db.shared.get('events');\n \n // getting the times, starting by most recent time\n var times = Object.keys(eventsDB);\n times.reverse();\n \n // and render for each day the time\n Dom.div(function () {\n Dom.style({\n textAlign: 'center',\n marginTop: '1em'\n });\n \n times.forEach(function (time) {\n // show what day it is\n timeMessage(timeString(time));\n \n // display the events\n var events = eventsDB[time];\n events.reverse();\n events.forEach(renderEvent);\n });\n });\n }",
"async getAllTablesInTime (req, res) {\n try {\n var time = req.param('time')\n const Op = Sequelize.Op\n /* Select all tables and count customers in time period */\n const table = await Table.findAll({\n attributes: ['id', 'name', 'seatCount', 'roomId', [sequelize.fn('count', sequelize.col('Customers.id')), 'customersCount']],\n include: [{\n model: Customer,\n attributes: [],\n where: Sequelize.and(\n {\n dateIn: {\n [Op.lte]: time\n }\n },\n Sequelize.or(\n {\n dateOut: null\n },\n {\n dateOut: {\n [Op.gte]: time\n }\n }\n )\n ),\n required: false\n },\n {\n model: Room,\n attributes: ['name']\n }],\n group: ['Table.id'],\n required: false\n })\n res.send(table)\n } catch (err) {\n res.status(500).send({\n error: 'An error has occured during fetch'\n })\n }\n }",
"function getBookedTables (bookings) {\n var currentTime = new Date()\n var bookedTables = []\n bookings.forEach(function (booking) {\n // console.log(booking.time.substring(0,2))\n if (parseInt(booking.time.substring(0, 2)) <= currentTime.getHours() && parseInt(booking.time.substring(0, 2)) + 1 >= currentTime.getHours()) {\n bookedTables.push(parseInt(booking.tableID))\n }\n })\n return bookedTables\n}",
"function _list() {\r\n\t\tvar len = _events.length,\r\n\t\t\ti, out = '';\r\n\t\tfor (i = 0; i < len; i += 1) {\r\n\t\t\tout += _events[i].name + ' ' + _events[i].time + '\\n';\r\n\t\t}\r\n\t\tconsole.log(out);\r\n\t}",
"function QueryRecordings() {\n\tvar z = String(fs.readFileSync('recordings.htm'));\n\tz = z.split('\\n');\n\tfor (var i = 0; i < z.length; i++) {\n\t\tvar a = z[i].indexOf('\">') + 2;\n\t\tvar code = z[i].substr(a, z[i].indexOf(' - ') - a);\n\n\t\tGetTimetable(code, 2013, function () { });\n\t}\n}",
"function tableTimers(){\n\tsetInterval(main_loadBrowser, 600000);\n\tsetInterval(main_loadLog, 600000);\n}",
"timerList() {\n const timers = [];\n this._timerQueue.forEach((value, key) => {\n timers.push(key);\n });\n return timers;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Base device profile to be extended with device specific implementations. | function BaseDeviceProfile() {
this.audioNeedsTranscodingCodecs = []; // fill these with audio codecs that the implemented device can handle natively
this.videoNeedsTranscodingCodecs = []; // fill these with video codecs that the implemented device can handle natively
this.validFormats = []; // fill these with video formats that the implemented device can handle natively
this.transcodeOptions = {
rescaleVideo : false, // BaseDeviceProfile.prototype.rescale
subtitle : false, // BaseDeviceProfile.prototype.hardCodeSubtitle
audioShiftCorrect : false // BaseDeviceProfile.prototype.correctAudioOffset
};
/**
* @todo: whutz this?
* @param {[type]} probeData [description]
* @return {[type]} [description]
*/
this.canPlayContainer = function (probeData) {
throw new Error("canPlayContainer : Not Implemented");
};
/**
* Implement this method to return device specific ffmpeg flags for a probed media
* @param {object} probeData ffmpeg probe data
* @param {[type]} forceTranscode force transcode even if native format?
* @return {Promise} [description]
*/
this.getFFmpegFlags = function (probeData, forceTranscode) {
throw new Error("getFFmpegFlags : Not Implemented!");
};
} | [
"function DeviceProfile( server ) {\n this.impl = new require( './dao/' +\n nconf.get( \"impl_directory\" ) +\n '/deviceProfiles.js' );\n\n modelAPI = server;\n}",
"function device(profile_name) {\n\treturn _.assign({}, device_profiles[profile_name]);\n}",
"static getDeviceProfile(profileName) {\n return profiles[profileName];\n }",
"function extend(base)\r\n{\r\n /* save base properies/methods, to use in our methods */\r\n $super = base;\r\n\r\n /* concatenate device-specific configs */\r\n devSpecific.config = base.config.concat(devSpecific.config);\r\n\r\n return (Object.assign({}, base, devSpecific));\r\n}",
"GetProfilesforDeviceID(string, uint, IScanProfile) {\n\n }",
"async addDeviceProfile (dataAPI, network, deviceProfileId) {\n const proto = await this.getProtocol(network)\n return proto.addDeviceProfile(network, deviceProfileId, dataAPI)\n }",
"function extend(base)\r\n{\r\n /* save base properies/methods, to use in our methods */\r\n $super = base;\r\n\r\n /* concatenate device-specific configs */\r\n devSpecific.config = base.config.concat(\r\n Common.newIntPri()).concat(devSpecific.config);\r\n\r\n /* merge and overwrite base module attributes */\r\n return (Object.assign({}, base, devSpecific));\r\n}",
"GetDefaultProfile(string, IScanProfile) {\n\n }",
"function extend(base)\r\n{\r\n /* save base properies/methods, to use in our methods */\r\n $super = base;\r\n\r\n /* concatenate device-specific configs */\r\n devSpecific.config = base.config.concat(devSpecific.config);\r\n\r\n /* merge and overwrite base module attributes */\r\n return (Object.assign({}, base, devSpecific));\r\n}",
"function extend(base)\r\n{\r\n /* save base properies/methods, to use in our methods */\r\n $super = base;\r\n\r\n /* concatenate device-specific configs */\r\n devSpecific.config = base.config.concat(base.pinConfig).concat(devSpecific.config);\r\n\r\n /* merge and overwrite base module attributes */\r\n return (Object.assign({}, base, devSpecific));\r\n}",
"whichProfile() {\n\t\tthis.profile = 'particle';\n\t\tthis.readProfileData();\n\t}",
"function extend(base)\n{\n /* merge and overwrite base module attributes */\n let result = Object.assign({}, base, devSpecific);\n\n /* concatenate device-specific configs */\n result.config = base.config.concat(devSpecific.config);\n\n return (result);\n}",
"function sampleExtendedProfile () {\n let profile = new SolidProfile(sampleProfileUrl, parsedProfileGraph, rdf)\n let urlPrivateProfile = 'https://localhost:8443/settings/prefs.ttl'\n let graphPrivateProfile = getPrefsGraph(urlPrivateProfile)\n profile.appendFromGraph(graphPrivateProfile, urlPrivateProfile)\n profile.isLoaded = true\n return profile\n}",
"function assignProfile(device, profiles) {\n var profile = false;\n var deviceProfileId = device.rorg.value + '_' + device.funcId.value + '_' + device.typeId.value;\n angular.forEach(profiles, function(v, k) {\n //console.log('deviceProfileId: ' + deviceProfileId)\n //console.log('v.id: ' + v.id)\n //var profileId = parseInt(v._rorg) + '_' + parseInt(v._func) + '_' + parseInt(v._type);\n if (deviceProfileId == v.id) {\n profile = v;\n return;\n }\n });\n return profile;\n }",
"function Device() {}",
"OpenProfile(GUID, IScanProfile) {\n\n }",
"function Profile() {\n _classCallCheck(this, Profile);\n\n Profile.initialize(this);\n }",
"function Device() {\n Principal.apply(this, arguments);\n\n this.type = 'device';\n}",
"function Profile() {\n var self = this;\n self.environments = {};\n Environment.publicEnvironments.forEach(function (env) {\n self.addEnvironment(env);\n });\n self.subscriptions = {};\n\n self.onSubscriptionUpdated = this.save.bind(this);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Requests doc, encodes to base64 | function getEncodedDoc(url) {
return new Promise((resolve, reject) => {
const filepath = `${__base}encoding/${url.substring(url.lastIndexOf('/')+1)}`;
const ws = fs.createWriteStream(filepath);
// Get file
request.get(url).pipe(ws);
// Watch results
ws.on('error', (error) => {
console.log('Error saving file');
return reject(error);
}).on('finish', () => {
// Now read our file in base64
fs.readFile(filepath, { encoding: 'base64'}, (error, data) => {
if (error) {
console.log('Error reading file: ' + filepath);
return reject(error);
}
// Now delete
fs.unlink(filepath, (delErr) => {
if(delErr) {
console.log('Error deleting file...sending anyway: ' + filepath);
}
return resolve(data);
});
});
});
});
} | [
"function getDocumentAsBase64(documentId, caseId) {\n return new Promise(function (resolve, reject) {\n const request = new XMLHttpRequest();\n\n request.onreadystatechange = function () {\n if (request.readyState == 4) {\n if (caseId) {\n $(\"#loadLetter\")\n .empty()\n .append('Load')\n .prop(\"disabled\", false);\n } else {\n $(\"#loadTemplate\")\n .empty()\n .append('Load')\n .prop(\"disabled\", false);\n }\n const response = JSON.parse(request.response);\n if (response.result) {\n resolve(response.data);\n } else {\n updateStatus(response.message, \"danger\");\n reject(request.status);\n }\n }\n }\n\n let url = window.localStorage.getItem(\"serverSettings\") + \"b/system/v3/template/load_template?template_id=\" + documentId;\n if (caseId) {\n url = url + \"&caseid=\" + caseId;\n }\n request.open(\"GET\", url);\n request.setRequestHeader(\"authorisation\", window.localStorage.getItem(\"token\"));\n request.setRequestHeader(\"Accept\", \"application/json, text/plain, */*\");\n request.send();\n });\n}",
"function encodeAuthScript() {\n doc.setValue(btoa(doc.getValue()));\n}",
"function cargarDoc(){\n onRequest({ opcion : 4 ,doc:\"\"}, respDoc);\n \n}",
"function getConvertedPdfBase64(docBase64){\n return new Promise((resolve,reject) =>{\n getHtml(docBase64).then( html =>{\n let options = { format: 'A4' };\n let file = { content: html};\n html_to_pdf.generatePdf(file, options).then(pdfBuffer => {\n resolve(Buffer.from(pdfBuffer).toString('base64'));\n // console.log('PDF Buffer : ',pdfBuffer);\n }).catch(error =>{\n reject(error);\n });\n }).catch(error =>{\n console.log('error while getting pdf buffer'+ error);\n });\n });\n}",
"async function getPrintableDocs(req,res) {\n res.contentType('application/pdf')\n res.end(fs.readFileSync('./test.pdf'),'binary')\n}",
"async getDocumentByCode ( p_auth, p_document_code, p_document_id, p_document_name, p_document_ext ) {\n const AUTHORIZATION = `${p_auth.token_type} ${p_auth.access_token}`\n const PATH = 'Med_get_documento_b24'\n const documentBlob = await RNFetchBlob.config({ fileCache : true, })\n .fetch('GET', `${ BASE_API_URL }${ BASE_PATH_URL }${ PATH }?p_docu_cod_clave=${ p_document_code }`, {\n Authorization: AUTHORIZATION, 'Content-Type': CONTENT_TYPE,\n })\n .then((res) => {\n let status = res.info().status;\n if(status == 200) {\n // the conversion is done in native code //let base64Str = res.base64() //console.log(base64Str) // the following conversions are done in js, it's SYNC //let text = res.text()\n let json = res.json()\n return json\n } \n else { /* handle other status codes */ }\n })\n .catch((errorMessage, statusCode) => {\n console.log(errorMessage, statusCode)\n })\n const { fs } = RNFetchBlob\n const DownloadDir = Platform.OS === 'ios' ? fs.dirs['MainBundleDir'] : fs.dirs['SDCardDir'] + '/EducApp/Documentos'\n if (Platform.OS === 'android') { RNFetchBlob.fs.mkdir(DownloadDir) }\n const NEW_FILE_PATH = `${ DownloadDir }/${p_document_id}_${p_document_name}.${p_document_ext}`\n RNFetchBlob.fs.createFile(NEW_FILE_PATH, documentBlob.retorno, 'base64')\n return NEW_FILE_PATH \n }",
"getContentBase64() {\n\t\tif (!this._content) {\n\t\t\treturn null;\n\t\t}\n\t\treturn Buffer.from(this._content).toString(\"base64\");\n\t}",
"_encodeBase64() {\n let encoded = btoa(this._body);\n let ret = \"\";\n let length = encoded.length;\n let i = 0;\n let limit = 72;\n while (true) {\n if (i * limit > length) {\n break;\n }\n ret += encoded.substr(i * limit, limit) + \"\\r\\n\";\n i++;\n }\n return ret;\n }",
"function newxmlHttpReq(url)\r\n{\r\n console.log(url)\r\n var xhr22222222 = new XMLHttpRequest();\r\n\r\n xhr22222222.open(\"GET\", url);\r\n xhr22222222.responseType = \"blob\";\r\n xhr22222222.send();\r\n return new Promise(function (resolve, reject) {\r\n xhr22222222.onreadystatechange = function() {\r\n if (this.readyState !== 4) return;\r\n if (this.status >= 200 && this.status < 300) {\r\n\r\n var reader = new FileReader();\r\n reader.readAsDataURL(this.response); \r\n reader.onloadend = function() {\r\n var b64data = reader.result; \r\n // document.getElementById(\"25333109\").src = base64data;\r\n base64data = b64data;\r\n resolve(\"ggggfdgfgdfgfdgfdgfd\")\r\n }\r\n }\r\n else{\r\n console.log(\"request failed\")\r\n base64data = \"data:,\";\r\n reject(\"dfgdfgsfghdfghxfghfghdfhg \")\r\n }\r\n}\r\n});\r\n}",
"function assembleOpenApiDocument() {\n return loadFile(baseOpenApiFile);\n}",
"function getDocument() {\n let request = new XMLHttpRequest();\n let authString = getCookie('authorization');\n request.open('GET', '../api/v1/document/' + documentId);\n if(authString !== undefined){\n request.setRequestHeader('authorization', authString);\n };\n request.responseType = 'json';\n request.send();\n request.onload = function () {\n if(request.response === 'Bad Authorization' ){\n alert('Bad Authorization');\n return null;\n };\n let data = request.response;\n showDocument(data);\n }\n}",
"getContentBase64() {\n\t\treturn this._contentBase64;\n\t}",
"function generateDocLink() {\n var documentName = self.singleDoc.doc_name;\n inatkeDocumentsDataService.downloadDocument(documentId)\n .then(function (response) {\n if (response && response != '') {\n var file = new Blob([response], { type: 'application/binary' });\n var fileURL = URL.createObjectURL(file);\n var link = document.createElement('a');\n link.href = fileURL;\n link.download = documentName;\n link.click();\n } else {\n notificationService.error('Unable to download document');\n }\n\n }, function (error) {\n notificationService.error('document categories not loaded');\n });\n }",
"async function retrieveDoc(config, auth) {\n const client = google.docs({ version: 'v1', auth });\n const doc = await docToArchieML({\n client,\n documentId: config.DOC_URL.match(/[-\\w]{25,}/)[0]\n });\n\n // Set local variables for HTML\n PH_CONFIG.plugins['posthtml-expressions'].locals = {\n top: {},\n credits: '',\n footer: '',\n ...doc,\n ...config,\n };\n\n // Write new config to .posthtmlrc, which triggers hot module replacement\n await writePostHTMLConfig(PH_CONFIG);\n\n // Write doc data again to data/doc.json. (Example use case: accessing\n // information in the doc in client-side JavaScript).\n await fs.writeFile(\n path.join(process.cwd(), './data/doc.json'),\n JSON.stringify(doc, null, 2),\n );\n console.log('[download-doc] Successfully wrote ./data/doc.json');\n}",
"function getGDocsXMLfromURL_sendText(auth, URL, protocol, thingToSend) {\n var request = new XMLHttpRequest();\n var asynchronous = false;\n request.open(protocol, URL, asynchronous);\n \n request.setRequestHeader(\"GData-Version\", \"2.0\");\n request.setRequestHeader(\"Authorization\", \"GoogleLogin auth=\" +auth);\n request.setRequestHeader(\"If-Match\", \"*\"); \n request.setRequestHeader(\"Connection\", \"close\");\n request.setRequestHeader(\"Content-Length\", thingToSend.length);\n request.setRequestHeader(\"Content-Type\", \"text/plain;\");\n request.send(thingToSend);\n\n if (request.status == 200) {\n var data = request.responseText;\n return data;\n } else {\n throw new Error('ERROR: ' + request.status + ' ' +\n request.statusText);\n }\n}",
"function getSnapshot(docid) { \n if(docid <=0){\n console.error(\"docid not valid\");\n }\n var xhr = new XMLHttpRequest();\n var url = \"http://127.0.0.1:3883/getsnap?docid=\" + docid;\n xhr.open('GET', url, true);\n xhr.responseType = 'json'; //设置返回响应数据的类型\n xhr.onload = function() {\n if (this.status === 200) {\n console.log(this.response);\n var base64Url = 'data:'+this.response.mimetype+';base64,'+this.response.base64;\n $('#images').append('<hr><p><b>' + this.response.filename + '</b></p><hr>');\n $('#images').append('<img src=' + base64Url + ' alt=\"image\" />');\n } \n }\n xhr.send();\n}",
"function getBase64Data(url) {\n\tvar defer = q.defer();\n\n\trequest({url, encoding: 'base64'}, (err, res, body) => {\n\t\tif (err) {\n\t\t\tdefer.reject(err);\n\t\t}\n\n\t\tdefer.resolve(body);\n\t});\n\n\treturn defer.promise;\n}",
"function downloadDoc(docId, email, passcode){\n var docName = \"Docsend-\"+docId+\".pdf\";\n $.ajax({\n url: \"/download/\"+docId,\n data: {email: email, passcode: passcode},\n success: function(data){\n const url = window.URL.createObjectURL(new Blob([data]));\n const link = document.createElement('a');\n link.href = url;\n link.setAttribute('download', docName);\n document.body.appendChild(link);\n link.click();\n updateDocumentPanel(docId, 'complete');\n\n },\n statusCode:{\n 400: function(response){\n updateDocumentPanel(docId, 'error');\n }\n }\n });\n}",
"function getDocumentBody(data) {\n\tvar xmlDoc=loadXMLDoc(data);\n\tvar b = JSON.parse(xmlDoc); \n\tvar docBodyUrl \t= b.thisURL;\t\t\t\n\tvar docBody \t= b.document.body;\n\treturn docBody;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Display string for the list of active spaces | get spaces() {
return ((this.form.controls.space_list.value || []).map((space) => space.name).join(', ') ||
'No Spaces selected');
} | [
"get spaces() {\n return ((this.form.controls.space_list.value || []).map(space => space.name).join(', ') ||\n 'No Spaces selected');\n }",
"function renderSpacesList(spaces) {\n let spaceEl;\n\n nodes.openSpaces.innerHTML = '';\n nodes.closedSpaces.innerHTML = '';\n\n spaces.forEach(space => {\n spaceEl = renderSpaceListEl(space);\n if (space.windowId) {\n nodes.openSpaces.appendChild(spaceEl);\n } else {\n nodes.closedSpaces.appendChild(spaceEl);\n }\n });\n }",
"function dispArr() \n{\n for (l = 0; l < spaceArr.length; l++) \n {\n space = space + \" \" + spaceArr[l];\n }\n return space;\n}",
"function formatActiveSpaces (spaces) {\n _.forEach(spaces, function (space) {\n if (!_.has(space, 'details.capacity')) {\n _.set(space, 'details.capacity', 'NA');\n }\n\n });\n }",
"function showLevelSpaces() {\n spacesList.filter(function(item) {\n return item.values().level === selectedLevel.toString();\n });\n }",
"function showAnswerSpaces() {\n state.answerName = state.characterNames[Math.floor(Math.random() * state.characterNames.length)];\n state.answerNameSplit = state.answerName.split(\"\");\n for (i = 0; i < state.answerNameSplit.length; i++) {\n // console.log(i);\n state.answerSpaces.push(\"_\");\n }\n answerSpacesText.innerHTML = state.answerSpaces.join(\" \");\n}",
"function AddSpaceToTerminal(){\n\tvar elems = document.getElementsByClassName('terminal');\n\tfor (var i = 0; i< elems.length;i++){\n\t\t\n\t\telems[i].innerHTML += \" \";\n\t}\t\n}",
"function showLevelSpaces() {\n\t\tspacesList.filter(function(item) { \n\t\t\treturn item.values().level === selectedLevel.toString(); \n\t\t});\n\t}",
"addPhraseToDisplay () {\n let phraseObject = this.phrase.split(\"\");\n let invisStart = '<ul>'\n for(let i = 0; i < phraseObject.length; i++) {\n if(phraseObject[i] !== \" \") {\n invisStart += `<li class=\"hide letter ${phraseObject[i]}\">${phraseObject[i]}</li>`\n } else {\n invisStart += `<li class=\"space\"> </li>`\n }\n }\n invisStart += '</ul>'\n let theBoard = document.getElementById('phrase')\n theBoard.innerHTML = invisStart\n }",
"function showLevelSpaces() {\n spacesList.filter(function(item) { \n return item.values().level === selectedLevel.toString(); \n });\n }",
"function ACCspace()\n{\n\twriteText(' ');\n}",
"function printBlankSpaces(){\n\t\tguessArray = []\t\t\t\t\t//making the guessArray empty after each new word is selected\n\t\tvar wordLength = word.length;\n\t\tvar blankLines=\"\";\n\t\tvar div =\"\";\n\t\t\n\t\tblankLines+=\"<pre>\";\n\n\t\tfor(var x = 0; x < wordLength -1; x++){\n\t\t\tblankLines += \" _ \";\n\t\t\tguessArray.push(\" _ \");\n\t\t}\n\n\t\tblankLines+=\"</pre>\";\n\n\t\tdiv = document.getElementById(\"wordlines\");\n\t\tdiv.innerHTML = blankLines;\n\t}",
"getDisplay() {\n const display = []\n for (let letter of this.secretWord) {\n display.push(\n this.lettersGuessed.includes(letter) || letter === ' ' \n ? letter\n : '-'\n )\n }\n return display.join('')\n }",
"function setSpaces(){\n var spaces = \"\";\n for (var i=0; i < $scope.lengthOfWord; i++){\n spaces+=\"_ \";\n }\n return spaces.trim();\n }",
"function drawPlaySpace() {\n for (i = 0; i < playSpace.length; i++) {\n document.getElementById(\"play-space\").innerHTML = playSpace.join(' ');\n }\n}",
"function addSpaceText() {\n\tsetNewMode(0);\n\tappendText(document.getElementById(\"wkk_key_spacebar\"));\n}",
"function showFree() {\n var s = '';\n gameState.free.forEach(function(ch) {\n s += '<span class=\"h5p-hangman-freechar\">' + ch + '</span>';\n })\n gameState.divAlphabeth.innerHTML = s;\n }",
"function addSpaceText() {\n\tappendText(\" \");\n}",
"space() {\n\t\t\tthis.append(' ');\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add icons provided by ant design. | addIcon(...icons) {
icons.forEach(icon => {
this._svgDefinitions.set(withSuffix(icon.name, icon.theme), icon);
});
} | [
"_setupIcons() {\n const customIcons = getWithDefault(this, 'customIcons', {});\n var newIcons = smartExtend(customIcons, defaultIcons);\n set(this, 'icons', O.create(newIcons));\n }",
"setupIcons() {\n // Under icons\n this.add.image(this.canvasGame.width / 2 - 330, 150, 'env').setScale(0.4);\n this.add.image(this.canvasGame.width / 2 - 110, 150, 'soc').setScale(0.4);\n this.add.image(this.canvasGame.width / 2 + 110, 150, 'eco').setScale(0.4);\n this.add.image(this.canvasGame.width / 2 + 330, 150, 'res').setScale(0.4);\n\n // Over icons\n this.envMask = this.add.image(this.canvasGame.width / 2 - 330, 150, 'env').setScale(0.4);\n this.envMask.tint = 0x808080;\n this.socMask = this.add.image(this.canvasGame.width / 2 - 110, 150, 'soc').setScale(0.4);\n this.socMask.tint = 0x808080;\n this.ecoMask = this.add.image(this.canvasGame.width / 2 + 110, 150, 'eco').setScale(0.4);\n this.ecoMask.tint = 0x808080;\n this.resMask = this.add.image(this.canvasGame.width / 2 + 330, 150, 'res').setScale(0.4);\n this.resMask.tint = 0x808080;\n\n this.updateIcons();\n }",
"addIcon () {\n if (!this.options.icon) {\n return;\n }\n\n if (this.options.iconset) {\n if (this.options.iconset.startsWith('fa')) {\n this.classNames.push(this.options.iconset, `fa-${this.options.icon}`);\n } else {\n this.classNames.push(this.options.iconset, `${this.options.iconset}-${this.options.icon}`);\n }\n } else {\n this.classNames.push(`icon-${this.options.icon}`);\n }\n }",
"function addAllFeatherIcons(attr = { viewBox: \"0 0 24 24\", width: \"100\", height: \"100\" }) {\r\n Object.values(feather.icons).forEach((i) => {\r\n const svg = i.toSvg(attr);\r\n (0, obsidian_1__default['default'].addIcon)(`feather-${i.name}`, svg);\r\n });\r\n}",
"function addAllFeatherIcons(attr = { viewBox: \"0 0 24 24\", width: \"100\", height: \"100\" }) {\n Object.values(feather.icons).forEach((i) => {\n const svg = i.toSvg(attr);\n (0, obsidian_1.addIcon)(`feather-${i.name}`, svg);\n });\n}",
"function renderIcons() {}",
"registerSVGIcons() {\n const editorIcons = _igniteui_material_icons_extended__WEBPACK_IMPORTED_MODULE_12__[\"editor\"];\n editorIcons.forEach(icon => this.iconService.addSvgIconFromText(icon.name, icon.value, 'imx-icons'));\n this.iconService.addSvgIconFromText(_igniteui_material_icons_extended__WEBPACK_IMPORTED_MODULE_12__[\"pinLeft\"].name, _igniteui_material_icons_extended__WEBPACK_IMPORTED_MODULE_12__[\"pinLeft\"].value, 'imx-icons');\n this.iconService.addSvgIconFromText(_igniteui_material_icons_extended__WEBPACK_IMPORTED_MODULE_12__[\"unpinLeft\"].name, _igniteui_material_icons_extended__WEBPACK_IMPORTED_MODULE_12__[\"unpinLeft\"].value, 'imx-icons');\n }",
"function icon(){}",
"function iconFor(ant){\n var icon, container;\n \n if(ant.container){ //if ant holds another (e.g., bodyguard)\n container = true; //note there is a container\n if (ant.contained != null) { \n ant = ant.contained; //ant is now whoever is inside\n }\n }\n\n icon = antIcons[ant.name];\n if(icon === undefined){\n icon = '?'; //unrecognized\n }\n\n if(container){\n icon = clc.bgGreen(icon); //draw container as green background\n }\n \n return icon;\n}",
"function addIcons(icon_style, icon_position) {\n \n // Icon style\n switch(icon_style) {\n default:\n var icon_minus = '<i class=\"ionicons ion-ios-volume-low asi-player-icon asi-minus-icon\"></i>';\n var icon_plus = '<i class=\"ionicons ion-ios-volume-high asi-player-icon asi-plus-icon\"></i>';\n break;\n \n case 'super_cool':\n // here, put the icons super_cool\n break;\n } \n $images.each(function(index, image) {\n var asi_id = $(this).attr('asi-id');\n $(icon_minus).insertAfter($(this)).attr('asi-id', asi_id);\n $(icon_plus).insertAfter($(this)).attr('asi-id', asi_id);\n });\n }",
"function initIcons() {\n iconSelected = makeStopIcon(\"/file/mm_20_yellow.png\");\n iconBackground = makeStopIcon(\"/file/mm_20_blue_trans.png\");\n iconBackgroundStation = makeStopIcon(\"/file/mm_20_red_trans.png\");\n}",
"function addIcons(){\n$('#home span').append('<i class=\"icon-home\"> </i>');\n$('#services span').append('<i class=\"icon-building\"> </i>');\n$('#contact span').append('<i class=\"icon-group\"> </i>');\n$('#faq span').append('<i class=\"icon-comments\"> </i>');\n$('#clients span:first').append('<i class=\"icon-book\"> </i>');\n$('#clients span:last').html(' <i class=\"icon-caret-right\"></i></i>');\n$('#members span').append('<i class=\"icon-key\"> </i>');\n$('#quicklinks span:first').append('<i class=\"icon-bookmark\"> </i>');\n$('#quicklinks span:last').html(' <i class=\"icon-caret-right\"></i></i>');\n$('#searchbutton span').append('<i class=\"icon-search\"></i>');\n}",
"function addBuiltIns(PfeIcon){[{name:\"web\",path:\"https://access.redhat.com/webassets/avalon/j/lib/rh-iconfont-svgs\"},{name:\"rh\",path:\"https://access.redhat.com/webassets/avalon/j/lib/rh-iconfont-svgs\"}].forEach(function(set){return PfeIcon.addIconSet(set.name,set.path,function(name,iconSetName,iconSetPath){var regex=new RegExp(\"^\".concat(iconSetName,\"(-icon)?-(.*)\")),_regex$exec=regex.exec(name),_regex$exec2=babelHelpers.slicedToArray(_regex$exec,3),iconName=_regex$exec2[2],iconId=\"\".concat(iconSetName,\"-icon-\").concat(iconName),iconPath=\"\".concat(iconSetPath,\"/\").concat(iconId,\".svg\");return iconPath})})}",
"function mkdWidgetIcons() {\n var widgetIcons = $('.textwidget .mkd-icon-shortcode');\n if (widgetIcons.length) {\n widgetIcons.each(function(){\n var widgetIcon = $(this),\n widgetIconLink = widgetIcon.find('a'),\n widgetIconElement = widgetIconLink.find('> span');\n widgetIconElement.clone().appendTo(widgetIconLink).addClass('mkd-additional-icon');\n widgetIcon.addClass('mkd-rotate');\n });\n }\n }",
"function generateIcons() {\n return {\n ...faIcons,\n ...patternflyIcons,\n ...customIcons,\n };\n}",
"function GenIcon() {\n}",
"addIcons(icons, img) {\n for (let icon of icons) {\n this.addIcon(icon, img);\n }\n }",
"function configureIconsets() {\n // default icon set is needed because some of Angular Material directives have hardcoded svg icon names;\n // radio menu options use `check` icon which can be found in `navigation` icon set; since there is no easy way of overriding the icon name, the default icon set will have duplicates needed by such directives\n // NOTE use the gulp makesvgcache task to add new icons\n $mdIconProvider.defaultIconSet('app/default.svg').iconSet('action', 'app/action.svg').iconSet('alert', 'app/alert.svg').iconSet('communication', 'app/communication.svg').iconSet('community', 'app/community.svg').iconSet('content', 'app/content.svg').iconSet('editor', 'app/editor.svg').iconSet('file', 'app/file.svg').iconSet('hardware', 'app/hardware.svg').iconSet('image', 'app/image.svg').iconSet('maps', 'app/maps.svg').iconSet('navigation', 'app/navigation.svg').iconSet('social', 'app/social.svg').iconSet('toggle', 'app/toggle.svg');\n }",
"generateCustomIcons() {\n const factory = this.cfr.resolveComponentFactory(LuxIconComponent);\n let index = 0;\n this.matStepLabels.forEach((stepLabel) => {\n this.generateCustomIconForStep(stepLabel, this.luxSteps.toArray()[index], factory);\n index++;\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show an input mask / Requires: / inputElem: Input element who's mask should be shown eslintdisablenextline nounusedvars | function showMask(inputElem) {
let inputMask = getMask(inputElem);
let inputValue;
if (inputMask !== false) {
$(inputMask).find('.input-mask-positioner').
removeClass('d-none');
inputValue = $(inputMask).find('.input-value');
if ($(inputValue).length > 0) {
return;
}
updateMask(inputElem);
}
} | [
"function hideMask(inputElem) {\n let inputMask = getMask(inputElem);\n let inputValue;\n if (inputMask !== false) {\n $(inputMask).find('.input-mask-positioner').\n addClass('d-none');\n inputValue = $(inputMask).find('.input-value');\n if ($(inputValue).length > 0) {\n return;\n }\n $(inputElem).removeClass('adjust-start-padding-for-mask');\n }\n}",
"_setMaskToInput() {\n const that = this;\n let mask = '';\n\n for (let i = 0; i < that._mask.length; i++) {\n const maskElement = that._mask[i];\n let newCharacter;\n\n if (maskElement.type === 'literal' || maskElement.type === 'separator' || maskElement.type === 'placeholder' || maskElement.type === 'currency') {\n newCharacter = maskElement.character;\n }\n else if (maskElement.type === 'mask' && maskElement.character !== '') {\n switch (maskElement.escapeSymbol) {\n case '>':\n newCharacter = maskElement.character.toUpperCase();\n break;\n case '<':\n newCharacter = maskElement.character.toLowerCase();\n break;\n case '|':\n newCharacter = maskElement.character;\n break;\n case '\\\\':\n newCharacter = maskElement.character;\n break;\n default:\n newCharacter = maskElement.character;\n break;\n }\n }\n else {\n newCharacter = maskElement.defaultCharacter;\n }\n\n mask = mask + newCharacter;\n }\n\n that.$.input.value = mask;\n }",
"showMask() {\n document.getElementById(\"maskText\").classList.add(\"visible\");\n }",
"function FormMask() {}",
"function updateMask(inputElem) {\n let inputMask = getMask(inputElem);\n let inputValue;\n let maskWidth;\n let inputStartPadding;\n let adjustedPadding;\n if (inputMask !== false) {\n inputValue = $(inputMask).find('.input-value');\n if ($(inputValue).length > 0) {\n $(inputValue).html($(inputElem).val());\n return;\n }\n $(inputElem).removeClass('adjust-start-padding-for-mask');\n maskWidth = parseFloat($(inputMask).find('.input-mask-value').\n outerWidth());\n inputStartPadding = parseFloat($(inputElem).css('padding-left'));\n adjustedPadding = parseFloat(maskWidth + inputStartPadding + 4) + 'px';\n $(':root').css('--adjust-start-padding-for-mask', adjustedPadding);\n $(inputElem).addClass('adjust-start-padding-for-mask');\n }\n}",
"#masking() {\n\t\tthis.#evaluateMask()\n\t\tthis.input.value = Mask.masking(this.input.value, this.mask)\n\t}",
"function positionMask(inputElem) {\n let inputMaskPositioner = $(inputElem).closest('.input-mask-wrapper').\n find('.input-mask .input-mask-positioner');\n let halfInput = $(inputElem).outerHeight(true) / 2;\n let halfMask = $(inputMaskPositioner).outerHeight(true) / 2;\n $(inputMaskPositioner).css('top', -Math.abs(halfInput + halfMask));\n updateMask($(inputElem));\n}",
"function getMask(inputElem) {\n let inputMask;\n if (isDomElem(inputElem) === true) {\n inputMask = $(inputElem).closest('.input-mask-wrapper').\n find('.input-mask');\n if (inputMask.length > 0) {\n return inputMask;\n }\n }\n return false;\n}",
"function addMask({inputElem, mask, leadingMask = false, maskId, extraClasses}) {\n if (!isDomElem(inputElem)) {\n return;\n }\n\n if (!mask) {\n return;\n }\n\n $(inputElem).wrap(\n '<span class=\"input-mask-wrapper d-block\"></span>');\n\n let inputValue = `<span class=\"input-value\"></span>\n `;\n if (leadingMask === true) {\n inputValue = '';\n }\n\n $(inputElem).closest('.input-mask-wrapper').\n append(`\n <div class=\"input-mask position-relative pe-none\">\n <span class=\"input-mask-positioner border-0 p-0 d-block w-100 ` +\n `position-absolute overflow-hidden text-nowrap\">\n ` + inputValue +\n `<span class=\"input-mask-value\">${mask}</span>\n </span>\n </div>\n `);\n\n if (!maskId) {\n if ($(inputElem).attr('id').length > 0) {\n maskId = $(inputElem).attr('id') + '_input_mask';\n }\n }\n\n let inputMask = $(inputElem).closest('.input-mask-wrapper').\n find('.input-mask');\n\n if (maskId.length > 0) {\n $(inputMask).attr('id', maskId);\n }\n\n let inputPaddingStart = parseFloat($(inputElem).css('padding-left'));\n let inputPaddingEnd = parseFloat($(inputElem).css('padding-right'));\n $(inputMask).css('margin-left', inputPaddingStart + 'px');\n if ($(inputElem).attr('type').\n toLowerCase() === 'number') {\n inputPaddingEnd += 20;\n }\n $(inputMask).css('margin-right', inputPaddingEnd + 'px');\n\n let inputMaskPositioner = $(inputMask).find('.input-mask-positioner');\n\n if (extraClasses && Array.isArray(extraClasses)) {\n extraClasses.forEach((clss) => {\n $(inputMaskPositioner).addClass(clss);\n });\n }\n\n positionMask(inputElem);\n}",
"function setMaskSlot(mask) {\n document.getElementById(\"mask-slot\").innerHTML = mask;\n}",
"function telefonoInput(input){\n $(input).inputmask('+99 (999) 999-99-99', { placeholder: '+__ (___) ___-__-__' });\n }",
"function applyMask() {\n setElementValue.call(this, this.promptMask);\n setMaskValue.call(this, this.value);\n}",
"function InputMaskedPhone() {\n var self = this;\n\n var Inputmask = require('inputmask');\n\n var input = document.querySelectorAll('.js-input-phone');\n\n self.init = function() {\n if(input) {\n var phoneMask = new Inputmask({\n 'mask': '+7 (999) 999 99 99',\n 'placeholder': '_'\n });\n\n phoneMask.mask(input);\n }\n };\n\n}",
"_initMaskValueLog() {\n if (document.getElementById('maskGetValue')) {\n const mask = IMask(document.getElementById('maskGetValue'), {\n mask: '(000) 000-00-00',\n lazy: false,\n });\n\n document.getElementById('maskGetValue').setAttribute('mask', mask);\n\n document.getElementById('logButton').addEventListener('click', (event) => {\n console.log(mask.value);\n });\n\n document.getElementById('logUnmaskedButton').addEventListener('click', (event) => {\n console.log(mask.unmaskedValue);\n });\n }\n }",
"function showMask(stimulusPoint, stimulusGroup) {\n // hide fixation point during mask rendering\n fixationStructure.attr({ display: \"none\" });\n\n const maskRadius = trial.radius * 1.5 * scale_factor;\n const r2 = maskRadius * maskRadius;\n\n // hide the entire stimulus group for now\n stimulusGroup.attr({\n display: \"none\"\n });\n\n // remove the ground truth stimulus\n stimulusPoint.remove();\n\n // generate random masks\n const numOfMaskPoints = Math.ceil(trial.mask_dot_ratio *\n trial.radius);// mask dots density not change with scale_factor\n const maskGroup = s.group();\n let maskGenerated = 0;\n maskGroup.transform(translation);\n\n while (maskGenerated < numOfMaskPoints) {\n const x = (Math.random() - 0.5) * 2 * maskRadius;\n const y = (Math.random() - 0.5) * 2 * maskRadius;\n // check if the randomly generated point is within the mask circle\n if (x * x + y * y < r2) {\n const maskPoint = s.circle(x, y, 3 * scale_factor);\n maskGroup.add(maskPoint);\n maskGenerated += 1;\n }\n }\n\n // render the mask for 1000ms, then transition to the last frame to collect\n // subject response.\n jsPsych.pluginAPI.setTimeout(function () {\n solicitResponse(stimulusGroup, maskGroup);\n }, 1000);\n\n }",
"function createMask() {\n Object(_syncfusion_ej2_base__WEBPACK_IMPORTED_MODULE_0__[\"attributes\"])(this.element, {\n 'role': 'textbox', 'autocomplete': 'off', 'autocorrect': 'off', 'autocapitalize': 'off',\n 'spellcheck': 'false', 'aria-live': 'assertive', 'aria-valuenow': ''\n });\n if (this.mask) {\n var splitMask = this.mask.split(']');\n for (var i = 0; i < splitMask.length; i++) {\n if (splitMask[i][splitMask[i].length - 1] === '\\\\') {\n splitMask[i] = splitMask[i] + ']';\n var splitInnerMask = splitMask[i].split('[');\n for (var j = 0; j < splitInnerMask.length; j++) {\n if (splitInnerMask[j][splitInnerMask[j].length - 1] === '\\\\') {\n splitInnerMask[j] = splitInnerMask[j] + '[';\n }\n pushIntoRegExpCollec.call(this, splitInnerMask[j]);\n }\n }\n else {\n var splitInnerMask = splitMask[i].split('[');\n if (splitInnerMask.length > 1) {\n var chkSpace = false;\n for (var j = 0; j < splitInnerMask.length; j++) {\n if (splitInnerMask[j] === '\\\\') {\n this.customRegExpCollec.push('[');\n this.hiddenMask += splitInnerMask[j] + '[';\n }\n else if (splitInnerMask[j] === '') {\n chkSpace = true;\n }\n else if ((splitInnerMask[j] !== '' && chkSpace) || j === splitInnerMask.length - 1) {\n this.customRegExpCollec.push('[' + splitInnerMask[j] + ']');\n this.hiddenMask += this.promptChar;\n chkSpace = false;\n }\n else {\n pushIntoRegExpCollec.call(this, splitInnerMask[j]);\n }\n }\n }\n else {\n pushIntoRegExpCollec.call(this, splitInnerMask[0]);\n }\n }\n }\n this.escapeMaskValue = this.hiddenMask;\n this.promptMask = this.hiddenMask.replace(/[09?LCAa#&]/g, this.promptChar);\n if (!Object(_syncfusion_ej2_base__WEBPACK_IMPORTED_MODULE_0__[\"isNullOrUndefined\"])(this.customCharacters)) {\n for (var i = 0; i < this.promptMask.length; i++) {\n if (!Object(_syncfusion_ej2_base__WEBPACK_IMPORTED_MODULE_0__[\"isNullOrUndefined\"])(this.customCharacters[this.promptMask[i]])) {\n this.promptMask = this.promptMask.replace(new RegExp(this.promptMask[i], 'g'), this.promptChar);\n }\n }\n }\n var escapeNumber = 0;\n if (this.hiddenMask.match(new RegExp(/\\\\/))) {\n for (var i = 0; i < this.hiddenMask.length; i++) {\n var j = 0;\n if (i >= 1) {\n j = i;\n }\n escapeNumber = this.hiddenMask.length - this.promptMask.length;\n j = j - escapeNumber;\n if ((i > 0 && this.hiddenMask[i - 1] !== '\\\\') && (this.hiddenMask[i] === '>' ||\n this.hiddenMask[i] === '<' || this.hiddenMask[i] === '|')) {\n this.promptMask = this.promptMask.substring(0, j) +\n this.promptMask.substring((i + 1) - escapeNumber, this.promptMask.length);\n this.escapeMaskValue = this.escapeMaskValue.substring(0, j) +\n this.escapeMaskValue.substring((i + 1) - escapeNumber, this.escapeMaskValue.length);\n }\n if (this.hiddenMask[i] === '\\\\') {\n this.promptMask = this.promptMask.substring(0, j) + this.hiddenMask[i + 1] +\n this.promptMask.substring((i + 2) - escapeNumber, this.promptMask.length);\n this.escapeMaskValue = this.escapeMaskValue.substring(0, j) + this.escapeMaskValue[i + 1] +\n this.escapeMaskValue.substring((i + 2) - escapeNumber, this.escapeMaskValue.length);\n }\n }\n }\n else {\n this.promptMask = this.promptMask.replace(/[>|<]/g, '');\n this.escapeMaskValue = this.hiddenMask.replace(/[>|<]/g, '');\n }\n Object(_syncfusion_ej2_base__WEBPACK_IMPORTED_MODULE_0__[\"attributes\"])(this.element, { 'aria-invalid': 'false' });\n }\n}",
"show() {\n const me = this;\n\n if (me.hasTimeout('hide')) {\n // TODO: Consider this behaviour, should showing a mask which is not fully hidden resolve?\n me.resolve();\n me.clearTimeout('hide');\n }\n\n if (!me.element.mask) {\n me.create();\n }\n const { element, maskElement } = me;\n\n if (!maskElement) return; // already masked by other instance, only allowing one\n\n element.classList.add('b-masked');\n maskElement.classList.add('b-visible');\n maskElement.classList.remove('b-hidden');\n me.shown = true;\n\n // blur has to blur child elements\n if (me.mode.endsWith('blur')) {\n DomHelper.forEachChild(element, (child) => {\n if (child !== maskElement) {\n child.classList.add(`b-masked-${me.mode}`);\n }\n });\n }\n }",
"static mask(element, msg) {\n return this.adapter.mask(element, msg);\n }",
"function InputMaskedPhone() {\n var self = this;\n\n var Inputmask = (typeof window !== \"undefined\" ? window['Inputmask'] : typeof global !== \"undefined\" ? global['Inputmask'] : null);\n\n var input = document.querySelectorAll('.js-input-phone');\n\n self.init = function() {\n if(input) {\n var phoneMask = new Inputmask({\n 'mask': '+7 (999) 999 99 99',\n 'placeholder': '_'\n });\n\n phoneMask.mask(input);\n }\n };\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a modal and assign it as the form container. Then calls the builder. | modal() {
const modal = new Modal({
style: this.options.style,
title: 'Test',
});
this.container = modal.body;
document.body.appendChild(modal.modal);
this.insertForm();
modal.onHide(this.builder.clearForm.bind(this.builder));
return modal;
} | [
"createFormModal() {\n this.setModalHeader();\n this.setDisplayAndFocus();\n this.listenOnCloseModal();\n this.listenKeyNavigation();\n this.listenKeyClose();\n this.submitForm();\n }",
"function popupFormModal() {\n\n function onModalFormEvent(eventName /*, eventData */) {\n Y.log('Event raised by form in modal: ' + eventName, 'debug', NAME);\n }\n\n function onModalReady(){\n\n var formSettings = {\n divId: 'divModalTest',\n formId: 'forms_Test_Start.form', // formID corresponds to template filename\n formVersion: 1, // bind to a specific version of this form\n ownerCollection: 'test', // owner of any generated PDFs or submissions\n ownerId: 'test', // owner of any generated PDFs or submissions\n onFormEvent: onModalFormEvent, // callback for template events\n setWidth: 538 // bootstrap 3 modals don't expand by default\n };\n\n Y.doccirrus.comctl.setModalAlert('');\n Y.doccirrus.formloader.addFormToDiv( formSettings );\n\n }\n\n Y.doccirrus.comctl.setModal(\n 'Form in Modal Test',\n '<div id=\"divModalTest\" />',\n null,\n null,\n onModalReady\n );\n\n // test\n }",
"open() {\n console.assert (this.form, 'can not open dialog without form')\n this.createModal().modal('show') \n }",
"createhiddenModalForm() {\n // creation of the modal\n this.innerHTML = \"<div id='myModal' class='modal' tabindex='-1' role='dialog'> \" +\n \"<div class='modal-dialog' role='document'> \" +\n \" <div class='modal-content'> \" +\n \" <div class='modal-header'> \" +\n \" <div id='modalTitle' class='modal-title'> myTitle </div> \" +\n \" <button type='button' class='close' data-dismiss='modal' aria-label='Close'> \" +\n \" <span aria-hidden='true'>×</span> \" +\n \" </button> \" +\n \" </div> \" +\n \" <div class='modal-body'> \" +\n \" <div id='modalContent'> myContent </div> \" +\n \" </div> \" +\n \" <div class='modal-footer'> \" +\n \" <button id='modalClose' type='button' class='btn btn-secondary' data-dismiss='modal'>Close</button> \" +\n \" <button id='modalButton' type='button' class='btn btn-primary'> myButtonLabel </button> \" +\n \" </div>\" +\n \" </div>\" +\n \" </div>\" +\n \" </div> \";\n }",
"function openModalForm() {\n\treturn modalForm.modal({\n\t\tbackdrop: 'static',\n\t\tkeyboard: false\n\t});\n}",
"function buildModalSimple() {\n let id = makeid();\n let html = `<div id='${id}' class='modal' tabindex='-1' role='dialog' data-bs-backdrop=\"static\" data-bs-keyboard=\"false\"> \n <div class='modal-dialog modal-dialog-centered' role='document'> \n <div class='modal-content'> \n <div class='modal-header'> \n <div id=\"${id}Header\"></div>\n \n <button type='button' class='close modal-close btn-close' aria-label='Cancel'><!--<span aria-hidden='true'>×</span>--></button>\n </div>\n <div id=\"form_alert\"></div>\n <div class='modal-body' id=\"${id}Body\">\n </div>\n </div>\n </div>\t\n </div>`;\n $('body').append(html);\n //let modal = $(`#${id}`);\n /*modal.modal({\n backdrop: 'static',\n keyboard: false,\n //show: true\n });*/\n\n //NEW MODAL FORMAT\n let modal = new bootstrap.Modal(document.getElementById(id), {\n keyboard: false,\n backdrop: 'static'\n });\n\n modal.show();\n\n $(document).on('click', `#${id} .modal-close`, function() {\n forceCloseModal(id);\n });\n\n return id;\n}",
"showCreateModal() {\n\t\t\tif(this.availableCounters == []) {\n\t\t\t\ttoastr.error('Campos no cargados');\n\t\t\t}\n\n\t\t\tEvent.$emit(\n\t\t\t\t'InitializeKpiForm', 'new',\t{\n\t\t\t\t\t'tech': this.filter.tech,\n\t\t\t\t\t'vendor': this.filter.vendor,\n\t\t\t\t\t'type': this.filter.type\n\t\t\t\t},\n\t\t\t\tthis.partials\n\t\t\t);\n\t\t}",
"_setupModal() {\n this.modal = new Shepherd_modal({\n target: this.options.modalContainer || document.body,\n props: {\n classPrefix: this.classPrefix,\n styles: this.styles\n }\n });\n }",
"function PopulateCreateModal() {\n\n\t}",
"renderModal(){\n let modalBody = emotionFormModalBody()\n\n let div = document.createElement('div')\n div.classList.add(\"py-2\",\"border-top\",\"border-bottom\")\n\n let name = document.createElement('h6')\n name.classList.add(\"d-inline\")\n name.innerHTML = this.name\n div.appendChild(name)\n\n let btn = document.createElement('button')\n btn.classList.add(\"btn\",\"btn-primary\",\"btn-sm\",\"rounded-pill\",\"mx-5\")\n btn.setAttribute(\"data-id\",this.id)\n btn.innerHTML = \"Add\"\n\n const toggleFunc = emotionFormFunctions.call(btn)\n btn.addEventListener(\"click\",toggleFunc)\n\n div.appendChild(btn)\n\n modalBody.appendChild(div)\n\n return div\n }",
"function createModal() {\n RequestNewCardModal().then((json) => {\n const modal = document.querySelector('body').prepend(getChild(json));\n document.querySelector('.modal-container #close').addEventListener('click', closeModal);\n document.querySelector('.modal-container').addEventListener('click', closeModal);\n document.querySelector('.modal-container .button').addEventListener('click', requestNewCard);\n });\n}",
"function getNewDojoForm(e) {\n e.preventDefault();\n\n $.post($(this).attr(\"action\"), $(this).serialize(), function(res){\n $(\"#modal-body\").html(res.html);\n });\n\n $(\"#dojoModal\").modal(\"show\");\n}",
"insertForm() {\n this.builder = new Builder(this.container, this.options.template, {\n style: this.options.style,\n formContainerClass: this.options.formContainerClass,\n inputGroupClass: this.options.inputGroupClass,\n inputClass: this.options.inputClass,\n labelClass: this.options.labelClass,\n btnClass: this.options.btnClass,\n errorClass: this.options.errorClass,\n successClass: this.options.successClass,\n });\n this.build();\n }",
"createModalForm(dialogDetails) {\n var inputs = dialogDetails['inputs']\n var submitCallback = dialogDetails['submitCallback'];\n\n var $parentDiv = $('<div>');\n $parentDiv.appendTo($(document.body));\n var shadow = setUpShadowDOM($parentDiv);\n\n $frame = setUpModal(shadow);\n\n // Set up some useful refs\n var $frameDocument = $frame.contents();\n var $frameWindow = $($frame[0].contentWindow);\n var $modal = $frameDocument.find('.mtr-modal-content');\n var $modalForm = $modal.find(\".mtr-modal-form\");\n\n for (var i = 0; i < inputs.length; i++) {\n addModalInput($modalForm, inputs[i], i);\n }\n\n $('<input class=\"btn btn-success\" type=\"submit\" value=\"submit\">').appendTo($modalForm);\n\n // Callback and then remove the modal, upon submit\n $modalForm.on('submit', function (e) {\n var res = { 'inputs': [] };\n\n $modalForm.find('.mtr-form-input-row').each(function (idx) {\n res['inputs'].push($(this).find('.mtr-form-input').val())\n })\n\n submitCallback(res);\n\n $parentDiv.remove(); // Remove modal when we're done\n // Stops the normal form processing.\n e.preventDefault();\n });\n\n // Remove modal when ESC is pressed\n $frameDocument.on('keyup.27', function (e) {\n if (e.which == 27) { // escape key maps to keycode `27`\n $parentDiv.remove();\n }\n });\n\n $(document).on('click', function (event) {\n if (!hasShadowParent(event.target)) {\n $parentDiv.remove();\n }\n });\n }",
"function callResourcesModal(){\n $('body div.k-dialog-container #modal').remove();\n var modalb = new ResourcesModalBox(title_msg = null);\n var modalc = new uploadResourcesModalContent();\n $('.k-dialog-container').append(modalb);\n $('.k-dialog-container .modal-footer').css('padding', '35px');\n $('#modal').modal('show');\n}",
"static createModal(options) {\r\n function getStyle(styleObj) {\r\n let styleStr = \"\";\r\n if (styleObj) {\r\n for (let key in styleObj) {\r\n if (styleObj.hasOwnProperty(key)) {\r\n styleStr += `${key}: ${styleObj[key]}; `;\r\n }\r\n }\r\n }\r\n return styleStr;\r\n }\r\n let id = null;\r\n if (ObjectUtil.validString(options.id)) {\r\n id = options.id;\r\n }\r\n else {\r\n id = ObjectUtil.guid();\r\n }\r\n let bodyStyle = getStyle(options.modalContentStyle);\r\n let styleStr = getStyle(options.modalBodyStyle);\r\n let html = `<div class=\"FetishModal\" id=\"${id}\"> \r\n <div class=\"FSmodalContent\" style=\"${bodyStyle}\"> \r\n <div class=\"FSmodalHeader\"> \r\n <span class=\"FSclose\">×</span> \r\n <h5 class=\"FSmodalTitle\">${options.title}</h5> \r\n </div> \r\n <div class=\"FSModalBody\" style=\"${styleStr}\">${options.body}</div>`;\r\n if (ObjectUtil.validString(options.footer)) {\r\n html += ` <div class=\"FSModalFooter\"> \r\n ${options.footer} \r\n </div>`;\r\n }\r\n html += `</div></div>`;\r\n let modal = DomUtil.createElementFromHTML(html);\r\n window.onclick = (event) => {\r\n if (event.target == modal) {\r\n DomUtil.closeModal(modal);\r\n }\r\n };\r\n DomUtil.offOn(DomUtil.bySelector(\".FSclose\", modal), \"click\", e => {\r\n DomUtil.closeModal(modal);\r\n });\r\n return modal;\r\n }",
"function createModalInstance(modalConfig) {\n return createModal(modalConfig);\n }",
"function Modal() {\n\t\tthis._init();\n\t}",
"function main_show_modal(button) \n{\n var modal_form_id = button.attr(\"modal_form_id\");\n var modal_form_url = button.attr(\"modal_form_url\");\n \n $(modal_form_id).find(\"modal-body\").load(modal_form_url);\n $(modal_form_id).modal(\"show\");\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creates the div elements that represent the pieces | function setupPieces(puzzle) {
puzzle.innerHTML = "";
for (var i = 1; i <= 15; i++) {
var piece = document.createElement("div");
piece.className = "piece normal";
piece.id = "x" + i;
piece.innerHTML = i;
piece.onmouseover = mouseOver;
piece.onmouseout = mouseOut;
puzzle.appendChild(piece);
}
} | [
"function addPieces() {\n for (var i=0;i<24;i++){\n $('div #pieces').append($('<div class=\"piece\"><div>'));\n }\n}",
"function createPuzzle(pieces) {\n\t\tvar area = document.getElementById('puzzlearea');\n\t\t\n\t\tfor (var i = 0; i < pieces; i++) {\n\t\t\tvar newPiece = document.createElement('div');\n \t\tvar posY = Math.floor((i / 4)) * 100;\n\t\t\tvar posX = (i % 4) * 100;\n\n\t\t\tnewPiece.className = 'piece';\n\t\t\tnewPiece.innerHTML = i + 1;\n\t\t\tnewPiece.style.top = posY + 'px';\n\t\t\tnewPiece.style.left = posX + 'px';\n\t\t\tnewPiece.style.backgroundPosition = (-posX) + 'px ' + (-posY) + 'px';\n\n\t\t\tarea.appendChild(newPiece);\n\t\t}\n\t}",
"renderManualScreen(){\n let container = document.createElement(\"div\");\n container.classList.add(\"manual-screen\");\n\n this.piecesNames.map((a, i) => {\n //create a wrapper div for each pair img/name\n let imgNameDiv = document.createElement(\"div\");\n imgNameDiv.classList.add(\"manual-screen-wrap\");\n //creates a div with the name of the piece\n let divName = document.createElement(\"div\");\n divName.classList.add(\"manual-screen-name\");\n divName.innerHTML = this.piecesNames[i];\n\n //creates an image element and adds a class\n let image = new Image();\n image.classList.add(\"manual-screen-img\");\n image.src = this.piecesSrc[i][i];\n\n //appends the img and the text to the container\n imgNameDiv.appendChild(image);\n imgNameDiv.appendChild(divName);\n container.appendChild(imgNameDiv);\n })\n\n this.mainContainer.appendChild(container);\n }",
"function init()\n{\n for (let i = 8; i > 0; i--)\n {\n for (let k = 0; k < 8; k++) \n {\n let mark = squareNames[k] + i;\n let div = document.createElement(\"div\");\n div.id = mark;\n \n div.style.width = \"98px\";\n div.style.height = \"98px\";\n div.style.cssFloat = 'left';\n div.style.border = 'solid 1px';\n \n //div.addEventListener('ondrop', drop_handler);\n document.getElementById(\"canvas\").appendChild(div);\n let piece = {\n mark: mark,\n chessPiece: \"\",\n pieceDiv: div,\n };\n \n initPiece(mark, piece);\n\n //board[i-1][k] = piece;\n board[mark] = piece;\n }\n }\n}",
"function makeContainers(){\n const mainContent = grabElement(\"main\");\n const familyContainer = makeElement(\"div\");\n familyContainer.setAttribute(\"class\", \"family-container\");\n const titleContainer = makeElement(\"div\");\n titleContainer.setAttribute(\"class\", \"title-container\");\n const quarterInfo = makeElement(\"div\");\n quarterInfo.setAttribute(\"class\", \"quarter-info\");\n mainContent.appendChild(quarterInfo);\n mainContent.insertBefore(familyContainer, quarterInfo);\n mainContent.insertBefore(titleContainer, familyContainer);\n}",
"function domGenerate() {\n for (var i = 0; i < totalNumberOfDivs; i++) {\n document.getElementById('game_board').appendChild(myDivArray[i]);\n\n }\n }",
"function placePieces() {\r\n clearBoard();\r\n for (i = 0; i < 8; i++) {\r\n for (j = 0; j < 8; j++) {\r\n if (!pieces[i][j]) {\r\n continue;\r\n }\r\n let curPiece = document.createElement(\"img\");\r\n curPiece.className = \"Piece\";\r\n let pname = pieceName[pieces[i][j].piece];\r\n curPiece.id = pname + i + j;\r\n curPiece.src = \"Images/\" + colorName[pieces[i][j].color] + \"-\" + pname + \".png\";\r\n squares[i][j].appendChild(curPiece);\r\n }\r\n }\r\n}",
"function makePuzzlePieces() {\n // Makes an array of left and right pieces containers names\n let piecesContainer = [\"leftSidePieces\", \"rightSidePieces\"];\n // Based on the puzzle chosen, gets the pieces of that puzzle from Json file\n for (let p = 0; p < puzzles.length; p++) {\n if (puzzleId === puzzles[p].id) {\n // Gets pieces images from Json file and assigns them to an array\n for (let j = 0; j < numPieces; j++) {\n let pieceImage = puzzles[p].pieces[j];\n allPiecesImgAddress.push(pieceImage);\n }\n }\n }\n // Gets the first image address length and assigns to a variable\n firstPieceLength = allPiecesImgAddress[0].length;\n\n // Makes two columns of puzzle pieces and displays them on the sides\n let numPiecesToShow = 0;\n let totalNumPiecesToShow = 24;\n let numPiecesContainers = 2;\n\n // Makes two columns of puzzle pieces\n for (var g = 0; g < numPiecesContainers; g++) {\n // Creates puzzle pieces\n for (let i = numPiecesToShow; i < totalNumPiecesToShow; i++) {\n // Defines a vertical rectangular area of display for the pieces\n displayableAreaHeight = Math.floor(($('.columns').height() / 2));\n displayableAreaWidth = Math.floor($('.columns').width() / 4.5);\n\n // According to the column chosen increases or decreases left border value\n if (g === 0) {\n borderLeft = -30;\n } else if (g === 1) {\n borderLeft = +30;\n }\n\n // Generates random x and y position\n let randPosX = borderLeft + Math.floor((Math.random() * (displayableAreaWidth)));\n let randPosY = Math.floor((Math.random() * (displayableAreaHeight)));\n\n // Gets random image from the array and assigns to the html element\n let pieceImgAddress = getRandomElement(allPiecesImgAddress);\n // Gets the number embeded in the image address in order to be used in the piece id name\n let pieceId = findPieceId(pieceImgAddress);\n // Creates the piece\n let piece = $('<img>').attr({\n id: `piece${pieceId}`,\n src: `${pieceImgAddress}`\n }).appendTo(`#${piecesContainer[g]}`);\n piece.css({\n \"width\": \"4.5vw\",\n \"left\": `${randPosX}px`,\n \"top\": `${randPosY}px`,\n \"position\": \"relative\"\n });\n // Makes it draggable\n piece.draggable();\n // makes an array of pieces\n puzzlePieces.push(piece);\n // Removes the current image from the images array so that it won't be used again\n removeRandomElement(pieceImgAddress);\n }\n // Goes for the next column\n numPiecesToShow += 24;\n totalNumPiecesToShow += 24;\n }\n}",
"function init_pieces() {\n var row_index,\n col_index,\n pawn,\n \n white_king_index = [7, 4],\n black_king_index = [0, 4],\n \n white_queen_index = [7, 3],\n black_queen_index = [0, 3],\n\n white_bishop_1_index = [7, 2],\n black_bishop_1_index = [0, 2],\n white_bishop_2_index = [7, 5],\n black_bishop_2_index = [0, 5],\n\n white_knight_1_index = [7, 1],\n black_knight_1_index = [0, 1],\n white_knight_2_index = [7, 6],\n black_knight_2_index = [0, 6],\n\n white_rook_1_index = [7, 0],\n black_rook_1_index = [0, 0],\n white_rook_2_index = [7, 7],\n black_rook_2_index = [0, 7],\n\n piece;\n\n // Init black pawns\n row_index = 1;\n pawn = piece_factory(CONSTANTS.PIECES.PAWN, CONSTANTS.COLOURS.BLACK);\n for (col_index = 0; col_index < 8; col_index++) {\n piece = $(pawn).clone();\n $('[data-row_index=\"' + row_index + '\"][data-col_index=\"' + col_index + '\"]').append(piece);\n make_piece_draggable(piece);\n }\n\n // Init white pawns\n row_index = 6;\n pawn = piece_factory(CONSTANTS.PIECES.PAWN, CONSTANTS.COLOURS.WHITE);\n for (col_index = 0; col_index < 8; col_index++) {\n piece = $(pawn).clone();\n $('[data-row_index=\"' + row_index + '\"][data-col_index=\"' + col_index + '\"]').append(piece);\n make_piece_draggable(piece);\n }\n\n // Init Kings\n piece = piece_factory(CONSTANTS.PIECES.KING, CONSTANTS.COLOURS.WHITE);\n $(SQUARE.get_square_at(white_king_index[0], white_king_index[1])).append(piece);\n make_piece_draggable(piece);\n\n piece = piece_factory(CONSTANTS.PIECES.KING, CONSTANTS.COLOURS.BLACK);\n $(SQUARE.get_square_at(black_king_index[0], black_king_index[1])).append(piece);\n make_piece_draggable(piece);\n\n // Init Queens\n piece = piece_factory(CONSTANTS.PIECES.QUEEN, CONSTANTS.COLOURS.WHITE);\n $(SQUARE.get_square_at(white_queen_index[0], white_queen_index[1])).append(piece);\n make_piece_draggable(piece);\n\n piece = piece_factory(CONSTANTS.PIECES.QUEEN, CONSTANTS.COLOURS.BLACK);\n $(SQUARE.get_square_at(black_queen_index[0], black_queen_index[1])).append(piece);\n make_piece_draggable(piece);\n\n // Init Bishops\n piece = piece_factory(CONSTANTS.PIECES.BISHOP, CONSTANTS.COLOURS.WHITE);\n $(SQUARE.get_square_at(white_bishop_1_index[0], white_bishop_1_index[1])).append(piece);\n make_piece_draggable(piece);\n\n piece = piece_factory(CONSTANTS.PIECES.BISHOP, CONSTANTS.COLOURS.BLACK);\n $(SQUARE.get_square_at(black_bishop_1_index[0], black_bishop_1_index[1])).append(piece);\n make_piece_draggable(piece);\n\n piece = piece_factory(CONSTANTS.PIECES.BISHOP, CONSTANTS.COLOURS.WHITE);\n $(SQUARE.get_square_at(white_bishop_2_index[0], white_bishop_2_index[1])).append(piece);\n make_piece_draggable(piece);\n\n piece = piece_factory(CONSTANTS.PIECES.BISHOP, CONSTANTS.COLOURS.BLACK);\n $(SQUARE.get_square_at(black_bishop_2_index[0], black_bishop_2_index[1])).append(piece);\n make_piece_draggable(piece);\n\n // Init Knights\n piece = piece_factory(CONSTANTS.PIECES.KNIGHT, CONSTANTS.COLOURS.WHITE);\n $(SQUARE.get_square_at(white_knight_1_index[0], white_knight_1_index[1])).append(piece);\n make_piece_draggable(piece);\n\n piece = piece_factory(CONSTANTS.PIECES.KNIGHT, CONSTANTS.COLOURS.BLACK);\n $(SQUARE.get_square_at(black_knight_1_index[0], black_knight_1_index[1])).append(piece);\n make_piece_draggable(piece);\n\n piece = piece_factory(CONSTANTS.PIECES.KNIGHT, CONSTANTS.COLOURS.WHITE);\n $(SQUARE.get_square_at(white_knight_2_index[0], white_knight_2_index[1])).append(piece);\n make_piece_draggable(piece);\n\n piece = piece_factory(CONSTANTS.PIECES.KNIGHT, CONSTANTS.COLOURS.BLACK);\n $(SQUARE.get_square_at(black_knight_2_index[0], black_knight_2_index[1])).append(piece);\n make_piece_draggable(piece);\n\n // Init Rooks\n piece = piece_factory(CONSTANTS.PIECES.ROOK, CONSTANTS.COLOURS.WHITE);\n $(SQUARE.get_square_at(white_rook_1_index[0], white_rook_1_index[1])).append(piece);\n make_piece_draggable(piece);\n\n piece = piece_factory(CONSTANTS.PIECES.ROOK, CONSTANTS.COLOURS.BLACK);\n $(SQUARE.get_square_at(black_rook_1_index[0], black_rook_1_index[1])).append(piece);\n make_piece_draggable(piece);\n\n piece = piece_factory(CONSTANTS.PIECES.ROOK, CONSTANTS.COLOURS.WHITE);\n $(SQUARE.get_square_at(white_rook_2_index[0], white_rook_2_index[1])).append(piece);\n make_piece_draggable(piece);\n\n piece = piece_factory(CONSTANTS.PIECES.ROOK, CONSTANTS.COLOURS.BLACK);\n $(SQUARE.get_square_at(black_rook_2_index[0], black_rook_2_index[1])).append(piece);\n make_piece_draggable(piece);\n}",
"function createInitalDivs() {\n\n let mainContainer = createDivElement({id: 'mainContainer'});\n\n let movieDisplays = createDivElement({id: 'movieDisplays'});\n\n let sideBar = createDivElement({id: 'sideBar'});\n\n let available = createDivElement({id: 'aDiv', class: 'movieDivs'});\n\n let rented = createDivElement({id: 'rDiv', class: 'movieDivs'});\n\n document.body.appendChild(mainContainer);\n\n mainContainer.appendChild(movieDisplays);t\n mainContainer.appendChild(sideBar);\n\n movieDisplays.appendChild(available);\n movieDisplays.appendChild(rented);\n \n}",
"function getPiece(name, color, i0, i1, i2, i3) {\n var $piece = $(\n ['<div class=\"'+name+' piece\">',\n ' <div class=\"'+color+' box '+i0+'\"></div>',\n ' <div class=\"'+color+' box '+i1+'\"></div>',\n ' <div class=\"'+color+' box '+i2+'\"></div>',\n ' <div class=\"'+color+' box '+i3+'\"></div>',\n '</div>'].join('\\n'));\n $piece.data('boxes', [boxes[i0], boxes[i1], boxes[i2], boxes[i3]]);\n $piece.data('color', color);\n return $piece;\n }",
"function makeDivs (gridSize) {\n for (square = 1; square <= (gridSize * gridSize); square++) {\n let newBlock = document.createElement('div');\n container.appendChild(newBlock).className=\"block\";\n };\n}",
"function divMaker () {\n\n var addx = 1;\n\tvar addy = 1;\n\tvar addwidth = 1;\n\tvar addheight = 1;\n\n var divAttr = '';\n\n\tfor (j = 0; j <= 9; j++) {\n\t\tfor (i = 0; i <= (colorArr.length - 1); i++) {\n\n\t\t\tdivAttr +=\n '<div style=\"position: fixed;' +\n posX +\n ': ' +\n (addx += parseInt(userDate.charAt(1))) +\n 'px;' +\n posY +\n ': ' +\n (addy += parseInt(userDate.charAt(2))) +\n 'px; background-color: ' +\n colorArr[i] +\n '; width:' +\n (addwidth += parseInt(userDate.charAt(3) + 2)) +\n 'px; height:' +\n (addheight += parseInt(userDate.charAt(3) + 2)) +\n 'px;\" class=\"blocks\"></div>'\n\n };\n };\n return divAttr;\n}",
"function generateElements() {\n for (var i = 0; i <= num; i++) {\n var el = $('<div id=\"div-0' + (i + 1) + '\" class=\"block shadow-' + (Math.round(Math.random() * 4) + 1) + '\"></div>');\n $container.append(el);\n }\n positionElements();\n }",
"function createDivs() {\r\n const dateNow = Date.now();\r\n var title, phpNo, cctvNo, NN;\r\n for ( var index = 0; index < camDef.length; index++ ) {\r\n [ title, phpNo, cctvNo ] = camDef[ index ];\r\n NN = `00${index}`.slice( -2 );\r\n\r\n newDiv = document.createElement( \"div\" );\r\n newDiv.className = \"col-12 col-s-6 col-m-4 col-l-3 col-xl-3\";\r\n\r\n newFigure = document.createElement( \"figure\" );\r\n\r\n newFigCap = document.createElement( \"figcaption\" );\r\n newFigCap.id = `iFIGCAP${NN}`;\r\n newFigCap.innerHTML = title;\r\n\r\n newImg = document.createElement( \"img\" );\r\n newImg.id = `iIMG${NN}`;\r\n newImg.src = \"#\";\r\n newImg.alt = phpNo;\r\n newImg.slot = NN;\r\n newImg.style.width = \"100%\";\r\n newImg.style.maxWidth = \"100%\";\r\n newImg.onclick = toggleEmbiggen;\r\n\r\n newFigure.appendChild( newFigCap );\r\n newFigure.appendChild( newImg );\r\n\r\n newDiv.appendChild( newFigure );\r\n\r\n iDIVMain.appendChild( newDiv );\r\n\r\n tester[ index ] = new Image();\r\n tester[ index ].src = `${HeadCCTV}${cctvNo}${TailCCTV}${dateNow}`;\r\n tester[ index ].alt = phpNo;\r\n tester[ index ].slot = NN;\r\n tester[ index ].addEventListener( \"load\", testImageResponse );\r\n tester[ index ].addEventListener( \"error\", testImageResponse );\r\n }\r\n\r\n /* And now for iDIVAlt */\r\n newFigure = document.createElement( \"figure\" );\r\n\r\n newFigCap = document.createElement( \"figcaption\" );\r\n newFigCap.id = \"iFIGCAPAlt\";\r\n\r\n newImg = document.createElement( \"img\" );\r\n newImg.id = \"iIMGAlt\";\r\n newImg.src = \"#\";\r\n newImg.alt = \"#\";\r\n newImg.style.width = \"100%\";\r\n newImg.style.maxWidth = \"100%\";\r\n newImg.onclick = toggleEmbiggen;\r\n\r\n newFigure.appendChild( newFigCap );\r\n newFigure.appendChild( newImg );\r\n\r\n iDIVAlt.appendChild( document.createTextNode( \"Click on image to exit full screen.\" ) );\r\n iDIVAlt.appendChild( newFigure );\r\n\r\n }",
"function initDivs() {\n for (let i = 0; i < 16 * 16; i++) {\n const newDiv = document.createElement('div');\n newDiv.className = 'divs';\n gameGrid.appendChild(newDiv);\n }\n}",
"createStartPieces() {\n // king\n this.pieces.push(new King(\"bk\", \"b\", 4, 0));\n this.pieces.push(new King(\"wk\", \"w\", 4, 7));\n\n // queen\n this.pieces.push(new Queen(\"bq\", \"b\", 3, 0));\n this.pieces.push(new Queen(\"wq\", \"w\", 3, 7));\n\n // Knight\n this.pieces.push(new Knight(\"wn\", \"w\", 1, 7));\n this.pieces.push(new Knight(\"wn\", \"w\", 6, 7));\n this.pieces.push(new Knight(\"bn\", \"b\", 1, 0));\n this.pieces.push(new Knight(\"bn\", \"b\", 6, 0));\n\n // Rook\n this.pieces.push(new Rook(\"wr\", \"w\", 0, 7));\n this.pieces.push(new Rook(\"wr\", \"w\", 7, 7));\n this.pieces.push(new Rook(\"br\", \"b\", 0, 0));\n this.pieces.push(new Rook(\"br\", \"b\", 7, 0));\n\n // Bishop\n this.pieces.push(new Bishop(\"wb\", \"w\", 2, 7));\n this.pieces.push(new Bishop(\"wb\", \"w\", 5, 7));\n this.pieces.push(new Bishop(\"bb\", \"b\", 2, 0));\n this.pieces.push(new Bishop(\"bb\", \"b\", 5, 0)); \n\n // pawns\n for (let i = 0; i < 8; i++) {\n this.pieces.push(new Pawn(\"wp\", \"w\", i, 6));\n this.pieces.push(new Pawn(\"bp\", \"b\", i, 1));\n }\n }",
"function buildPieces(){\n var i;\n var piece;\n var xPos = 0;\n var yPos = 0;\n for(i = 0;i < difficulty * difficulty;i++){\n piece = {};\n piece.sx = xPos;\n piece.sy = yPos;\n pieces.push(piece);\n xPos += pieceWidth;\n if(xPos >= puzzleWidth){\n xPos = 0;\n yPos += pieceHeight;\n }\n }\n // shuffles puzzle on view\n shufflePuzzle();\n }",
"createPieces() {\n this.createBlackPieces();\n this.createWhitePieces();\n this.createMixPieces();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uses Dean McNamee's omggif library and Anthony Dekker's NeuQuant quantizer (JS 0.3 version with many fixes) | function Animated_GIF(options) {
'use strict';
var width = 160, height = 120, canvas = null, ctx = null, repeat = 0, delay = 250;
var frames = [];
var numRenderedFrames = 0;
var onRenderCompleteCallback = function() {};
var onRenderProgressCallback = function() {};
var workers = [], availableWorkers = [], numWorkers, workerPath;
var generatingGIF = false;
options = options || {};
numWorkers = options.numWorkers || 2;
workerPath = options.workerPath || 'src/quantizer.js'; // XXX hardcoded path
for(var i = 0; i < numWorkers; i++) {
var w = new Worker(workerPath);
workers.push(w);
availableWorkers.push(w);
}
// ---
// Return a worker for processing a frame
function getWorker() {
if(availableWorkers.length === 0) {
throw ('No workers left!');
}
return availableWorkers.pop();
}
// Restore a worker to the pool
function freeWorker(worker) {
availableWorkers.push(worker);
}
// Faster/closurized bufferToString function
// (caching the String.fromCharCode values)
var bufferToString = (function() {
var byteMap = [];
for(var i = 0; i < 256; i++) {
byteMap[i] = String.fromCharCode(i);
}
return (function(buffer) {
var numberValues = buffer.length;
var str = '';
for(var i = 0; i < numberValues; i++) {
str += byteMap[ buffer[i] ];
}
return str;
});
})();
function startRendering(completeCallback) {
var numFrames = frames.length;
onRenderCompleteCallback = completeCallback;
for(var i = 0; i < numWorkers && i < frames.length; i++) {
processFrame(i);
}
}
function processFrame(position) {
var frame;
var worker;
frame = frames[position];
if(frame.beingProcessed || frame.done) {
console.error('Frame already being processed or done!', frame.position);
onFrameFinished();
return;
}
frame.beingProcessed = true;
worker = getWorker();
worker.onmessage = function(ev) {
var data = ev.data;
// Delete original data, and free memory
delete(frame.data);
// TODO grrr... HACK for object -> Array
frame.pixels = Array.prototype.slice.call(data.pixels);
frame.palette = Array.prototype.slice.call(data.palette);
frame.done = true;
frame.beingProcessed = false;
freeWorker(worker);
onFrameFinished();
};
// TODO maybe look into transfer objects
// for further efficiency
var frameData = frame.data;
//worker.postMessage(frameData, [frameData]);
worker.postMessage(frameData);
}
function processNextFrame() {
var position = -1;
for(var i = 0; i < frames.length; i++) {
var frame = frames[i];
if(!frame.done && !frame.beingProcessed) {
position = i;
break;
}
}
if(position >= 0) {
processFrame(position);
}
}
function onFrameFinished() { // ~~~ taskFinished
// The GIF is not written until we're done with all the frames
// because they might not be processed in the same order
var allDone = frames.every(function(frame) {
return !frame.beingProcessed && frame.done;
});
numRenderedFrames++;
onRenderProgressCallback(numRenderedFrames * 0.75 / frames.length);
if(allDone) {
if(!generatingGIF) {
generateGIF(frames, onRenderCompleteCallback);
}
} else {
setTimeout(processNextFrame, 1);
}
}
// Takes the already processed data in frames and feeds it to a new
// GifWriter instance in order to get the binary GIF file
function generateGIF(frames, callback) {
// TODO: Weird: using a simple JS array instead of a typed array,
// the files are WAY smaller o_o. Patches/explanations welcome!
var buffer = []; // new Uint8Array(width * height * frames.length * 5);
var gifWriter = new GifWriter(buffer, width, height, { loop: repeat });
generatingGIF = true;
frames.forEach(function(frame) {
onRenderProgressCallback(0.75 + 0.25 * frame.position * 1.0 / frames.length);
gifWriter.addFrame(0, 0, width, height, frame.pixels, {
palette: frame.palette,
delay: delay
});
});
gifWriter.end();
onRenderProgressCallback(1.0);
frames = [];
generatingGIF = false;
callback(buffer);
}
// ---
this.setSize = function(w, h) {
width = w;
height = h;
canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
ctx = canvas.getContext('2d');
};
// Internally, GIF uses tenths of seconds to store the delay
this.setDelay = function(seconds) {
delay = seconds * 0.1;
};
// From GIF: 0 = loop forever, null = not looping, n > 0 = loop n times and stop
this.setRepeat = function(r) {
repeat = r;
};
this.addFrame = function(element) {
if(ctx === null) {
this.setSize(width, height);
}
ctx.drawImage(element, 0, 0, width, height);
var data = ctx.getImageData(0, 0, width, height);
this.addFrameImageData(data.data);
};
this.addFrameImageData = function(imageData) {
var dataLength = imageData.length,
imageDataArray = new Uint8Array(imageData);
frames.push({ data: imageDataArray, done: false, beingProcessed: false, position: frames.length });
};
this.onRenderProgress = function(callback) {
onRenderProgressCallback = callback;
};
this.isRendering = function() {
return generatingGIF;
};
this.getBase64GIF = function(completeCallback) {
var onRenderComplete = function(buffer) {
var str = bufferToString(buffer);
var gif = 'data:image/gif;base64,' + btoa(str);
completeCallback(gif);
};
startRendering(onRenderComplete);
};
} | [
"function NeuQuant() {\n var exports = {};\n var netsize = 256;\n /* number of colours used */\n\n /* four primes near 500 - assume no image has a length so large */\n\n /* that it is divisible by all four primes */\n\n var prime1 = 499;\n var prime2 = 491;\n var prime3 = 487;\n var prime4 = 503;\n var minpicturebytes = 3 * prime4;\n /* minimum size for input image */\n\n /*\n * Program Skeleton ---------------- [select samplefac in range 1..30] [read\n * image from input file] pic = (unsigned char*) malloc(3*width*height);\n * initnet(pic,3*width*height,samplefac); learn(); unbiasnet(); [write output\n * image header, using writecolourmap(f)] inxbuild(); write output image using\n * inxsearch(b,g,r)\n */\n\n /*\n * Network Definitions -------------------\n */\n\n var maxnetpos = netsize - 1;\n var netbiasshift = 4;\n /* bias for colour values */\n\n var ncycles = 100;\n /* no. of learning cycles */\n\n /* defs for freq and bias */\n\n var intbiasshift = 16;\n /* bias for fractions */\n\n var intbias = 1 << intbiasshift;\n var gammashift = 10;\n /* gamma = 1024 */\n\n var gamma = 1 << gammashift;\n var betashift = 10;\n var beta = intbias >> betashift;\n /* beta = 1/1024 */\n\n var betagamma = intbias << gammashift - betashift;\n /* defs for decreasing radius factor */\n\n var initrad = netsize >> 3;\n /* for 256 cols, radius starts */\n\n var radiusbiasshift = 6;\n /* at 32.0 biased by 6 bits */\n\n var radiusbias = 1 << radiusbiasshift;\n var initradius = initrad * radiusbias;\n /* and decreases by a */\n\n var radiusdec = 30;\n /* factor of 1/30 each cycle */\n\n /* defs for decreasing alpha factor */\n\n var alphabiasshift = 10;\n /* alpha starts at 1.0 */\n\n var initalpha = 1 << alphabiasshift;\n var alphadec;\n /* biased by 10 bits */\n\n /* radbias and alpharadbias used for radpower calculation */\n\n var radbiasshift = 8;\n var radbias = 1 << radbiasshift;\n var alpharadbshift = alphabiasshift + radbiasshift;\n var alpharadbias = 1 << alpharadbshift;\n /*\n * Types and Global Variables --------------------------\n */\n\n var thepicture;\n /* the input image itself */\n\n var lengthcount;\n /* lengthcount = H*W*3 */\n\n var samplefac;\n /* sampling factor 1..30 */\n // typedef int pixel[4]; /* BGRc */\n\n var network;\n /* the network itself - [netsize][4] */\n\n var netindex = [];\n /* for network lookup - really 256 */\n\n var bias = [];\n /* bias and freq arrays for learning */\n\n var freq = [];\n var radpower = [];\n\n var NeuQuant = exports.NeuQuant = function NeuQuant(thepic, len, sample) {\n var i;\n var p;\n thepicture = thepic;\n lengthcount = len;\n samplefac = sample;\n network = new Array(netsize);\n\n for (i = 0; i < netsize; i++) {\n network[i] = new Array(4);\n p = network[i];\n p[0] = p[1] = p[2] = (i << netbiasshift + 8) / netsize;\n freq[i] = intbias / netsize;\n /* 1/netsize */\n\n bias[i] = 0;\n }\n };\n\n var colorMap = function colorMap() {\n var map = [];\n var index = new Array(netsize);\n\n for (var i = 0; i < netsize; i++) {\n index[network[i][3]] = i;\n }\n\n var k = 0;\n\n for (var l = 0; l < netsize; l++) {\n var j = index[l];\n map[k++] = network[j][0];\n map[k++] = network[j][1];\n map[k++] = network[j][2];\n }\n\n return map;\n };\n /*\n * Insertion sort of network and building of netindex[0..255] (to do after\n * unbias)\n * -------------------------------------------------------------------------------\n */\n\n\n var inxbuild = function inxbuild() {\n var i;\n var j;\n var smallpos;\n var smallval;\n var p;\n var q;\n var previouscol;\n var startpos;\n previouscol = 0;\n startpos = 0;\n\n for (i = 0; i < netsize; i++) {\n p = network[i];\n smallpos = i;\n smallval = p[1];\n /* index on g */\n\n /* find smallest in i..netsize-1 */\n\n for (j = i + 1; j < netsize; j++) {\n q = network[j];\n\n if (q[1] < smallval) {\n /* index on g */\n smallpos = j;\n smallval = q[1];\n /* index on g */\n }\n }\n\n q = network[smallpos];\n /* swap p (i) and q (smallpos) entries */\n\n if (i != smallpos) {\n j = q[0];\n q[0] = p[0];\n p[0] = j;\n j = q[1];\n q[1] = p[1];\n p[1] = j;\n j = q[2];\n q[2] = p[2];\n p[2] = j;\n j = q[3];\n q[3] = p[3];\n p[3] = j;\n }\n /* smallval entry is now in position i */\n\n\n if (smallval != previouscol) {\n netindex[previouscol] = startpos + i >> 1;\n\n for (j = previouscol + 1; j < smallval; j++) {\n netindex[j] = i;\n }\n\n previouscol = smallval;\n startpos = i;\n }\n }\n\n netindex[previouscol] = startpos + maxnetpos >> 1;\n\n for (j = previouscol + 1; j < 256; j++) {\n netindex[j] = maxnetpos;\n }\n /* really 256 */\n\n };\n /*\n * Main Learning Loop ------------------\n */\n\n\n var learn = function learn() {\n var i;\n var j;\n var b;\n var g;\n var r;\n var radius;\n var rad;\n var alpha;\n var step;\n var delta;\n var samplepixels;\n var p;\n var pix;\n var lim;\n if (lengthcount < minpicturebytes) samplefac = 1;\n alphadec = 30 + (samplefac - 1) / 3;\n p = thepicture;\n pix = 0;\n lim = lengthcount;\n samplepixels = lengthcount / (3 * samplefac);\n delta = samplepixels / ncycles | 0;\n alpha = initalpha;\n radius = initradius;\n rad = radius >> radiusbiasshift;\n if (rad <= 1) rad = 0;\n\n for (i = 0; i < rad; i++) {\n radpower[i] = alpha * ((rad * rad - i * i) * radbias / (rad * rad));\n }\n\n if (lengthcount < minpicturebytes) step = 3;else if (lengthcount % prime1 !== 0) step = 3 * prime1;else if (lengthcount % prime2 !== 0) step = 3 * prime2;else if (lengthcount % prime3 !== 0) step = 3 * prime3;else step = 3 * prime4;\n i = 0;\n\n while (i < samplepixels) {\n b = (p[pix + 0] & 0xff) << netbiasshift;\n g = (p[pix + 1] & 0xff) << netbiasshift;\n r = (p[pix + 2] & 0xff) << netbiasshift;\n j = contest(b, g, r);\n altersingle(alpha, j, b, g, r);\n if (rad !== 0) alterneigh(rad, j, b, g, r);\n /* alter neighbours */\n\n pix += step;\n if (pix >= lim) pix -= lengthcount;\n i++;\n if (delta === 0) delta = 1;\n\n if (i % delta === 0) {\n alpha -= alpha / alphadec;\n radius -= radius / radiusdec;\n rad = radius >> radiusbiasshift;\n if (rad <= 1) rad = 0;\n\n for (j = 0; j < rad; j++) {\n radpower[j] = alpha * ((rad * rad - j * j) * radbias / (rad * rad));\n }\n }\n }\n };\n /*\n ** Search for BGR values 0..255 (after net is unbiased) and return colour\n * index\n * ----------------------------------------------------------------------------\n */\n\n\n var map = exports.map = function map(b, g, r) {\n var i;\n var j;\n var dist;\n var a;\n var bestd;\n var p;\n var best;\n bestd = 1000;\n /* biggest possible dist is 256*3 */\n\n best = -1;\n i = netindex[g];\n /* index on g */\n\n j = i - 1;\n /* start at netindex[g] and work outwards */\n\n while (i < netsize || j >= 0) {\n if (i < netsize) {\n p = network[i];\n dist = p[1] - g;\n /* inx key */\n\n if (dist >= bestd) i = netsize;\n /* stop iter */\n else {\n i++;\n if (dist < 0) dist = -dist;\n a = p[0] - b;\n if (a < 0) a = -a;\n dist += a;\n\n if (dist < bestd) {\n a = p[2] - r;\n if (a < 0) a = -a;\n dist += a;\n\n if (dist < bestd) {\n bestd = dist;\n best = p[3];\n }\n }\n }\n }\n\n if (j >= 0) {\n p = network[j];\n dist = g - p[1];\n /* inx key - reverse dif */\n\n if (dist >= bestd) j = -1;\n /* stop iter */\n else {\n j--;\n if (dist < 0) dist = -dist;\n a = p[0] - b;\n if (a < 0) a = -a;\n dist += a;\n\n if (dist < bestd) {\n a = p[2] - r;\n if (a < 0) a = -a;\n dist += a;\n\n if (dist < bestd) {\n bestd = dist;\n best = p[3];\n }\n }\n }\n }\n }\n\n return best;\n };\n\n var process = exports.process = function process() {\n learn();\n unbiasnet();\n inxbuild();\n return colorMap();\n };\n /*\n * Unbias network to give byte values 0..255 and record position i to prepare\n * for sort\n * -----------------------------------------------------------------------------------\n */\n\n\n var unbiasnet = function unbiasnet() {\n var i;\n var j;\n\n for (i = 0; i < netsize; i++) {\n network[i][0] >>= netbiasshift;\n network[i][1] >>= netbiasshift;\n network[i][2] >>= netbiasshift;\n network[i][3] = i;\n /* record colour no */\n }\n };\n /*\n * Move adjacent neurons by precomputed alpha*(1-((i-j)^2/[r]^2)) in\n * radpower[|i-j|]\n * ---------------------------------------------------------------------------------\n */\n\n\n var alterneigh = function alterneigh(rad, i, b, g, r) {\n var j;\n var k;\n var lo;\n var hi;\n var a;\n var m;\n var p;\n lo = i - rad;\n if (lo < -1) lo = -1;\n hi = i + rad;\n if (hi > netsize) hi = netsize;\n j = i + 1;\n k = i - 1;\n m = 1;\n\n while (j < hi || k > lo) {\n a = radpower[m++];\n\n if (j < hi) {\n p = network[j++];\n\n try {\n p[0] -= a * (p[0] - b) / alpharadbias;\n p[1] -= a * (p[1] - g) / alpharadbias;\n p[2] -= a * (p[2] - r) / alpharadbias;\n } catch (e) {} // prevents 1.3 miscompilation\n\n }\n\n if (k > lo) {\n p = network[k--];\n\n try {\n p[0] -= a * (p[0] - b) / alpharadbias;\n p[1] -= a * (p[1] - g) / alpharadbias;\n p[2] -= a * (p[2] - r) / alpharadbias;\n } catch (e) {}\n }\n }\n };\n /*\n * Move neuron i towards biased (b,g,r) by factor alpha\n * ----------------------------------------------------\n */\n\n\n var altersingle = function altersingle(alpha, i, b, g, r) {\n /* alter hit neuron */\n var n = network[i];\n n[0] -= alpha * (n[0] - b) / initalpha;\n n[1] -= alpha * (n[1] - g) / initalpha;\n n[2] -= alpha * (n[2] - r) / initalpha;\n };\n /*\n * Search for biased BGR values ----------------------------\n */\n\n\n var contest = function contest(b, g, r) {\n /* finds closest neuron (min dist) and updates freq */\n\n /* finds best neuron (min dist-bias) and returns position */\n\n /* for frequently chosen neurons, freq[i] is high and bias[i] is negative */\n\n /* bias[i] = gamma*((1/netsize)-freq[i]) */\n var i;\n var dist;\n var a;\n var biasdist;\n var betafreq;\n var bestpos;\n var bestbiaspos;\n var bestd;\n var bestbiasd;\n var n;\n bestd = ~(1 << 31);\n bestbiasd = bestd;\n bestpos = -1;\n bestbiaspos = bestpos;\n\n for (i = 0; i < netsize; i++) {\n n = network[i];\n dist = n[0] - b;\n if (dist < 0) dist = -dist;\n a = n[1] - g;\n if (a < 0) a = -a;\n dist += a;\n a = n[2] - r;\n if (a < 0) a = -a;\n dist += a;\n\n if (dist < bestd) {\n bestd = dist;\n bestpos = i;\n }\n\n biasdist = dist - (bias[i] >> intbiasshift - netbiasshift);\n\n if (biasdist < bestbiasd) {\n bestbiasd = biasdist;\n bestbiaspos = i;\n }\n\n betafreq = freq[i] >> betashift;\n freq[i] -= betafreq;\n bias[i] += betafreq << gammashift;\n }\n\n freq[bestpos] += beta;\n bias[bestpos] -= betagamma;\n return bestbiaspos;\n };\n\n NeuQuant.apply(this, arguments);\n return exports;\n}",
"function NeuQuant(pixels, samplefac) {\n var network; // int[netsize][4]\n var netindex; // for network lookup - really 256\n // bias and freq arrays for learning\n var bias;\n var freq;\n var radpower;\n /*\n Private Method: init\n \n sets up arrays\n */\n function init() {\n network = [];\n netindex = [];\n bias = [];\n freq = [];\n radpower = [];\n var i, v;\n for (i = 0; i < netsize; i++) {\n v = (i << (netbiasshift + 8)) / netsize;\n network[i] = [v, v, v];\n freq[i] = intbias / netsize;\n bias[i] = 0;\n }\n }\n /*\n Private Method: unbiasnet\n \n unbiases network to give byte values 0..255 and record position i to prepare for sort\n */\n function unbiasnet() {\n for (var i = 0; i < netsize; i++) {\n network[i][0] >>= netbiasshift;\n network[i][1] >>= netbiasshift;\n network[i][2] >>= netbiasshift;\n network[i][3] = i; // record color number\n }\n }\n /*\n Private Method: altersingle\n \n moves neuron *i* towards biased (b,g,r) by factor *alpha*\n */\n function altersingle(alpha, i, b, g, r) {\n network[i][0] -= (alpha * (network[i][0] - b)) / initalpha;\n network[i][1] -= (alpha * (network[i][1] - g)) / initalpha;\n network[i][2] -= (alpha * (network[i][2] - r)) / initalpha;\n }\n /*\n Private Method: alterneigh\n \n moves neurons in *radius* around index *i* towards biased (b,g,r) by factor *alpha*\n */\n function alterneigh(radius, i, b, g, r) {\n var lo = Math.abs(i - radius);\n var hi = Math.min(i + radius, netsize);\n var j = i + 1;\n var k = i - 1;\n var m = 1;\n var p, a;\n while ((j < hi) || (k > lo)) {\n a = radpower[m++];\n if (j < hi) {\n p = network[j++];\n p[0] -= (a * (p[0] - b)) / alpharadbias;\n p[1] -= (a * (p[1] - g)) / alpharadbias;\n p[2] -= (a * (p[2] - r)) / alpharadbias;\n }\n if (k > lo) {\n p = network[k--];\n p[0] -= (a * (p[0] - b)) / alpharadbias;\n p[1] -= (a * (p[1] - g)) / alpharadbias;\n p[2] -= (a * (p[2] - r)) / alpharadbias;\n }\n }\n }\n /*\n Private Method: contest\n \n searches for biased BGR values\n */\n function contest(b, g, r) {\n /*\n finds closest neuron (min dist) and updates freq\n finds best neuron (min dist-bias) and returns position\n for frequently chosen neurons, freq[i] is high and bias[i] is negative\n bias[i] = gamma * ((1 / netsize) - freq[i])\n */\n var bestd = ~(1 << 31);\n var bestbiasd = bestd;\n var bestpos = -1;\n var bestbiaspos = bestpos;\n var i, n, dist, biasdist, betafreq;\n for (i = 0; i < netsize; i++) {\n n = network[i];\n dist = Math.abs(n[0] - b) + Math.abs(n[1] - g) + Math.abs(n[2] - r);\n if (dist < bestd) {\n bestd = dist;\n bestpos = i;\n }\n biasdist = dist - ((bias[i]) >> (intbiasshift - netbiasshift));\n if (biasdist < bestbiasd) {\n bestbiasd = biasdist;\n bestbiaspos = i;\n }\n betafreq = (freq[i] >> betashift);\n freq[i] -= betafreq;\n bias[i] += (betafreq << gammashift);\n }\n freq[bestpos] += beta;\n bias[bestpos] -= betagamma;\n return bestbiaspos;\n }\n /*\n Private Method: inxbuild\n \n sorts network and builds netindex[0..255]\n */\n function inxbuild() {\n var i, j, p, q, smallpos, smallval, previouscol = 0, startpos = 0;\n for (i = 0; i < netsize; i++) {\n p = network[i];\n smallpos = i;\n smallval = p[1]; // index on g\n // find smallest in i..netsize-1\n for (j = i + 1; j < netsize; j++) {\n q = network[j];\n if (q[1] < smallval) { // index on g\n smallpos = j;\n smallval = q[1]; // index on g\n }\n }\n q = network[smallpos];\n // swap p (i) and q (smallpos) entries\n if (i != smallpos) {\n j = q[0];\n q[0] = p[0];\n p[0] = j;\n j = q[1];\n q[1] = p[1];\n p[1] = j;\n j = q[2];\n q[2] = p[2];\n p[2] = j;\n j = q[3];\n q[3] = p[3];\n p[3] = j;\n }\n // smallval entry is now in position i\n if (smallval != previouscol) {\n netindex[previouscol] = (startpos + i) >> 1;\n for (j = previouscol + 1; j < smallval; j++)\n netindex[j] = i;\n previouscol = smallval;\n startpos = i;\n }\n }\n netindex[previouscol] = (startpos + maxnetpos) >> 1;\n for (j = previouscol + 1; j < 256; j++)\n netindex[j] = maxnetpos; // really 256\n }\n /*\n Private Method: inxsearch\n \n searches for BGR values 0..255 and returns a color index\n */\n function inxsearch(b, g, r) {\n var a, p, dist;\n var bestd = 1000; // biggest possible dist is 256*3\n var best = -1;\n var i = netindex[g]; // index on g\n var j = i - 1; // start at netindex[g] and work outwards\n while ((i < netsize) || (j >= 0)) {\n if (i < netsize) {\n p = network[i];\n dist = p[1] - g; // inx key\n if (dist >= bestd)\n i = netsize; // stop iter\n else {\n i++;\n if (dist < 0)\n dist = -dist;\n a = p[0] - b;\n if (a < 0)\n a = -a;\n dist += a;\n if (dist < bestd) {\n a = p[2] - r;\n if (a < 0)\n a = -a;\n dist += a;\n if (dist < bestd) {\n bestd = dist;\n best = p[3];\n }\n }\n }\n }\n if (j >= 0) {\n p = network[j];\n dist = g - p[1]; // inx key - reverse dif\n if (dist >= bestd)\n j = -1; // stop iter\n else {\n j--;\n if (dist < 0)\n dist = -dist;\n a = p[0] - b;\n if (a < 0)\n a = -a;\n dist += a;\n if (dist < bestd) {\n a = p[2] - r;\n if (a < 0)\n a = -a;\n dist += a;\n if (dist < bestd) {\n bestd = dist;\n best = p[3];\n }\n }\n }\n }\n }\n return best;\n }\n /*\n Private Method: learn\n \n \"Main Learning Loop\"\n */\n function learn() {\n var i;\n var lengthcount = pixels.length;\n var alphadec = toInt(30 + ((samplefac - 1) / 3));\n var samplepixels = toInt(lengthcount / (3 * samplefac));\n var delta = toInt(samplepixels / ncycles);\n var alpha = initalpha;\n var radius = initradius;\n var rad = radius >> radiusbiasshift;\n if (rad <= 1)\n rad = 0;\n for (i = 0; i < rad; i++)\n radpower[i] = toInt(alpha * (((rad * rad - i * i) * radbias) / (rad * rad)));\n var step;\n if (lengthcount < minpicturebytes) {\n samplefac = 1;\n step = 3;\n }\n else if ((lengthcount % prime1) !== 0) {\n step = 3 * prime1;\n }\n else if ((lengthcount % prime2) !== 0) {\n step = 3 * prime2;\n }\n else if ((lengthcount % prime3) !== 0) {\n step = 3 * prime3;\n }\n else {\n step = 3 * prime4;\n }\n var b, g, r, j;\n var pix = 0; // current pixel\n i = 0;\n while (i < samplepixels) {\n b = (pixels[pix] & 0xff) << netbiasshift;\n g = (pixels[pix + 1] & 0xff) << netbiasshift;\n r = (pixels[pix + 2] & 0xff) << netbiasshift;\n j = contest(b, g, r);\n altersingle(alpha, j, b, g, r);\n if (rad !== 0)\n alterneigh(rad, j, b, g, r); // alter neighbours\n pix += step;\n if (pix >= lengthcount)\n pix -= lengthcount;\n i++;\n if (delta === 0)\n delta = 1;\n if (i % delta === 0) {\n alpha -= alpha / alphadec;\n radius -= radius / radiusdec;\n rad = radius >> radiusbiasshift;\n if (rad <= 1)\n rad = 0;\n for (j = 0; j < rad; j++)\n radpower[j] = toInt(alpha * (((rad * rad - j * j) * radbias) / (rad * rad)));\n }\n }\n }\n /*\n Method: buildColormap\n \n 1. initializes network\n 2. trains it\n 3. removes misconceptions\n 4. builds colorindex\n */\n function buildColormap() {\n init();\n learn();\n unbiasnet();\n inxbuild();\n }\n this.buildColormap = buildColormap;\n /*\n Method: getColormap\n \n builds colormap from the index\n \n returns array in the format:\n \n >\n > [r, g, b, r, g, b, r, g, b, ..]\n >\n */\n function getColormap() {\n var map = [];\n var index = [];\n for (var i = 0; i < netsize; i++)\n index[network[i][3]] = i;\n var k = 0;\n for (var l = 0; l < netsize; l++) {\n var j = index[l];\n map[k++] = (network[j][0]);\n map[k++] = (network[j][1]);\n map[k++] = (network[j][2]);\n }\n return map;\n }\n this.getColormap = getColormap;\n /*\n Method: lookupRGB\n \n looks for the closest *r*, *g*, *b* color in the map and\n returns its index\n */\n this.lookupRGB = inxsearch;\n}",
"function NeuQuant(pixels, samplefac) {\n var network; // int[netsize][4]\n var netindex; // for network lookup - really 256\n\n // bias and freq arrays for learning\n var bias;\n var freq;\n var radpower;\n\n /*\n Private Method: init\n\n sets up arrays\n */\n function init() {\n network = [];\n netindex = new Int32Array(256);\n bias = new Int32Array(netsize);\n freq = new Int32Array(netsize);\n radpower = new Int32Array(netsize >> 3);\n\n var i, v;\n for (i = 0; i < netsize; i++) {\n v = (i << (netbiasshift + 8)) / netsize;\n network[i] = new Float64Array([v, v, v, 0]);\n //network[i] = [v, v, v, 0]\n freq[i] = intbias / netsize;\n bias[i] = 0;\n }\n }\n\n /*\n Private Method: unbiasnet\n\n unbiases network to give byte values 0..255 and record position i to prepare for sort\n */\n function unbiasnet() {\n for (var i = 0; i < netsize; i++) {\n network[i][0] >>= netbiasshift;\n network[i][1] >>= netbiasshift;\n network[i][2] >>= netbiasshift;\n network[i][3] = i; // record color number\n }\n }\n\n /*\n Private Method: altersingle\n\n moves neuron *i* towards biased (b,g,r) by factor *alpha*\n */\n function altersingle(alpha, i, b, g, r) {\n network[i][0] -= (alpha * (network[i][0] - b)) / initalpha;\n network[i][1] -= (alpha * (network[i][1] - g)) / initalpha;\n network[i][2] -= (alpha * (network[i][2] - r)) / initalpha;\n }\n\n /*\n Private Method: alterneigh\n\n moves neurons in *radius* around index *i* towards biased (b,g,r) by factor *alpha*\n */\n function alterneigh(radius, i, b, g, r) {\n var lo = Math.abs(i - radius);\n var hi = Math.min(i + radius, netsize);\n\n var j = i + 1;\n var k = i - 1;\n var m = 1;\n\n var p, a;\n while ((j < hi) || (k > lo)) {\n a = radpower[m++];\n\n if (j < hi) {\n p = network[j++];\n p[0] -= (a * (p[0] - b)) / alpharadbias;\n p[1] -= (a * (p[1] - g)) / alpharadbias;\n p[2] -= (a * (p[2] - r)) / alpharadbias;\n }\n\n if (k > lo) {\n p = network[k--];\n p[0] -= (a * (p[0] - b)) / alpharadbias;\n p[1] -= (a * (p[1] - g)) / alpharadbias;\n p[2] -= (a * (p[2] - r)) / alpharadbias;\n }\n }\n }\n\n /*\n Private Method: contest\n\n searches for biased BGR values\n */\n function contest(b, g, r) {\n /*\n finds closest neuron (min dist) and updates freq\n finds best neuron (min dist-bias) and returns position\n for frequently chosen neurons, freq[i] is high and bias[i] is negative\n bias[i] = gamma * ((1 / netsize) - freq[i])\n */\n\n var bestd = ~(1 << 31);\n var bestbiasd = bestd;\n var bestpos = -1;\n var bestbiaspos = bestpos;\n\n var i, n, dist, biasdist, betafreq;\n for (i = 0; i < netsize; i++) {\n n = network[i];\n\n dist = Math.abs(n[0] - b) + Math.abs(n[1] - g) + Math.abs(n[2] - r);\n if (dist < bestd) {\n bestd = dist;\n bestpos = i;\n }\n\n biasdist = dist - ((bias[i]) >> (intbiasshift - netbiasshift));\n if (biasdist < bestbiasd) {\n bestbiasd = biasdist;\n bestbiaspos = i;\n }\n\n betafreq = (freq[i] >> betashift);\n freq[i] -= betafreq;\n bias[i] += (betafreq << gammashift);\n }\n\n freq[bestpos] += beta;\n bias[bestpos] -= betagamma;\n\n return bestbiaspos;\n }\n\n /*\n Private Method: inxbuild\n\n sorts network and builds netindex[0..255]\n */\n function inxbuild() {\n var i, j, p, q, smallpos, smallval, previouscol = 0, startpos = 0;\n for (i = 0; i < netsize; i++) {\n p = network[i];\n smallpos = i;\n smallval = p[1]; // index on g\n // find smallest in i..netsize-1\n for (j = i + 1; j < netsize; j++) {\n q = network[j];\n if (q[1] < smallval) { // index on g\n smallpos = j;\n smallval = q[1]; // index on g\n }\n }\n q = network[smallpos];\n // swap p (i) and q (smallpos) entries\n if (i != smallpos) {\n j = q[0]; q[0] = p[0]; p[0] = j;\n j = q[1]; q[1] = p[1]; p[1] = j;\n j = q[2]; q[2] = p[2]; p[2] = j;\n j = q[3]; q[3] = p[3]; p[3] = j;\n }\n // smallval entry is now in position i\n\n if (smallval != previouscol) {\n netindex[previouscol] = (startpos + i) >> 1;\n for (j = previouscol + 1; j < smallval; j++)\n netindex[j] = i;\n previouscol = smallval;\n startpos = i;\n }\n }\n netindex[previouscol] = (startpos + maxnetpos) >> 1;\n for (j = previouscol + 1; j < 256; j++)\n netindex[j] = maxnetpos; // really 256\n }\n\n /*\n Private Method: inxsearch\n\n searches for BGR values 0..255 and returns a color index\n */\n function inxsearch(b, g, r) {\n var a, p, dist;\n\n var bestd = 1000; // biggest possible dist is 256*3\n var best = -1;\n\n var i = netindex[g]; // index on g\n var j = i - 1; // start at netindex[g] and work outwards\n\n while ((i < netsize) || (j >= 0)) {\n if (i < netsize) {\n p = network[i];\n dist = p[1] - g; // inx key\n if (dist >= bestd) i = netsize; // stop iter\n else {\n i++;\n if (dist < 0) dist = -dist;\n a = p[0] - b; if (a < 0) a = -a;\n dist += a;\n if (dist < bestd) {\n a = p[2] - r; if (a < 0) a = -a;\n dist += a;\n if (dist < bestd) {\n bestd = dist;\n best = p[3];\n }\n }\n }\n }\n if (j >= 0) {\n p = network[j];\n dist = g - p[1]; // inx key - reverse dif\n if (dist >= bestd) j = -1; // stop iter\n else {\n j--;\n if (dist < 0) dist = -dist;\n a = p[0] - b; if (a < 0) a = -a;\n dist += a;\n if (dist < bestd) {\n a = p[2] - r; if (a < 0) a = -a;\n dist += a;\n if (dist < bestd) {\n bestd = dist;\n best = p[3];\n }\n }\n }\n }\n }\n\n return best;\n }\n\n /*\n Private Method: learn\n\n \"Main Learning Loop\"\n */\n function learn() {\n var i;\n\n var lengthcount = pixels.length;\n var alphadec = 30 + ((samplefac - 1) / 3);\n var samplepixels = lengthcount / (3 * samplefac);\n var delta = ~~(samplepixels / ncycles);\n var alpha = initalpha;\n var radius = initradius;\n\n var rad = radius >> radiusbiasshift;\n\n if (rad <= 1) rad = 0;\n for (i = 0; i < rad; i++)\n radpower[i] = alpha * (((rad * rad - i * i) * radbias) / (rad * rad));\n\n var step;\n if (lengthcount < minpicturebytes) {\n samplefac = 1;\n step = 3;\n } else if ((lengthcount % prime1) !== 0) {\n step = 3 * prime1;\n } else if ((lengthcount % prime2) !== 0) {\n step = 3 * prime2;\n } else if ((lengthcount % prime3) !== 0) {\n step = 3 * prime3;\n } else {\n step = 3 * prime4;\n }\n\n var b, g, r, j;\n var pix = 0; // current pixel\n\n i = 0;\n while (i < samplepixels) {\n b = (pixels[pix] & 0xff) << netbiasshift;\n g = (pixels[pix + 1] & 0xff) << netbiasshift;\n r = (pixels[pix + 2] & 0xff) << netbiasshift;\n\n j = contest(b, g, r);\n\n altersingle(alpha, j, b, g, r);\n if (rad !== 0) alterneigh(rad, j, b, g, r); // alter neighbours\n\n pix += step;\n if (pix >= lengthcount) pix -= lengthcount;\n\n i++;\n\n if (delta === 0) delta = 1;\n if (i % delta === 0) {\n alpha -= alpha / alphadec;\n radius -= radius / radiusdec;\n rad = radius >> radiusbiasshift;\n\n if (rad <= 1) rad = 0;\n for (j = 0; j < rad; j++)\n radpower[j] = alpha * (((rad * rad - j * j) * radbias) / (rad * rad));\n }\n }\n }\n\n /*\n Method: buildColormap\n\n 1. initializes network\n 2. trains it\n 3. removes misconceptions\n 4. builds colorindex\n */\n function buildColormap() {\n init();\n learn();\n unbiasnet();\n inxbuild();\n }\n this.buildColormap = buildColormap;\n\n /*\n Method: getColormap\n\n builds colormap from the index\n\n returns array in the format:\n\n >\n > [r, g, b, r, g, b, r, g, b, ..]\n >\n */\n function getColormap() {\n var map = [];\n var index = [];\n\n for (var i = 0; i < netsize; i++)\n index[network[i][3]] = i;\n\n var k = 0;\n for (var l = 0; l < netsize; l++) {\n var j = index[l];\n map[k++] = (network[j][0]);\n map[k++] = (network[j][1]);\n map[k++] = (network[j][2]);\n }\n return map;\n }\n this.getColormap = getColormap;\n\n /*\n Method: lookupRGB\n\n looks for the closest *r*, *g*, *b* color in the map and\n returns its index\n */\n this.lookupRGB = inxsearch;\n}",
"function NeuQuant(pixels, samplefac) {\n var network; // int[netsize][4]\n var netindex; // for network lookup - really 256\n \n // bias and freq arrays for learning\n var bias;\n var freq;\n var radpower;\n \n /*\n Private Method: init\n \n sets up arrays\n */\n function init() {\n network = [];\n netindex = new Int32Array(256);\n bias = new Int32Array(netsize);\n freq = new Int32Array(netsize);\n radpower = new Int32Array(netsize >> 3);\n \n var i, v;\n for (i = 0; i < netsize; i++) {\n v = (i << (netbiasshift + 8)) / netsize;\n network[i] = new Float64Array([v, v, v, 0]);\n //network[i] = [v, v, v, 0]\n freq[i] = intbias / netsize;\n bias[i] = 0;\n }\n }\n \n /*\n Private Method: unbiasnet\n \n unbiases network to give byte values 0..255 and record position i to prepare for sort\n */\n function unbiasnet() {\n for (var i = 0; i < netsize; i++) {\n network[i][0] >>= netbiasshift;\n network[i][1] >>= netbiasshift;\n network[i][2] >>= netbiasshift;\n network[i][3] = i; // record color number\n }\n }\n \n /*\n Private Method: altersingle\n \n moves neuron *i* towards biased (b,g,r) by factor *alpha*\n */\n function altersingle(alpha, i, b, g, r) {\n network[i][0] -= (alpha * (network[i][0] - b)) / initalpha;\n network[i][1] -= (alpha * (network[i][1] - g)) / initalpha;\n network[i][2] -= (alpha * (network[i][2] - r)) / initalpha;\n }\n \n /*\n Private Method: alterneigh\n \n moves neurons in *radius* around index *i* towards biased (b,g,r) by factor *alpha*\n */\n function alterneigh(radius, i, b, g, r) {\n var lo = Math.abs(i - radius);\n var hi = Math.min(i + radius, netsize);\n \n var j = i + 1;\n var k = i - 1;\n var m = 1;\n \n var p, a;\n while ((j < hi) || (k > lo)) {\n a = radpower[m++];\n \n if (j < hi) {\n p = network[j++];\n p[0] -= (a * (p[0] - b)) / alpharadbias;\n p[1] -= (a * (p[1] - g)) / alpharadbias;\n p[2] -= (a * (p[2] - r)) / alpharadbias;\n }\n \n if (k > lo) {\n p = network[k--];\n p[0] -= (a * (p[0] - b)) / alpharadbias;\n p[1] -= (a * (p[1] - g)) / alpharadbias;\n p[2] -= (a * (p[2] - r)) / alpharadbias;\n }\n }\n }\n \n /*\n Private Method: contest\n \n searches for biased BGR values\n */\n function contest(b, g, r) {\n /*\n finds closest neuron (min dist) and updates freq\n finds best neuron (min dist-bias) and returns position\n for frequently chosen neurons, freq[i] is high and bias[i] is negative\n bias[i] = gamma * ((1 / netsize) - freq[i])\n */\n \n var bestd = ~(1 << 31);\n var bestbiasd = bestd;\n var bestpos = -1;\n var bestbiaspos = bestpos;\n \n var i, n, dist, biasdist, betafreq;\n for (i = 0; i < netsize; i++) {\n n = network[i];\n \n dist = Math.abs(n[0] - b) + Math.abs(n[1] - g) + Math.abs(n[2] - r);\n if (dist < bestd) {\n bestd = dist;\n bestpos = i;\n }\n \n biasdist = dist - ((bias[i]) >> (intbiasshift - netbiasshift));\n if (biasdist < bestbiasd) {\n bestbiasd = biasdist;\n bestbiaspos = i;\n }\n \n betafreq = (freq[i] >> betashift);\n freq[i] -= betafreq;\n bias[i] += (betafreq << gammashift);\n }\n \n freq[bestpos] += beta;\n bias[bestpos] -= betagamma;\n \n return bestbiaspos;\n }\n \n /*\n Private Method: inxbuild\n \n sorts network and builds netindex[0..255]\n */\n function inxbuild() {\n var i, j, p, q, smallpos, smallval, previouscol = 0, startpos = 0;\n for (i = 0; i < netsize; i++) {\n p = network[i];\n smallpos = i;\n smallval = p[1]; // index on g\n // find smallest in i..netsize-1\n for (j = i + 1; j < netsize; j++) {\n q = network[j];\n if (q[1] < smallval) { // index on g\n smallpos = j;\n smallval = q[1]; // index on g\n }\n }\n q = network[smallpos];\n // swap p (i) and q (smallpos) entries\n if (i != smallpos) {\n j = q[0]; q[0] = p[0]; p[0] = j;\n j = q[1]; q[1] = p[1]; p[1] = j;\n j = q[2]; q[2] = p[2]; p[2] = j;\n j = q[3]; q[3] = p[3]; p[3] = j;\n }\n // smallval entry is now in position i\n \n if (smallval != previouscol) {\n netindex[previouscol] = (startpos + i) >> 1;\n for (j = previouscol + 1; j < smallval; j++)\n netindex[j] = i;\n previouscol = smallval;\n startpos = i;\n }\n }\n netindex[previouscol] = (startpos + maxnetpos) >> 1;\n for (j = previouscol + 1; j < 256; j++)\n netindex[j] = maxnetpos; // really 256\n }\n \n /*\n Private Method: inxsearch\n \n searches for BGR values 0..255 and returns a color index\n */\n function inxsearch(b, g, r) {\n var a, p, dist;\n \n var bestd = 1000; // biggest possible dist is 256*3\n var best = -1;\n \n var i = netindex[g]; // index on g\n var j = i - 1; // start at netindex[g] and work outwards\n \n while ((i < netsize) || (j >= 0)) {\n if (i < netsize) {\n p = network[i];\n dist = p[1] - g; // inx key\n if (dist >= bestd) i = netsize; // stop iter\n else {\n i++;\n if (dist < 0) dist = -dist;\n a = p[0] - b; if (a < 0) a = -a;\n dist += a;\n if (dist < bestd) {\n a = p[2] - r; if (a < 0) a = -a;\n dist += a;\n if (dist < bestd) {\n bestd = dist;\n best = p[3];\n }\n }\n }\n }\n if (j >= 0) {\n p = network[j];\n dist = g - p[1]; // inx key - reverse dif\n if (dist >= bestd) j = -1; // stop iter\n else {\n j--;\n if (dist < 0) dist = -dist;\n a = p[0] - b; if (a < 0) a = -a;\n dist += a;\n if (dist < bestd) {\n a = p[2] - r; if (a < 0) a = -a;\n dist += a;\n if (dist < bestd) {\n bestd = dist;\n best = p[3];\n }\n }\n }\n }\n }\n \n return best;\n }\n \n /*\n Private Method: learn\n \n \"Main Learning Loop\"\n */\n function learn() {\n var i;\n \n var lengthcount = pixels.length;\n var alphadec = 30 + ((samplefac - 1) / 3);\n var samplepixels = lengthcount / (3 * samplefac);\n var delta = ~~(samplepixels / ncycles);\n var alpha = initalpha;\n var radius = initradius;\n \n var rad = radius >> radiusbiasshift;\n \n if (rad <= 1) rad = 0;\n for (i = 0; i < rad; i++)\n radpower[i] = alpha * (((rad * rad - i * i) * radbias) / (rad * rad));\n \n var step;\n if (lengthcount < minpicturebytes) {\n samplefac = 1;\n step = 3;\n } else if ((lengthcount % prime1) !== 0) {\n step = 3 * prime1;\n } else if ((lengthcount % prime2) !== 0) {\n step = 3 * prime2;\n } else if ((lengthcount % prime3) !== 0) {\n step = 3 * prime3;\n } else {\n step = 3 * prime4;\n }\n \n var b, g, r, j;\n var pix = 0; // current pixel\n \n i = 0;\n while (i < samplepixels) {\n b = (pixels[pix] & 0xff) << netbiasshift;\n g = (pixels[pix + 1] & 0xff) << netbiasshift;\n r = (pixels[pix + 2] & 0xff) << netbiasshift;\n \n j = contest(b, g, r);\n \n altersingle(alpha, j, b, g, r);\n if (rad !== 0) alterneigh(rad, j, b, g, r); // alter neighbours\n \n pix += step;\n if (pix >= lengthcount) pix -= lengthcount;\n \n i++;\n \n if (delta === 0) delta = 1;\n if (i % delta === 0) {\n alpha -= alpha / alphadec;\n radius -= radius / radiusdec;\n rad = radius >> radiusbiasshift;\n \n if (rad <= 1) rad = 0;\n for (j = 0; j < rad; j++)\n radpower[j] = alpha * (((rad * rad - j * j) * radbias) / (rad * rad));\n }\n }\n }\n \n /*\n Method: buildColormap\n \n 1. initializes network\n 2. trains it\n 3. removes misconceptions\n 4. builds colorindex\n */\n function buildColormap() {\n init();\n learn();\n unbiasnet();\n inxbuild();\n }\n this.buildColormap = buildColormap;\n \n /*\n Method: getColormap\n \n builds colormap from the index\n \n returns array in the format:\n \n >\n > [r, g, b, r, g, b, r, g, b, ..]\n >\n */\n function getColormap() {\n var map = [];\n var index = [];\n \n for (var i = 0; i < netsize; i++)\n index[network[i][3]] = i;\n \n var k = 0;\n for (var l = 0; l < netsize; l++) {\n var j = index[l];\n map[k++] = (network[j][0]);\n map[k++] = (network[j][1]);\n map[k++] = (network[j][2]);\n }\n return map;\n }\n this.getColormap = getColormap;\n \n /*\n Method: lookupRGB\n \n looks for the closest *r*, *g*, *b* color in the map and\n returns its index\n */\n this.lookupRGB = inxsearch;\n }",
"function Quantize(){var bs;this.rv=null;var rv;this.qupvt=null;var qupvt;var vbr=new VBRQuantize();var tk;this.setModules=function(_bs,_rv,_qupvt,_tk){bs=_bs;rv=_rv;this.rv=_rv;qupvt=_qupvt;this.qupvt=_qupvt;tk=_tk;vbr.setModules(qupvt,tk);};/**\n * convert from L/R <. Mid/Side\n */this.ms_convert=function(l3_side,gr){for(var i=0;i<576;++i){var l=l3_side.tt[gr][0].xr[i];var r=l3_side.tt[gr][1].xr[i];l3_side.tt[gr][0].xr[i]=(l+r)*(Util.SQRT2*0.5);l3_side.tt[gr][1].xr[i]=(l-r)*(Util.SQRT2*0.5);}};/**\n * mt 6/99\n *\n * initializes cod_info, scalefac and xrpow\n *\n * returns 0 if all energies in xr are zero, else 1\n */function init_xrpow_core(cod_info,xrpow,upper,sum){sum=0;for(var i=0;i<=upper;++i){var tmp=Math.abs(cod_info.xr[i]);sum+=tmp;xrpow[i]=Math.sqrt(tmp*Math.sqrt(tmp));if(xrpow[i]>cod_info.xrpow_max)cod_info.xrpow_max=xrpow[i];}return sum;}this.init_xrpow=function(gfc,cod_info,xrpow){var sum=0;var upper=0|cod_info.max_nonzero_coeff;cod_info.xrpow_max=0;/*\n * check if there is some energy we have to quantize and calculate xrpow\n * matching our fresh scalefactors\n */Arrays.fill(xrpow,upper,576,0);sum=init_xrpow_core(cod_info,xrpow,upper,sum);/*\n * return 1 if we have something to quantize, else 0\n */if(sum>1E-20){var j=0;if((gfc.substep_shaping&2)!=0)j=1;for(var i=0;i<cod_info.psymax;i++){gfc.pseudohalf[i]=j;}return true;}Arrays.fill(cod_info.l3_enc,0,576,0);return false;};/**\n * Gabriel Bouvigne feb/apr 2003<BR>\n * Analog silence detection in partitionned sfb21 or sfb12 for short blocks\n *\n * From top to bottom of sfb, changes to 0 coeffs which are below ath. It\n * stops on the first coeff higher than ath.\n */function psfb21_analogsilence(gfc,cod_info){var ath=gfc.ATH;var xr=cod_info.xr;if(cod_info.block_type!=Encoder.SHORT_TYPE){/* NORM, START or STOP type, but not SHORT blocks */var stop=false;for(var gsfb=Encoder.PSFB21-1;gsfb>=0&&!stop;gsfb--){var start=gfc.scalefac_band.psfb21[gsfb];var end=gfc.scalefac_band.psfb21[gsfb+1];var ath21=qupvt.athAdjust(ath.adjust,ath.psfb21[gsfb],ath.floor);if(gfc.nsPsy.longfact[21]>1e-12)ath21*=gfc.nsPsy.longfact[21];for(var j=end-1;j>=start;j--){if(Math.abs(xr[j])<ath21)xr[j]=0;else{stop=true;break;}}}}else{/* note: short blocks coeffs are reordered */for(var block=0;block<3;block++){var stop=false;for(var gsfb=Encoder.PSFB12-1;gsfb>=0&&!stop;gsfb--){var start=gfc.scalefac_band.s[12]*3+(gfc.scalefac_band.s[13]-gfc.scalefac_band.s[12])*block+(gfc.scalefac_band.psfb12[gsfb]-gfc.scalefac_band.psfb12[0]);var end=start+(gfc.scalefac_band.psfb12[gsfb+1]-gfc.scalefac_band.psfb12[gsfb]);var ath12=qupvt.athAdjust(ath.adjust,ath.psfb12[gsfb],ath.floor);if(gfc.nsPsy.shortfact[12]>1e-12)ath12*=gfc.nsPsy.shortfact[12];for(var j=end-1;j>=start;j--){if(Math.abs(xr[j])<ath12)xr[j]=0;else{stop=true;break;}}}}}}this.init_outer_loop=function(gfc,cod_info){/*\n * initialize fresh cod_info\n */cod_info.part2_3_length=0;cod_info.big_values=0;cod_info.count1=0;cod_info.global_gain=210;cod_info.scalefac_compress=0;/* mixed_block_flag, block_type was set in psymodel.c */cod_info.table_select[0]=0;cod_info.table_select[1]=0;cod_info.table_select[2]=0;cod_info.subblock_gain[0]=0;cod_info.subblock_gain[1]=0;cod_info.subblock_gain[2]=0;cod_info.subblock_gain[3]=0;/* this one is always 0 */cod_info.region0_count=0;cod_info.region1_count=0;cod_info.preflag=0;cod_info.scalefac_scale=0;cod_info.count1table_select=0;cod_info.part2_length=0;cod_info.sfb_lmax=Encoder.SBPSY_l;cod_info.sfb_smin=Encoder.SBPSY_s;cod_info.psy_lmax=gfc.sfb21_extra?Encoder.SBMAX_l:Encoder.SBPSY_l;cod_info.psymax=cod_info.psy_lmax;cod_info.sfbmax=cod_info.sfb_lmax;cod_info.sfbdivide=11;for(var sfb=0;sfb<Encoder.SBMAX_l;sfb++){cod_info.width[sfb]=gfc.scalefac_band.l[sfb+1]-gfc.scalefac_band.l[sfb];/* which is always 0. */cod_info.window[sfb]=3;}if(cod_info.block_type==Encoder.SHORT_TYPE){var ixwork=new_float(576);cod_info.sfb_smin=0;cod_info.sfb_lmax=0;if(cod_info.mixed_block_flag!=0){/*\n * MPEG-1: sfbs 0-7 long block, 3-12 short blocks MPEG-2(.5):\n * sfbs 0-5 long block, 3-12 short blocks\n */cod_info.sfb_smin=3;cod_info.sfb_lmax=gfc.mode_gr*2+4;}cod_info.psymax=cod_info.sfb_lmax+3*((gfc.sfb21_extra?Encoder.SBMAX_s:Encoder.SBPSY_s)-cod_info.sfb_smin);cod_info.sfbmax=cod_info.sfb_lmax+3*(Encoder.SBPSY_s-cod_info.sfb_smin);cod_info.sfbdivide=cod_info.sfbmax-18;cod_info.psy_lmax=cod_info.sfb_lmax;/* re-order the short blocks, for more efficient encoding below *//* By Takehiro TOMINAGA *//*\n * Within each scalefactor band, data is given for successive time\n * windows, beginning with window 0 and ending with window 2. Within\n * each window, the quantized values are then arranged in order of\n * increasing frequency...\n */var ix=gfc.scalefac_band.l[cod_info.sfb_lmax];System.arraycopy(cod_info.xr,0,ixwork,0,576);for(var sfb=cod_info.sfb_smin;sfb<Encoder.SBMAX_s;sfb++){var start=gfc.scalefac_band.s[sfb];var end=gfc.scalefac_band.s[sfb+1];for(var window=0;window<3;window++){for(var l=start;l<end;l++){cod_info.xr[ix++]=ixwork[3*l+window];}}}var j=cod_info.sfb_lmax;for(var sfb=cod_info.sfb_smin;sfb<Encoder.SBMAX_s;sfb++){cod_info.width[j]=cod_info.width[j+1]=cod_info.width[j+2]=gfc.scalefac_band.s[sfb+1]-gfc.scalefac_band.s[sfb];cod_info.window[j]=0;cod_info.window[j+1]=1;cod_info.window[j+2]=2;j+=3;}}cod_info.count1bits=0;cod_info.sfb_partition_table=qupvt.nr_of_sfb_block[0][0];cod_info.slen[0]=0;cod_info.slen[1]=0;cod_info.slen[2]=0;cod_info.slen[3]=0;cod_info.max_nonzero_coeff=575;/*\n * fresh scalefactors are all zero\n */Arrays.fill(cod_info.scalefac,0);psfb21_analogsilence(gfc,cod_info);};function BinSearchDirection(ordinal){this.ordinal=ordinal;}BinSearchDirection.BINSEARCH_NONE=new BinSearchDirection(0);BinSearchDirection.BINSEARCH_UP=new BinSearchDirection(1);BinSearchDirection.BINSEARCH_DOWN=new BinSearchDirection(2);/**\n * author/date??\n *\n * binary step size search used by outer_loop to get a quantizer step size\n * to start with\n */function bin_search_StepSize(gfc,cod_info,desired_rate,ch,xrpow){var nBits;var CurrentStep=gfc.CurrentStep[ch];var flagGoneOver=false;var start=gfc.OldValue[ch];var Direction=BinSearchDirection.BINSEARCH_NONE;cod_info.global_gain=start;desired_rate-=cod_info.part2_length;for(;;){var step;nBits=tk.count_bits(gfc,xrpow,cod_info,null);if(CurrentStep==1||nBits==desired_rate)break;/* nothing to adjust anymore */if(nBits>desired_rate){/* increase Quantize_StepSize */if(Direction==BinSearchDirection.BINSEARCH_DOWN)flagGoneOver=true;if(flagGoneOver)CurrentStep/=2;Direction=BinSearchDirection.BINSEARCH_UP;step=CurrentStep;}else{/* decrease Quantize_StepSize */if(Direction==BinSearchDirection.BINSEARCH_UP)flagGoneOver=true;if(flagGoneOver)CurrentStep/=2;Direction=BinSearchDirection.BINSEARCH_DOWN;step=-CurrentStep;}cod_info.global_gain+=step;if(cod_info.global_gain<0){cod_info.global_gain=0;flagGoneOver=true;}if(cod_info.global_gain>255){cod_info.global_gain=255;flagGoneOver=true;}}while(nBits>desired_rate&&cod_info.global_gain<255){cod_info.global_gain++;nBits=tk.count_bits(gfc,xrpow,cod_info,null);}gfc.CurrentStep[ch]=start-cod_info.global_gain>=4?4:2;gfc.OldValue[ch]=cod_info.global_gain;cod_info.part2_3_length=nBits;return nBits;}this.trancate_smallspectrums=function(gfc,gi,l3_xmin,work){var distort=new_float(L3Side.SFBMAX);if(0==(gfc.substep_shaping&4)&&gi.block_type==Encoder.SHORT_TYPE||(gfc.substep_shaping&0x80)!=0)return;qupvt.calc_noise(gi,l3_xmin,distort,new CalcNoiseResult(),null);for(var j=0;j<576;j++){var xr=0.0;if(gi.l3_enc[j]!=0)xr=Math.abs(gi.xr[j]);work[j]=xr;}var j=0;var sfb=8;if(gi.block_type==Encoder.SHORT_TYPE)sfb=6;do{var allowedNoise,trancateThreshold;var nsame,start;var width=gi.width[sfb];j+=width;if(distort[sfb]>=1.0)continue;Arrays.sort(work,j-width,width);if(BitStream.EQ(work[j-1],0.0))continue;/* all zero sfb */allowedNoise=(1.0-distort[sfb])*l3_xmin[sfb];trancateThreshold=0.0;start=0;do{var noise;for(nsame=1;start+nsame<width;nsame++){if(BitStream.NEQ(work[start+j-width],work[start+j+nsame-width]))break;}noise=work[start+j-width]*work[start+j-width]*nsame;if(allowedNoise<noise){if(start!=0)trancateThreshold=work[start+j-width-1];break;}allowedNoise-=noise;start+=nsame;}while(start<width);if(BitStream.EQ(trancateThreshold,0.0))continue;do{if(Math.abs(gi.xr[j-width])<=trancateThreshold)gi.l3_enc[j-width]=0;}while(--width>0);}while(++sfb<gi.psymax);gi.part2_3_length=tk.noquant_count_bits(gfc,gi,null);};/**\n * author/date??\n *\n * Function: Returns zero if there is a scalefac which has not been\n * amplified. Otherwise it returns one.\n */function loop_break(cod_info){for(var sfb=0;sfb<cod_info.sfbmax;sfb++){if(cod_info.scalefac[sfb]+cod_info.subblock_gain[cod_info.window[sfb]]==0)return false;}return true;}/* mt 5/99: Function: Improved calc_noise for a single channel */function penalties(noise){return Util.FAST_LOG10(0.368+0.632*noise*noise*noise);}/**\n * author/date??\n *\n * several different codes to decide which quantization is better\n */function get_klemm_noise(distort,gi){var klemm_noise=1E-37;for(var sfb=0;sfb<gi.psymax;sfb++){klemm_noise+=penalties(distort[sfb]);}return Math.max(1e-20,klemm_noise);}function quant_compare(quant_comp,best,calc,gi,distort){/**\n * noise is given in decibels (dB) relative to masking thesholds.<BR>\n *\n * over_noise: ??? (the previous comment is fully wrong)<BR>\n * tot_noise: ??? (the previous comment is fully wrong)<BR>\n * max_noise: max quantization noise\n */var better;switch(quant_comp){default:case 9:{if(best.over_count>0){/* there are distorted sfb */better=calc.over_SSD<=best.over_SSD;if(calc.over_SSD==best.over_SSD)better=calc.bits<best.bits;}else{/* no distorted sfb */better=calc.max_noise<0&&calc.max_noise*10+calc.bits<=best.max_noise*10+best.bits;}break;}case 0:better=calc.over_count<best.over_count||calc.over_count==best.over_count&&calc.over_noise<best.over_noise||calc.over_count==best.over_count&&BitStream.EQ(calc.over_noise,best.over_noise)&&calc.tot_noise<best.tot_noise;break;case 8:calc.max_noise=get_klemm_noise(distort,gi);//$FALL-THROUGH$\ncase 1:better=calc.max_noise<best.max_noise;break;case 2:better=calc.tot_noise<best.tot_noise;break;case 3:better=calc.tot_noise<best.tot_noise&&calc.max_noise<best.max_noise;break;case 4:better=calc.max_noise<=0.0&&best.max_noise>0.2||calc.max_noise<=0.0&&best.max_noise<0.0&&best.max_noise>calc.max_noise-0.2&&calc.tot_noise<best.tot_noise||calc.max_noise<=0.0&&best.max_noise>0.0&&best.max_noise>calc.max_noise-0.2&&calc.tot_noise<best.tot_noise+best.over_noise||calc.max_noise>0.0&&best.max_noise>-0.05&&best.max_noise>calc.max_noise-0.1&&calc.tot_noise+calc.over_noise<best.tot_noise+best.over_noise||calc.max_noise>0.0&&best.max_noise>-0.1&&best.max_noise>calc.max_noise-0.15&&calc.tot_noise+calc.over_noise+calc.over_noise<best.tot_noise+best.over_noise+best.over_noise;break;case 5:better=calc.over_noise<best.over_noise||BitStream.EQ(calc.over_noise,best.over_noise)&&calc.tot_noise<best.tot_noise;break;case 6:better=calc.over_noise<best.over_noise||BitStream.EQ(calc.over_noise,best.over_noise)&&(calc.max_noise<best.max_noise||BitStream.EQ(calc.max_noise,best.max_noise)&&calc.tot_noise<=best.tot_noise);break;case 7:better=calc.over_count<best.over_count||calc.over_noise<best.over_noise;break;}if(best.over_count==0){/*\n * If no distorted bands, only use this quantization if it is\n * better, and if it uses less bits. Unfortunately, part2_3_length\n * is sometimes a poor estimator of the final size at low bitrates.\n */better=better&&calc.bits<best.bits;}return better;}/**\n * author/date??\n *\n * <PRE>\n * Amplify the scalefactor bands that violate the masking threshold.\n * See ISO 11172-3 Section C.1.5.4.3.5\n *\n * distort[] = noise/masking\n * distort[] > 1 ==> noise is not masked\n * distort[] < 1 ==> noise is masked\n * max_dist = maximum value of distort[]\n *\n * Three algorithms:\n * noise_shaping_amp\n * 0 Amplify all bands with distort[]>1.\n *\n * 1 Amplify all bands with distort[] >= max_dist^(.5);\n * ( 50% in the db scale)\n *\n * 2 Amplify first band with distort[] >= max_dist;\n *\n *\n * For algorithms 0 and 1, if max_dist < 1, then amplify all bands\n * with distort[] >= .95*max_dist. This is to make sure we always\n * amplify at least one band.\n * </PRE>\n */function amp_scalefac_bands(gfp,cod_info,distort,xrpow,bRefine){var gfc=gfp.internal_flags;var ifqstep34;if(cod_info.scalefac_scale==0){ifqstep34=1.29683955465100964055;/* 2**(.75*.5) */}else{ifqstep34=1.68179283050742922612;/* 2**(.75*1) */}/* compute maximum value of distort[] */var trigger=0;for(var sfb=0;sfb<cod_info.sfbmax;sfb++){if(trigger<distort[sfb])trigger=distort[sfb];}var noise_shaping_amp=gfc.noise_shaping_amp;if(noise_shaping_amp==3){if(bRefine)noise_shaping_amp=2;else noise_shaping_amp=1;}switch(noise_shaping_amp){case 2:/* amplify exactly 1 band */break;case 1:/* amplify bands within 50% of max (on db scale) */if(trigger>1.0)trigger=Math.pow(trigger,.5);else trigger*=.95;break;case 0:default:/* ISO algorithm. amplify all bands with distort>1 */if(trigger>1.0)trigger=1.0;else trigger*=.95;break;}var j=0;for(var sfb=0;sfb<cod_info.sfbmax;sfb++){var width=cod_info.width[sfb];var l;j+=width;if(distort[sfb]<trigger)continue;if((gfc.substep_shaping&2)!=0){gfc.pseudohalf[sfb]=0==gfc.pseudohalf[sfb]?1:0;if(0==gfc.pseudohalf[sfb]&&gfc.noise_shaping_amp==2)return;}cod_info.scalefac[sfb]++;for(l=-width;l<0;l++){xrpow[j+l]*=ifqstep34;if(xrpow[j+l]>cod_info.xrpow_max)cod_info.xrpow_max=xrpow[j+l];}if(gfc.noise_shaping_amp==2)return;}}/**\n * Takehiro Tominaga 2000-xx-xx\n *\n * turns on scalefac scale and adjusts scalefactors\n */function inc_scalefac_scale(cod_info,xrpow){var ifqstep34=1.29683955465100964055;var j=0;for(var sfb=0;sfb<cod_info.sfbmax;sfb++){var width=cod_info.width[sfb];var s=cod_info.scalefac[sfb];if(cod_info.preflag!=0)s+=qupvt.pretab[sfb];j+=width;if((s&1)!=0){s++;for(var l=-width;l<0;l++){xrpow[j+l]*=ifqstep34;if(xrpow[j+l]>cod_info.xrpow_max)cod_info.xrpow_max=xrpow[j+l];}}cod_info.scalefac[sfb]=s>>1;}cod_info.preflag=0;cod_info.scalefac_scale=1;}/**\n * Takehiro Tominaga 2000-xx-xx\n *\n * increases the subblock gain and adjusts scalefactors\n */function inc_subblock_gain(gfc,cod_info,xrpow){var sfb;var scalefac=cod_info.scalefac;/* subbloc_gain can't do anything in the long block region */for(sfb=0;sfb<cod_info.sfb_lmax;sfb++){if(scalefac[sfb]>=16)return true;}for(var window=0;window<3;window++){var s1=0;var s2=0;for(sfb=cod_info.sfb_lmax+window;sfb<cod_info.sfbdivide;sfb+=3){if(s1<scalefac[sfb])s1=scalefac[sfb];}for(;sfb<cod_info.sfbmax;sfb+=3){if(s2<scalefac[sfb])s2=scalefac[sfb];}if(s1<16&&s2<8)continue;if(cod_info.subblock_gain[window]>=7)return true;/*\n * even though there is no scalefactor for sfb12 subblock gain\n * affects upper frequencies too, that's why we have to go up to\n * SBMAX_s\n */cod_info.subblock_gain[window]++;var j=gfc.scalefac_band.l[cod_info.sfb_lmax];for(sfb=cod_info.sfb_lmax+window;sfb<cod_info.sfbmax;sfb+=3){var amp;var width=cod_info.width[sfb];var s=scalefac[sfb];s=s-(4>>cod_info.scalefac_scale);if(s>=0){scalefac[sfb]=s;j+=width*3;continue;}scalefac[sfb]=0;{var gain=210+(s<<cod_info.scalefac_scale+1);amp=qupvt.IPOW20(gain);}j+=width*(window+1);for(var l=-width;l<0;l++){xrpow[j+l]*=amp;if(xrpow[j+l]>cod_info.xrpow_max)cod_info.xrpow_max=xrpow[j+l];}j+=width*(3-window-1);}{var amp=qupvt.IPOW20(202);j+=cod_info.width[sfb]*(window+1);for(var l=-cod_info.width[sfb];l<0;l++){xrpow[j+l]*=amp;if(xrpow[j+l]>cod_info.xrpow_max)cod_info.xrpow_max=xrpow[j+l];}}}return false;}/**\n * <PRE>\n * Takehiro Tominaga /date??\n * Robert Hegemann 2000-09-06: made a function of it\n *\n * amplifies scalefactor bands,\n * - if all are already amplified returns 0\n * - if some bands are amplified too much:\n * * try to increase scalefac_scale\n * * if already scalefac_scale was set\n * try on short blocks to increase subblock gain\n * </PRE>\n */function balance_noise(gfp,cod_info,distort,xrpow,bRefine){var gfc=gfp.internal_flags;amp_scalefac_bands(gfp,cod_info,distort,xrpow,bRefine);/*\n * check to make sure we have not amplified too much loop_break returns\n * 0 if there is an unamplified scalefac scale_bitcount returns 0 if no\n * scalefactors are too large\n */var status=loop_break(cod_info);if(status)return false;/* all bands amplified *//*\n * not all scalefactors have been amplified. so these scalefacs are\n * possibly valid. encode them:\n */if(gfc.mode_gr==2)status=tk.scale_bitcount(cod_info);else status=tk.scale_bitcount_lsf(gfc,cod_info);if(!status)return true;/* amplified some bands not exceeding limits *//*\n * some scalefactors are too large. lets try setting scalefac_scale=1\n */if(gfc.noise_shaping>1){Arrays.fill(gfc.pseudohalf,0);if(0==cod_info.scalefac_scale){inc_scalefac_scale(cod_info,xrpow);status=false;}else{if(cod_info.block_type==Encoder.SHORT_TYPE&&gfc.subblock_gain>0){status=inc_subblock_gain(gfc,cod_info,xrpow)||loop_break(cod_info);}}}if(!status){if(gfc.mode_gr==2)status=tk.scale_bitcount(cod_info);else status=tk.scale_bitcount_lsf(gfc,cod_info);}return!status;}/**\n * <PRE>\n * Function: The outer iteration loop controls the masking conditions\n * of all scalefactorbands. It computes the best scalefac and\n * global gain. This module calls the inner iteration loop\n *\n * mt 5/99 completely rewritten to allow for bit reservoir control,\n * mid/side channels with L/R or mid/side masking thresholds,\n * and chooses best quantization instead of last quantization when\n * no distortion free quantization can be found.\n *\n * added VBR support mt 5/99\n *\n * some code shuffle rh 9/00\n * </PRE>\n *\n * @param l3_xmin\n * allowed distortion\n * @param xrpow\n * coloured magnitudes of spectral\n * @param targ_bits\n * maximum allowed bits\n */this.outer_loop=function(gfp,cod_info,l3_xmin,xrpow,ch,targ_bits){var gfc=gfp.internal_flags;var cod_info_w=new GrInfo();var save_xrpow=new_float(576);var distort=new_float(L3Side.SFBMAX);var best_noise_info=new CalcNoiseResult();var better;var prev_noise=new CalcNoiseData();var best_part2_3_length=9999999;var bEndOfSearch=false;var bRefine=false;var best_ggain_pass1=0;bin_search_StepSize(gfc,cod_info,targ_bits,ch,xrpow);if(0==gfc.noise_shaping)/* fast mode, no noise shaping, we are ready */return 100;/* default noise_info.over_count *//* compute the distortion in this quantization *//* coefficients and thresholds both l/r (or both mid/side) */qupvt.calc_noise(cod_info,l3_xmin,distort,best_noise_info,prev_noise);best_noise_info.bits=cod_info.part2_3_length;cod_info_w.assign(cod_info);var age=0;System.arraycopy(xrpow,0,save_xrpow,0,576);while(!bEndOfSearch){/* BEGIN MAIN LOOP */do{var noise_info=new CalcNoiseResult();var search_limit;var maxggain=255;/*\n * When quantization with no distorted bands is found, allow up\n * to X new unsuccesful tries in serial. This gives us more\n * possibilities for different quant_compare modes. Much more\n * than 3 makes not a big difference, it is only slower.\n */if((gfc.substep_shaping&2)!=0){search_limit=20;}else{search_limit=3;}/*\n * Check if the last scalefactor band is distorted. in VBR mode\n * we can't get rid of the distortion, so quit now and VBR mode\n * will try again with more bits. (makes a 10% speed increase,\n * the files I tested were binary identical, 2000/05/20 Robert\n * Hegemann) distort[] > 1 means noise > allowed noise\n */if(gfc.sfb21_extra){if(distort[cod_info_w.sfbmax]>1.0)break;if(cod_info_w.block_type==Encoder.SHORT_TYPE&&(distort[cod_info_w.sfbmax+1]>1.0||distort[cod_info_w.sfbmax+2]>1.0))break;}/* try a new scalefactor conbination on cod_info_w */if(!balance_noise(gfp,cod_info_w,distort,xrpow,bRefine))break;if(cod_info_w.scalefac_scale!=0)maxggain=254;/*\n * inner_loop starts with the initial quantization step computed\n * above and slowly increases until the bits < huff_bits. Thus\n * it is important not to start with too large of an inital\n * quantization step. Too small is ok, but inner_loop will take\n * longer\n */var huff_bits=targ_bits-cod_info_w.part2_length;if(huff_bits<=0)break;/*\n * increase quantizer stepsize until needed bits are below\n * maximum\n */while((cod_info_w.part2_3_length=tk.count_bits(gfc,xrpow,cod_info_w,prev_noise))>huff_bits&&cod_info_w.global_gain<=maxggain){cod_info_w.global_gain++;}if(cod_info_w.global_gain>maxggain)break;if(best_noise_info.over_count==0){while((cod_info_w.part2_3_length=tk.count_bits(gfc,xrpow,cod_info_w,prev_noise))>best_part2_3_length&&cod_info_w.global_gain<=maxggain){cod_info_w.global_gain++;}if(cod_info_w.global_gain>maxggain)break;}/* compute the distortion in this quantization */qupvt.calc_noise(cod_info_w,l3_xmin,distort,noise_info,prev_noise);noise_info.bits=cod_info_w.part2_3_length;/*\n * check if this quantization is better than our saved\n * quantization\n */if(cod_info.block_type!=Encoder.SHORT_TYPE){// NORM, START or STOP type\nbetter=gfp.quant_comp;}else better=gfp.quant_comp_short;better=quant_compare(better,best_noise_info,noise_info,cod_info_w,distort)?1:0;/* save data so we can restore this quantization later */if(better!=0){best_part2_3_length=cod_info.part2_3_length;best_noise_info=noise_info;cod_info.assign(cod_info_w);age=0;/* save data so we can restore this quantization later *//* store for later reuse */System.arraycopy(xrpow,0,save_xrpow,0,576);}else{/* early stop? */if(gfc.full_outer_loop==0){if(++age>search_limit&&best_noise_info.over_count==0)break;if(gfc.noise_shaping_amp==3&&bRefine&&age>30)break;if(gfc.noise_shaping_amp==3&&bRefine&&cod_info_w.global_gain-best_ggain_pass1>15)break;}}}while(cod_info_w.global_gain+cod_info_w.scalefac_scale<255);if(gfc.noise_shaping_amp==3){if(!bRefine){/* refine search */cod_info_w.assign(cod_info);System.arraycopy(save_xrpow,0,xrpow,0,576);age=0;best_ggain_pass1=cod_info_w.global_gain;bRefine=true;}else{/* search already refined, stop */bEndOfSearch=true;}}else{bEndOfSearch=true;}}/*\n * finish up\n */if(gfp.VBR==VbrMode.vbr_rh||gfp.VBR==VbrMode.vbr_mtrh)/* restore for reuse on next try */System.arraycopy(save_xrpow,0,xrpow,0,576);/*\n * do the 'substep shaping'\n */else if((gfc.substep_shaping&1)!=0)trancate_smallspectrums(gfc,cod_info,l3_xmin,xrpow);return best_noise_info.over_count;};/**\n * Robert Hegemann 2000-09-06\n *\n * update reservoir status after FINAL quantization/bitrate\n */this.iteration_finish_one=function(gfc,gr,ch){var l3_side=gfc.l3_side;var cod_info=l3_side.tt[gr][ch];/*\n * try some better scalefac storage\n */tk.best_scalefac_store(gfc,gr,ch,l3_side);/*\n * best huffman_divide may save some bits too\n */if(gfc.use_best_huffman==1)tk.best_huffman_divide(gfc,cod_info);/*\n * update reservoir status after FINAL quantization/bitrate\n */rv.ResvAdjust(gfc,cod_info);};/**\n *\n * 2000-09-04 Robert Hegemann\n *\n * @param l3_xmin\n * allowed distortion of the scalefactor\n * @param xrpow\n * coloured magnitudes of spectral values\n */this.VBR_encode_granule=function(gfp,cod_info,l3_xmin,xrpow,ch,min_bits,max_bits){var gfc=gfp.internal_flags;var bst_cod_info=new GrInfo();var bst_xrpow=new_float(576);var Max_bits=max_bits;var real_bits=max_bits+1;var this_bits=(max_bits+min_bits)/2;var dbits,over,found=0;var sfb21_extra=gfc.sfb21_extra;Arrays.fill(bst_cod_info.l3_enc,0);/*\n * search within round about 40 bits of optimal\n */do{if(this_bits>Max_bits-42)gfc.sfb21_extra=false;else gfc.sfb21_extra=sfb21_extra;over=outer_loop(gfp,cod_info,l3_xmin,xrpow,ch,this_bits);/*\n * is quantization as good as we are looking for ? in this case: is\n * no scalefactor band distorted?\n */if(over<=0){found=1;/*\n * now we know it can be done with \"real_bits\" and maybe we can\n * skip some iterations\n */real_bits=cod_info.part2_3_length;/*\n * store best quantization so far\n */bst_cod_info.assign(cod_info);System.arraycopy(xrpow,0,bst_xrpow,0,576);/*\n * try with fewer bits\n */max_bits=real_bits-32;dbits=max_bits-min_bits;this_bits=(max_bits+min_bits)/2;}else{/*\n * try with more bits\n */min_bits=this_bits+32;dbits=max_bits-min_bits;this_bits=(max_bits+min_bits)/2;if(found!=0){found=2;/*\n * start again with best quantization so far\n */cod_info.assign(bst_cod_info);System.arraycopy(bst_xrpow,0,xrpow,0,576);}}}while(dbits>12);gfc.sfb21_extra=sfb21_extra;/*\n * found=0 => nothing found, use last one found=1 => we just found the\n * best and left the loop found=2 => we restored a good one and have now\n * l3_enc to restore too\n */if(found==2){System.arraycopy(bst_cod_info.l3_enc,0,cod_info.l3_enc,0,576);}};/**\n * Robert Hegemann 2000-09-05\n *\n * calculates * how many bits are available for analog silent granules * how\n * many bits to use for the lowest allowed bitrate * how many bits each\n * bitrate would provide\n */this.get_framebits=function(gfp,frameBits){var gfc=gfp.internal_flags;/*\n * always use at least this many bits per granule per channel unless we\n * detect analog silence, see below\n */gfc.bitrate_index=gfc.VBR_min_bitrate;var bitsPerFrame=bs.getframebits(gfp);/*\n * bits for analog silence\n */gfc.bitrate_index=1;bitsPerFrame=bs.getframebits(gfp);for(var i=1;i<=gfc.VBR_max_bitrate;i++){gfc.bitrate_index=i;var mb=new MeanBits(bitsPerFrame);frameBits[i]=rv.ResvFrameBegin(gfp,mb);bitsPerFrame=mb.bits;}};/* RH: this one needs to be overhauled sometime *//**\n * <PRE>\n * 2000-09-04 Robert Hegemann\n *\n * * converts LR to MS coding when necessary\n * * calculates allowed/adjusted quantization noise amounts\n * * detects analog silent frames\n *\n * some remarks:\n * - lower masking depending on Quality setting\n * - quality control together with adjusted ATH MDCT scaling\n * on lower quality setting allocate more noise from\n * ATH masking, and on higher quality setting allocate\n * less noise from ATH masking.\n * - experiments show that going more than 2dB over GPSYCHO's\n * limits ends up in very annoying artefacts\n * </PRE>\n */this.VBR_old_prepare=function(gfp,pe,ms_ener_ratio,ratio,l3_xmin,frameBits,min_bits,max_bits,bands){var gfc=gfp.internal_flags;var masking_lower_db,adjust=0.0;var analog_silence=1;var bits=0;gfc.bitrate_index=gfc.VBR_max_bitrate;var avg=rv.ResvFrameBegin(gfp,new MeanBits(0))/gfc.mode_gr;get_framebits(gfp,frameBits);for(var gr=0;gr<gfc.mode_gr;gr++){var mxb=qupvt.on_pe(gfp,pe,max_bits[gr],avg,gr,0);if(gfc.mode_ext==Encoder.MPG_MD_MS_LR){ms_convert(gfc.l3_side,gr);qupvt.reduce_side(max_bits[gr],ms_ener_ratio[gr],avg,mxb);}for(var ch=0;ch<gfc.channels_out;++ch){var cod_info=gfc.l3_side.tt[gr][ch];if(cod_info.block_type!=Encoder.SHORT_TYPE){// NORM, START or STOP type\nadjust=1.28/(1+Math.exp(3.5-pe[gr][ch]/300.))-0.05;masking_lower_db=gfc.PSY.mask_adjust-adjust;}else{adjust=2.56/(1+Math.exp(3.5-pe[gr][ch]/300.))-0.14;masking_lower_db=gfc.PSY.mask_adjust_short-adjust;}gfc.masking_lower=Math.pow(10.0,masking_lower_db*0.1);init_outer_loop(gfc,cod_info);bands[gr][ch]=qupvt.calc_xmin(gfp,ratio[gr][ch],cod_info,l3_xmin[gr][ch]);if(bands[gr][ch]!=0)analog_silence=0;min_bits[gr][ch]=126;bits+=max_bits[gr][ch];}}for(var gr=0;gr<gfc.mode_gr;gr++){for(var ch=0;ch<gfc.channels_out;ch++){if(bits>frameBits[gfc.VBR_max_bitrate]){max_bits[gr][ch]*=frameBits[gfc.VBR_max_bitrate];max_bits[gr][ch]/=bits;}if(min_bits[gr][ch]>max_bits[gr][ch])min_bits[gr][ch]=max_bits[gr][ch];}/* for ch */}/* for gr */return analog_silence;};this.bitpressure_strategy=function(gfc,l3_xmin,min_bits,max_bits){for(var gr=0;gr<gfc.mode_gr;gr++){for(var ch=0;ch<gfc.channels_out;ch++){var gi=gfc.l3_side.tt[gr][ch];var pxmin=l3_xmin[gr][ch];var pxminPos=0;for(var sfb=0;sfb<gi.psy_lmax;sfb++){pxmin[pxminPos++]*=1.+.029*sfb*sfb/Encoder.SBMAX_l/Encoder.SBMAX_l;}if(gi.block_type==Encoder.SHORT_TYPE){for(var sfb=gi.sfb_smin;sfb<Encoder.SBMAX_s;sfb++){pxmin[pxminPos++]*=1.+.029*sfb*sfb/Encoder.SBMAX_s/Encoder.SBMAX_s;pxmin[pxminPos++]*=1.+.029*sfb*sfb/Encoder.SBMAX_s/Encoder.SBMAX_s;pxmin[pxminPos++]*=1.+.029*sfb*sfb/Encoder.SBMAX_s/Encoder.SBMAX_s;}}max_bits[gr][ch]=0|Math.max(min_bits[gr][ch],0.9*max_bits[gr][ch]);}}};this.VBR_new_prepare=function(gfp,pe,ratio,l3_xmin,frameBits,max_bits){var gfc=gfp.internal_flags;var analog_silence=1;var avg=0,bits=0;var maximum_framebits;if(!gfp.free_format){gfc.bitrate_index=gfc.VBR_max_bitrate;var mb=new MeanBits(avg);rv.ResvFrameBegin(gfp,mb);avg=mb.bits;get_framebits(gfp,frameBits);maximum_framebits=frameBits[gfc.VBR_max_bitrate];}else{gfc.bitrate_index=0;var mb=new MeanBits(avg);maximum_framebits=rv.ResvFrameBegin(gfp,mb);avg=mb.bits;frameBits[0]=maximum_framebits;}for(var gr=0;gr<gfc.mode_gr;gr++){qupvt.on_pe(gfp,pe,max_bits[gr],avg,gr,0);if(gfc.mode_ext==Encoder.MPG_MD_MS_LR){ms_convert(gfc.l3_side,gr);}for(var ch=0;ch<gfc.channels_out;++ch){var cod_info=gfc.l3_side.tt[gr][ch];gfc.masking_lower=Math.pow(10.0,gfc.PSY.mask_adjust*0.1);init_outer_loop(gfc,cod_info);if(0!=qupvt.calc_xmin(gfp,ratio[gr][ch],cod_info,l3_xmin[gr][ch]))analog_silence=0;bits+=max_bits[gr][ch];}}for(var gr=0;gr<gfc.mode_gr;gr++){for(var ch=0;ch<gfc.channels_out;ch++){if(bits>maximum_framebits){max_bits[gr][ch]*=maximum_framebits;max_bits[gr][ch]/=bits;}}/* for ch */}/* for gr */return analog_silence;};/**\n * calculates target bits for ABR encoding\n *\n * mt 2000/05/31\n */this.calc_target_bits=function(gfp,pe,ms_ener_ratio,targ_bits,analog_silence_bits,max_frame_bits){var gfc=gfp.internal_flags;var l3_side=gfc.l3_side;var res_factor;var gr,ch,totbits,mean_bits=0;gfc.bitrate_index=gfc.VBR_max_bitrate;var mb=new MeanBits(mean_bits);max_frame_bits[0]=rv.ResvFrameBegin(gfp,mb);mean_bits=mb.bits;gfc.bitrate_index=1;mean_bits=bs.getframebits(gfp)-gfc.sideinfo_len*8;analog_silence_bits[0]=mean_bits/(gfc.mode_gr*gfc.channels_out);mean_bits=gfp.VBR_mean_bitrate_kbps*gfp.framesize*1000;if((gfc.substep_shaping&1)!=0)mean_bits*=1.09;mean_bits/=gfp.out_samplerate;mean_bits-=gfc.sideinfo_len*8;mean_bits/=gfc.mode_gr*gfc.channels_out;/**\n * <PRE>\n * res_factor is the percentage of the target bitrate that should\n * be used on average. the remaining bits are added to the\n * bitreservoir and used for difficult to encode frames.\n *\n * Since we are tracking the average bitrate, we should adjust\n * res_factor \"on the fly\", increasing it if the average bitrate\n * is greater than the requested bitrate, and decreasing it\n * otherwise. Reasonable ranges are from .9 to 1.0\n *\n * Until we get the above suggestion working, we use the following\n * tuning:\n * compression ratio res_factor\n * 5.5 (256kbps) 1.0 no need for bitreservoir\n * 11 (128kbps) .93 7% held for reservoir\n *\n * with linear interpolation for other values.\n * </PRE>\n */res_factor=.93+.07*(11.0-gfp.compression_ratio)/(11.0-5.5);if(res_factor<.90)res_factor=.90;if(res_factor>1.00)res_factor=1.00;for(gr=0;gr<gfc.mode_gr;gr++){var sum=0;for(ch=0;ch<gfc.channels_out;ch++){targ_bits[gr][ch]=int(res_factor*mean_bits);if(pe[gr][ch]>700){var add_bits=int((pe[gr][ch]-700)/1.4);var cod_info=l3_side.tt[gr][ch];targ_bits[gr][ch]=int(res_factor*mean_bits);/* short blocks use a little extra, no matter what the pe */if(cod_info.block_type==Encoder.SHORT_TYPE){if(add_bits<mean_bits/2)add_bits=mean_bits/2;}/* at most increase bits by 1.5*average */if(add_bits>mean_bits*3/2)add_bits=mean_bits*3/2;else if(add_bits<0)add_bits=0;targ_bits[gr][ch]+=add_bits;}if(targ_bits[gr][ch]>LameInternalFlags.MAX_BITS_PER_CHANNEL){targ_bits[gr][ch]=LameInternalFlags.MAX_BITS_PER_CHANNEL;}sum+=targ_bits[gr][ch];}/* for ch */if(sum>LameInternalFlags.MAX_BITS_PER_GRANULE){for(ch=0;ch<gfc.channels_out;++ch){targ_bits[gr][ch]*=LameInternalFlags.MAX_BITS_PER_GRANULE;targ_bits[gr][ch]/=sum;}}}/* for gr */if(gfc.mode_ext==Encoder.MPG_MD_MS_LR)for(gr=0;gr<gfc.mode_gr;gr++){qupvt.reduce_side(targ_bits[gr],ms_ener_ratio[gr],mean_bits*gfc.channels_out,LameInternalFlags.MAX_BITS_PER_GRANULE);}/*\n * sum target bits\n */totbits=0;for(gr=0;gr<gfc.mode_gr;gr++){for(ch=0;ch<gfc.channels_out;ch++){if(targ_bits[gr][ch]>LameInternalFlags.MAX_BITS_PER_CHANNEL)targ_bits[gr][ch]=LameInternalFlags.MAX_BITS_PER_CHANNEL;totbits+=targ_bits[gr][ch];}}/*\n * repartion target bits if needed\n */if(totbits>max_frame_bits[0]){for(gr=0;gr<gfc.mode_gr;gr++){for(ch=0;ch<gfc.channels_out;ch++){targ_bits[gr][ch]*=max_frame_bits[0];targ_bits[gr][ch]/=totbits;}}}};}/*\n * MP3 window subband -> subband filtering -> mdct routine\n *\n * Copyright (c) 1999-2000 Takehiro Tominaga\n *\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *//*\n * Special Thanks to Patrick De Smet for your advices.\n *//* $Id: NewMDCT.java,v 1.11 2011/05/24 20:48:06 kenchis Exp $ *///package mp3;",
"function GIFEncoder() {\n for (var i = 0, chr = {}; i < 256; i++) {\n chr[i] = String.fromCharCode(i);\n }\n\n function ByteArray() {\n this.bin = [];\n }\n\n ByteArray.prototype.getData = function () {\n for (var v = '', l = this.bin.length, i = 0; i < l; i++) {\n v += chr[this.bin[i]];\n }\n\n return v;\n };\n\n ByteArray.prototype.writeByte = function (val) {\n this.bin.push(val);\n };\n\n ByteArray.prototype.writeUTFBytes = function (string) {\n for (var l = string.length, _i = 0; _i < l; _i++) {\n this.writeByte(string.charCodeAt(_i));\n }\n };\n\n ByteArray.prototype.writeBytes = function (array, offset, length) {\n for (var l = length || array.length, _i2 = offset || 0; _i2 < l; _i2++) {\n this.writeByte(array[_i2]);\n }\n };\n\n var exports = {};\n var width; // image size\n\n var height;\n var transparent = null; // transparent color if given\n\n var transIndex; // transparent index in color table\n\n var repeat = -1; // no repeat\n\n var delay = 0; // frame delay (hundredths)\n\n var started = false; // ready to output frames\n\n var out;\n var image; // current frame\n\n var pixels; // BGR byte array from frame\n\n var indexedPixels; // converted frame indexed to palette\n\n var colorDepth; // number of bit planes\n\n var colorTab; // RGB palette\n\n var usedEntry = []; // active palette entries\n\n var palSize = 7; // color table size (bits-1)\n\n var dispose = -1; // disposal code (-1 = use default)\n\n var closeStream = false; // close stream when finished\n\n var firstFrame = true;\n var sizeSet = false; // if false, get size from first frame\n\n var sample = 10; // default sample interval for quantizer\n\n var comment = 'Generated by jsgif (https://github.com/antimatter15/jsgif/)'; // default comment for generated gif\n\n /**\n * Sets the delay time between each frame, or changes it for subsequent frames\n * (applies to last frame added)\n * int delay time in milliseconds\n * @param ms\n */\n\n var setDelay = exports.setDelay = function setDelay(ms) {\n delay = Math.round(ms / 10);\n };\n /**\n * Sets the GIF frame disposal code for the last added frame and any\n *\n * subsequent frames. Default is 0 if no transparent color has been set,\n * otherwise 2.\n * @param code\n * int disposal code.\n */\n\n\n var setDispose = exports.setDispose = function setDispose(code) {\n if (code >= 0) dispose = code;\n };\n /**\n * Sets the number of times the set of GIF frames should be played. Default is\n * 1; 0 means play indefinitely. Must be invoked before the first image is\n * added.\n *\n * @param iter\n * int number of iterations.\n * @return\n */\n\n\n var setRepeat = exports.setRepeat = function setRepeat(iter) {\n if (iter >= 0) repeat = iter;\n };\n /**\n * Sets the transparent color for the last added frame and any subsequent\n * frames. Since all colors are subject to modification in the quantization\n * process, the color in the final palette for each frame closest to the given\n * color becomes the transparent color for that frame. May be set to null to\n * indicate no transparent color.\n * @param\n * Color to be treated as transparent on display.\n */\n\n\n var setTransparent = exports.setTransparent = function setTransparent(c) {\n transparent = c;\n };\n /**\n * Sets the comment for the block comment\n * @param\n * string to be insterted as comment\n */\n\n\n var setComment = exports.setComment = function setComment(c) {\n comment = c;\n };\n /**\n * The addFrame method takes an incoming BitmapData object to create each frames\n * @param\n * BitmapData object to be treated as a GIF's frame\n */\n\n\n var addFrame = exports.addFrame = function addFrame(im, is_imageData) {\n if (im === null || !started || out === null) {\n throw new Error('Please call start method before calling addFrame');\n }\n\n var ok = true;\n\n try {\n if (!is_imageData) {\n image = im.getImageData(0, 0, im.canvas.width, im.canvas.height).data;\n if (!sizeSet) setSize(im.canvas.width, im.canvas.height);\n } else if (im instanceof ImageData) {\n image = im.data;\n\n if (!sizeset || width != im.width || height != im.height) {\n setSize(im.width, im.height);\n } else {}\n } else if (im instanceof Uint8ClampedArray) {\n if (im.length == width * height * 4) {\n image = im;\n } else {\n console.log('Please set the correct size: ImageData length mismatch');\n ok = false;\n }\n } else {\n console.log('Please provide correct input');\n ok = false;\n }\n\n getImagePixels(); // convert to correct format if necessary\n\n analyzePixels(); // build color table & map pixels\n\n if (firstFrame) {\n writeLSD(); // logical screen descriptior\n\n writePalette(); // global color table\n\n if (repeat >= 0) {\n // use NS app extension to indicate reps\n writeNetscapeExt();\n }\n }\n\n writeGraphicCtrlExt(); // write graphic control extension\n\n if (comment !== '') {\n writeCommentExt(); // write comment extension\n }\n\n writeImageDesc(); // image descriptor\n\n if (!firstFrame) writePalette(); // local color table\n\n writePixels(); // encode and write pixel data\n\n firstFrame = false;\n } catch (e) {\n console.log(e);\n ok = false;\n }\n\n return ok;\n };\n /**\n * @description: Downloads the encoded gif with the given name\n * No need of any conversion from the stream data (out) to base64\n * Solves the issue of large file sizes when there are more frames\n * and does not involve in creation of any temporary data in the process\n * so no wastage of memory, and speeds up the process of downloading\n * to just calling this function.\n * @parameter {String} filename filename used for downloading the gif\n */\n\n\n var download = exports.download = function download(filename) {\n if (out === null || closeStream == false) {\n console.log('Please call start method and add frames and call finish method before calling download');\n } else {\n filename = filename !== undefined ? filename.endsWith('.gif') ? filename : \"\".concat(filename, \".gif\") : 'download.gif';\n var templink = document.createElement('a');\n templink.download = filename;\n templink.href = URL.createObjectURL(new Blob([new Uint8Array(out.bin)], {\n type: 'image/gif'\n }));\n templink.click();\n }\n };\n /**\n * Adds final trailer to the GIF stream, if you don't call the finish method\n * the GIF stream will not be valid.\n */\n\n\n var finish = exports.finish = function finish() {\n if (!started) return false;\n var ok = true;\n started = false;\n\n try {\n out.writeByte(0x3b); // gif trailer\n\n closeStream = true;\n } catch (e) {\n ok = false;\n }\n\n return ok;\n };\n /**\n * Resets some members so that a new stream can be started.\n * This method is actually called by the start method\n */\n\n\n var reset = function reset() {\n // reset for subsequent use\n transIndex = 0;\n image = null;\n pixels = null;\n indexedPixels = null;\n colorTab = null;\n closeStream = false;\n firstFrame = true;\n };\n /**\n * * Sets frame rate in frames per second. Equivalent to\n * <code>setDelay(1000/fps)</code>.\n * @param fps\n * float frame rate (frames per second)\n */\n\n\n var setFrameRate = exports.setFrameRate = function setFrameRate(fps) {\n if (fps != 0xf) delay = Math.round(100 / fps);\n };\n /**\n * Sets quality of color quantization (conversion of images to the maximum 256\n * colors allowed by the GIF specification). Lower values (minimum = 1)\n * produce better colors, but slow processing significantly. 10 is the\n * default, and produces good color mapping at reasonable speeds. Values\n * greater than 20 do not yield significant improvements in speed.\n * @param quality\n * int greater than 0.\n * @return\n */\n\n\n var setQuality = exports.setQuality = function setQuality(quality) {\n if (quality < 1) quality = 1;\n sample = quality;\n };\n /**\n * Sets the GIF frame size. The default size is the size of the first frame\n * added if this method is not invoked.\n * @param w\n * int frame width.\n * @param h\n * int frame width.\n */\n\n\n var setSize = exports.setSize = function setSize(w, h) {\n if (started && !firstFrame) return;\n width = w;\n height = h;\n if (width < 1) width = 320;\n if (height < 1) height = 240;\n sizeSet = true;\n };\n /**\n * Initiates GIF file creation on the given stream.\n * @param os\n * OutputStream on which GIF images are written.\n * @return false if initial write failed.\n */\n\n\n var start = exports.start = function start() {\n reset();\n var ok = true;\n closeStream = false;\n out = new ByteArray();\n\n try {\n out.writeUTFBytes('GIF89a'); // header\n } catch (e) {\n ok = false;\n }\n\n return started = ok;\n };\n\n var cont = exports.cont = function cont() {\n reset();\n var ok = true;\n closeStream = false;\n out = new ByteArray();\n return started = ok;\n };\n /**\n * Analyzes image colors and creates color map.\n */\n\n\n var analyzePixels = function analyzePixels() {\n var len = pixels.length;\n var nPix = len / 3;\n indexedPixels = [];\n var nq = new NeuQuant(pixels, len, sample); // initialize quantizer\n\n colorTab = nq.process(); // create reduced palette\n // map image pixels to new palette\n\n var k = 0;\n\n for (var j = 0; j < nPix; j++) {\n var index = nq.map(pixels[k++] & 0xff, pixels[k++] & 0xff, pixels[k++] & 0xff);\n usedEntry[index] = true;\n indexedPixels[j] = index;\n }\n\n pixels = null;\n colorDepth = 8;\n palSize = 7; // get closest match to transparent color if specified\n\n if (transparent !== null) {\n transIndex = findClosest(transparent);\n }\n };\n /**\n * Returns index of palette color closest to c\n */\n\n\n var findClosest = function findClosest(c) {\n if (colorTab === null) return -1;\n var r = (c & 0xFF0000) >> 16;\n var g = (c & 0x00FF00) >> 8;\n var b = c & 0x0000FF;\n var minpos = 0;\n var dmin = 256 * 256 * 256;\n var len = colorTab.length;\n\n for (var _i3 = 0; _i3 < len;) {\n var dr = r - (colorTab[_i3++] & 0xff);\n var dg = g - (colorTab[_i3++] & 0xff);\n var db = b - (colorTab[_i3] & 0xff);\n var d = dr * dr + dg * dg + db * db;\n var index = _i3 / 3;\n\n if (usedEntry[index] && d < dmin) {\n dmin = d;\n minpos = index;\n }\n\n _i3++;\n }\n\n return minpos;\n };\n /**\n * Extracts image pixels into byte array \"pixels\n */\n\n\n var getImagePixels = function getImagePixels() {\n var w = width;\n var h = height;\n pixels = [];\n var data = image;\n var count = 0;\n\n for (var _i4 = 0; _i4 < h; _i4++) {\n for (var j = 0; j < w; j++) {\n var b = _i4 * w * 4 + j * 4;\n pixels[count++] = data[b];\n pixels[count++] = data[b + 1];\n pixels[count++] = data[b + 2];\n }\n }\n };\n /**\n * Writes Graphic Control Extension\n */\n\n\n var writeGraphicCtrlExt = function writeGraphicCtrlExt() {\n out.writeByte(0x21); // extension introducer\n\n out.writeByte(0xf9); // GCE label\n\n out.writeByte(4); // data block size\n\n var transp;\n var disp;\n\n if (transparent === null) {\n transp = 0;\n disp = 0; // dispose = no action\n } else {\n transp = 1;\n disp = 2; // force clear if using transparent color\n }\n\n if (dispose >= 0) {\n disp = dispose & 7; // user override\n }\n\n disp <<= 2; // packed fields\n\n out.writeByte(0 // 1:3 reserved\n | disp // 4:6 disposal\n | 0 // 7 user input - 0 = none\n | transp); // 8 transparency flag\n\n WriteShort(delay); // delay x 1/100 sec\n\n out.writeByte(transIndex); // transparent color index\n\n out.writeByte(0); // block terminator\n };\n /**\n * Writes Comment Extention\n */\n\n\n var writeCommentExt = function writeCommentExt() {\n out.writeByte(0x21); // extension introducer\n\n out.writeByte(0xfe); // comment label\n\n out.writeByte(comment.length); // Block Size (s)\n\n out.writeUTFBytes(comment);\n out.writeByte(0); // block terminator\n };\n /**\n * Writes Image Descriptor\n */\n\n\n var writeImageDesc = function writeImageDesc() {\n out.writeByte(0x2c); // image separator\n\n WriteShort(0); // image position x,y = 0,0\n\n WriteShort(0);\n WriteShort(width); // image size\n\n WriteShort(height); // packed fields\n\n if (firstFrame) {\n // no LCT - GCT is used for first (or only) frame\n out.writeByte(0);\n } else {\n // specify normal LCT\n out.writeByte(0x80 // 1 local color table 1=yes\n | 0 // 2 interlace - 0=no\n | 0 // 3 sorted - 0=no\n | 0 // 4-5 reserved\n | palSize); // 6-8 size of color table\n }\n };\n /**\n * Writes Logical Screen Descriptor\n */\n\n\n var writeLSD = function writeLSD() {\n // logical screen size\n WriteShort(width);\n WriteShort(height); // packed fields\n\n out.writeByte(0x80 // 1 : global color table flag = 1 (gct used)\n | 0x70 // 2-4 : color resolution = 7\n | 0x00 // 5 : gct sort flag = 0\n | palSize); // 6-8 : gct size\n\n out.writeByte(0); // background color index\n\n out.writeByte(0); // pixel aspect ratio - assume 1:1\n };\n /**\n * Writes Netscape application extension to define repeat count.\n */\n\n\n var writeNetscapeExt = function writeNetscapeExt() {\n out.writeByte(0x21); // extension introducer\n\n out.writeByte(0xff); // app extension label\n\n out.writeByte(11); // block size\n\n out.writeUTFBytes('NETSCAPE' + '2.0'); // app id + auth code\n\n out.writeByte(3); // sub-block size\n\n out.writeByte(1); // loop sub-block id\n\n WriteShort(repeat); // loop count (extra iterations, 0=repeat forever)\n\n out.writeByte(0); // block terminator\n };\n /**\n * Writes color table\n */\n\n\n var writePalette = function writePalette() {\n out.writeBytes(colorTab);\n var n = 3 * 256 - colorTab.length;\n\n for (var _i5 = 0; _i5 < n; _i5++) {\n out.writeByte(0);\n }\n };\n\n var WriteShort = function WriteShort(pValue) {\n out.writeByte(pValue & 0xFF);\n out.writeByte(pValue >> 8 & 0xFF);\n };\n /**\n * Encodes and writes pixel data\n */\n\n\n var writePixels = function writePixels() {\n var myencoder = new LZWEncoder(width, height, indexedPixels, colorDepth);\n myencoder.encode(out);\n };\n /**\n * Retrieves the GIF stream\n */\n\n\n var stream = exports.stream = function stream() {\n return out;\n };\n\n var setProperties = exports.setProperties = function setProperties(has_start, is_first) {\n started = has_start;\n firstFrame = is_first;\n };\n\n return exports;\n}",
"function quantize(c, p, idx, total) {\n var img = new Image();\n img.onload = function() {\n var opts = { colors: 10, boxSize: [200,200], initColors: 256 };\n var q = new RgbQuant(opts);\n q.sample(img);\n\n var pal = q.palette(true, true);\n var threshold = 150;\n var neutral = 15;\n pal = pal.filter(function(rgb) {\n if (rgb[0]<threshold && rgb[1]<threshold && rgb[2]<threshold) return true;\n var d1 = Math.abs(rgb[0] - rgb[1]);\n var d2 = Math.abs(rgb[1] - rgb[2]);\n var d3 = Math.abs(rgb[2] - rgb[0]);\n // weed out neutrals as best we can\n return !(d1<neutral && d2<neutral && d3<neutral);\n });\n\n var rgb, cinfo;\n for(var i = 0; i <pal.length; i++) {\n rgb = pal[i];\n cinfo = document.createElement(\"span\");\n cinfo.classList.add(\"color-info\");\n color = \"rgb(\"+rgb[0]+\",\"+rgb[1]+\",\"+rgb[2]+\")\";\n cinfo.style.background = color;\n cinfo.style.border = color;\n cinfo.onclick = (function(rgb, color, img) {\n return function() {\n setColor(idx, rgb, color, img);\n }\n }(rgb, color, img));\n if(i===0) { cinfo.click(); }\n p.appendChild(cinfo);\n }\n };\n img.src = c.toDataURL(\"image/png\");\n return {\n img: img,\n canvas: c\n };\n}",
"function NeuQuant(pixels, samplefac) {\n\t var network; // int[netsize][4]\n\t var netindex; // for network lookup - really 256\n\n\t // bias and freq arrays for learning\n\t var bias;\n\t var freq;\n\t var radpower;\n\n\t /*\n\t Private Method: init\n\n\t sets up arrays\n\t */\n\t function init() {\n\t network = [];\n\t netindex = new Int32Array(256);\n\t bias = new Int32Array(netsize);\n\t freq = new Int32Array(netsize);\n\t radpower = new Int32Array(netsize >> 3);\n\n\t var i, v;\n\t for (i = 0; i < netsize; i++) {\n\t v = (i << (netbiasshift + 8)) / netsize;\n\t network[i] = new Float64Array([v, v, v, 0]);\n\t //network[i] = [v, v, v, 0]\n\t freq[i] = intbias / netsize;\n\t bias[i] = 0;\n\t }\n\t }\n\n\t /*\n\t Private Method: unbiasnet\n\n\t unbiases network to give byte values 0..255 and record position i to prepare for sort\n\t */\n\t function unbiasnet() {\n\t for (var i = 0; i < netsize; i++) {\n\t network[i][0] >>= netbiasshift;\n\t network[i][1] >>= netbiasshift;\n\t network[i][2] >>= netbiasshift;\n\t network[i][3] = i; // record color number\n\t }\n\t }\n\n\t /*\n\t Private Method: altersingle\n\n\t moves neuron *i* towards biased (b,g,r) by factor *alpha*\n\t */\n\t function altersingle(alpha, i, b, g, r) {\n\t network[i][0] -= (alpha * (network[i][0] - b)) / initalpha;\n\t network[i][1] -= (alpha * (network[i][1] - g)) / initalpha;\n\t network[i][2] -= (alpha * (network[i][2] - r)) / initalpha;\n\t }\n\n\t /*\n\t Private Method: alterneigh\n\n\t moves neurons in *radius* around index *i* towards biased (b,g,r) by factor *alpha*\n\t */\n\t function alterneigh(radius, i, b, g, r) {\n\t var lo = Math.abs(i - radius);\n\t var hi = Math.min(i + radius, netsize);\n\n\t var j = i + 1;\n\t var k = i - 1;\n\t var m = 1;\n\n\t var p, a;\n\t while ((j < hi) || (k > lo)) {\n\t a = radpower[m++];\n\n\t if (j < hi) {\n\t p = network[j++];\n\t p[0] -= (a * (p[0] - b)) / alpharadbias;\n\t p[1] -= (a * (p[1] - g)) / alpharadbias;\n\t p[2] -= (a * (p[2] - r)) / alpharadbias;\n\t }\n\n\t if (k > lo) {\n\t p = network[k--];\n\t p[0] -= (a * (p[0] - b)) / alpharadbias;\n\t p[1] -= (a * (p[1] - g)) / alpharadbias;\n\t p[2] -= (a * (p[2] - r)) / alpharadbias;\n\t }\n\t }\n\t }\n\n\t /*\n\t Private Method: contest\n\n\t searches for biased BGR values\n\t */\n\t function contest(b, g, r) {\n\t /*\n\t finds closest neuron (min dist) and updates freq\n\t finds best neuron (min dist-bias) and returns position\n\t for frequently chosen neurons, freq[i] is high and bias[i] is negative\n\t bias[i] = gamma * ((1 / netsize) - freq[i])\n\t */\n\n\t var bestd = ~(1 << 31);\n\t var bestbiasd = bestd;\n\t var bestpos = -1;\n\t var bestbiaspos = bestpos;\n\n\t var i, n, dist, biasdist, betafreq;\n\t for (i = 0; i < netsize; i++) {\n\t n = network[i];\n\n\t dist = Math.abs(n[0] - b) + Math.abs(n[1] - g) + Math.abs(n[2] - r);\n\t if (dist < bestd) {\n\t bestd = dist;\n\t bestpos = i;\n\t }\n\n\t biasdist = dist - ((bias[i]) >> (intbiasshift - netbiasshift));\n\t if (biasdist < bestbiasd) {\n\t bestbiasd = biasdist;\n\t bestbiaspos = i;\n\t }\n\n\t betafreq = (freq[i] >> betashift);\n\t freq[i] -= betafreq;\n\t bias[i] += (betafreq << gammashift);\n\t }\n\n\t freq[bestpos] += beta;\n\t bias[bestpos] -= betagamma;\n\n\t return bestbiaspos;\n\t }\n\n\t /*\n\t Private Method: inxbuild\n\n\t sorts network and builds netindex[0..255]\n\t */\n\t function inxbuild() {\n\t var i, j, p, q, smallpos, smallval, previouscol = 0, startpos = 0;\n\t for (i = 0; i < netsize; i++) {\n\t p = network[i];\n\t smallpos = i;\n\t smallval = p[1]; // index on g\n\t // find smallest in i..netsize-1\n\t for (j = i + 1; j < netsize; j++) {\n\t q = network[j];\n\t if (q[1] < smallval) { // index on g\n\t smallpos = j;\n\t smallval = q[1]; // index on g\n\t }\n\t }\n\t q = network[smallpos];\n\t // swap p (i) and q (smallpos) entries\n\t if (i != smallpos) {\n\t j = q[0]; q[0] = p[0]; p[0] = j;\n\t j = q[1]; q[1] = p[1]; p[1] = j;\n\t j = q[2]; q[2] = p[2]; p[2] = j;\n\t j = q[3]; q[3] = p[3]; p[3] = j;\n\t }\n\t // smallval entry is now in position i\n\n\t if (smallval != previouscol) {\n\t netindex[previouscol] = (startpos + i) >> 1;\n\t for (j = previouscol + 1; j < smallval; j++)\n\t netindex[j] = i;\n\t previouscol = smallval;\n\t startpos = i;\n\t }\n\t }\n\t netindex[previouscol] = (startpos + maxnetpos) >> 1;\n\t for (j = previouscol + 1; j < 256; j++)\n\t netindex[j] = maxnetpos; // really 256\n\t }\n\n\t /*\n\t Private Method: inxsearch\n\n\t searches for BGR values 0..255 and returns a color index\n\t */\n\t function inxsearch(b, g, r) {\n\t var a, p, dist;\n\n\t var bestd = 1000; // biggest possible dist is 256*3\n\t var best = -1;\n\n\t var i = netindex[g]; // index on g\n\t var j = i - 1; // start at netindex[g] and work outwards\n\n\t while ((i < netsize) || (j >= 0)) {\n\t if (i < netsize) {\n\t p = network[i];\n\t dist = p[1] - g; // inx key\n\t if (dist >= bestd) i = netsize; // stop iter\n\t else {\n\t i++;\n\t if (dist < 0) dist = -dist;\n\t a = p[0] - b; if (a < 0) a = -a;\n\t dist += a;\n\t if (dist < bestd) {\n\t a = p[2] - r; if (a < 0) a = -a;\n\t dist += a;\n\t if (dist < bestd) {\n\t bestd = dist;\n\t best = p[3];\n\t }\n\t }\n\t }\n\t }\n\t if (j >= 0) {\n\t p = network[j];\n\t dist = g - p[1]; // inx key - reverse dif\n\t if (dist >= bestd) j = -1; // stop iter\n\t else {\n\t j--;\n\t if (dist < 0) dist = -dist;\n\t a = p[0] - b; if (a < 0) a = -a;\n\t dist += a;\n\t if (dist < bestd) {\n\t a = p[2] - r; if (a < 0) a = -a;\n\t dist += a;\n\t if (dist < bestd) {\n\t bestd = dist;\n\t best = p[3];\n\t }\n\t }\n\t }\n\t }\n\t }\n\n\t return best;\n\t }\n\n\t /*\n\t Private Method: learn\n\n\t \"Main Learning Loop\"\n\t */\n\t function learn() {\n\t var i;\n\n\t var lengthcount = pixels.length;\n\t var alphadec = 30 + ((samplefac - 1) / 3);\n\t var samplepixels = lengthcount / (3 * samplefac);\n\t var delta = ~~(samplepixels / ncycles);\n\t var alpha = initalpha;\n\t var radius = initradius;\n\n\t var rad = radius >> radiusbiasshift;\n\n\t if (rad <= 1) rad = 0;\n\t for (i = 0; i < rad; i++)\n\t radpower[i] = alpha * (((rad * rad - i * i) * radbias) / (rad * rad));\n\n\t var step;\n\t if (lengthcount < minpicturebytes) {\n\t samplefac = 1;\n\t step = 3;\n\t } else if ((lengthcount % prime1) !== 0) {\n\t step = 3 * prime1;\n\t } else if ((lengthcount % prime2) !== 0) {\n\t step = 3 * prime2;\n\t } else if ((lengthcount % prime3) !== 0) {\n\t step = 3 * prime3;\n\t } else {\n\t step = 3 * prime4;\n\t }\n\n\t var b, g, r, j;\n\t var pix = 0; // current pixel\n\n\t i = 0;\n\t while (i < samplepixels) {\n\t b = (pixels[pix] & 0xff) << netbiasshift;\n\t g = (pixels[pix + 1] & 0xff) << netbiasshift;\n\t r = (pixels[pix + 2] & 0xff) << netbiasshift;\n\n\t j = contest(b, g, r);\n\n\t altersingle(alpha, j, b, g, r);\n\t if (rad !== 0) alterneigh(rad, j, b, g, r); // alter neighbours\n\n\t pix += step;\n\t if (pix >= lengthcount) pix -= lengthcount;\n\n\t i++;\n\n\t if (delta === 0) delta = 1;\n\t if (i % delta === 0) {\n\t alpha -= alpha / alphadec;\n\t radius -= radius / radiusdec;\n\t rad = radius >> radiusbiasshift;\n\n\t if (rad <= 1) rad = 0;\n\t for (j = 0; j < rad; j++)\n\t radpower[j] = alpha * (((rad * rad - j * j) * radbias) / (rad * rad));\n\t }\n\t }\n\t }\n\n\t /*\n\t Method: buildColormap\n\n\t 1. initializes network\n\t 2. trains it\n\t 3. removes misconceptions\n\t 4. builds colorindex\n\t */\n\t function buildColormap() {\n\t init();\n\t learn();\n\t unbiasnet();\n\t inxbuild();\n\t }\n\t this.buildColormap = buildColormap;\n\n\t /*\n\t Method: getColormap\n\n\t builds colormap from the index\n\n\t returns array in the format:\n\n\t >\n\t > [r, g, b, r, g, b, r, g, b, ..]\n\t >\n\t */\n\t function getColormap() {\n\t var map = [];\n\t var index = [];\n\n\t for (var i = 0; i < netsize; i++)\n\t index[network[i][3]] = i;\n\n\t var k = 0;\n\t for (var l = 0; l < netsize; l++) {\n\t var j = index[l];\n\t map[k++] = (network[j][0]);\n\t map[k++] = (network[j][1]);\n\t map[k++] = (network[j][2]);\n\t }\n\t return map;\n\t }\n\t this.getColormap = getColormap;\n\n\t /*\n\t Method: lookupRGB\n\n\t looks for the closest *r*, *g*, *b* color in the map and\n\t returns its index\n\t */\n\t this.lookupRGB = inxsearch;\n\t}",
"function Animated_GIF() {\n var width = 160, height = 120, canvas = null, ctx = null, repeat = 0, delay = 250;\n var buffer, gifWriter, pixels, numFrames, maxNumFrames = 100;\n var currentPalette, currentPaletteArray, currentPaletteComponents, maxNumColors = 256;\n\n function allocateResources() {\n var total = maxNumFrames;\n\n numFrames = 0;\n buffer = new Uint8Array( width * height * total * 5 );\n gifWriter = new GifWriter( buffer, width, height, { loop: repeat } );\n pixels = new Uint8Array( width * height );\n currentPalette = null;\n }\n\n this.setSize = function(w, h) {\n width = w;\n height = h;\n canvas = document.createElement('canvas');\n canvas.width = w;\n canvas.height = h;\n ctx = canvas.getContext('2d');\n allocateResources();\n };\n\n this.setDelay = function(d) {\n delay = d;\n };\n\n this.setRepeat = function(r) {\n repeat = r;\n };\n\n this.setMaxNumColors = function(v) {\n maxNumColors = v;\n };\n\n this.addFrame = function(element) {\n if( numFrames >= maxNumFrames ) {\n return;\n }\n\n ctx.drawImage(element, 0, 0, width, height);\n data = ctx.getImageData(0, 0, width, height);\n\n this.addFrameImageData(data);\n };\n\n this.addFrameImageData = function(imageData) {\n var data = imageData.data;\n var length = data.length;\n var numberPixels = length / 4; // 4 components = rgba\n var sampleInterval = 10;\n var bgrPixels = [];\n var offset = 0;\n var i, r, g, b;\n\n // extract RGB values into BGR for the quantizer\n while(offset < length) {\n r = data[offset++];\n g = data[offset++];\n b = data[offset++];\n bgrPixels.push(b);\n bgrPixels.push(g);\n bgrPixels.push(r);\n \n offset++;\n }\n \n var nq = new NeuQuant(bgrPixels, bgrPixels.length, sampleInterval);\n\n var paletteBGR = nq.process(); // create reduced palette\n var palette = [];\n\n for(i = 0; i < paletteBGR.length; i+=3) {\n b = paletteBGR[i];\n g = paletteBGR[i+1];\n r = paletteBGR[i+2];\n palette.push(r << 16 | g << 8 | b);\n }\n var paletteArray = new Uint32Array(palette);\n\n var k = 0;\n for (var j = 0; j < numberPixels; j++) {\n b = bgrPixels[k++];\n g = bgrPixels[k++];\n r = bgrPixels[k++];\n var index = nq.map(b, g, r);\n pixels[j] = index;\n }\n \n gifWriter.addFrame(0, 0, width, height, pixels, { palette: paletteArray, delay: delay });\n\n };\n\n this.getGIF = function() {\n var numberValues = gifWriter.end();\n var str = '';\n\n for(var i = 0; i < numberValues; i++) {\n str += String.fromCharCode( buffer[i] );\n }\n\n return str;\n };\n\n this.getB64GIF = function() {\n return 'data:image/gif;base64,' + btoa(this.getGIF());\n };\n\n\n // ---\n \n this.setSize(width, height);\n\n}",
"function NeuQuant(networkSize){\n /**\n * Constants\n */\n const ncycles = 100; // number of learning cycles\n const maxnetpos = networkSize - 1;\n\n // defs for freq and bias\n const netbiasshift = 4; // bias for colour values\n const intbiasshift = 16; // bias for fractions\n const intbias = (1 << intbiasshift);\n const gammashift = 10;\n const betashift = 10;\n const beta = (intbias >> betashift); /* beta = 1/1024 */\n const betagamma = (intbias << (gammashift - betashift));\n\n // defs for decreasing radius factor\n const initrad = (networkSize >> 3); // for 256 cols, radius starts\n const radiusbiasshift = 6; // at 32.0 biased by 6 bits\n const radiusbias = (1 << radiusbiasshift);\n const initradius = (initrad * radiusbias); //and decreases by a\n const radiusdec = 30; // factor of 1/30 each cycle\n\n // defs for decreasing alpha factor\n const alphabiasshift = 10; // alpha starts at 1.0\n const initalpha = (1 << alphabiasshift);\n\n /* radbias and alpharadbias used for radpower calculation */\n const radbiasshift = 8;\n const radbias = (1 << radbiasshift);\n const alpharadbshift = (alphabiasshift + radbiasshift);\n const alpharadbias = (1 << alpharadbshift);\n \n \n /**\n * Variables initialized by init\n */\n let network; // int[netsize][4]\n let netindex; // for network lookup - really 256\n\n // bias and freq arrays for learning\n let bias;\n let freq;\n let radpower;\n\n /*\n Private Method: init\n sets up arrays\n */\n function init(){\n network = [];\n netindex = new Int32Array(256);\n bias = new Int32Array(networkSize);\n freq = new Int32Array(networkSize);\n radpower = new Int32Array(networkSize >> 3);\n\n for(let i = 0; i < networkSize; i++){\n const v = (i << (netbiasshift + 8)) / networkSize;\n network[i] = new Float64Array([v, v, v, 0]);\n freq[i] = intbias / networkSize;\n bias[i] = 0;\n }\n }\n\n /*\n Private Method: unbiasnet\n unbiases network to give byte values 0..255 and record position i to prepare for sort\n */\n function unbiasnet(){\n for(let i = 0; i < networkSize; i++){\n network[i][0] >>= netbiasshift;\n network[i][1] >>= netbiasshift;\n network[i][2] >>= netbiasshift;\n network[i][3] = i; // record color number\n }\n }\n\n /*\n Private Method: altersingle\n moves neuron *i* towards biased (b,g,r) by factor *alpha*\n */\n function altersingle(alpha, i, b, g, r){\n network[i][0] -= (alpha * (network[i][0] - b)) / initalpha;\n network[i][1] -= (alpha * (network[i][1] - g)) / initalpha;\n network[i][2] -= (alpha * (network[i][2] - r)) / initalpha;\n }\n\n /*\n Private Method: alterneigh\n moves neurons in *radius* around index *i* towards biased (b,g,r) by factor *alpha*\n */\n function alterneigh(radius, i, b, g, r) {\n const lo = Math.abs(i - radius);\n const hi = Math.min(i + radius, networkSize);\n\n let j = i + 1;\n let k = i - 1;\n let m = 1;\n\n while((j < hi) || (k > lo)){\n const a = radpower[m++];\n\n if (j < hi) {\n const p = network[j++];\n p[0] -= (a * (p[0] - b)) / alpharadbias;\n p[1] -= (a * (p[1] - g)) / alpharadbias;\n p[2] -= (a * (p[2] - r)) / alpharadbias;\n }\n\n if(k > lo){\n const p = network[k--];\n p[0] -= (a * (p[0] - b)) / alpharadbias;\n p[1] -= (a * (p[1] - g)) / alpharadbias;\n p[2] -= (a * (p[2] - r)) / alpharadbias;\n }\n }\n }\n\n /*\n Private Method: contest\n searches for biased BGR values\n */\n function contest(b, g, r) {\n /*\n finds closest neuron (min dist) and updates freq\n finds best neuron (min dist-bias) and returns position\n for frequently chosen neurons, freq[i] is high and bias[i] is negative\n bias[i] = gamma * ((1 / netsize) - freq[i])\n */\n\n let bestd = ~(1 << 31);\n let bestbiasd = bestd;\n let bestpos = -1;\n let bestbiaspos = bestpos;\n\n for(let i = 0; i < networkSize; i++){\n const n = network[i];\n\n const dist = Math.abs(n[0] - b) + Math.abs(n[1] - g) + Math.abs(n[2] - r);\n if(dist < bestd){\n bestd = dist;\n bestpos = i;\n }\n\n const biasdist = dist - ((bias[i]) >> (intbiasshift - netbiasshift));\n if(biasdist < bestbiasd){\n bestbiasd = biasdist;\n bestbiaspos = i;\n }\n\n const betafreq = (freq[i] >> betashift);\n freq[i] -= betafreq;\n bias[i] += (betafreq << gammashift);\n }\n\n freq[bestpos] += beta;\n bias[bestpos] -= betagamma;\n\n return bestbiaspos;\n }\n\n /*\n Private Method: inxbuild\n sorts network and builds netindex[0..255]\n */\n function inxbuild() {\n let previouscol = 0;\n let startpos = 0;\n for (let i = 0; i < networkSize; i++) {\n const p = network[i];\n let smallpos = i;\n let smallval = p[1]; // index on g\n // find smallest in i..netsize-1\n for (let j = i + 1; j < networkSize; j++) {\n const q = network[j];\n if (q[1] < smallval) { // index on g\n smallpos = j;\n smallval = q[1]; // index on g\n }\n }\n const q = network[smallpos];\n\n if(i !== smallpos){\n // swap p (i) and q (smallpos) entries\n for(let j=0;j<4;j++){\n const temp = q[j];\n q[j] = p[j];\n p[j] = temp;\n }\n }\n // smallval entry is now in position i\n if(smallval !== previouscol){\n netindex[previouscol] = (startpos + i) >> 1;\n for(let j = previouscol + 1; j < smallval; j++){\n netindex[j] = i;\n }\n previouscol = smallval;\n startpos = i;\n }\n }\n netindex[previouscol] = (startpos + maxnetpos) >> 1;\n for(let j = previouscol + 1; j < 256; j++){\n netindex[j] = maxnetpos; // really 256\n } \n }\n\n /*\n Private Method: learn\n \"Main Learning Loop\"\n Note that you will get infinite loop if image that is completely transparent is used\n */\n function learn(pixels, samplefac, progressCallback) {\n //these calculations were done supposing pixels had no alpha, so divide by 4 * 3 to get length of pixels without alpha\n const pixelLength = pixels.length;\n //originally was divided by 3, but not sure if we should be \n //dividing by 4 now that we are using rgb instead of rgba\n //however, with samplefac 10 with colors less than 256, divide by 4 gives better results\n //compared to dividing by 3, which gives duller, less saturated result\n const alphadec = 30 + ((samplefac - 1) / 4);\n const samplepixels = pixelLength / (4 * samplefac);\n let delta = ~~(samplepixels / ncycles);\n let alpha = initalpha;\n let radius = initradius;\n\n let rad = radius >> radiusbiasshift;\n if(rad <= 1){ \n rad = 0;\n }\n for(let i = 0; i < rad; i++){\n radpower[i] = alpha * (((rad * rad - i * i) * radbias) / (rad * rad));\n }\n \n const DEFAULT_STEP = 4;\n let step = DEFAULT_STEP;\n\n // four primes near 500 - assume no image has a length so large that it is\n // divisible by all four primes\n const prime1 = 499;\n const prime2 = 491;\n const prime3 = 487;\n const prime4 = 503;\n const minpicturebytes = (4 * prime4);\n if(pixelLength >= minpicturebytes){\n if((pixelLength % prime1) !== 0){\n step *= prime1;\n } \n else if ((pixelLength % prime2) !== 0){\n step *= prime2;\n } \n else if((pixelLength % prime3) !== 0){\n step *= prime3;\n } \n else{\n step *= prime4;\n }\n }\n \n let pixelIndex = 0; // current pixel\n let i = 0;\n let hasTransparentPixels = false;\n let hasUsedProgressCallback = samplefac > 5;\n const halfDone = Math.floor(samplepixels / 2);\n while(i < samplepixels){\n //skip transparent pixels\n if(pixels[pixelIndex+3] === 0){\n hasTransparentPixels = true;\n pixelIndex += step;\n\n //to avoid infinite loops\n if(pixelIndex >= pixelLength){\n pixelIndex = 0;\n step = DEFAULT_STEP;\n }\n continue;\n }\n const b = (pixels[pixelIndex] & 0xff) << netbiasshift;\n const g = (pixels[pixelIndex + 1] & 0xff) << netbiasshift;\n const r = (pixels[pixelIndex + 2] & 0xff) << netbiasshift;\n const j = contest(b, g, r);\n\n altersingle(alpha, j, b, g, r);\n if (rad !== 0){\n alterneigh(rad, j, b, g, r); // alter neighbours\n }\n\n i++;\n delta = delta === 0 ? 1 : delta;\n if(i % delta === 0){\n alpha -= alpha / alphadec;\n radius -= radius / radiusdec;\n rad = radius >> radiusbiasshift;\n rad = rad <= 1 ? 0 : rad;\n\n for(let j = 0; j < rad; j++){\n radpower[j] = alpha * (((rad * rad - j * j) * radbias) / (rad * rad));\n }\n }\n pixelIndex += step;\n if(pixelIndex >= pixelLength){\n pixelIndex = 0;\n //if we get past the end of pixels array, and there are transparent pixels reset step to every pixel,\n //so we don't get caught in a potentially infinite loop if there are transparent pixels\n //don't do this unless we have to, since this leads to worse results\n if(hasTransparentPixels){\n step = DEFAULT_STEP;\n }\n if(!hasUsedProgressCallback && i >= halfDone){\n hasUsedProgressCallback = true;\n progressCallback(50);\n }\n }\n }\n }\n\n /*\n Method: buildColormap\n 1. initializes network\n 2. trains it\n 3. removes misconceptions\n 4. builds colorindex\n \n Arguments:\n pixels - array of pixels in RGBA format; e.g. [r, g, b, a, r, g, b, a]\n samplefac - sampling factor 1 to 30 where lower is better quality\n */\n this.buildColormap = function(pixels, samplefac, progressCallback){\n init();\n learn(pixels, samplefac, progressCallback);\n unbiasnet();\n inxbuild();\n return getColormap();\n };\n\n /*\n Method: getColormap\n builds colormap from the index\n returns array in the format:\n >\n > [r, g, b, r, g, b, r, g, b, ..]\n >\n */\n function getColormap(){\n const map = new Uint8Array(networkSize*3);\n const index = [];\n\n for(let i = 0; i < networkSize; i++){\n index[network[i][3]] = i;\n }\n\n for(let i = 0, k=0; i < networkSize; i++){\n const j = index[i];\n map[k++] = network[j][0];\n map[k++] = network[j][1];\n map[k++] = network[j][2];\n }\n return map;\n }\n}",
"function Quantize() {\n var bs;\n this.rv = null;\n var rv;\n this.qupvt = null;\n var qupvt;\n\n var vbr = new VBRQuantize();\n var tk;\n\n this.setModules = function (_bs, _rv, _qupvt, _tk) {\n bs = _bs;\n rv = _rv;\n this.rv = _rv;\n qupvt = _qupvt;\n this.qupvt = _qupvt;\n tk = _tk;\n vbr.setModules(qupvt, tk);\n }\n\n /**\n * convert from L/R <. Mid/Side\n */\n this.ms_convert = function (l3_side, gr) {\n for (var i = 0; i < 576; ++i) {\n var l = l3_side.tt[gr][0].xr[i];\n var r = l3_side.tt[gr][1].xr[i];\n l3_side.tt[gr][0].xr[i] = (l + r) * (Util.SQRT2 * 0.5);\n l3_side.tt[gr][1].xr[i] = (l - r) * (Util.SQRT2 * 0.5);\n }\n };\n\n /**\n * mt 6/99\n *\n * initializes cod_info, scalefac and xrpow\n *\n * returns 0 if all energies in xr are zero, else 1\n */\n function init_xrpow_core(cod_info, xrpow, upper, sum) {\n sum = 0;\n for (var i = 0; i <= upper; ++i) {\n var tmp = Math.abs(cod_info.xr[i]);\n sum += tmp;\n xrpow[i] = Math.sqrt(tmp * Math.sqrt(tmp));\n\n if (xrpow[i] > cod_info.xrpow_max)\n cod_info.xrpow_max = xrpow[i];\n }\n return sum;\n }\n\n this.init_xrpow = function (gfc, cod_info, xrpow) {\n var sum = 0;\n var upper = 0 | cod_info.max_nonzero_coeff;\n\n cod_info.xrpow_max = 0;\n\n /*\n * check if there is some energy we have to quantize and calculate xrpow\n * matching our fresh scalefactors\n */\n\n Arrays.fill(xrpow, upper, 576, 0);\n\n sum = init_xrpow_core(cod_info, xrpow, upper, sum);\n\n /*\n * return 1 if we have something to quantize, else 0\n */\n if (sum > 1E-20) {\n var j = 0;\n if ((gfc.substep_shaping & 2) != 0)\n j = 1;\n\n for (var i = 0; i < cod_info.psymax; i++)\n gfc.pseudohalf[i] = j;\n\n return true;\n }\n\n Arrays.fill(cod_info.l3_enc, 0, 576, 0);\n return false;\n }\n\n /**\n * Gabriel Bouvigne feb/apr 2003<BR>\n * Analog silence detection in partitionned sfb21 or sfb12 for short blocks\n *\n * From top to bottom of sfb, changes to 0 coeffs which are below ath. It\n * stops on the first coeff higher than ath.\n */\n function psfb21_analogsilence(gfc, cod_info) {\n var ath = gfc.ATH;\n var xr = cod_info.xr;\n\n if (cod_info.block_type != Encoder.SHORT_TYPE) {\n /* NORM, START or STOP type, but not SHORT blocks */\n var stop = false;\n for (var gsfb = Encoder.PSFB21 - 1; gsfb >= 0 && !stop; gsfb--) {\n var start = gfc.scalefac_band.psfb21[gsfb];\n var end = gfc.scalefac_band.psfb21[gsfb + 1];\n var ath21 = qupvt.athAdjust(ath.adjust, ath.psfb21[gsfb],\n ath.floor);\n\n if (gfc.nsPsy.longfact[21] > 1e-12)\n ath21 *= gfc.nsPsy.longfact[21];\n\n for (var j = end - 1; j >= start; j--) {\n if (Math.abs(xr[j]) < ath21)\n xr[j] = 0;\n else {\n stop = true;\n break;\n }\n }\n }\n } else {\n /* note: short blocks coeffs are reordered */\n for (var block = 0; block < 3; block++) {\n var stop = false;\n for (var gsfb = Encoder.PSFB12 - 1; gsfb >= 0 && !stop; gsfb--) {\n var start = gfc.scalefac_band.s[12]\n * 3\n + (gfc.scalefac_band.s[13] - gfc.scalefac_band.s[12])\n * block\n + (gfc.scalefac_band.psfb12[gsfb] - gfc.scalefac_band.psfb12[0]);\n var end = start\n + (gfc.scalefac_band.psfb12[gsfb + 1] - gfc.scalefac_band.psfb12[gsfb]);\n var ath12 = qupvt.athAdjust(ath.adjust, ath.psfb12[gsfb],\n ath.floor);\n\n if (gfc.nsPsy.shortfact[12] > 1e-12)\n ath12 *= gfc.nsPsy.shortfact[12];\n\n for (var j = end - 1; j >= start; j--) {\n if (Math.abs(xr[j]) < ath12)\n xr[j] = 0;\n else {\n stop = true;\n break;\n }\n }\n }\n }\n }\n\n }\n\n this.init_outer_loop = function (gfc, cod_info) {\n /*\n * initialize fresh cod_info\n */\n cod_info.part2_3_length = 0;\n cod_info.big_values = 0;\n cod_info.count1 = 0;\n cod_info.global_gain = 210;\n cod_info.scalefac_compress = 0;\n /* mixed_block_flag, block_type was set in psymodel.c */\n cod_info.table_select[0] = 0;\n cod_info.table_select[1] = 0;\n cod_info.table_select[2] = 0;\n cod_info.subblock_gain[0] = 0;\n cod_info.subblock_gain[1] = 0;\n cod_info.subblock_gain[2] = 0;\n cod_info.subblock_gain[3] = 0;\n /* this one is always 0 */\n cod_info.region0_count = 0;\n cod_info.region1_count = 0;\n cod_info.preflag = 0;\n cod_info.scalefac_scale = 0;\n cod_info.count1table_select = 0;\n cod_info.part2_length = 0;\n cod_info.sfb_lmax = Encoder.SBPSY_l;\n cod_info.sfb_smin = Encoder.SBPSY_s;\n cod_info.psy_lmax = gfc.sfb21_extra ? Encoder.SBMAX_l : Encoder.SBPSY_l;\n cod_info.psymax = cod_info.psy_lmax;\n cod_info.sfbmax = cod_info.sfb_lmax;\n cod_info.sfbdivide = 11;\n for (var sfb = 0; sfb < Encoder.SBMAX_l; sfb++) {\n cod_info.width[sfb] = gfc.scalefac_band.l[sfb + 1]\n - gfc.scalefac_band.l[sfb];\n /* which is always 0. */\n cod_info.window[sfb] = 3;\n }\n if (cod_info.block_type == Encoder.SHORT_TYPE) {\n var ixwork = new_float(576);\n\n cod_info.sfb_smin = 0;\n cod_info.sfb_lmax = 0;\n if (cod_info.mixed_block_flag != 0) {\n /*\n * MPEG-1: sfbs 0-7 long block, 3-12 short blocks MPEG-2(.5):\n * sfbs 0-5 long block, 3-12 short blocks\n */\n cod_info.sfb_smin = 3;\n cod_info.sfb_lmax = gfc.mode_gr * 2 + 4;\n }\n cod_info.psymax = cod_info.sfb_lmax\n + 3\n * ((gfc.sfb21_extra ? Encoder.SBMAX_s : Encoder.SBPSY_s) - cod_info.sfb_smin);\n cod_info.sfbmax = cod_info.sfb_lmax + 3\n * (Encoder.SBPSY_s - cod_info.sfb_smin);\n cod_info.sfbdivide = cod_info.sfbmax - 18;\n cod_info.psy_lmax = cod_info.sfb_lmax;\n /* re-order the short blocks, for more efficient encoding below */\n /* By Takehiro TOMINAGA */\n /*\n * Within each scalefactor band, data is given for successive time\n * windows, beginning with window 0 and ending with window 2. Within\n * each window, the quantized values are then arranged in order of\n * increasing frequency...\n */\n var ix = gfc.scalefac_band.l[cod_info.sfb_lmax];\n System.arraycopy(cod_info.xr, 0, ixwork, 0, 576);\n for (var sfb = cod_info.sfb_smin; sfb < Encoder.SBMAX_s; sfb++) {\n var start = gfc.scalefac_band.s[sfb];\n var end = gfc.scalefac_band.s[sfb + 1];\n for (var window = 0; window < 3; window++) {\n for (var l = start; l < end; l++) {\n cod_info.xr[ix++] = ixwork[3 * l + window];\n }\n }\n }\n\n var j = cod_info.sfb_lmax;\n for (var sfb = cod_info.sfb_smin; sfb < Encoder.SBMAX_s; sfb++) {\n cod_info.width[j] = cod_info.width[j + 1] = cod_info.width[j + 2] = gfc.scalefac_band.s[sfb + 1]\n - gfc.scalefac_band.s[sfb];\n cod_info.window[j] = 0;\n cod_info.window[j + 1] = 1;\n cod_info.window[j + 2] = 2;\n j += 3;\n }\n }\n\n cod_info.count1bits = 0;\n cod_info.sfb_partition_table = qupvt.nr_of_sfb_block[0][0];\n cod_info.slen[0] = 0;\n cod_info.slen[1] = 0;\n cod_info.slen[2] = 0;\n cod_info.slen[3] = 0;\n\n cod_info.max_nonzero_coeff = 575;\n\n /*\n * fresh scalefactors are all zero\n */\n Arrays.fill(cod_info.scalefac, 0);\n\n psfb21_analogsilence(gfc, cod_info);\n };\n\n function BinSearchDirection(ordinal) {\n this.ordinal = ordinal;\n }\n\n BinSearchDirection.BINSEARCH_NONE = new BinSearchDirection(0);\n BinSearchDirection.BINSEARCH_UP = new BinSearchDirection(1);\n BinSearchDirection.BINSEARCH_DOWN = new BinSearchDirection(2);\n\n /**\n * author/date??\n *\n * binary step size search used by outer_loop to get a quantizer step size\n * to start with\n */\n function bin_search_StepSize(gfc, cod_info, desired_rate, ch, xrpow) {\n var nBits;\n var CurrentStep = gfc.CurrentStep[ch];\n var flagGoneOver = false;\n var start = gfc.OldValue[ch];\n var Direction = BinSearchDirection.BINSEARCH_NONE;\n cod_info.global_gain = start;\n desired_rate -= cod_info.part2_length;\n\n for (; ;) {\n var step;\n nBits = tk.count_bits(gfc, xrpow, cod_info, null);\n\n if (CurrentStep == 1 || nBits == desired_rate)\n break;\n /* nothing to adjust anymore */\n\n if (nBits > desired_rate) {\n /* increase Quantize_StepSize */\n if (Direction == BinSearchDirection.BINSEARCH_DOWN)\n flagGoneOver = true;\n\n if (flagGoneOver)\n CurrentStep /= 2;\n Direction = BinSearchDirection.BINSEARCH_UP;\n step = CurrentStep;\n } else {\n /* decrease Quantize_StepSize */\n if (Direction == BinSearchDirection.BINSEARCH_UP)\n flagGoneOver = true;\n\n if (flagGoneOver)\n CurrentStep /= 2;\n Direction = BinSearchDirection.BINSEARCH_DOWN;\n step = -CurrentStep;\n }\n cod_info.global_gain += step;\n if (cod_info.global_gain < 0) {\n cod_info.global_gain = 0;\n flagGoneOver = true;\n }\n if (cod_info.global_gain > 255) {\n cod_info.global_gain = 255;\n flagGoneOver = true;\n }\n }\n\n\n while (nBits > desired_rate && cod_info.global_gain < 255) {\n cod_info.global_gain++;\n nBits = tk.count_bits(gfc, xrpow, cod_info, null);\n }\n gfc.CurrentStep[ch] = (start - cod_info.global_gain >= 4) ? 4 : 2;\n gfc.OldValue[ch] = cod_info.global_gain;\n cod_info.part2_3_length = nBits;\n return nBits;\n }\n\n this.trancate_smallspectrums = function (gfc, gi, l3_xmin, work) {\n var distort = new_float(L3Side.SFBMAX);\n\n if ((0 == (gfc.substep_shaping & 4) && gi.block_type == Encoder.SHORT_TYPE)\n || (gfc.substep_shaping & 0x80) != 0)\n return;\n qupvt.calc_noise(gi, l3_xmin, distort, new CalcNoiseResult(), null);\n for (var j = 0; j < 576; j++) {\n var xr = 0.0;\n if (gi.l3_enc[j] != 0)\n xr = Math.abs(gi.xr[j]);\n work[j] = xr;\n }\n\n var j = 0;\n var sfb = 8;\n if (gi.block_type == Encoder.SHORT_TYPE)\n sfb = 6;\n do {\n var allowedNoise, trancateThreshold;\n var nsame, start;\n\n var width = gi.width[sfb];\n j += width;\n if (distort[sfb] >= 1.0)\n continue;\n\n Arrays.sort(work, j - width, width);\n if (BitStream.EQ(work[j - 1], 0.0))\n continue;\n /* all zero sfb */\n\n allowedNoise = (1.0 - distort[sfb]) * l3_xmin[sfb];\n trancateThreshold = 0.0;\n start = 0;\n do {\n var noise;\n for (nsame = 1; start + nsame < width; nsame++)\n if (BitStream.NEQ(work[start + j - width], work[start + j\n + nsame - width]))\n break;\n\n noise = work[start + j - width] * work[start + j - width]\n * nsame;\n if (allowedNoise < noise) {\n if (start != 0)\n trancateThreshold = work[start + j - width - 1];\n break;\n }\n allowedNoise -= noise;\n start += nsame;\n } while (start < width);\n if (BitStream.EQ(trancateThreshold, 0.0))\n continue;\n\n do {\n if (Math.abs(gi.xr[j - width]) <= trancateThreshold)\n gi.l3_enc[j - width] = 0;\n } while (--width > 0);\n } while (++sfb < gi.psymax);\n\n gi.part2_3_length = tk.noquant_count_bits(gfc, gi, null);\n };\n\n /**\n * author/date??\n *\n * Function: Returns zero if there is a scalefac which has not been\n * amplified. Otherwise it returns one.\n */\n function loop_break(cod_info) {\n for (var sfb = 0; sfb < cod_info.sfbmax; sfb++)\n if (cod_info.scalefac[sfb]\n + cod_info.subblock_gain[cod_info.window[sfb]] == 0)\n return false;\n\n return true;\n }\n\n /* mt 5/99: Function: Improved calc_noise for a single channel */\n\n function penalties(noise) {\n return Util.FAST_LOG10((0.368 + 0.632 * noise * noise * noise));\n }\n\n /**\n * author/date??\n *\n * several different codes to decide which quantization is better\n */\n function get_klemm_noise(distort, gi) {\n var klemm_noise = 1E-37;\n for (var sfb = 0; sfb < gi.psymax; sfb++)\n klemm_noise += penalties(distort[sfb]);\n\n return Math.max(1e-20, klemm_noise);\n }\n\n function quant_compare(quant_comp, best, calc, gi, distort) {\n /**\n * noise is given in decibels (dB) relative to masking thesholds.<BR>\n *\n * over_noise: ??? (the previous comment is fully wrong)<BR>\n * tot_noise: ??? (the previous comment is fully wrong)<BR>\n * max_noise: max quantization noise\n */\n var better;\n\n switch (quant_comp) {\n default:\n case 9:\n {\n if (best.over_count > 0) {\n /* there are distorted sfb */\n better = calc.over_SSD <= best.over_SSD;\n if (calc.over_SSD == best.over_SSD)\n better = calc.bits < best.bits;\n } else {\n /* no distorted sfb */\n better = ((calc.max_noise < 0) && ((calc.max_noise * 10 + calc.bits) <= (best.max_noise * 10 + best.bits)));\n }\n break;\n }\n\n case 0:\n better = calc.over_count < best.over_count\n || (calc.over_count == best.over_count && calc.over_noise < best.over_noise)\n || (calc.over_count == best.over_count\n && BitStream.EQ(calc.over_noise, best.over_noise) && calc.tot_noise < best.tot_noise);\n break;\n\n case 8:\n calc.max_noise = get_klemm_noise(distort, gi);\n //$FALL-THROUGH$\n case 1:\n better = calc.max_noise < best.max_noise;\n break;\n case 2:\n better = calc.tot_noise < best.tot_noise;\n break;\n case 3:\n better = (calc.tot_noise < best.tot_noise)\n && (calc.max_noise < best.max_noise);\n break;\n case 4:\n better = (calc.max_noise <= 0.0 && best.max_noise > 0.2)\n || (calc.max_noise <= 0.0 && best.max_noise < 0.0\n && best.max_noise > calc.max_noise - 0.2 && calc.tot_noise < best.tot_noise)\n || (calc.max_noise <= 0.0 && best.max_noise > 0.0\n && best.max_noise > calc.max_noise - 0.2 && calc.tot_noise < best.tot_noise\n + best.over_noise)\n || (calc.max_noise > 0.0 && best.max_noise > -0.05\n && best.max_noise > calc.max_noise - 0.1 && calc.tot_noise\n + calc.over_noise < best.tot_noise\n + best.over_noise)\n || (calc.max_noise > 0.0 && best.max_noise > -0.1\n && best.max_noise > calc.max_noise - 0.15 && calc.tot_noise\n + calc.over_noise + calc.over_noise < best.tot_noise\n + best.over_noise + best.over_noise);\n break;\n case 5:\n better = calc.over_noise < best.over_noise\n || (BitStream.EQ(calc.over_noise, best.over_noise) && calc.tot_noise < best.tot_noise);\n break;\n case 6:\n better = calc.over_noise < best.over_noise\n || (BitStream.EQ(calc.over_noise, best.over_noise) && (calc.max_noise < best.max_noise || (BitStream\n .EQ(calc.max_noise, best.max_noise) && calc.tot_noise <= best.tot_noise)));\n break;\n case 7:\n better = calc.over_count < best.over_count\n || calc.over_noise < best.over_noise;\n break;\n }\n\n if (best.over_count == 0) {\n /*\n * If no distorted bands, only use this quantization if it is\n * better, and if it uses less bits. Unfortunately, part2_3_length\n * is sometimes a poor estimator of the final size at low bitrates.\n */\n better = better && calc.bits < best.bits;\n }\n\n return better;\n }\n\n /**\n * author/date??\n *\n * <PRE>\n * Amplify the scalefactor bands that violate the masking threshold.\n * See ISO 11172-3 Section C.1.5.4.3.5\n *\n * distort[] = noise/masking\n * distort[] > 1 ==> noise is not masked\n * distort[] < 1 ==> noise is masked\n * max_dist = maximum value of distort[]\n *\n * Three algorithms:\n * noise_shaping_amp\n * 0 Amplify all bands with distort[]>1.\n *\n * 1 Amplify all bands with distort[] >= max_dist^(.5);\n * ( 50% in the db scale)\n *\n * 2 Amplify first band with distort[] >= max_dist;\n *\n *\n * For algorithms 0 and 1, if max_dist < 1, then amplify all bands\n * with distort[] >= .95*max_dist. This is to make sure we always\n * amplify at least one band.\n * </PRE>\n */\n function amp_scalefac_bands(gfp, cod_info, distort, xrpow, bRefine) {\n var gfc = gfp.internal_flags;\n var ifqstep34;\n\n if (cod_info.scalefac_scale == 0) {\n ifqstep34 = 1.29683955465100964055;\n /* 2**(.75*.5) */\n } else {\n ifqstep34 = 1.68179283050742922612;\n /* 2**(.75*1) */\n }\n\n /* compute maximum value of distort[] */\n var trigger = 0;\n for (var sfb = 0; sfb < cod_info.sfbmax; sfb++) {\n if (trigger < distort[sfb])\n trigger = distort[sfb];\n }\n\n var noise_shaping_amp = gfc.noise_shaping_amp;\n if (noise_shaping_amp == 3) {\n if (bRefine)\n noise_shaping_amp = 2;\n else\n noise_shaping_amp = 1;\n }\n switch (noise_shaping_amp) {\n case 2:\n /* amplify exactly 1 band */\n break;\n\n case 1:\n /* amplify bands within 50% of max (on db scale) */\n if (trigger > 1.0)\n trigger = Math.pow(trigger, .5);\n else\n trigger *= .95;\n break;\n\n case 0:\n default:\n /* ISO algorithm. amplify all bands with distort>1 */\n if (trigger > 1.0)\n trigger = 1.0;\n else\n trigger *= .95;\n break;\n }\n\n var j = 0;\n for (var sfb = 0; sfb < cod_info.sfbmax; sfb++) {\n var width = cod_info.width[sfb];\n var l;\n j += width;\n if (distort[sfb] < trigger)\n continue;\n\n if ((gfc.substep_shaping & 2) != 0) {\n gfc.pseudohalf[sfb] = (0 == gfc.pseudohalf[sfb]) ? 1 : 0;\n if (0 == gfc.pseudohalf[sfb] && gfc.noise_shaping_amp == 2)\n return;\n }\n cod_info.scalefac[sfb]++;\n for (l = -width; l < 0; l++) {\n xrpow[j + l] *= ifqstep34;\n if (xrpow[j + l] > cod_info.xrpow_max)\n cod_info.xrpow_max = xrpow[j + l];\n }\n\n if (gfc.noise_shaping_amp == 2)\n return;\n }\n }\n\n /**\n * Takehiro Tominaga 2000-xx-xx\n *\n * turns on scalefac scale and adjusts scalefactors\n */\n function inc_scalefac_scale(cod_info, xrpow) {\n var ifqstep34 = 1.29683955465100964055;\n\n var j = 0;\n for (var sfb = 0; sfb < cod_info.sfbmax; sfb++) {\n var width = cod_info.width[sfb];\n var s = cod_info.scalefac[sfb];\n if (cod_info.preflag != 0)\n s += qupvt.pretab[sfb];\n j += width;\n if ((s & 1) != 0) {\n s++;\n for (var l = -width; l < 0; l++) {\n xrpow[j + l] *= ifqstep34;\n if (xrpow[j + l] > cod_info.xrpow_max)\n cod_info.xrpow_max = xrpow[j + l];\n }\n }\n cod_info.scalefac[sfb] = s >> 1;\n }\n cod_info.preflag = 0;\n cod_info.scalefac_scale = 1;\n }\n\n /**\n * Takehiro Tominaga 2000-xx-xx\n *\n * increases the subblock gain and adjusts scalefactors\n */\n function inc_subblock_gain(gfc, cod_info, xrpow) {\n var sfb;\n var scalefac = cod_info.scalefac;\n\n /* subbloc_gain can't do anything in the long block region */\n for (sfb = 0; sfb < cod_info.sfb_lmax; sfb++) {\n if (scalefac[sfb] >= 16)\n return true;\n }\n\n for (var window = 0; window < 3; window++) {\n var s1 = 0;\n var s2 = 0;\n\n for (sfb = cod_info.sfb_lmax + window; sfb < cod_info.sfbdivide; sfb += 3) {\n if (s1 < scalefac[sfb])\n s1 = scalefac[sfb];\n }\n for (; sfb < cod_info.sfbmax; sfb += 3) {\n if (s2 < scalefac[sfb])\n s2 = scalefac[sfb];\n }\n\n if (s1 < 16 && s2 < 8)\n continue;\n\n if (cod_info.subblock_gain[window] >= 7)\n return true;\n\n /*\n * even though there is no scalefactor for sfb12 subblock gain\n * affects upper frequencies too, that's why we have to go up to\n * SBMAX_s\n */\n cod_info.subblock_gain[window]++;\n var j = gfc.scalefac_band.l[cod_info.sfb_lmax];\n for (sfb = cod_info.sfb_lmax + window; sfb < cod_info.sfbmax; sfb += 3) {\n var amp;\n var width = cod_info.width[sfb];\n var s = scalefac[sfb];\n s = s - (4 >> cod_info.scalefac_scale);\n if (s >= 0) {\n scalefac[sfb] = s;\n j += width * 3;\n continue;\n }\n\n scalefac[sfb] = 0;\n {\n var gain = 210 + (s << (cod_info.scalefac_scale + 1));\n amp = qupvt.IPOW20(gain);\n }\n j += width * (window + 1);\n for (var l = -width; l < 0; l++) {\n xrpow[j + l] *= amp;\n if (xrpow[j + l] > cod_info.xrpow_max)\n cod_info.xrpow_max = xrpow[j + l];\n }\n j += width * (3 - window - 1);\n }\n\n {\n var amp = qupvt.IPOW20(202);\n j += cod_info.width[sfb] * (window + 1);\n for (var l = -cod_info.width[sfb]; l < 0; l++) {\n xrpow[j + l] *= amp;\n if (xrpow[j + l] > cod_info.xrpow_max)\n cod_info.xrpow_max = xrpow[j + l];\n }\n }\n }\n return false;\n }\n\n /**\n * <PRE>\n * Takehiro Tominaga /date??\n * Robert Hegemann 2000-09-06: made a function of it\n *\n * amplifies scalefactor bands,\n * - if all are already amplified returns 0\n * - if some bands are amplified too much:\n * * try to increase scalefac_scale\n * * if already scalefac_scale was set\n * try on short blocks to increase subblock gain\n * </PRE>\n */\n function balance_noise(gfp, cod_info, distort, xrpow, bRefine) {\n var gfc = gfp.internal_flags;\n\n amp_scalefac_bands(gfp, cod_info, distort, xrpow, bRefine);\n\n /*\n * check to make sure we have not amplified too much loop_break returns\n * 0 if there is an unamplified scalefac scale_bitcount returns 0 if no\n * scalefactors are too large\n */\n\n var status = loop_break(cod_info);\n\n if (status)\n return false;\n /* all bands amplified */\n\n /*\n * not all scalefactors have been amplified. so these scalefacs are\n * possibly valid. encode them:\n */\n if (gfc.mode_gr == 2)\n status = tk.scale_bitcount(cod_info);\n else\n status = tk.scale_bitcount_lsf(gfc, cod_info);\n\n if (!status)\n return true;\n /* amplified some bands not exceeding limits */\n\n /*\n * some scalefactors are too large. lets try setting scalefac_scale=1\n */\n if (gfc.noise_shaping > 1) {\n Arrays.fill(gfc.pseudohalf, 0);\n if (0 == cod_info.scalefac_scale) {\n inc_scalefac_scale(cod_info, xrpow);\n status = false;\n } else {\n if (cod_info.block_type == Encoder.SHORT_TYPE\n && gfc.subblock_gain > 0) {\n status = (inc_subblock_gain(gfc, cod_info, xrpow) || loop_break(cod_info));\n }\n }\n }\n\n if (!status) {\n if (gfc.mode_gr == 2)\n status = tk.scale_bitcount(cod_info);\n else\n status = tk.scale_bitcount_lsf(gfc, cod_info);\n }\n return !status;\n }\n\n /**\n * <PRE>\n * Function: The outer iteration loop controls the masking conditions\n * of all scalefactorbands. It computes the best scalefac and\n * global gain. This module calls the inner iteration loop\n *\n * mt 5/99 completely rewritten to allow for bit reservoir control,\n * mid/side channels with L/R or mid/side masking thresholds,\n * and chooses best quantization instead of last quantization when\n * no distortion free quantization can be found.\n *\n * added VBR support mt 5/99\n *\n * some code shuffle rh 9/00\n * </PRE>\n *\n * @param l3_xmin\n * allowed distortion\n * @param xrpow\n * coloured magnitudes of spectral\n * @param targ_bits\n * maximum allowed bits\n */\n this.outer_loop = function (gfp, cod_info, l3_xmin, xrpow, ch, targ_bits) {\n var gfc = gfp.internal_flags;\n var cod_info_w = new GrInfo();\n var save_xrpow = new_float(576);\n var distort = new_float(L3Side.SFBMAX);\n var best_noise_info = new CalcNoiseResult();\n var better;\n var prev_noise = new CalcNoiseData();\n var best_part2_3_length = 9999999;\n var bEndOfSearch = false;\n var bRefine = false;\n var best_ggain_pass1 = 0;\n\n bin_search_StepSize(gfc, cod_info, targ_bits, ch, xrpow);\n\n if (0 == gfc.noise_shaping)\n /* fast mode, no noise shaping, we are ready */\n return 100;\n /* default noise_info.over_count */\n\n /* compute the distortion in this quantization */\n /* coefficients and thresholds both l/r (or both mid/side) */\n qupvt.calc_noise(cod_info, l3_xmin, distort, best_noise_info,\n prev_noise);\n best_noise_info.bits = cod_info.part2_3_length;\n\n cod_info_w.assign(cod_info);\n var age = 0;\n System.arraycopy(xrpow, 0, save_xrpow, 0, 576);\n\n while (!bEndOfSearch) {\n /* BEGIN MAIN LOOP */\n do {\n var noise_info = new CalcNoiseResult();\n var search_limit;\n var maxggain = 255;\n\n /*\n * When quantization with no distorted bands is found, allow up\n * to X new unsuccesful tries in serial. This gives us more\n * possibilities for different quant_compare modes. Much more\n * than 3 makes not a big difference, it is only slower.\n */\n\n if ((gfc.substep_shaping & 2) != 0) {\n search_limit = 20;\n } else {\n search_limit = 3;\n }\n\n /*\n * Check if the last scalefactor band is distorted. in VBR mode\n * we can't get rid of the distortion, so quit now and VBR mode\n * will try again with more bits. (makes a 10% speed increase,\n * the files I tested were binary identical, 2000/05/20 Robert\n * Hegemann) distort[] > 1 means noise > allowed noise\n */\n if (gfc.sfb21_extra) {\n if (distort[cod_info_w.sfbmax] > 1.0)\n break;\n if (cod_info_w.block_type == Encoder.SHORT_TYPE\n && (distort[cod_info_w.sfbmax + 1] > 1.0 || distort[cod_info_w.sfbmax + 2] > 1.0))\n break;\n }\n\n /* try a new scalefactor conbination on cod_info_w */\n if (!balance_noise(gfp, cod_info_w, distort, xrpow, bRefine))\n break;\n if (cod_info_w.scalefac_scale != 0)\n maxggain = 254;\n\n /*\n * inner_loop starts with the initial quantization step computed\n * above and slowly increases until the bits < huff_bits. Thus\n * it is important not to start with too large of an inital\n * quantization step. Too small is ok, but inner_loop will take\n * longer\n */\n var huff_bits = targ_bits - cod_info_w.part2_length;\n if (huff_bits <= 0)\n break;\n\n /*\n * increase quantizer stepsize until needed bits are below\n * maximum\n */\n while ((cod_info_w.part2_3_length = tk.count_bits(gfc, xrpow,\n cod_info_w, prev_noise)) > huff_bits\n && cod_info_w.global_gain <= maxggain)\n cod_info_w.global_gain++;\n\n if (cod_info_w.global_gain > maxggain)\n break;\n\n if (best_noise_info.over_count == 0) {\n\n while ((cod_info_w.part2_3_length = tk.count_bits(gfc,\n xrpow, cod_info_w, prev_noise)) > best_part2_3_length\n && cod_info_w.global_gain <= maxggain)\n cod_info_w.global_gain++;\n\n if (cod_info_w.global_gain > maxggain)\n break;\n }\n\n /* compute the distortion in this quantization */\n qupvt.calc_noise(cod_info_w, l3_xmin, distort, noise_info,\n prev_noise);\n noise_info.bits = cod_info_w.part2_3_length;\n\n /*\n * check if this quantization is better than our saved\n * quantization\n */\n if (cod_info.block_type != Encoder.SHORT_TYPE) {\n // NORM, START or STOP type\n better = gfp.quant_comp;\n } else\n better = gfp.quant_comp_short;\n\n better = quant_compare(better, best_noise_info, noise_info,\n cod_info_w, distort) ? 1 : 0;\n\n /* save data so we can restore this quantization later */\n if (better != 0) {\n best_part2_3_length = cod_info.part2_3_length;\n best_noise_info = noise_info;\n cod_info.assign(cod_info_w);\n age = 0;\n /* save data so we can restore this quantization later */\n /* store for later reuse */\n System.arraycopy(xrpow, 0, save_xrpow, 0, 576);\n } else {\n /* early stop? */\n if (gfc.full_outer_loop == 0) {\n if (++age > search_limit\n && best_noise_info.over_count == 0)\n break;\n if ((gfc.noise_shaping_amp == 3) && bRefine && age > 30)\n break;\n if ((gfc.noise_shaping_amp == 3)\n && bRefine\n && (cod_info_w.global_gain - best_ggain_pass1) > 15)\n break;\n }\n }\n } while ((cod_info_w.global_gain + cod_info_w.scalefac_scale) < 255);\n\n if (gfc.noise_shaping_amp == 3) {\n if (!bRefine) {\n /* refine search */\n cod_info_w.assign(cod_info);\n System.arraycopy(save_xrpow, 0, xrpow, 0, 576);\n age = 0;\n best_ggain_pass1 = cod_info_w.global_gain;\n\n bRefine = true;\n } else {\n /* search already refined, stop */\n bEndOfSearch = true;\n }\n\n } else {\n bEndOfSearch = true;\n }\n }\n\n /*\n * finish up\n */\n if (gfp.VBR == VbrMode.vbr_rh || gfp.VBR == VbrMode.vbr_mtrh)\n /* restore for reuse on next try */\n System.arraycopy(save_xrpow, 0, xrpow, 0, 576);\n /*\n * do the 'substep shaping'\n */\n else if ((gfc.substep_shaping & 1) != 0)\n trancate_smallspectrums(gfc, cod_info, l3_xmin, xrpow);\n\n return best_noise_info.over_count;\n }\n\n /**\n * Robert Hegemann 2000-09-06\n *\n * update reservoir status after FINAL quantization/bitrate\n */\n this.iteration_finish_one = function (gfc, gr, ch) {\n var l3_side = gfc.l3_side;\n var cod_info = l3_side.tt[gr][ch];\n\n /*\n * try some better scalefac storage\n */\n tk.best_scalefac_store(gfc, gr, ch, l3_side);\n\n /*\n * best huffman_divide may save some bits too\n */\n if (gfc.use_best_huffman == 1)\n tk.best_huffman_divide(gfc, cod_info);\n\n /*\n * update reservoir status after FINAL quantization/bitrate\n */\n rv.ResvAdjust(gfc, cod_info);\n };\n\n /**\n *\n * 2000-09-04 Robert Hegemann\n *\n * @param l3_xmin\n * allowed distortion of the scalefactor\n * @param xrpow\n * coloured magnitudes of spectral values\n */\n this.VBR_encode_granule = function (gfp, cod_info, l3_xmin, xrpow, ch, min_bits, max_bits) {\n var gfc = gfp.internal_flags;\n var bst_cod_info = new GrInfo();\n var bst_xrpow = new_float(576);\n var Max_bits = max_bits;\n var real_bits = max_bits + 1;\n var this_bits = (max_bits + min_bits) / 2;\n var dbits, over, found = 0;\n var sfb21_extra = gfc.sfb21_extra;\n\n Arrays.fill(bst_cod_info.l3_enc, 0);\n\n /*\n * search within round about 40 bits of optimal\n */\n do {\n\n if (this_bits > Max_bits - 42)\n gfc.sfb21_extra = false;\n else\n gfc.sfb21_extra = sfb21_extra;\n\n over = outer_loop(gfp, cod_info, l3_xmin, xrpow, ch, this_bits);\n\n /*\n * is quantization as good as we are looking for ? in this case: is\n * no scalefactor band distorted?\n */\n if (over <= 0) {\n found = 1;\n /*\n * now we know it can be done with \"real_bits\" and maybe we can\n * skip some iterations\n */\n real_bits = cod_info.part2_3_length;\n\n /*\n * store best quantization so far\n */\n bst_cod_info.assign(cod_info);\n System.arraycopy(xrpow, 0, bst_xrpow, 0, 576);\n\n /*\n * try with fewer bits\n */\n max_bits = real_bits - 32;\n dbits = max_bits - min_bits;\n this_bits = (max_bits + min_bits) / 2;\n } else {\n /*\n * try with more bits\n */\n min_bits = this_bits + 32;\n dbits = max_bits - min_bits;\n this_bits = (max_bits + min_bits) / 2;\n\n if (found != 0) {\n found = 2;\n /*\n * start again with best quantization so far\n */\n cod_info.assign(bst_cod_info);\n System.arraycopy(bst_xrpow, 0, xrpow, 0, 576);\n }\n }\n } while (dbits > 12);\n\n gfc.sfb21_extra = sfb21_extra;\n\n /*\n * found=0 => nothing found, use last one found=1 => we just found the\n * best and left the loop found=2 => we restored a good one and have now\n * l3_enc to restore too\n */\n if (found == 2) {\n System.arraycopy(bst_cod_info.l3_enc, 0, cod_info.l3_enc, 0, 576);\n }\n }\n\n /**\n * Robert Hegemann 2000-09-05\n *\n * calculates * how many bits are available for analog silent granules * how\n * many bits to use for the lowest allowed bitrate * how many bits each\n * bitrate would provide\n */\n this.get_framebits = function (gfp, frameBits) {\n var gfc = gfp.internal_flags;\n\n /*\n * always use at least this many bits per granule per channel unless we\n * detect analog silence, see below\n */\n gfc.bitrate_index = gfc.VBR_min_bitrate;\n var bitsPerFrame = bs.getframebits(gfp);\n\n /*\n * bits for analog silence\n */\n gfc.bitrate_index = 1;\n bitsPerFrame = bs.getframebits(gfp);\n\n for (var i = 1; i <= gfc.VBR_max_bitrate; i++) {\n gfc.bitrate_index = i;\n var mb = new MeanBits(bitsPerFrame);\n frameBits[i] = rv.ResvFrameBegin(gfp, mb);\n bitsPerFrame = mb.bits;\n }\n };\n\n /* RH: this one needs to be overhauled sometime */\n\n /**\n * <PRE>\n * 2000-09-04 Robert Hegemann\n *\n * * converts LR to MS coding when necessary\n * * calculates allowed/adjusted quantization noise amounts\n * * detects analog silent frames\n *\n * some remarks:\n * - lower masking depending on Quality setting\n * - quality control together with adjusted ATH MDCT scaling\n * on lower quality setting allocate more noise from\n * ATH masking, and on higher quality setting allocate\n * less noise from ATH masking.\n * - experiments show that going more than 2dB over GPSYCHO's\n * limits ends up in very annoying artefacts\n * </PRE>\n */\n this.VBR_old_prepare = function (gfp, pe, ms_ener_ratio, ratio, l3_xmin, frameBits, min_bits,\n max_bits, bands) {\n var gfc = gfp.internal_flags;\n\n var masking_lower_db, adjust = 0.0;\n var analog_silence = 1;\n var bits = 0;\n\n gfc.bitrate_index = gfc.VBR_max_bitrate;\n var avg = rv.ResvFrameBegin(gfp, new MeanBits(0)) / gfc.mode_gr;\n\n get_framebits(gfp, frameBits);\n\n for (var gr = 0; gr < gfc.mode_gr; gr++) {\n var mxb = qupvt.on_pe(gfp, pe, max_bits[gr], avg, gr, 0);\n if (gfc.mode_ext == Encoder.MPG_MD_MS_LR) {\n ms_convert(gfc.l3_side, gr);\n qupvt.reduce_side(max_bits[gr], ms_ener_ratio[gr], avg, mxb);\n }\n for (var ch = 0; ch < gfc.channels_out; ++ch) {\n var cod_info = gfc.l3_side.tt[gr][ch];\n\n if (cod_info.block_type != Encoder.SHORT_TYPE) {\n // NORM, START or STOP type\n adjust = 1.28 / (1 + Math\n .exp(3.5 - pe[gr][ch] / 300.)) - 0.05;\n masking_lower_db = gfc.PSY.mask_adjust - adjust;\n } else {\n adjust = 2.56 / (1 + Math\n .exp(3.5 - pe[gr][ch] / 300.)) - 0.14;\n masking_lower_db = gfc.PSY.mask_adjust_short - adjust;\n }\n gfc.masking_lower = Math.pow(10.0,\n masking_lower_db * 0.1);\n\n init_outer_loop(gfc, cod_info);\n bands[gr][ch] = qupvt.calc_xmin(gfp, ratio[gr][ch], cod_info,\n l3_xmin[gr][ch]);\n if (bands[gr][ch] != 0)\n analog_silence = 0;\n\n min_bits[gr][ch] = 126;\n\n bits += max_bits[gr][ch];\n }\n }\n for (var gr = 0; gr < gfc.mode_gr; gr++) {\n for (var ch = 0; ch < gfc.channels_out; ch++) {\n if (bits > frameBits[gfc.VBR_max_bitrate]) {\n max_bits[gr][ch] *= frameBits[gfc.VBR_max_bitrate];\n max_bits[gr][ch] /= bits;\n }\n if (min_bits[gr][ch] > max_bits[gr][ch])\n min_bits[gr][ch] = max_bits[gr][ch];\n\n }\n /* for ch */\n }\n /* for gr */\n\n return analog_silence;\n };\n\n this.bitpressure_strategy = function (gfc, l3_xmin, min_bits, max_bits) {\n for (var gr = 0; gr < gfc.mode_gr; gr++) {\n for (var ch = 0; ch < gfc.channels_out; ch++) {\n var gi = gfc.l3_side.tt[gr][ch];\n var pxmin = l3_xmin[gr][ch];\n var pxminPos = 0;\n for (var sfb = 0; sfb < gi.psy_lmax; sfb++)\n pxmin[pxminPos++] *= 1. + .029 * sfb * sfb\n / Encoder.SBMAX_l / Encoder.SBMAX_l;\n\n if (gi.block_type == Encoder.SHORT_TYPE) {\n for (var sfb = gi.sfb_smin; sfb < Encoder.SBMAX_s; sfb++) {\n pxmin[pxminPos++] *= 1. + .029 * sfb * sfb\n / Encoder.SBMAX_s / Encoder.SBMAX_s;\n pxmin[pxminPos++] *= 1. + .029 * sfb * sfb\n / Encoder.SBMAX_s / Encoder.SBMAX_s;\n pxmin[pxminPos++] *= 1. + .029 * sfb * sfb\n / Encoder.SBMAX_s / Encoder.SBMAX_s;\n }\n }\n max_bits[gr][ch] = 0 | Math.max(min_bits[gr][ch],\n 0.9 * max_bits[gr][ch]);\n }\n }\n };\n\n this.VBR_new_prepare = function (gfp, pe, ratio, l3_xmin, frameBits, max_bits) {\n var gfc = gfp.internal_flags;\n\n var analog_silence = 1;\n var avg = 0, bits = 0;\n var maximum_framebits;\n\n if (!gfp.free_format) {\n gfc.bitrate_index = gfc.VBR_max_bitrate;\n\n var mb = new MeanBits(avg);\n rv.ResvFrameBegin(gfp, mb);\n avg = mb.bits;\n\n get_framebits(gfp, frameBits);\n maximum_framebits = frameBits[gfc.VBR_max_bitrate];\n } else {\n gfc.bitrate_index = 0;\n var mb = new MeanBits(avg);\n maximum_framebits = rv.ResvFrameBegin(gfp, mb);\n avg = mb.bits;\n frameBits[0] = maximum_framebits;\n }\n\n for (var gr = 0; gr < gfc.mode_gr; gr++) {\n qupvt.on_pe(gfp, pe, max_bits[gr], avg, gr, 0);\n if (gfc.mode_ext == Encoder.MPG_MD_MS_LR) {\n ms_convert(gfc.l3_side, gr);\n }\n for (var ch = 0; ch < gfc.channels_out; ++ch) {\n var cod_info = gfc.l3_side.tt[gr][ch];\n\n gfc.masking_lower = Math.pow(10.0,\n gfc.PSY.mask_adjust * 0.1);\n\n init_outer_loop(gfc, cod_info);\n if (0 != qupvt.calc_xmin(gfp, ratio[gr][ch], cod_info,\n l3_xmin[gr][ch]))\n analog_silence = 0;\n\n bits += max_bits[gr][ch];\n }\n }\n for (var gr = 0; gr < gfc.mode_gr; gr++) {\n for (var ch = 0; ch < gfc.channels_out; ch++) {\n if (bits > maximum_framebits) {\n max_bits[gr][ch] *= maximum_framebits;\n max_bits[gr][ch] /= bits;\n }\n\n }\n /* for ch */\n }\n /* for gr */\n\n return analog_silence;\n };\n\n /**\n * calculates target bits for ABR encoding\n *\n * mt 2000/05/31\n */\n this.calc_target_bits = function (gfp, pe, ms_ener_ratio, targ_bits, analog_silence_bits, max_frame_bits) {\n var gfc = gfp.internal_flags;\n var l3_side = gfc.l3_side;\n var res_factor;\n var gr, ch, totbits, mean_bits = 0;\n\n gfc.bitrate_index = gfc.VBR_max_bitrate;\n var mb = new MeanBits(mean_bits);\n max_frame_bits[0] = rv.ResvFrameBegin(gfp, mb);\n mean_bits = mb.bits;\n\n gfc.bitrate_index = 1;\n mean_bits = bs.getframebits(gfp) - gfc.sideinfo_len * 8;\n analog_silence_bits[0] = mean_bits / (gfc.mode_gr * gfc.channels_out);\n\n mean_bits = gfp.VBR_mean_bitrate_kbps * gfp.framesize * 1000;\n if ((gfc.substep_shaping & 1) != 0)\n mean_bits *= 1.09;\n mean_bits /= gfp.out_samplerate;\n mean_bits -= gfc.sideinfo_len * 8;\n mean_bits /= (gfc.mode_gr * gfc.channels_out);\n\n /**\n * <PRE>\n * res_factor is the percentage of the target bitrate that should\n * be used on average. the remaining bits are added to the\n * bitreservoir and used for difficult to encode frames.\n *\n * Since we are tracking the average bitrate, we should adjust\n * res_factor \"on the fly\", increasing it if the average bitrate\n * is greater than the requested bitrate, and decreasing it\n * otherwise. Reasonable ranges are from .9 to 1.0\n *\n * Until we get the above suggestion working, we use the following\n * tuning:\n * compression ratio res_factor\n * 5.5 (256kbps) 1.0 no need for bitreservoir\n * 11 (128kbps) .93 7% held for reservoir\n *\n * with linear interpolation for other values.\n * </PRE>\n */\n res_factor = .93 + .07 * (11.0 - gfp.compression_ratio)\n / (11.0 - 5.5);\n if (res_factor < .90)\n res_factor = .90;\n if (res_factor > 1.00)\n res_factor = 1.00;\n\n for (gr = 0; gr < gfc.mode_gr; gr++) {\n var sum = 0;\n for (ch = 0; ch < gfc.channels_out; ch++) {\n targ_bits[gr][ch] = (int)(res_factor * mean_bits);\n\n if (pe[gr][ch] > 700) {\n var add_bits = (int)((pe[gr][ch] - 700) / 1.4);\n\n var cod_info = l3_side.tt[gr][ch];\n targ_bits[gr][ch] = (int)(res_factor * mean_bits);\n\n /* short blocks use a little extra, no matter what the pe */\n if (cod_info.block_type == Encoder.SHORT_TYPE) {\n if (add_bits < mean_bits / 2)\n add_bits = mean_bits / 2;\n }\n /* at most increase bits by 1.5*average */\n if (add_bits > mean_bits * 3 / 2)\n add_bits = mean_bits * 3 / 2;\n else if (add_bits < 0)\n add_bits = 0;\n\n targ_bits[gr][ch] += add_bits;\n }\n if (targ_bits[gr][ch] > LameInternalFlags.MAX_BITS_PER_CHANNEL) {\n targ_bits[gr][ch] = LameInternalFlags.MAX_BITS_PER_CHANNEL;\n }\n sum += targ_bits[gr][ch];\n }\n /* for ch */\n if (sum > LameInternalFlags.MAX_BITS_PER_GRANULE) {\n for (ch = 0; ch < gfc.channels_out; ++ch) {\n targ_bits[gr][ch] *= LameInternalFlags.MAX_BITS_PER_GRANULE;\n targ_bits[gr][ch] /= sum;\n }\n }\n }\n /* for gr */\n\n if (gfc.mode_ext == Encoder.MPG_MD_MS_LR)\n for (gr = 0; gr < gfc.mode_gr; gr++) {\n qupvt.reduce_side(targ_bits[gr], ms_ener_ratio[gr], mean_bits\n * gfc.channels_out,\n LameInternalFlags.MAX_BITS_PER_GRANULE);\n }\n\n /*\n * sum target bits\n */\n totbits = 0;\n for (gr = 0; gr < gfc.mode_gr; gr++) {\n for (ch = 0; ch < gfc.channels_out; ch++) {\n if (targ_bits[gr][ch] > LameInternalFlags.MAX_BITS_PER_CHANNEL)\n targ_bits[gr][ch] = LameInternalFlags.MAX_BITS_PER_CHANNEL;\n totbits += targ_bits[gr][ch];\n }\n }\n\n /*\n * repartion target bits if needed\n */\n if (totbits > max_frame_bits[0]) {\n for (gr = 0; gr < gfc.mode_gr; gr++) {\n for (ch = 0; ch < gfc.channels_out; ch++) {\n targ_bits[gr][ch] *= max_frame_bits[0];\n targ_bits[gr][ch] /= totbits;\n }\n }\n }\n }\n\n}",
"function Quantize() {\n var bs;\n this.rv = null;\n var rv;\n this.qupvt = null;\n var qupvt;\n\n var vbr = new VBRQuantize();\n var tk;\n\n this.setModules = function (_bs, _rv, _qupvt, _tk) {\n bs = _bs;\n rv = _rv;\n this.rv = _rv;\n qupvt = _qupvt;\n this.qupvt = _qupvt;\n tk = _tk;\n vbr.setModules(qupvt, tk);\n }\n\n /**\n * convert from L/R <. Mid/Side\n */\n this.ms_convert = function (l3_side, gr) {\n for (var i = 0; i < 576; ++i) {\n var l = l3_side.tt[gr][0].xr[i];\n var r = l3_side.tt[gr][1].xr[i];\n l3_side.tt[gr][0].xr[i] = (l + r) * (Util.SQRT2 * 0.5);\n l3_side.tt[gr][1].xr[i] = (l - r) * (Util.SQRT2 * 0.5);\n }\n };\n\n /**\n * mt 6/99\n *\n * initializes cod_info, scalefac and xrpow\n *\n * returns 0 if all energies in xr are zero, else 1\n */\n function init_xrpow_core(cod_info, xrpow, upper, sum) {\n sum = 0;\n for (var i = 0; i <= upper; ++i) {\n var tmp = Math.abs(cod_info.xr[i]);\n sum += tmp;\n xrpow[i] = Math.sqrt(tmp * Math.sqrt(tmp));\n\n if (xrpow[i] > cod_info.xrpow_max)\n cod_info.xrpow_max = xrpow[i];\n }\n return sum;\n }\n\n this.init_xrpow = function (gfc, cod_info, xrpow) {\n var sum = 0;\n var upper = 0 | cod_info.max_nonzero_coeff;\n\n cod_info.xrpow_max = 0;\n\n /*\n * check if there is some energy we have to quantize and calculate xrpow\n * matching our fresh scalefactors\n */\n\n Arrays.fill(xrpow, upper, 576, 0);\n\n sum = init_xrpow_core(cod_info, xrpow, upper, sum);\n\n /*\n * return 1 if we have something to quantize, else 0\n */\n if (sum > 1E-20) {\n var j = 0;\n if ((gfc.substep_shaping & 2) != 0)\n j = 1;\n\n for (var i = 0; i < cod_info.psymax; i++)\n gfc.pseudohalf[i] = j;\n\n return true;\n }\n\n Arrays.fill(cod_info.l3_enc, 0, 576, 0);\n return false;\n }\n\n /**\n * Gabriel Bouvigne feb/apr 2003<BR>\n * Analog silence detection in partitionned sfb21 or sfb12 for short blocks\n *\n * From top to bottom of sfb, changes to 0 coeffs which are below ath. It\n * stops on the first coeff higher than ath.\n */\n function psfb21_analogsilence(gfc, cod_info) {\n var ath = gfc.ATH;\n var xr = cod_info.xr;\n\n if (cod_info.block_type != Encoder.SHORT_TYPE) {\n /* NORM, START or STOP type, but not SHORT blocks */\n var stop = false;\n for (var gsfb = Encoder.PSFB21 - 1; gsfb >= 0 && !stop; gsfb--) {\n var start = gfc.scalefac_band.psfb21[gsfb];\n var end = gfc.scalefac_band.psfb21[gsfb + 1];\n var ath21 = qupvt.athAdjust(ath.adjust, ath.psfb21[gsfb],\n ath.floor);\n\n if (gfc.nsPsy.longfact[21] > 1e-12)\n ath21 *= gfc.nsPsy.longfact[21];\n\n for (var j = end - 1; j >= start; j--) {\n if (Math.abs(xr[j]) < ath21)\n xr[j] = 0;\n else {\n stop = true;\n break;\n }\n }\n }\n } else {\n /* note: short blocks coeffs are reordered */\n for (var block = 0; block < 3; block++) {\n var stop = false;\n for (var gsfb = Encoder.PSFB12 - 1; gsfb >= 0 && !stop; gsfb--) {\n var start = gfc.scalefac_band.s[12]\n * 3\n + (gfc.scalefac_band.s[13] - gfc.scalefac_band.s[12])\n * block\n + (gfc.scalefac_band.psfb12[gsfb] - gfc.scalefac_band.psfb12[0]);\n var end = start\n + (gfc.scalefac_band.psfb12[gsfb + 1] - gfc.scalefac_band.psfb12[gsfb]);\n var ath12 = qupvt.athAdjust(ath.adjust, ath.psfb12[gsfb],\n ath.floor);\n\n if (gfc.nsPsy.shortfact[12] > 1e-12)\n ath12 *= gfc.nsPsy.shortfact[12];\n\n for (var j = end - 1; j >= start; j--) {\n if (Math.abs(xr[j]) < ath12)\n xr[j] = 0;\n else {\n stop = true;\n break;\n }\n }\n }\n }\n }\n\n }\n\n this.init_outer_loop = function (gfc, cod_info) {\n /*\n * initialize fresh cod_info\n */\n cod_info.part2_3_length = 0;\n cod_info.big_values = 0;\n cod_info.count1 = 0;\n cod_info.global_gain = 210;\n cod_info.scalefac_compress = 0;\n /* mixed_block_flag, block_type was set in psymodel.c */\n cod_info.table_select[0] = 0;\n cod_info.table_select[1] = 0;\n cod_info.table_select[2] = 0;\n cod_info.subblock_gain[0] = 0;\n cod_info.subblock_gain[1] = 0;\n cod_info.subblock_gain[2] = 0;\n cod_info.subblock_gain[3] = 0;\n /* this one is always 0 */\n cod_info.region0_count = 0;\n cod_info.region1_count = 0;\n cod_info.preflag = 0;\n cod_info.scalefac_scale = 0;\n cod_info.count1table_select = 0;\n cod_info.part2_length = 0;\n cod_info.sfb_lmax = Encoder.SBPSY_l;\n cod_info.sfb_smin = Encoder.SBPSY_s;\n cod_info.psy_lmax = gfc.sfb21_extra ? Encoder.SBMAX_l : Encoder.SBPSY_l;\n cod_info.psymax = cod_info.psy_lmax;\n cod_info.sfbmax = cod_info.sfb_lmax;\n cod_info.sfbdivide = 11;\n for (var sfb = 0; sfb < Encoder.SBMAX_l; sfb++) {\n cod_info.width[sfb] = gfc.scalefac_band.l[sfb + 1]\n - gfc.scalefac_band.l[sfb];\n /* which is always 0. */\n cod_info.window[sfb] = 3;\n }\n if (cod_info.block_type == Encoder.SHORT_TYPE) {\n var ixwork = new_float(576);\n\n cod_info.sfb_smin = 0;\n cod_info.sfb_lmax = 0;\n if (cod_info.mixed_block_flag != 0) {\n /*\n * MPEG-1: sfbs 0-7 long block, 3-12 short blocks MPEG-2(.5):\n * sfbs 0-5 long block, 3-12 short blocks\n */\n cod_info.sfb_smin = 3;\n cod_info.sfb_lmax = gfc.mode_gr * 2 + 4;\n }\n cod_info.psymax = cod_info.sfb_lmax\n + 3\n * ((gfc.sfb21_extra ? Encoder.SBMAX_s : Encoder.SBPSY_s) - cod_info.sfb_smin);\n cod_info.sfbmax = cod_info.sfb_lmax + 3\n * (Encoder.SBPSY_s - cod_info.sfb_smin);\n cod_info.sfbdivide = cod_info.sfbmax - 18;\n cod_info.psy_lmax = cod_info.sfb_lmax;\n /* re-order the short blocks, for more efficient encoding below */\n /* By Takehiro TOMINAGA */\n /*\n * Within each scalefactor band, data is given for successive time\n * windows, beginning with window 0 and ending with window 2. Within\n * each window, the quantized values are then arranged in order of\n * increasing frequency...\n */\n var ix = gfc.scalefac_band.l[cod_info.sfb_lmax];\n System.arraycopy(cod_info.xr, 0, ixwork, 0, 576);\n for (var sfb = cod_info.sfb_smin; sfb < Encoder.SBMAX_s; sfb++) {\n var start = gfc.scalefac_band.s[sfb];\n var end = gfc.scalefac_band.s[sfb + 1];\n for (var window = 0; window < 3; window++) {\n for (var l = start; l < end; l++) {\n cod_info.xr[ix++] = ixwork[3 * l + window];\n }\n }\n }\n\n var j = cod_info.sfb_lmax;\n for (var sfb = cod_info.sfb_smin; sfb < Encoder.SBMAX_s; sfb++) {\n cod_info.width[j] = cod_info.width[j + 1] = cod_info.width[j + 2] = gfc.scalefac_band.s[sfb + 1]\n - gfc.scalefac_band.s[sfb];\n cod_info.window[j] = 0;\n cod_info.window[j + 1] = 1;\n cod_info.window[j + 2] = 2;\n j += 3;\n }\n }\n\n cod_info.count1bits = 0;\n cod_info.sfb_partition_table = qupvt.nr_of_sfb_block[0][0];\n cod_info.slen[0] = 0;\n cod_info.slen[1] = 0;\n cod_info.slen[2] = 0;\n cod_info.slen[3] = 0;\n\n cod_info.max_nonzero_coeff = 575;\n\n /*\n * fresh scalefactors are all zero\n */\n Arrays.fill(cod_info.scalefac, 0);\n\n psfb21_analogsilence(gfc, cod_info);\n };\n\n function BinSearchDirection(ordinal) {\n this.ordinal = ordinal;\n }\n\n BinSearchDirection.BINSEARCH_NONE = new BinSearchDirection(0);\n BinSearchDirection.BINSEARCH_UP = new BinSearchDirection(1);\n BinSearchDirection.BINSEARCH_DOWN = new BinSearchDirection(2);\n\n /**\n * author/date??\n *\n * binary step size search used by outer_loop to get a quantizer step size\n * to start with\n */\n function bin_search_StepSize(gfc, cod_info, desired_rate, ch, xrpow) {\n var nBits;\n var CurrentStep = gfc.CurrentStep[ch];\n var flagGoneOver = false;\n var start = gfc.OldValue[ch];\n var Direction = BinSearchDirection.BINSEARCH_NONE;\n cod_info.global_gain = start;\n desired_rate -= cod_info.part2_length;\n\n for (; ;) {\n var step;\n nBits = tk.count_bits(gfc, xrpow, cod_info, null);\n\n if (CurrentStep == 1 || nBits == desired_rate)\n break;\n /* nothing to adjust anymore */\n\n if (nBits > desired_rate) {\n /* increase Quantize_StepSize */\n if (Direction == BinSearchDirection.BINSEARCH_DOWN)\n flagGoneOver = true;\n\n if (flagGoneOver)\n CurrentStep /= 2;\n Direction = BinSearchDirection.BINSEARCH_UP;\n step = CurrentStep;\n } else {\n /* decrease Quantize_StepSize */\n if (Direction == BinSearchDirection.BINSEARCH_UP)\n flagGoneOver = true;\n\n if (flagGoneOver)\n CurrentStep /= 2;\n Direction = BinSearchDirection.BINSEARCH_DOWN;\n step = -CurrentStep;\n }\n cod_info.global_gain += step;\n if (cod_info.global_gain < 0) {\n cod_info.global_gain = 0;\n flagGoneOver = true;\n }\n if (cod_info.global_gain > 255) {\n cod_info.global_gain = 255;\n flagGoneOver = true;\n }\n }\n\n\n while (nBits > desired_rate && cod_info.global_gain < 255) {\n cod_info.global_gain++;\n nBits = tk.count_bits(gfc, xrpow, cod_info, null);\n }\n gfc.CurrentStep[ch] = (start - cod_info.global_gain >= 4) ? 4 : 2;\n gfc.OldValue[ch] = cod_info.global_gain;\n cod_info.part2_3_length = nBits;\n return nBits;\n }\n\n this.trancate_smallspectrums = function (gfc, gi, l3_xmin, work) {\n var distort = new_float(L3Side.SFBMAX);\n\n if ((0 == (gfc.substep_shaping & 4) && gi.block_type == Encoder.SHORT_TYPE)\n || (gfc.substep_shaping & 0x80) != 0)\n return;\n qupvt.calc_noise(gi, l3_xmin, distort, new CalcNoiseResult(), null);\n for (var j = 0; j < 576; j++) {\n var xr = 0.0;\n if (gi.l3_enc[j] != 0)\n xr = Math.abs(gi.xr[j]);\n work[j] = xr;\n }\n\n var j = 0;\n var sfb = 8;\n if (gi.block_type == Encoder.SHORT_TYPE)\n sfb = 6;\n do {\n var allowedNoise, trancateThreshold;\n var nsame, start;\n\n var width = gi.width[sfb];\n j += width;\n if (distort[sfb] >= 1.0)\n continue;\n\n Arrays.sort(work, j - width, width);\n if (BitStream.EQ(work[j - 1], 0.0))\n continue;\n /* all zero sfb */\n\n allowedNoise = (1.0 - distort[sfb]) * l3_xmin[sfb];\n trancateThreshold = 0.0;\n start = 0;\n do {\n var noise;\n for (nsame = 1; start + nsame < width; nsame++)\n if (BitStream.NEQ(work[start + j - width], work[start + j\n + nsame - width]))\n break;\n\n noise = work[start + j - width] * work[start + j - width]\n * nsame;\n if (allowedNoise < noise) {\n if (start != 0)\n trancateThreshold = work[start + j - width - 1];\n break;\n }\n allowedNoise -= noise;\n start += nsame;\n } while (start < width);\n if (BitStream.EQ(trancateThreshold, 0.0))\n continue;\n\n do {\n if (Math.abs(gi.xr[j - width]) <= trancateThreshold)\n gi.l3_enc[j - width] = 0;\n } while (--width > 0);\n } while (++sfb < gi.psymax);\n\n gi.part2_3_length = tk.noquant_count_bits(gfc, gi, null);\n };\n\n /**\n * author/date??\n *\n * Function: Returns zero if there is a scalefac which has not been\n * amplified. Otherwise it returns one.\n */\n function loop_break(cod_info) {\n for (var sfb = 0; sfb < cod_info.sfbmax; sfb++)\n if (cod_info.scalefac[sfb]\n + cod_info.subblock_gain[cod_info.window[sfb]] == 0)\n return false;\n\n return true;\n }\n\n /* mt 5/99: Function: Improved calc_noise for a single channel */\n\n function penalties(noise) {\n return Util.FAST_LOG10((0.368 + 0.632 * noise * noise * noise));\n }\n\n /**\n * author/date??\n *\n * several different codes to decide which quantization is better\n */\n function get_klemm_noise(distort, gi) {\n var klemm_noise = 1E-37;\n for (var sfb = 0; sfb < gi.psymax; sfb++)\n klemm_noise += penalties(distort[sfb]);\n\n return Math.max(1e-20, klemm_noise);\n }\n\n function quant_compare(quant_comp, best, calc, gi, distort) {\n /**\n * noise is given in decibels (dB) relative to masking thesholds.<BR>\n *\n * over_noise: ??? (the previous comment is fully wrong)<BR>\n * tot_noise: ??? (the previous comment is fully wrong)<BR>\n * max_noise: max quantization noise\n */\n var better;\n\n switch (quant_comp) {\n default:\n case 9:\n {\n if (best.over_count > 0) {\n /* there are distorted sfb */\n better = calc.over_SSD <= best.over_SSD;\n if (calc.over_SSD == best.over_SSD)\n better = calc.bits < best.bits;\n } else {\n /* no distorted sfb */\n better = ((calc.max_noise < 0) && ((calc.max_noise * 10 + calc.bits) <= (best.max_noise * 10 + best.bits)));\n }\n break;\n }\n\n case 0:\n better = calc.over_count < best.over_count\n || (calc.over_count == best.over_count && calc.over_noise < best.over_noise)\n || (calc.over_count == best.over_count\n && BitStream.EQ(calc.over_noise, best.over_noise) && calc.tot_noise < best.tot_noise);\n break;\n\n case 8:\n calc.max_noise = get_klemm_noise(distort, gi);\n //$FALL-THROUGH$\n case 1:\n better = calc.max_noise < best.max_noise;\n break;\n case 2:\n better = calc.tot_noise < best.tot_noise;\n break;\n case 3:\n better = (calc.tot_noise < best.tot_noise)\n && (calc.max_noise < best.max_noise);\n break;\n case 4:\n better = (calc.max_noise <= 0.0 && best.max_noise > 0.2)\n || (calc.max_noise <= 0.0 && best.max_noise < 0.0\n && best.max_noise > calc.max_noise - 0.2 && calc.tot_noise < best.tot_noise)\n || (calc.max_noise <= 0.0 && best.max_noise > 0.0\n && best.max_noise > calc.max_noise - 0.2 && calc.tot_noise < best.tot_noise\n + best.over_noise)\n || (calc.max_noise > 0.0 && best.max_noise > -0.05\n && best.max_noise > calc.max_noise - 0.1 && calc.tot_noise\n + calc.over_noise < best.tot_noise\n + best.over_noise)\n || (calc.max_noise > 0.0 && best.max_noise > -0.1\n && best.max_noise > calc.max_noise - 0.15 && calc.tot_noise\n + calc.over_noise + calc.over_noise < best.tot_noise\n + best.over_noise + best.over_noise);\n break;\n case 5:\n better = calc.over_noise < best.over_noise\n || (BitStream.EQ(calc.over_noise, best.over_noise) && calc.tot_noise < best.tot_noise);\n break;\n case 6:\n better = calc.over_noise < best.over_noise\n || (BitStream.EQ(calc.over_noise, best.over_noise) && (calc.max_noise < best.max_noise || (BitStream\n .EQ(calc.max_noise, best.max_noise) && calc.tot_noise <= best.tot_noise)));\n break;\n case 7:\n better = calc.over_count < best.over_count\n || calc.over_noise < best.over_noise;\n break;\n }\n\n if (best.over_count == 0) {\n /*\n * If no distorted bands, only use this quantization if it is\n * better, and if it uses less bits. Unfortunately, part2_3_length\n * is sometimes a poor estimator of the final size at low bitrates.\n */\n better = better && calc.bits < best.bits;\n }\n\n return better;\n }\n\n /**\n * author/date??\n *\n * <PRE>\n * Amplify the scalefactor bands that violate the masking threshold.\n * See ISO 11172-3 Section C.1.5.4.3.5\n *\n * distort[] = noise/masking\n * distort[] > 1 ==> noise is not masked\n * distort[] < 1 ==> noise is masked\n * max_dist = maximum value of distort[]\n *\n * Three algorithms:\n * noise_shaping_amp\n * 0 Amplify all bands with distort[]>1.\n *\n * 1 Amplify all bands with distort[] >= max_dist^(.5);\n * ( 50% in the db scale)\n *\n * 2 Amplify first band with distort[] >= max_dist;\n *\n *\n * For algorithms 0 and 1, if max_dist < 1, then amplify all bands\n * with distort[] >= .95*max_dist. This is to make sure we always\n * amplify at least one band.\n * </PRE>\n */\n function amp_scalefac_bands(gfp, cod_info, distort, xrpow, bRefine) {\n var gfc = gfp.internal_flags;\n var ifqstep34;\n\n if (cod_info.scalefac_scale == 0) {\n ifqstep34 = 1.29683955465100964055;\n /* 2**(.75*.5) */\n } else {\n ifqstep34 = 1.68179283050742922612;\n /* 2**(.75*1) */\n }\n\n /* compute maximum value of distort[] */\n var trigger = 0;\n for (var sfb = 0; sfb < cod_info.sfbmax; sfb++) {\n if (trigger < distort[sfb])\n trigger = distort[sfb];\n }\n\n var noise_shaping_amp = gfc.noise_shaping_amp;\n if (noise_shaping_amp == 3) {\n if (bRefine)\n noise_shaping_amp = 2;\n else\n noise_shaping_amp = 1;\n }\n switch (noise_shaping_amp) {\n case 2:\n /* amplify exactly 1 band */\n break;\n\n case 1:\n /* amplify bands within 50% of max (on db scale) */\n if (trigger > 1.0)\n trigger = Math.pow(trigger, .5);\n else\n trigger *= .95;\n break;\n\n case 0:\n default:\n /* ISO algorithm. amplify all bands with distort>1 */\n if (trigger > 1.0)\n trigger = 1.0;\n else\n trigger *= .95;\n break;\n }\n\n var j = 0;\n for (var sfb = 0; sfb < cod_info.sfbmax; sfb++) {\n var width = cod_info.width[sfb];\n var l;\n j += width;\n if (distort[sfb] < trigger)\n continue;\n\n if ((gfc.substep_shaping & 2) != 0) {\n gfc.pseudohalf[sfb] = (0 == gfc.pseudohalf[sfb]) ? 1 : 0;\n if (0 == gfc.pseudohalf[sfb] && gfc.noise_shaping_amp == 2)\n return;\n }\n cod_info.scalefac[sfb]++;\n for (l = -width; l < 0; l++) {\n xrpow[j + l] *= ifqstep34;\n if (xrpow[j + l] > cod_info.xrpow_max)\n cod_info.xrpow_max = xrpow[j + l];\n }\n\n if (gfc.noise_shaping_amp == 2)\n return;\n }\n }\n\n /**\n * Takehiro Tominaga 2000-xx-xx\n *\n * turns on scalefac scale and adjusts scalefactors\n */\n function inc_scalefac_scale(cod_info, xrpow) {\n var ifqstep34 = 1.29683955465100964055;\n\n var j = 0;\n for (var sfb = 0; sfb < cod_info.sfbmax; sfb++) {\n var width = cod_info.width[sfb];\n var s = cod_info.scalefac[sfb];\n if (cod_info.preflag != 0)\n s += qupvt.pretab[sfb];\n j += width;\n if ((s & 1) != 0) {\n s++;\n for (var l = -width; l < 0; l++) {\n xrpow[j + l] *= ifqstep34;\n if (xrpow[j + l] > cod_info.xrpow_max)\n cod_info.xrpow_max = xrpow[j + l];\n }\n }\n cod_info.scalefac[sfb] = s >> 1;\n }\n cod_info.preflag = 0;\n cod_info.scalefac_scale = 1;\n }\n\n /**\n * Takehiro Tominaga 2000-xx-xx\n *\n * increases the subblock gain and adjusts scalefactors\n */\n function inc_subblock_gain(gfc, cod_info, xrpow) {\n var sfb;\n var scalefac = cod_info.scalefac;\n\n /* subbloc_gain can't do anything in the long block region */\n for (sfb = 0; sfb < cod_info.sfb_lmax; sfb++) {\n if (scalefac[sfb] >= 16)\n return true;\n }\n\n for (var window = 0; window < 3; window++) {\n var s1 = 0;\n var s2 = 0;\n\n for (sfb = cod_info.sfb_lmax + window; sfb < cod_info.sfbdivide; sfb += 3) {\n if (s1 < scalefac[sfb])\n s1 = scalefac[sfb];\n }\n for (; sfb < cod_info.sfbmax; sfb += 3) {\n if (s2 < scalefac[sfb])\n s2 = scalefac[sfb];\n }\n\n if (s1 < 16 && s2 < 8)\n continue;\n\n if (cod_info.subblock_gain[window] >= 7)\n return true;\n\n /*\n * even though there is no scalefactor for sfb12 subblock gain\n * affects upper frequencies too, that's why we have to go up to\n * SBMAX_s\n */\n cod_info.subblock_gain[window]++;\n var j = gfc.scalefac_band.l[cod_info.sfb_lmax];\n for (sfb = cod_info.sfb_lmax + window; sfb < cod_info.sfbmax; sfb += 3) {\n var amp;\n var width = cod_info.width[sfb];\n var s = scalefac[sfb];\n s = s - (4 >> cod_info.scalefac_scale);\n if (s >= 0) {\n scalefac[sfb] = s;\n j += width * 3;\n continue;\n }\n\n scalefac[sfb] = 0;\n {\n var gain = 210 + (s << (cod_info.scalefac_scale + 1));\n amp = qupvt.IPOW20(gain);\n }\n j += width * (window + 1);\n for (var l = -width; l < 0; l++) {\n xrpow[j + l] *= amp;\n if (xrpow[j + l] > cod_info.xrpow_max)\n cod_info.xrpow_max = xrpow[j + l];\n }\n j += width * (3 - window - 1);\n }\n\n {\n var amp = qupvt.IPOW20(202);\n j += cod_info.width[sfb] * (window + 1);\n for (var l = -cod_info.width[sfb]; l < 0; l++) {\n xrpow[j + l] *= amp;\n if (xrpow[j + l] > cod_info.xrpow_max)\n cod_info.xrpow_max = xrpow[j + l];\n }\n }\n }\n return false;\n }\n\n /**\n * <PRE>\n * Takehiro Tominaga /date??\n * Robert Hegemann 2000-09-06: made a function of it\n *\n * amplifies scalefactor bands,\n * - if all are already amplified returns 0\n * - if some bands are amplified too much:\n * * try to increase scalefac_scale\n * * if already scalefac_scale was set\n * try on short blocks to increase subblock gain\n * </PRE>\n */\n function balance_noise(gfp, cod_info, distort, xrpow, bRefine) {\n var gfc = gfp.internal_flags;\n\n amp_scalefac_bands(gfp, cod_info, distort, xrpow, bRefine);\n\n /*\n * check to make sure we have not amplified too much loop_break returns\n * 0 if there is an unamplified scalefac scale_bitcount returns 0 if no\n * scalefactors are too large\n */\n\n var status = loop_break(cod_info);\n\n if (status)\n return false;\n /* all bands amplified */\n\n /*\n * not all scalefactors have been amplified. so these scalefacs are\n * possibly valid. encode them:\n */\n if (gfc.mode_gr == 2)\n status = tk.scale_bitcount(cod_info);\n else\n status = tk.scale_bitcount_lsf(gfc, cod_info);\n\n if (!status)\n return true;\n /* amplified some bands not exceeding limits */\n\n /*\n * some scalefactors are too large. lets try setting scalefac_scale=1\n */\n if (gfc.noise_shaping > 1) {\n Arrays.fill(gfc.pseudohalf, 0);\n if (0 == cod_info.scalefac_scale) {\n inc_scalefac_scale(cod_info, xrpow);\n status = false;\n } else {\n if (cod_info.block_type == Encoder.SHORT_TYPE\n && gfc.subblock_gain > 0) {\n status = (inc_subblock_gain(gfc, cod_info, xrpow) || loop_break(cod_info));\n }\n }\n }\n\n if (!status) {\n if (gfc.mode_gr == 2)\n status = tk.scale_bitcount(cod_info);\n else\n status = tk.scale_bitcount_lsf(gfc, cod_info);\n }\n return !status;\n }\n\n /**\n * <PRE>\n * Function: The outer iteration loop controls the masking conditions\n * of all scalefactorbands. It computes the best scalefac and\n * global gain. This module calls the inner iteration loop\n *\n * mt 5/99 completely rewritten to allow for bit reservoir control,\n * mid/side channels with L/R or mid/side masking thresholds,\n * and chooses best quantization instead of last quantization when\n * no distortion free quantization can be found.\n *\n * added VBR support mt 5/99\n\n *\n * some code shuffle rh 9/00\n * </PRE>\n *\n * @param l3_xmin\n * allowed distortion\n * @param xrpow\n * coloured magnitudes of spectral\n * @param targ_bits\n * maximum allowed bits\n */\n this.outer_loop = function (gfp, cod_info, l3_xmin, xrpow, ch, targ_bits) {\n var gfc = gfp.internal_flags;\n var cod_info_w = new GrInfo();\n var save_xrpow = new_float(576);\n var distort = new_float(L3Side.SFBMAX);\n var best_noise_info = new CalcNoiseResult();\n var better;\n var prev_noise = new CalcNoiseData();\n var best_part2_3_length = 9999999;\n var bEndOfSearch = false;\n var bRefine = false;\n var best_ggain_pass1 = 0;\n\n bin_search_StepSize(gfc, cod_info, targ_bits, ch, xrpow);\n\n if (0 == gfc.noise_shaping)\n /* fast mode, no noise shaping, we are ready */\n return 100;\n /* default noise_info.over_count */\n\n /* compute the distortion in this quantization */\n /* coefficients and thresholds both l/r (or both mid/side) */\n qupvt.calc_noise(cod_info, l3_xmin, distort, best_noise_info,\n prev_noise);\n best_noise_info.bits = cod_info.part2_3_length;\n\n cod_info_w.assign(cod_info);\n var age = 0;\n System.arraycopy(xrpow, 0, save_xrpow, 0, 576);\n\n while (!bEndOfSearch) {\n /* BEGIN MAIN LOOP */\n do {\n var noise_info = new CalcNoiseResult();\n var search_limit;\n var maxggain = 255;\n\n /*\n * When quantization with no distorted bands is found, allow up\n * to X new unsuccesful tries in serial. This gives us more\n * possibilities for different quant_compare modes. Much more\n * than 3 makes not a big difference, it is only slower.\n */\n\n if ((gfc.substep_shaping & 2) != 0) {\n search_limit = 20;\n } else {\n search_limit = 3;\n }\n\n /*\n * Check if the last scalefactor band is distorted. in VBR mode\n * we can't get rid of the distortion, so quit now and VBR mode\n * will try again with more bits. (makes a 10% speed increase,\n * the files I tested were binary identical, 2000/05/20 Robert\n * Hegemann) distort[] > 1 means noise > allowed noise\n */\n if (gfc.sfb21_extra) {\n if (distort[cod_info_w.sfbmax] > 1.0)\n break;\n if (cod_info_w.block_type == Encoder.SHORT_TYPE\n && (distort[cod_info_w.sfbmax + 1] > 1.0 || distort[cod_info_w.sfbmax + 2] > 1.0))\n break;\n }\n\n /* try a new scalefactor conbination on cod_info_w */\n if (!balance_noise(gfp, cod_info_w, distort, xrpow, bRefine))\n break;\n if (cod_info_w.scalefac_scale != 0)\n maxggain = 254;\n\n /*\n * inner_loop starts with the initial quantization step computed\n * above and slowly increases until the bits < huff_bits. Thus\n * it is important not to start with too large of an inital\n * quantization step. Too small is ok, but inner_loop will take\n * longer\n */\n var huff_bits = targ_bits - cod_info_w.part2_length;\n if (huff_bits <= 0)\n break;\n\n /*\n * increase quantizer stepsize until needed bits are below\n * maximum\n */\n while ((cod_info_w.part2_3_length = tk.count_bits(gfc, xrpow,\n cod_info_w, prev_noise)) > huff_bits\n && cod_info_w.global_gain <= maxggain)\n cod_info_w.global_gain++;\n\n if (cod_info_w.global_gain > maxggain)\n break;\n\n if (best_noise_info.over_count == 0) {\n\n while ((cod_info_w.part2_3_length = tk.count_bits(gfc,\n xrpow, cod_info_w, prev_noise)) > best_part2_3_length\n && cod_info_w.global_gain <= maxggain)\n cod_info_w.global_gain++;\n\n if (cod_info_w.global_gain > maxggain)\n break;\n }\n\n /* compute the distortion in this quantization */\n qupvt.calc_noise(cod_info_w, l3_xmin, distort, noise_info,\n prev_noise);\n noise_info.bits = cod_info_w.part2_3_length;\n\n /*\n * check if this quantization is better than our saved\n * quantization\n */\n if (cod_info.block_type != Encoder.SHORT_TYPE) {\n // NORM, START or STOP type\n better = gfp.quant_comp;\n } else\n better = gfp.quant_comp_short;\n\n better = quant_compare(better, best_noise_info, noise_info,\n cod_info_w, distort) ? 1 : 0;\n\n /* save data so we can restore this quantization later */\n if (better != 0) {\n best_part2_3_length = cod_info.part2_3_length;\n best_noise_info = noise_info;\n cod_info.assign(cod_info_w);\n age = 0;\n /* save data so we can restore this quantization later */\n /* store for later reuse */\n System.arraycopy(xrpow, 0, save_xrpow, 0, 576);\n } else {\n /* early stop? */\n if (gfc.full_outer_loop == 0) {\n if (++age > search_limit\n && best_noise_info.over_count == 0)\n break;\n if ((gfc.noise_shaping_amp == 3) && bRefine && age > 30)\n break;\n if ((gfc.noise_shaping_amp == 3)\n && bRefine\n && (cod_info_w.global_gain - best_ggain_pass1) > 15)\n break;\n }\n }\n } while ((cod_info_w.global_gain + cod_info_w.scalefac_scale) < 255);\n\n if (gfc.noise_shaping_amp == 3) {\n if (!bRefine) {\n /* refine search */\n cod_info_w.assign(cod_info);\n System.arraycopy(save_xrpow, 0, xrpow, 0, 576);\n age = 0;\n best_ggain_pass1 = cod_info_w.global_gain;\n\n bRefine = true;\n } else {\n /* search already refined, stop */\n bEndOfSearch = true;\n }\n\n } else {\n bEndOfSearch = true;\n }\n }\n\n /*\n * finish up\n */\n if (gfp.VBR == VbrMode.vbr_rh || gfp.VBR == VbrMode.vbr_mtrh)\n /* restore for reuse on next try */\n System.arraycopy(save_xrpow, 0, xrpow, 0, 576);\n /*\n * do the 'substep shaping'\n */\n else if ((gfc.substep_shaping & 1) != 0)\n trancate_smallspectrums(gfc, cod_info, l3_xmin, xrpow);\n\n return best_noise_info.over_count;\n }\n\n /**\n * Robert Hegemann 2000-09-06\n *\n * update reservoir status after FINAL quantization/bitrate\n */\n this.iteration_finish_one = function (gfc, gr, ch) {\n var l3_side = gfc.l3_side;\n var cod_info = l3_side.tt[gr][ch];\n\n /*\n * try some better scalefac storage\n */\n tk.best_scalefac_store(gfc, gr, ch, l3_side);\n\n /*\n * best huffman_divide may save some bits too\n */\n if (gfc.use_best_huffman == 1)\n tk.best_huffman_divide(gfc, cod_info);\n\n /*\n * update reservoir status after FINAL quantization/bitrate\n */\n rv.ResvAdjust(gfc, cod_info);\n };\n\n /**\n *\n * 2000-09-04 Robert Hegemann\n *\n * @param l3_xmin\n * allowed distortion of the scalefactor\n * @param xrpow\n * coloured magnitudes of spectral values\n */\n this.VBR_encode_granule = function (gfp, cod_info, l3_xmin, xrpow, ch, min_bits, max_bits) {\n var gfc = gfp.internal_flags;\n var bst_cod_info = new GrInfo();\n var bst_xrpow = new_float(576);\n var Max_bits = max_bits;\n var real_bits = max_bits + 1;\n var this_bits = (max_bits + min_bits) / 2;\n var dbits, over, found = 0;\n var sfb21_extra = gfc.sfb21_extra;\n\n Arrays.fill(bst_cod_info.l3_enc, 0);\n\n /*\n * search within round about 40 bits of optimal\n */\n do {\n\n if (this_bits > Max_bits - 42)\n gfc.sfb21_extra = false;\n else\n gfc.sfb21_extra = sfb21_extra;\n\n over = outer_loop(gfp, cod_info, l3_xmin, xrpow, ch, this_bits);\n\n /*\n * is quantization as good as we are looking for ? in this case: is\n * no scalefactor band distorted?\n */\n if (over <= 0) {\n found = 1;\n /*\n * now we know it can be done with \"real_bits\" and maybe we can\n * skip some iterations\n */\n real_bits = cod_info.part2_3_length;\n\n /*\n * store best quantization so far\n */\n bst_cod_info.assign(cod_info);\n System.arraycopy(xrpow, 0, bst_xrpow, 0, 576);\n\n /*\n * try with fewer bits\n */\n max_bits = real_bits - 32;\n dbits = max_bits - min_bits;\n this_bits = (max_bits + min_bits) / 2;\n } else {\n /*\n * try with more bits\n */\n min_bits = this_bits + 32;\n dbits = max_bits - min_bits;\n this_bits = (max_bits + min_bits) / 2;\n\n if (found != 0) {\n found = 2;\n /*\n * start again with best quantization so far\n */\n cod_info.assign(bst_cod_info);\n System.arraycopy(bst_xrpow, 0, xrpow, 0, 576);\n }\n }\n } while (dbits > 12);\n\n gfc.sfb21_extra = sfb21_extra;\n\n /*\n * found=0 => nothing found, use last one found=1 => we just found the\n * best and left the loop found=2 => we restored a good one and have now\n * l3_enc to restore too\n */\n if (found == 2) {\n System.arraycopy(bst_cod_info.l3_enc, 0, cod_info.l3_enc, 0, 576);\n }\n }\n\n /**\n * Robert Hegemann 2000-09-05\n *\n * calculates * how many bits are available for analog silent granules * how\n * many bits to use for the lowest allowed bitrate * how many bits each\n * bitrate would provide\n */\n this.get_framebits = function (gfp, frameBits) {\n var gfc = gfp.internal_flags;\n\n /*\n * always use at least this many bits per granule per channel unless we\n * detect analog silence, see below\n */\n gfc.bitrate_index = gfc.VBR_min_bitrate;\n var bitsPerFrame = bs.getframebits(gfp);\n\n /*\n * bits for analog silence\n */\n gfc.bitrate_index = 1;\n bitsPerFrame = bs.getframebits(gfp);\n\n for (var i = 1; i <= gfc.VBR_max_bitrate; i++) {\n gfc.bitrate_index = i;\n var mb = new MeanBits(bitsPerFrame);\n frameBits[i] = rv.ResvFrameBegin(gfp, mb);\n bitsPerFrame = mb.bits;\n }\n };\n\n /* RH: this one needs to be overhauled sometime */\n\n /**\n * <PRE>\n * 2000-09-04 Robert Hegemann\n *\n * * converts LR to MS coding when necessary\n * * calculates allowed/adjusted quantization noise amounts\n * * detects analog silent frames\n *\n * some remarks:\n * - lower masking depending on Quality setting\n * - quality control together with adjusted ATH MDCT scaling\n * on lower quality setting allocate more noise from\n * ATH masking, and on higher quality setting allocate\n * less noise from ATH masking.\n * - experiments show that going more than 2dB over GPSYCHO's\n * limits ends up in very annoying artefacts\n * </PRE>\n */\n this.VBR_old_prepare = function (gfp, pe, ms_ener_ratio, ratio, l3_xmin, frameBits, min_bits,\n max_bits, bands) {\n var gfc = gfp.internal_flags;\n\n var masking_lower_db, adjust = 0.0;\n var analog_silence = 1;\n var bits = 0;\n\n gfc.bitrate_index = gfc.VBR_max_bitrate;\n var avg = rv.ResvFrameBegin(gfp, new MeanBits(0)) / gfc.mode_gr;\n\n get_framebits(gfp, frameBits);\n\n for (var gr = 0; gr < gfc.mode_gr; gr++) {\n var mxb = qupvt.on_pe(gfp, pe, max_bits[gr], avg, gr, 0);\n if (gfc.mode_ext == Encoder.MPG_MD_MS_LR) {\n ms_convert(gfc.l3_side, gr);\n qupvt.reduce_side(max_bits[gr], ms_ener_ratio[gr], avg, mxb);\n }\n for (var ch = 0; ch < gfc.channels_out; ++ch) {\n var cod_info = gfc.l3_side.tt[gr][ch];\n\n if (cod_info.block_type != Encoder.SHORT_TYPE) {\n // NORM, START or STOP type\n adjust = 1.28 / (1 + Math\n .exp(3.5 - pe[gr][ch] / 300.)) - 0.05;\n masking_lower_db = gfc.PSY.mask_adjust - adjust;\n } else {\n adjust = 2.56 / (1 + Math\n .exp(3.5 - pe[gr][ch] / 300.)) - 0.14;\n masking_lower_db = gfc.PSY.mask_adjust_short - adjust;\n }\n gfc.masking_lower = Math.pow(10.0,\n masking_lower_db * 0.1);\n\n init_outer_loop(gfc, cod_info);\n bands[gr][ch] = qupvt.calc_xmin(gfp, ratio[gr][ch], cod_info,\n l3_xmin[gr][ch]);\n if (bands[gr][ch] != 0)\n analog_silence = 0;\n\n min_bits[gr][ch] = 126;\n\n bits += max_bits[gr][ch];\n }\n }\n for (var gr = 0; gr < gfc.mode_gr; gr++) {\n for (var ch = 0; ch < gfc.channels_out; ch++) {\n if (bits > frameBits[gfc.VBR_max_bitrate]) {\n max_bits[gr][ch] *= frameBits[gfc.VBR_max_bitrate];\n max_bits[gr][ch] /= bits;\n }\n if (min_bits[gr][ch] > max_bits[gr][ch])\n min_bits[gr][ch] = max_bits[gr][ch];\n\n }\n /* for ch */\n }\n /* for gr */\n\n return analog_silence;\n };\n\n this.bitpressure_strategy = function (gfc, l3_xmin, min_bits, max_bits) {\n for (var gr = 0; gr < gfc.mode_gr; gr++) {\n for (var ch = 0; ch < gfc.channels_out; ch++) {\n var gi = gfc.l3_side.tt[gr][ch];\n var pxmin = l3_xmin[gr][ch];\n var pxminPos = 0;\n for (var sfb = 0; sfb < gi.psy_lmax; sfb++)\n pxmin[pxminPos++] *= 1. + .029 * sfb * sfb\n / Encoder.SBMAX_l / Encoder.SBMAX_l;\n\n if (gi.block_type == Encoder.SHORT_TYPE) {\n for (var sfb = gi.sfb_smin; sfb < Encoder.SBMAX_s; sfb++) {\n pxmin[pxminPos++] *= 1. + .029 * sfb * sfb\n / Encoder.SBMAX_s / Encoder.SBMAX_s;\n pxmin[pxminPos++] *= 1. + .029 * sfb * sfb\n / Encoder.SBMAX_s / Encoder.SBMAX_s;\n pxmin[pxminPos++] *= 1. + .029 * sfb * sfb\n / Encoder.SBMAX_s / Encoder.SBMAX_s;\n }\n }\n max_bits[gr][ch] = 0 | Math.max(min_bits[gr][ch],\n 0.9 * max_bits[gr][ch]);\n }\n }\n };\n\n this.VBR_new_prepare = function (gfp, pe, ratio, l3_xmin, frameBits, max_bits) {\n var gfc = gfp.internal_flags;\n\n var analog_silence = 1;\n var avg = 0, bits = 0;\n var maximum_framebits;\n\n if (!gfp.free_format) {\n gfc.bitrate_index = gfc.VBR_max_bitrate;\n\n var mb = new MeanBits(avg);\n rv.ResvFrameBegin(gfp, mb);\n avg = mb.bits;\n\n get_framebits(gfp, frameBits);\n maximum_framebits = frameBits[gfc.VBR_max_bitrate];\n } else {\n gfc.bitrate_index = 0;\n var mb = new MeanBits(avg);\n maximum_framebits = rv.ResvFrameBegin(gfp, mb);\n avg = mb.bits;\n frameBits[0] = maximum_framebits;\n }\n\n for (var gr = 0; gr < gfc.mode_gr; gr++) {\n qupvt.on_pe(gfp, pe, max_bits[gr], avg, gr, 0);\n if (gfc.mode_ext == Encoder.MPG_MD_MS_LR) {\n ms_convert(gfc.l3_side, gr);\n }\n for (var ch = 0; ch < gfc.channels_out; ++ch) {\n var cod_info = gfc.l3_side.tt[gr][ch];\n\n gfc.masking_lower = Math.pow(10.0,\n gfc.PSY.mask_adjust * 0.1);\n\n init_outer_loop(gfc, cod_info);\n if (0 != qupvt.calc_xmin(gfp, ratio[gr][ch], cod_info,\n l3_xmin[gr][ch]))\n analog_silence = 0;\n\n bits += max_bits[gr][ch];\n }\n }\n for (var gr = 0; gr < gfc.mode_gr; gr++) {\n for (var ch = 0; ch < gfc.channels_out; ch++) {\n if (bits > maximum_framebits) {\n max_bits[gr][ch] *= maximum_framebits;\n max_bits[gr][ch] /= bits;\n }\n\n }\n /* for ch */\n }\n /* for gr */\n\n return analog_silence;\n };\n\n /**\n * calculates target bits for ABR encoding\n *\n * mt 2000/05/31\n */\n this.calc_target_bits = function (gfp, pe, ms_ener_ratio, targ_bits, analog_silence_bits, max_frame_bits) {\n var gfc = gfp.internal_flags;\n var l3_side = gfc.l3_side;\n var res_factor;\n var gr, ch, totbits, mean_bits = 0;\n\n gfc.bitrate_index = gfc.VBR_max_bitrate;\n var mb = new MeanBits(mean_bits);\n max_frame_bits[0] = rv.ResvFrameBegin(gfp, mb);\n mean_bits = mb.bits;\n\n gfc.bitrate_index = 1;\n mean_bits = bs.getframebits(gfp) - gfc.sideinfo_len * 8;\n analog_silence_bits[0] = mean_bits / (gfc.mode_gr * gfc.channels_out);\n\n mean_bits = gfp.VBR_mean_bitrate_kbps * gfp.framesize * 1000;\n if ((gfc.substep_shaping & 1) != 0)\n mean_bits *= 1.09;\n mean_bits /= gfp.out_samplerate;\n mean_bits -= gfc.sideinfo_len * 8;\n mean_bits /= (gfc.mode_gr * gfc.channels_out);\n\n /**\n * <PRE>\n * res_factor is the percentage of the target bitrate that should\n * be used on average. the remaining bits are added to the\n * bitreservoir and used for difficult to encode frames.\n *\n * Since we are tracking the average bitrate, we should adjust\n * res_factor \"on the fly\", increasing it if the average bitrate\n * is greater than the requested bitrate, and decreasing it\n * otherwise. Reasonable ranges are from .9 to 1.0\n *\n * Until we get the above suggestion working, we use the following\n * tuning:\n * compression ratio res_factor\n * 5.5 (256kbps) 1.0 no need for bitreservoir\n * 11 (128kbps) .93 7% held for reservoir\n *\n * with linear interpolation for other values.\n * </PRE>\n */\n res_factor = .93 + .07 * (11.0 - gfp.compression_ratio)\n / (11.0 - 5.5);\n if (res_factor < .90)\n res_factor = .90;\n if (res_factor > 1.00)\n res_factor = 1.00;\n\n for (gr = 0; gr < gfc.mode_gr; gr++) {\n var sum = 0;\n for (ch = 0; ch < gfc.channels_out; ch++) {\n targ_bits[gr][ch] = (int)(res_factor * mean_bits);\n\n if (pe[gr][ch] > 700) {\n var add_bits = (int)((pe[gr][ch] - 700) / 1.4);\n\n var cod_info = l3_side.tt[gr][ch];\n targ_bits[gr][ch] = (int)(res_factor * mean_bits);\n\n /* short blocks use a little extra, no matter what the pe */\n if (cod_info.block_type == Encoder.SHORT_TYPE) {\n if (add_bits < mean_bits / 2)\n add_bits = mean_bits / 2;\n }\n /* at most increase bits by 1.5*average */\n if (add_bits > mean_bits * 3 / 2)\n add_bits = mean_bits * 3 / 2;\n else if (add_bits < 0)\n add_bits = 0;\n\n targ_bits[gr][ch] += add_bits;\n }\n if (targ_bits[gr][ch] > LameInternalFlags.MAX_BITS_PER_CHANNEL) {\n targ_bits[gr][ch] = LameInternalFlags.MAX_BITS_PER_CHANNEL;\n }\n sum += targ_bits[gr][ch];\n }\n /* for ch */\n if (sum > LameInternalFlags.MAX_BITS_PER_GRANULE) {\n for (ch = 0; ch < gfc.channels_out; ++ch) {\n targ_bits[gr][ch] *= LameInternalFlags.MAX_BITS_PER_GRANULE;\n targ_bits[gr][ch] /= sum;\n }\n }\n }\n /* for gr */\n\n if (gfc.mode_ext == Encoder.MPG_MD_MS_LR)\n for (gr = 0; gr < gfc.mode_gr; gr++) {\n qupvt.reduce_side(targ_bits[gr], ms_ener_ratio[gr], mean_bits\n * gfc.channels_out,\n LameInternalFlags.MAX_BITS_PER_GRANULE);\n }\n\n /*\n * sum target bits\n */\n totbits = 0;\n for (gr = 0; gr < gfc.mode_gr; gr++) {\n for (ch = 0; ch < gfc.channels_out; ch++) {\n if (targ_bits[gr][ch] > LameInternalFlags.MAX_BITS_PER_CHANNEL)\n targ_bits[gr][ch] = LameInternalFlags.MAX_BITS_PER_CHANNEL;\n totbits += targ_bits[gr][ch];\n }\n }\n\n /*\n * repartion target bits if needed\n */\n if (totbits > max_frame_bits[0]) {\n for (gr = 0; gr < gfc.mode_gr; gr++) {\n for (ch = 0; ch < gfc.channels_out; ch++) {\n targ_bits[gr][ch] *= max_frame_bits[0];\n targ_bits[gr][ch] /= totbits;\n }\n }\n }\n }\n\n}",
"function applyNostalgia() \n{ \n var filter = 'saturate(40%) grayscale(100%) contrast(45%) sepia(100%)';\n setFilter(filter);\n}",
"function infopic(vqi,vqx,vqy){if(jpgnum[vqi]==0){jpgnext+=1;jpgnum[vqi]=jpgnext;\n s5=(vqi+10000).toString();s5=htpt+\"y\"+s5.substring(1,5)+\".jpg\";jpg[jpgnext].src=s5;};\n conget[ican].drawImage(jpg[jpgnum[vqi]],vqx,vqy); }",
"function leteFunksjon(a) {\n url = `https://api.giphy.com/v1/gifs/translate?api_key=4eZuDD7c5RB4TGPjY1m2BXYV63xHgwH7&s=${a}`\n nyGIF(url);\n}",
"function NDVI(image)\n{\n return image.expression('((b(\"B4\") - b(\"B3\")) / (b(\"B4\") + b(\"B3\")))');\n}",
"generateGIF(scale) {\n let canvas = document.createElement(\"canvas\")\n canvas.width = this.width * scale\n canvas.height = this.height * scale\n\n if (canvas.width === 0 || canvas.height === 0) {\n console.log(\"Skipping GIFGeneration because dimension is 0\")\n return\n }\n\n let ctx = canvas.getContext(\"2d\")\n\n let encoder = new GIFEncoder()\n encoder.setRepeat(0)\n encoder.setDelay(150)\n encoder.start()\n let usesTransparency = this.usesTransparency()\n if (usesTransparency) {\n encoder.setTransparent(0xFFFFF1)\n }\n\n for (let i = 0; i < this.maxTicks; i++) {\n ctx.clearRect(0, 0, canvas.width, canvas.height)\n ctx.fillStyle = \"#FFFFF1\"\n ctx.fillRect(0, 0, canvas.width, canvas.height)\n\n this.drawInCanvas(canvas, scale)\n this.tick()\n\n let imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)\n encoder.addFrame(imageData, true)\n }\n\n encoder.finish()\n\n let gifData = encoder.stream().getData()\n\n let base64GIFStr = 'data:image/gif;base64,' + encode64(gifData)\n return base64GIFStr\n }",
"function JPEGEncoder(a){function Z(){var b=(new Date).getTime();if(!a)a=50;X();K();L();M();Y(a);var c=(new Date).getTime()-b;console.log(\"Initialization \"+c+\"ms\")}function Y(a){if(a<=0){a=1}if(a>100){a=100}if(y==a)return;var b=0;if(a<50){b=Math.floor(5e3/a)}else{b=Math.floor(200-a*2)}I(b);y=a;console.log(\"Quality set to: \"+a+\"%\")}function X(){var a=String.fromCharCode;for(var b=0;b<256;b++){w[b]=a(b)}}function W(a,b,c,d,e){var f=e[0];var g=e[240];var h;const i=16;const j=63;const k=64;var l=Q(a,b);for(var o=0;o<k;++o){p[z[o]]=l[o]}var q=p[0]-c;c=p[0];if(q==0){N(d[0])}else{h=32767+q;N(d[n[h]]);N(m[h])}var r=63;for(;r>0&&p[r]==0;r--){}if(r==0){N(f);return c}var s=1;var t;while(s<=r){var u=s;for(;p[s]==0&&s<=r;++s){}var v=s-u;if(v>=i){t=v>>4;for(var w=1;w<=t;++w)N(g);v=v&15}h=32767+p[s];N(e[(v<<4)+n[h]]);N(m[h]);s++}if(r!=j){N(f)}return c}function V(){P(65498);P(12);O(3);O(1);O(0);O(2);O(17);O(3);O(17);O(0);O(63);O(0)}function U(){P(65476);P(418);O(0);for(var a=0;a<16;a++){O(A[a+1])}for(var b=0;b<=11;b++){O(B[b])}O(16);for(var c=0;c<16;c++){O(C[c+1])}for(var d=0;d<=161;d++){O(D[d])}O(1);for(var e=0;e<16;e++){O(E[e+1])}for(var f=0;f<=11;f++){O(F[f])}O(17);for(var g=0;g<16;g++){O(G[g+1])}for(var h=0;h<=161;h++){O(H[h])}}function T(){P(65499);P(132);O(0);for(var a=0;a<64;a++){O(e[a])}O(1);for(var b=0;b<64;b++){O(f[b])}}function S(a,b){P(65472);P(17);O(8);P(b);P(a);O(3);O(1);O(17);O(0);O(2);O(17);O(1);O(3);O(17);O(1)}function R(){P(65504);P(16);O(74);O(70);O(73);O(70);O(0);O(1);O(1);O(0);P(1);P(1);O(0);O(0)}function Q(a,b){var c,d,e,f,g,h,i,j;var k=0;var l;const m=8;const n=64;for(l=0;l<m;++l){c=a[k];d=a[k+1];e=a[k+2];f=a[k+3];g=a[k+4];h=a[k+5];i=a[k+6];j=a[k+7];var p=c+j;var q=c-j;var r=d+i;var s=d-i;var t=e+h;var u=e-h;var v=f+g;var w=f-g;var x=p+v;var y=p-v;var z=r+t;var A=r-t;a[k]=x+z;a[k+4]=x-z;var B=(A+y)*.707106781;a[k+2]=y+B;a[k+6]=y-B;x=w+u;z=u+s;A=s+q;var C=(x-A)*.382683433;var D=.5411961*x+C;var E=1.306562965*A+C;var F=z*.707106781;var G=q+F;var H=q-F;a[k+5]=H+D;a[k+3]=H-D;a[k+1]=G+E;a[k+7]=G-E;k+=8}k=0;for(l=0;l<m;++l){c=a[k];d=a[k+8];e=a[k+16];f=a[k+24];g=a[k+32];h=a[k+40];i=a[k+48];j=a[k+56];var I=c+j;var J=c-j;var K=d+i;var L=d-i;var M=e+h;var N=e-h;var O=f+g;var P=f-g;var Q=I+O;var R=I-O;var S=K+M;var T=K-M;a[k]=Q+S;a[k+32]=Q-S;var U=(T+R)*.707106781;a[k+16]=R+U;a[k+48]=R-U;Q=P+N;S=N+L;T=L+J;var V=(Q-T)*.382683433;var W=.5411961*Q+V;var X=1.306562965*T+V;var Y=S*.707106781;var Z=J+Y;var $=J-Y;a[k+40]=$+W;a[k+24]=$-W;a[k+8]=Z+X;a[k+56]=Z-X;k++}var _;for(l=0;l<n;++l){_=a[l]*b[l];o[l]=_>0?_+.5|0:_-.5|0}return o}function P(a){O(a>>8&255);O(a&255)}function O(a){q.push(w[a])}function N(a){var b=a[0];var c=a[1]-1;while(c>=0){if(b&1<<c){r|=1<<s}c--;s--;if(s<0){if(r==255){O(255);O(0)}else{O(r)}s=7;r=0}}}function M(){for(var a=0;a<256;a++){x[a]=19595*a;x[a+256>>0]=38470*a;x[a+512>>0]=7471*a+32768;x[a+768>>0]=-11059*a;x[a+1024>>0]=-21709*a;x[a+1280>>0]=32768*a+8421375;x[a+1536>>0]=-27439*a;x[a+1792>>0]=-5329*a}}function L(){var a=1;var b=2;for(var c=1;c<=15;c++){for(var d=a;d<b;d++){n[32767+d]=c;m[32767+d]=[];m[32767+d][1]=c;m[32767+d][0]=d}for(var e=-(b-1);e<=-a;e++){n[32767+e]=c;m[32767+e]=[];m[32767+e][1]=c;m[32767+e][0]=b-1+e}a<<=1;b<<=1}}function K(){i=J(A,B);j=J(E,F);k=J(C,D);l=J(G,H)}function J(a,b){var c=0;var d=0;var e=new Array;for(var f=1;f<=16;f++){for(var g=1;g<=a[f];g++){e[b[d]]=[];e[b[d]][0]=c;e[b[d]][1]=f;d++;c++}c*=2}return e}function I(a){var b=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99];for(var c=0;c<64;c++){var i=d((b[c]*a+50)/100);if(i<1){i=1}else if(i>255){i=255}e[z[c]]=i}var j=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99];for(var k=0;k<64;k++){var l=d((j[k]*a+50)/100);if(l<1){l=1}else if(l>255){l=255}f[z[k]]=l}var m=[1,1.387039845,1.306562965,1.175875602,1,.785694958,.5411961,.275899379];var n=0;for(var o=0;o<8;o++){for(var p=0;p<8;p++){g[n]=1/(e[z[n]]*m[o]*m[p]*8);h[n]=1/(f[z[n]]*m[o]*m[p]*8);n++}}}var b=this;var c=Math.round;var d=Math.floor;var e=new Array(64);var f=new Array(64);var g=new Array(64);var h=new Array(64);var i;var j;var k;var l;var m=new Array(65535);var n=new Array(65535);var o=new Array(64);var p=new Array(64);var q=[];var r=0;var s=7;var t=new Array(64);var u=new Array(64);var v=new Array(64);var w=new Array(256);var x=new Array(2048);var y;var z=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63];var A=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0];var B=[0,1,2,3,4,5,6,7,8,9,10,11];var C=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125];var D=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250];var E=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0];var F=[0,1,2,3,4,5,6,7,8,9,10,11];var G=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119];var H=[0,1,2,3,17,4,5,33,49,6,18,65,81,7,97,113,19,34,50,129,8,20,66,145,161,177,193,9,35,51,82,240,21,98,114,209,10,22,36,52,225,37,241,23,24,25,26,38,39,40,41,42,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,130,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,226,227,228,229,230,231,232,233,234,242,243,244,245,246,247,248,249,250];this.encode=function(a,b){var c=(new Date).getTime();if(b)Y(b);q=new Array;r=0;s=7;P(65496);R();T();S(a.width,a.height);U();V();var d=0;var e=0;var f=0;r=0;s=7;this.encode.displayName=\"_encode_\";var m=a.data;var n=a.width;var o=a.height;var p=n*4;var w=n*3;var y,z=0;var A,B,C;var D,E,F,G,H;while(z<o){y=0;while(y<p){D=p*z+y;E=D;F=-1;G=0;for(H=0;H<64;H++){G=H>>3;F=(H&7)*4;E=D+G*p+F;if(z+G>=o){E-=p*(z+1+G-o)}if(y+F>=p){E-=y+F-p+4}A=m[E++];B=m[E++];C=m[E++];t[H]=(x[A]+x[B+256>>0]+x[C+512>>0]>>16)-128;u[H]=(x[A+768>>0]+x[B+1024>>0]+x[C+1280>>0]>>16)-128;v[H]=(x[A+1280>>0]+x[B+1536>>0]+x[C+1792>>0]>>16)-128}d=W(t,g,d,i,k);e=W(u,h,e,j,l);f=W(v,h,f,j,l);y+=32}z+=8}if(s>=0){var I=[];I[1]=s+1;I[0]=(1<<s+1)-1;N(I)}P(65497);var J=\"data:image/jpeg;base64,\"+btoa(q.join(\"\"));q=[];var K=(new Date).getTime()-c;console.log(\"Encoding time: \"+K+\"ms\");return J};Z()}",
"function quantize(d) {\n return \"q\" + Math.min(8, ~~(data[d.id] * 9 / 12)) + \"-9\";\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
issue 246: on_after_filter callback triggered twice from checklist filter | function afterFilter(){
ct++;
module('TableFilter with on_after_filter callback');
test('after filter callback fired once', function() {
// assert
deepEqual(ct, 1, 'Nb of times is fired');
deepEqual(tf.getFilterValue(1), ['Canberra'], 'Selected option');
});
} | [
"on_global_filter_configuration_changed() {\n }",
"function _afterFilter(isGlobal, server, err, msg, session, resp, opts, cb) {\n let fm;\n if (isGlobal) {\n fm = server.globalFilterService;\n } else {\n fm = server.filterService;\n }\n\n if (fm) {\n if (isGlobal) {\n fm.afterFilter(err, msg, session, resp, () => { /* do nothing */ });\n } else {\n fm.afterFilter(err, msg, session, resp, (err) => {\n cb(err, resp, opts);\n });\n }\n }\n}",
"onStateFilterUpdated() {\n }",
"onFiltersCleared() {\n }",
"doneFiltering() {\n filtered = false\n }",
"filterCallback() {\n this.confirmCallback(this.lessonsSet);\n }",
"function wait_for_apply_filter() {\n if (list_url_calls < 1) {\n setTimeout(wait_for_apply_filter, 5);\n } else {\n expect(spy).to.have.been.calledOnce;\n }\n }",
"onNameFilterUpdated() {\n }",
"function handleFilterCheck() {\n $('.js-filter-checked').click(event => {\n console.log('handle filter ran');\n toggleFilter(STORE);\n renderShoppingList();\n });\n}",
"global_filter_configuration_changed() {\n this.on_global_filter_configuration_changed()\n }",
"function onLanguageFiltersChange() {\n // `vm.filters.languages` is still out of sync at this point,\n // but in next cycle after `$timeout` we have updated version.\n $timeout(function () {\n // Save new value to cache\n FiltersService.set('languages', vm.filters.languages || []);\n\n onFiltersUpdated();\n });\n }",
"function finishRenderFilters() {\n $window.UnicalApiBehaviors.filterToggle();\n }",
"function patientListModule_createfilterListFailureCallback(response) {\n kony.print(\"filter create service service failed\");\n}",
"function onFiltersChanged(filters){\n\n }",
"function patientListModule_filterListFailureCallback(response) {\n kony.print(\"get filter service service failed\");\n}",
"function executeOnFilters(fn) {\n\t var appState = getAppState();\n\t var globalFilters = [];\n\t var appFilters = [];\n\n\t if (globalState.filters) globalFilters = globalState.filters;\n\t if (appState && appState.filters) appFilters = appState.filters;\n\n\t globalFilters.concat(appFilters).forEach(fn);\n\t }",
"function finishUsingConsoleFilter() {\n\tconsoleFilterRefs--;\n\n\t// Note: Instead of reverting `console.warning` back to the original\n\t// when the reference counter reaches 0, we leave our hook installed\n\t// to prevent potential race conditions once `check` is made async\n}",
"function ActivityFilterCallback(data, div) \n{\n\tIS_FILTER_ALREADY_APPLIED=true;\n\tvar status = data[\"status\"];\n\tif (status == SUCCESS) {\n\t\tviewUpdatedActivities();\n\t} \n\telse {\n\t\tshowNoResultsMsg(\"updatedActivities\"); //if filtering is not success show no results message\n\t}\n}",
"function onFilterChange() {\n $log.debug(\"LazyGrid:Filter Changed\");\n self.fields.filter = [];\n if (angular.isDefined(self.fields.promise.refresh)) {\n $timeout.cancel(self.fields.promise.refresh);\n }\n self.fields.promise.refresh = $timeout(function () {\n self.fn.refresh();\n }\n , 1000);\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find all the locations around this block that are not infected | function vulnerable_neighbors (x, y) {
vulnerable = [];
list = calculate_Neighbors(x, y);
for (var dir in list) {
item = list[dir]
i = item[0]
j = item[1]
if (list_of_blocks[i] == undefined || (list_of_blocks[i][j] == null)) {
vulnerable.push(item)
}
}
return vulnerable;
} | [
"getAffectedLocations() {\n let c1 = this.source.clone();\n c1.reset();\n c1.transform(this.axis, this.layerMask, this.angle);\n return c1.getUnsolvedParts();\n }",
"function findUnexplored() {\n var unexplored = [];\n Object.keys(_robot.explored).forEach(function (loc) {\n var point = stringToPoint(loc);\n for(var maze_loc in _maze[point.y][point.x].outgoing) {\n if(!(maze_loc in _robot.explored)) {\n unexplored.push(stringToPoint(maze_loc));\n }\n }\n });\n return unexplored;\n}",
"#getUnavailableLocations() {\n let res = [];\n for (let player of this.allPlayers) {\n res.push(...player.snake.place);\n }\n if (this.foods) {\n res.push(...this.foods.getFoodCurrentLocations());\n }\n return res;\n }",
"getOccupiedPositions(onlyMoved) {\n const queryParams = {\n position: 0,\n status: 'ok',\n };\n if (onlyMoved) {\n queryParams.moved = true;\n }\n const blockers = this.where(queryParams);\n\n const positions = [];\n for (let i = 0, l = blockers.length; i < l; i++) {\n const mos = blockers[i].moves;\n if (mos.length > 0) {\n const mo = mos.at(mos.length - 1);\n positions.push(new Position({\n x: mo.attributes.x,\n y: mo.attributes.y,\n }));\n }\n }\n return positions;\n }",
"getLocatorsSync() {\n let locators = [];\n let height = this.getCurHeightSync();\n let pow = 0;\n\n if (height === -1) { return []; }\n\n while (true) {\n let i = Math.max(height + 1 - Math.pow(2, pow), 0);\n locators.push(this.getBlockIdAtSync(i));\n if (i === 0) { break; }\n pow += 1;\n }\n return locators;\n }",
"function getAllLocations() {\n var spaces = [];\n for (var i = 0; i < gLevel.size; i++) {\n for (var j = 0; j < gLevel.size; j++) {\n var coord = { i: i, j: j };\n if (!gBoard[i][j].isMine) spaces.push(coord);\n }\n }\n return spaces;\n}",
"getPossibleNodeLocations() {\r\n\t\t// Stores the possible node locations\r\n\t\tlet posNodes = [];\r\n\t\t\r\n\t\t// Iterate over every node node in the output layer\r\n\t\tfor (let n of this.outputs) {\r\n\t\t\t// Get all the possible node locations for each node and add it\r\n\t\t\t// to the cumulative node positions array.\r\n\t\t\tposNodes = posNodes.concat(n.getPossibleNodeLocations());\r\n\t\t}\r\n\t\t\r\n\t\t// Return the possible node locations.\r\n\t\treturn posNodes;\r\n\t}",
"function findFreeLocations() {\n const fineRows = Math.floor(randomMap.numRows / CONSTANTS.LOCATION_RADIUS);\n const fineColumns = Math.floor(randomMap.numColumns / CONSTANTS.LOCATION_RADIUS);\n generationData.gridRows = Math.floor(randomMap.numRows / CONSTANTS.LOCATION_DIST);\n generationData.gridColumns = Math.floor(randomMap.numColumns / CONSTANTS.LOCATION_DIST);\n const fineGrid = [];\n generationData.locationGrid = [];\n\n for (let i = 0; i < fineRows * fineColumns; ++i) {\n fineGrid.push(0);\n if (i < generationData.gridRows * generationData.gridColumns) {\n generationData.locationGrid.push(0);\n }\n }\n\n function round(x) {\n const result = Math.round(x);\n return {result, dir: result === Math.floor(x) ? 1 : -1};\n }\n\n for (let i = CONSTANTS.LOCATION_RADIUS + 1; i < randomMap.numRows - CONSTANTS.LOCATION_RADIUS - 1; ++i) {\n for (let j = CONSTANTS.LOCATION_RADIUS + 1; j < randomMap.numColumns - CONSTANTS.LOCATION_RADIUS - 1; ++j) {\n if (getTile(i, j).biomeID === -1) continue;\n\n const row = round(i / CONSTANTS.LOCATION_RADIUS);\n const column = round(j / CONSTANTS.LOCATION_RADIUS);\n\n let validIndex = 0;\n let index = (row.result + row.dir) * fineColumns + column.result + column.dir;\n if (index < fineRows * fineColumns) {\n if (fineGrid[index] !== 0) continue;\n validIndex = index;\n }\n index = (row.result + row.dir) * fineColumns + column.result;\n if (index < fineRows * fineColumns) {\n if (fineGrid[index] !== 0) continue;\n validIndex = index;\n }\n index = row.result * fineColumns + column.result + column.dir;\n if (index < fineRows * fineColumns) {\n if (fineGrid[index] !== 0) continue;\n validIndex = index;\n }\n index = row.result * fineColumns + column.result;\n if (index < fineRows * fineColumns) {\n if (fineGrid[index] !== 0) continue;\n validIndex = index;\n }\n\n if (isTileGround(i, j)) {\n if (isTileGround(i + CONSTANTS.LOCATION_RADIUS, j)\n && isTileGround(i - CONSTANTS.LOCATION_RADIUS, j)\n && isTileGround(i, j + CONSTANTS.LOCATION_RADIUS)\n && isTileGround(i, j - CONSTANTS.LOCATION_RADIUS)) {\n fineGrid[validIndex] = {i, j, isAllowed: isTileGround};\n }\n } else if (isTileWater(i, j)) {\n if (isTileWater(i + CONSTANTS.LOCATION_RADIUS, j)\n && isTileWater(i - CONSTANTS.LOCATION_RADIUS, j)\n && isTileWater(i, j + CONSTANTS.LOCATION_RADIUS)\n && isTileWater(i, j - CONSTANTS.LOCATION_RADIUS)) {\n fineGrid[validIndex] = {i, j, isAllowed: isTileWater};\n }\n }\n }\n }\n\n function areNeighborsFree(i, j, isAllowed) {\n for (let k = 0; k < CONSTANTS.LOCATION_RADIUS; ++k) {\n for (let l = 0; l < CONSTANTS.LOCATION_RADIUS - k; ++l) {\n if (!isAllowed(i + k, j + l)\n || !isAllowed(i + k, j - l)\n || !isAllowed(i - k, j + l)\n || !isAllowed(i - k, j - l)) {\n return false;\n }\n }\n }\n return true;\n }\n\n for (let k = 0; k < fineRows; ++k) {\n for (let l = 0; l < fineColumns; ++l) {\n const tile = fineGrid[k * fineColumns + l];\n if (tile !== 0) {\n const row = round(tile.i / CONSTANTS.LOCATION_DIST);\n const column = round(tile.j / CONSTANTS.LOCATION_DIST);\n\n let validIndex = 0;\n let index = (row.result + row.dir) * generationData.gridColumns + column.result + column.dir;\n if (index < generationData.gridRows * generationData.gridColumns) {\n if (generationData.locationGrid[index] !== 0) continue;\n validIndex = index;\n }\n index = (row.result + row.dir) * generationData.gridColumns + column.result;\n if (index < generationData.gridRows * generationData.gridColumns) {\n if (generationData.locationGrid[index] !== 0) continue;\n validIndex = index;\n }\n index = row.result * generationData.gridColumns + column.result + column.dir;\n if (index < generationData.gridRows * generationData.gridColumns) {\n if (generationData.locationGrid[index] !== 0) continue;\n validIndex = index;\n }\n index = row.result * generationData.gridColumns + column.result;\n if (index < generationData.gridRows * generationData.gridColumns) {\n if (generationData.locationGrid[index] !== 0) continue;\n validIndex = index;\n }\n\n if (areNeighborsFree(tile.i, tile.j, tile.isAllowed)) {\n generationData.locationGrid[validIndex] = {i: tile.i, j: tile.j};\n generationData.biomeGraph.biomes[getTile(tile.i, tile.j).biomeID].locations.push({i: tile.i, j: tile.j});\n }\n }\n }\n }\n}",
"findOnlyPossibePositions (cellPos, step) {\n // getAll possible moves \n let allPos = this.findAllPositions(cellPos, step);\n\n let filter1 = this.filterOutOfBoundaryMoves(allPos);\n \n // filter by both opp bot id and block id\n let filter2 = this.filterById(filter1, [2, -1]);\n return filter2;\n }",
"function getSafeLoc(board) {\n var locs = [];\n for (var i = 0; i < board.length; i++) {\n for (var j = 0; j < board[0].length; j++) {\n if (!board[i][j].isMine && !board[i][j].isShown) locs.push({ i: i, j: j });\n }\n }\n return locs[getRandomInt(0, locs.length - 1)];\n}",
"function getNoMineCells(board) {\n var noMineCells = []\n for (var i = 0; i < board.length; i++) {\n for (var j = 0; j < board.length; j++) {\n if (board[i][j].isMine) continue\n if (board[i][j].isShown) continue\n var currPos = {\n i,\n j\n }\n noMineCells.push(currPos)\n }\n }\n return noMineCells\n}",
"function getlookblock(){\n let searchpos = {};\n searchpos.x = gfx.camera.position.x;\n searchpos.y = gfx.camera.position.y;\n searchpos.z = gfx.camera.position.z;\n console.log(Math.floor(searchpos.x));\n console.log(Math.floor(searchpos.y));\n console.log(Math.floor(searchpos.z));\n\n \n for(let i = 0; i < 30; i++){\n searchpos.x += lookvector.x * i * 1; //using 0.2 increment for testing, this should be tested and heightened later\n searchpos.y += lookvector.y * i * 1;\n searchpos.z += lookvector.z * i * 1;\n\n console.log(Math.floor(searchpos.x));\n console.log(Math.floor(searchpos.y));\n console.log(Math.floor(searchpos.z));\n\n\n if(blocks[Math.floor(searchpos.x + 0.5)] != undefined){\n if(blocks[Math.floor(searchpos.x + 0.5)][Math.floor(searchpos.y + 0.5)] != undefined){\n if(blocks[Math.floor(searchpos.x + 0.5)][Math.floor(searchpos.y + 0.5)][Math.floor(searchpos.z + 0.5)] != undefined){\n console.log(\"block found\");\n addblock(Math.floor(searchpos.x + 0.5), Math.floor(searchpos.y + 0.5), Math.floor(searchpos.z + 0.5), \"select\");\n break;\n }\n }\n }\n }\n}",
"avoidEnemyLocations(enemyPositionsToAvoid) {\n let largestSumDist = null;\n let avoidLocs = [];\n let robotMap = this.getVisibleRobotMap();\n if (enemyPositionsToAvoid.length > 0){\n\n let positionsToGoTo = search.circle(this, this.me.x, this.me.y, 4);\n for (let i = 0; i < positionsToGoTo.length; i++) {\n let thisSumDist = 0;\n let pos = positionsToGoTo[i];\n if (search.emptyPos(pos[0], pos[1], robotMap, this.map)){\n for (let j = 0; j < enemyPositionsToAvoid.length; j++) {\n thisSumDist += qmath.dist(pos[0], pos[1], enemyPositionsToAvoid[j][0], enemyPositionsToAvoid[j][1]);\n }\n avoidLocs.push({pos:pos, dist:thisSumDist});\n }\n }\n }\n if (avoidLocs.length > 0) {\n //FORCE A MOVE AWAY\n\n avoidLocs.sort(function(a,b) {\n return b.dist - a.dist;\n })\n let rels = base.rel(this.me.x, this.me.y, avoidLocs[0].pos[0], avoidLocs[0].pos[1]);\n return rels;\n }\n else {\n return null;\n }\n }",
"function availableAntennaLocationsForWholeTowerLeg(blockedHeights, leg){\n var availableLocations = []\n for (antenna of leg){\n if (!blockedHeights.includes(antenna)){\n if (!availableLocations.includes(antenna)){\n availableLocations.push(antenna);\n }\n }\n }\n\n return availableLocations;\n}",
"function infectBlock(fromBlock, dir, options) {\n lat1 = fromBlock.lat\n lng1 = fromBlock.lng\n new_lat_lng = newLatLng(lat1, lng1, dir);\n requestGeocode(new_lat_lng[0], new_lat_lng[1], infectBlockCallback, options)\n}",
"function getAvoidAreas() {\n\t\t\tvar layerAvoid = this.theMap.getLayersByName(this.AVOID)[0];\n\t\t\treturn layerAvoid.features;\n\t\t}",
"getPossibleNodeLocations() {\r\n\t\t// Array that holds locations that new nodes can be added to.\r\n\t\tlet posNodes = [];\r\n\t\t\r\n\t\t// Iterate over every previous node.\r\n\t\tfor (let i = 0; i < this.prevNodes.length; i++) {\r\n\t\t\t// Add the location which the new node can be placed. This is bascially\r\n\t\t\t// just the location of a weight as when a node is added, it is added\r\n\t\t\t// and intersects the weight.\r\n\t\t\tposNodes.push([this, i]);\r\n\t\t\t\r\n\t\t\t// If the previous node is not an input node, then get the\r\n\t\t\t// possible node locations of the previous node and add it to\r\n\t\t\t// the posNodes array.\r\n\t\t\tif (isNaN(Number(this.prevNodes[i]))) {\r\n\t\t\t\tposNodes.concat(this.prevNodes[i].getPossibleNodeLocations());\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\t// Return the possible node locations\r\n\t\treturn posNodes;\r\n\t}",
"function getAvoidAreas() {\n var layerAvoid = this.layerAvoid;\n return layerAvoid.getLayers();\n }",
"blocksTravelled(){\n let horizontal = Math.abs(eastWest.indexOf(this.beginningLocation.horizontal) - eastWest.indexOf(this.endingLocation.horizontal))\n let vertical = Math.abs(parseInt(this.beginningLocation.vertical)-parseInt(this.endingLocation.vertical))\n return (horizontal + vertical);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Just some polar functions to convert x/y into radius/angle | function polar_x(radius, angle) {return(radius * Math.cos(Math.PI/180*angle + Math.PI/180*270));} | [
"toPolarCoords() {\n return ({\n r: Math.sqrt(this.x ** 2 + this.y ** 2),\n a: Point.angle(this),\n });\n }",
"toPolar()\r\n {\r\n return createVector(this.center.x + this.radius * cos(this.angle), \r\n this.center.y + this.radius * sin(this.angle));\r\n }",
"polarToCartesian(cx, cy, r, angleDegrees) {\n let angleInRad = ((angleDegrees - 90) * Math.PI) / 180;\n let x = cx + r * Math.cos(angleInRad);\n let y = cy + r * Math.sin(angleInRad);\n return { x, y };\n }",
"function cartesianToPolar(x, y) {\n\n\t\tconst radius = height/6\n\t\tconst _x = (radius + 400 * y/height) * Math.sin(2 * Math.PI * x/width) + width/2\n\t\tconst _y = (radius + 400 * y/height) * Math.cos(2 * Math.PI * x/width) + height/2\n\n\t\treturn { X:_x, Y:_y}\n\t}",
"function cartesianToPolar(x,y) {\n var r = scope.radiusScale(x);\n var a = scope.thetaScale(y) - Math.PI/2;\n x = r * Math.cos(a) + size.width/2;\n y = r * Math.sin(a) + size.height/2;\n return ({x:x,y:y});\n\n }",
"function cartesianToPolar(x, y) {\n\t\tvar r = scope.radiusScale(x);\n\t\tvar a = scope.xScale(y) - Math.PI / 2;\n\t\tx = r * Math.cos(a) + size.width / 2;\n\t\ty = r * Math.sin(a) + size.height / 2;\n\t\treturn ({x: x, y: y});\n\t\t\n\t}",
"function polar(rFunctionOfTheta){\n return function(parameter){\n var theta = parameter;\n var radius = rFunctionOfTheta(theta);\n return [radius * Math.cos(theta), radius * Math.sin(theta)];\n }\n}",
"static toPolar(xyz){\r\n\t\tlet t = new Array();\r\n\t\tt[0] = Math.sqrt(xyz[0] * xyz[0] + xyz[1] * xyz[1] + xyz[2] * xyz[2]);\r\n\t\tt[1] = Math.acos(xyz[2] / t[0]);\r\n\t\tt[2] = Math.atan2(xyz[1], xyz[0]);\r\n\r\n\t\tif(t[1]<0){t[1]+=2*Math.PI;}\r\n\t\tif(t[2]<0){t[2]+=2*Math.PI;}\r\n\r\n\t\treturn t;\r\n\t}",
"get polarAngle() {\n return this._spherical.phi;\n }",
"function polar(inData, outData, x0, y0, width, height, callback) {\n /* Sets image data based on a polar coordinates filter.\n * The given callback is a function(distance, angle) that returns new [distance, angle].\n */\n x0 = width / 2 + (x0 || 0);\n y0 = height / 2 + (y0 || 0);\n var y1, x1, x, y, d, a, v;\n for (y1 = 0; y1 < height; y1 += 1) {\n for (x1 = 0; x1 < width; x1 += 1) {\n x = x1 - x0;\n y = y1 - y0;\n d = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));\n a = Math.atan2(y, x);\n v = callback(d, a);\n d = v[0];\n a = v[1];\n setPixel(outData, x1 + y1 * width, getPixel(inData,\n Math.round(x0 + Math.cos(a) * d) +\n Math.round(y0 + Math.sin(a) * d) * width\n ));\n }\n }\n}",
"function cartesian2Polar(point){\n var x = point[0];\n var y = point[1];\n var theta = rad2deg(Math.atan(y/x));\n \n // Q1: Use theta\n // Q2, Q3: Use theta + 180\n // Q4: Use theta + 360\n if(x < 0) theta += 180; // Handles Q2, Q3\n if(x > 0 && y < 0) theta += 360; // Handles Q4 \n \n if(x == 0){\n if(y > 0) theta = 90;\n else if(y < 0) theta = 270;\n else theta = 0;\n }\n \n return [magnitude(x,y), theta];\n}",
"function relative_polar(relative_angle, distance) {\n current_angle += relative_angle;\n // to keep angles within 360 range\n if (current_angle >= 360) current_angle %= 360;\n if (current_angle < 0) current_angle = 360 - current_angle;\n // will return delta x y\n return {\n x: Math.cos(rad(current_angle)) * distance,\n y: -Math.sin(rad(current_angle)) * distance\n }\n}",
"static fromPolar(angle, r = 1) {\n return new Point(r * Math.cos(angle), r * Math.sin(angle));\n }",
"pointToPolarAngle(point) {\n\t\tlet relativePoint = point.sub(this.center);\n\t\tlet angleInRadians = Math.acos(relativePoint.z/this.radius);\n\n\t\treturn angleInRadians;\n\n\t}",
"function polarToCartesian(r, theta) {\n return [r * Math.cos(theta), r * Math.sin(theta)];\n }",
"function yTrigonometricPosition(radius, angle)\n{\n return radius * Math.sin(angle);\n}",
"function polarAdd(origin, angle, length) {\n\t var x = origin[0];\n\t var y = origin[1];\n\t return [x + Math.cos(angle * 2 * Math.PI / 360) * length, y + -1.0 * Math.sin(angle * 2 * Math.PI / 360) * length];\n\t}",
"calcAngle(pointX, pointY) {\n let dimensions = this.sliderRing.getBoundingClientRect();\n let cx = dimensions.left + (dimensions.width / 2);\n let cy = dimensions.top + (dimensions.height / 2);\n\n let dx = pointX - cx;\n let dy = pointY - cy;\n // returns angle in degrees. + 90 is added to rotate coordinate system\n // so 0deg angle is at the top of the circle.\n let angle = Math.atan2(dy, dx) * 180 / Math.PI + 90;\n if (angle < 0) {\n angle += 360;\n }\n return angle;\n }",
"function polarAdd(origin, angle, length) {\n\t var x = origin[0];\n\t var y = origin[1];\n\t return [x + Math.cos(angle * 2 * Math.PI / 360) * length, y + -1 * Math.sin(angle * 2 * Math.PI / 360) * length];\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renders a Handlebars template, reading from a tag. Returns HTML. | function render(templateId, data) {
var source = document.getElementById(templateId).textContent
var template = Handlebars.compile(source)
return template(data)
} | [
"function renderTemplate() {\n\tvar app = document.getElementById('app')\n\tvar templateSource = document.getElementById('to-do-template')\n\tvar template = Handlebars.compile( templateSource.innerHTML )\n\tvar renderedTemplate = template( data )\n\n\tapp.innerHTML = renderedTemplate\n}",
"function render(context){\n var template = $(\"#stars-template\").html();\n var compile = Handlebars.compile(template);\n var html = compile(context);\n $(\".star-profiles\").html( html ).show();\n}",
"function stocktakingResultTemplate(data) {\n //takes template and populate it with passed array\n var rawTemplate = document.getElementById(\"stocktakingResultTemplate\").innerHTML;\n var compiledTemplate = Handlebars.compile(rawTemplate);\n var stocktakingStorageGeneratedHTML = compiledTemplate(data);\n // display template in choosen ID tag\n var storageContainer = document.getElementById(\"stocktakingResultContainer\");\n storageContainer.innerHTML = stocktakingStorageGeneratedHTML;\n}",
"function shoveToTemplate ( ) {\n completeHandlebarsTemplate = theTemplate( students.eta[ person ] );\n\n //CompleteHandlebarsTemplate is appended to the body\n $( \"section\" ).html( completeHandlebarsTemplate );\n}",
"compile( data ) {\n var source = this[0].innerHTML;\n var template = Handlebars.compile( source );\n return template( data );\n }",
"function renderHandlebars() {\n var html = HandlebarsTemplates['users/index'](); // place data in parens when you're sending data to hbs file\n // Use an ID to ensure only one, we don't want an array\n $('#map').append(html);\n }",
"function template( data ) {\n data = data || {};\n utils.extend( data, site.data );\n\n return through.obj( function( file, encoding, callback ) {\n var fileContents = file.contents.toString();\n var tmpl = Handlebars.compile( fileContents );\n file.contents = new Buffer( tmpl( data ) );\n return callback( null, file );\n });\n }",
"function displayHandlebarsTemplate(templatePath, templateData, targetEntity, callback, strategy) {\n // If we've already used this template once while on this page, don't bother\n // reading in that file again. Just pull it from memory.\n if (handlebarsTemplates[templatePath] === undefined) {\n $.ajax({\n type: 'GET',\n url: templatePath,\n datatype: 'text',\n success: function (templateContents, status, response) {\n handlebarsTemplates[templatePath] = Handlebars.compile(templateContents);\n renderHandlebarsTemplate(handlebarsTemplates[templatePath], templateData, targetEntity, strategy);\n if (callback != null) {\n callback();\n }\n },\n error: function (data, response, error) {\n bootbox.alert(\"An error occurred while rendering this screen. Please try again, and if the problem continues contact your system administrator.\", function() {});\n }\n });\n }\n else {\n renderHandlebarsTemplate(handlebarsTemplates[templatePath], templateData, targetEntity, strategy);\n if (callback != null) {\n callback();\n }\n }\n }",
"function handlebars(nome, cognome, eta){\r\n var source = $(\"#entry-template\").html();\r\n var template = Handlebars.compile(source);\r\n\r\n var context = {\r\n nome: nome,\r\n cognome: cognome,\r\n eta: eta,\r\n };\r\n\r\n var html = template(context);\r\n $(\".container\").append(html);\r\n}",
"function editStorageTemplate(data) {\n //takes template and populate it with passed array\n var rawTemplate = document.getElementById(\"editStorageTemplate\").innerHTML;\n var compiledTemplate = Handlebars.compile(rawTemplate);\n var editStorageGeneratedHTML = compiledTemplate(data);\n // display template in choosen ID tag\n var storageContainer = document.getElementById(\"editStorageContainer\");\n storageContainer.innerHTML = editStorageGeneratedHTML;\n}",
"bindHandlebarsTemplateToDom() {\n $(this.container).html(template());\n }",
"function renderHandlebarsTemplate(withTemplate,inElement,withData, cb){\r\n getTemplateAjax(withTemplate, function(template) {\r\n jqueryNoConflict(inElement).html(template(withData));\r\n if(typeof cb ===\"function\"){cb()};\r\n //console.log(cb)\r\n })\r\n}",
"function groupRestrictionTemplate(data) {\n //takes template and populate it with passed array\n var rawTemplate = document.getElementById(\"groupRestrictionTemplate\").innerHTML;\n var compiledTemplate = Handlebars.compile(rawTemplate);\n var storageRestrictionGeneratedHTML = compiledTemplate(data);\n // display template in choosen ID tag\n var storageContainer = document.getElementById(\"groupRestrictionContainer\");\n storageContainer.innerHTML = storageRestrictionGeneratedHTML;\n}",
"function render_template (template_id, data) {\n return nunjucks.renderString(document.getElementById(template_id).innerHTML, data);\n}",
"function renderAccordionTemplate() {\n $(\"#accordion-container\").html(renderHandlebarsTemplate(\"accordionTemplate\", accordion));\n}",
"function template(target, relative) {\n var raw = read(target, relative, true);\n return _handlebars2.default.compile(raw);\n}",
"render(data, template) {\n var html = template.innerHTML;\n\n // Attempts\n // to compile the tmplate.\n for (var key in data) {\n var placeholder = '{{' + key +'}}';\n\n if (html.search(placeholder) !== -1) {\n html = html.replace(placeholder, data[key]);\n }\n }\n\n this.el.innerHTML = html;\n }",
"function renderTag(template, tag, value) {\n if (!tag) {\n console.log('Resources:renderTag: The tag is invalid');\n return template;\n }\n if (value === null || value === undefined) {\n value = '';\n }\n var regex = new RegExp(tag, 'gmi');\n return template.replace(regex, value);\n }",
"function showProductMacTemplate(data) {\n //takes template and populate it with passed array\n var rawTemplate = document.getElementById(\"showProductMacTemplate\").innerHTML;\n var compiledTemplate = Handlebars.compile(rawTemplate);\n var storageRestrictionGeneratedHTML = compiledTemplate(data);\n // display template in choosen ID tag\n var storageContainer = document.getElementById(\"showProductMacContainer\");\n storageContainer.innerHTML = storageRestrictionGeneratedHTML;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reload the outbrain modules after the ajax call | function reloadOutBrainModules() {
if (typeof(OBR) !== "undefined" && typeof(OBR.extern) !== "undefined" &&
typeof(OBR.extern.researchWidget) !== "undefined") {
OBR.extern.researchWidget("http://" + document.location.hostname + document.location.pathname);
}
} | [
"function upcDoUpdate(){\n\tif(!singlePageSite){ //If it's not a single page site, remove the script for the modules loaded for the previous page\t\t\t\t\n\t\twhile($s(\"moduleScript\")) $(\"#moduleScript\").remove();\n\t}\t\t\t\t\n\tif(pageAjax.readyState===4){\n\t\tupdatePage();//parse response and finalize page update\n\t}\n}",
"function reloadProviders() {\n loading('Reloading Music Library');\n stopPlayer();\n enableControls(false);\n setNameAndTitle('Reloading Music Library...', '');\n $.getJSON('/rest/settings/providers/reload', function(data) {\n enableControls(true);\n loaded();\n initSettings();\n albums();\n }).error(showErrorState);\n}",
"function clearCache(module_name) {\n $.ajax({\n type: \"POST\",\n headers: { \"cache-control\": \"no-cache\" },\n async: false,\n url: tsDir + 'ajax.php',\n data: \"module=\"+module_name,\n success: function(data) {\n \n }\n });\n }",
"reloadModules() {\n this.moduleLib = {};\n\n fs.readdirSync(moduleStorage).forEach((module) => {\n const splitName = module.split(\".\");\n const isCrawlModule = splitName.length > 0 && splitName[splitName.length - 1] === 'js'; // check the file is a js-file\n\n if (isCrawlModule) {\n splitName.pop(); //remove file extension\n const moduleName = splitName.join('.');\n\n const module = require(path.join(moduleStorage, moduleName)); // load module\n let name = module.moduleName;\n if (!name || this.moduleLib[name]) {\n name = moduleName;\n }\n this.moduleLib[name] = { //save the module information\n name: name,\n path: path.join(moduleStorage, moduleName),\n expire: module.expires,\n status: threadStatus.inactive,\n lastParse: null,\n lastStart: null\n };\n }\n });\n\n //logging about loaded modules\n console.log(colors.cyan('Loaded crawler modules ', Object.keys(this.moduleLib).length));\n Object.keys(this.moduleLib).forEach((item) => {\n console.log(colors.cyan(colors.underline('\\tmodule name'), item));\n });\n\n // this.crawlAll(); // run crawling after reload\n this.initThreadWatcher();\n }",
"function ajax_Load() {\n //$(\".consoleLogOutput\").append('<div class=\"consoleLog_helm\">ajax_Load() event starting.</div>');\n \n if (helm.alreadyInitialized && helm.RefreshHelmDataAfterUpdatePanelPostBack) {\n helm.jQueryBindEvents();\n helm.Initialize(true); //true -> because this is after ajax request\n } else {\n //reset the refresh overrides\n helm.alreadyInitialized = true;\n helm.RefreshHelmDataAfterUpdatePanelPostBack = true;\n }\n \n }",
"function populateModulePage() {\n\t$.getJSON(\"../php/json-data-modules.php\", function(data) {\n\t\t//assign dataset to modules variable\n\t\tmodules = data.modules;\n\t\t//iterate through module data, append module information to moduleButtons div\n\t\t$.each(data.modules, function(index, module) {\n\t\t\t$(\"#moduleButtons\").append(\"<li class='individualModule' id='\" + module.moduleNo + \"'><a href='#moduleInfo'>\"+ module.moduleName+ \"</a></li>\");\n\t\t});\n\t\t//refresh the listview\n\t\t$(\"#moduleButtons\").listview(\"refresh\");\n \t});\n}",
"function refreshSamurai() {\n\n if (typeof mov.vars.adminUrl === \"undefined\") { return; }\n\n _$cls('cmsItem').each(function () {\n initElement(this);\n });\n \n }",
"function loadData () {\n ajaxRequest(settingsApp.url);\n }",
"function reload_experiments_tables() {\n $.ajax({\n dataType: \"json\",\n method: \"POST\",\n url: BaseURL,\n data: {\n action: \"all_experiments\"\n },\n success: fill_experiment_tables,\n });\n }",
"function RefreshAnnouncementsAjax() {\n $.ajax({\n url: '/lobby/ajax/announcements',\n success: function(data) {\n data=$(data)\n $('#announcement-ajax').html(data);\n }\n });\n }",
"function fnReloadGrid() {\n $ibTcReqHGrid.paragonGridReload();\n }",
"pandaUILoaded() { if (this.wasImporting) window.location.reload(); }",
"function reload_tree()\n {\n var $spinner = add_spinner($block.find('.commands'));\n\n $spinner.show();\n\n $.post(get_action_url(\"rest\"),\n {\n \"action\": \"render_tree\"\n },\n function(response)\n {\n $block.find(\".tree\").replaceWith($(response));\n $.init_item_tree();\n }, \"text\")\n .fail(function(response)\n {\n show_error(response);\n })\n .always(function(response)\n {\n $spinner.hide();\n });\n }",
"function getModuleData() {\n\t$.getJSON(\"../php/json-data-modules.php\", function(data) {\n\t\t//save module data to global variable modules\n\t\tmodules = data.modules;\n\t});\n}",
"function fnReloadGrid() {\n $domainGrid.paragonGridReload();\n }",
"function reload_data() {\n\t$.getJSON(\"/api/heatpumps\")\n\t.done(function( heatpumps) {\n\t\t$.each(heatpumps, function(index, heatpump) {\n\t\t\tupdate_heatpump_ui(heatpump)\n\t\t});\n\t})\n\t.fail(function() {\n\t\tconsole.log( \"Error calling /api/heatpumps...\" );\n\t})\n}",
"reload(){\n this.gunModule.reload();\n }",
"function initReplace(){\n\t\t\t//modify href by ajax\n\n\t\t\t$(\"#manageright a[name='ajax']\").bind(\"click\",function(){\n\t\n\t\t\t\t$.get(this.href,null,checkSuccess);\n\t\t\t\t\n\t\t\t\treturn false;\n\t\t\t}) \n\t\t\t\n\t\t\t$(\"#page a\").bind(\"click\",function(){\n\t\n\t\t\t\trightchange(this.href);\n\t\t\t\t\n\t\t\t\treturn false;\n\t\t\t}) \n\t\t\tvar option = {\n\t\t\tsuccess:checkSuccess\n\t\t\t}\n\t\t\t$(\"form\").ajaxForm(option);\n}",
"function wireUpLivemarkReload () {\n /*\n $('.reloadAllLivemarks').click(function (ev) {\n postMessage({ type: 'reloadAllLivemarks' });\n return false;\n });\n */\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Opens a printable boarding pass in a new window. Removes booking data from sessionStorage. | function printPass() {
var windowFeatures = "resizable=no,scrollable=no,width=900,height=450";
var passWindow = window.open("", '_blank', windowFeatures);
var type = "<!DOCTYPE html>";
var head = "<head><meta charset='utf-8'><title>Bookings</title><link rel='stylesheet' href='css/style.css'></head>";
var name = sessionStorage.getItem("name") + " " + sessionStorage.getItem("lastname");
var persnr = sessionStorage.getItem("persnr");
var seat = sessionStorage.getItem("seatnr");
var clas = sessionStorage.getItem("class");
var printBtn = "<input type='button' onClick='window.print()' value='Print'/>";
var section = "<section id='pass'><h2>Boarding Pass</h2><h3>Passenger name: " + name + "</h3><h3>Pers. Nr: " + persnr + "</h3><h3>Seat: " + seat + "</h3><h4>" + clas + " class</h4></section>";
var body = "<body id='boardingPass'>" + section + printBtn + "</body><footer></footer></html>";
passWindow.document.write(type + "<html>" + head + body);
sessionStorage.removeItem("name");
sessionStorage.removeItem("lastname");
sessionStorage.removeItem("persnr");
sessionStorage.removeItem("class");
sessionStorage.removeItem("seatnr");
} | [
"function Pophistory() {\r\n newWin=window.open('index.php?page=allshout','shouthistory','height=500,width=490,resizable=yes,scrollbars=yes');\r\n if (window.focus) {newWin.focus()}\r\n}",
"function openPrintable(sTitle, sURL)\r\n{\r\n\tvar win = null;\r\n\twin = window.open(sURL, sTitle, \"width=620,height=460,status=no,toolbar=no,scrollbars=yes\");\r\n}",
"function showTicket(booking){\n const win = window.open(\"\", \"Biljett\", \"resizable=yes,width=780,height=250\");\n const html = \"<!DOCTYPE html>\" +\n \"<html lang='en'>\" +\n \"<head>\"+\n \"<meta charset='UTF-8'>\"+\n \"<meta name='viewport' content='width=device-width, initial-scale=1.0'>\" +\n \"<title>Biljett</title>\" + \n \"<link rel='stylesheet' href='./css/style.css'>\"+\n \"</head>\"+\n \"<body>\"+\n \"<section class='ticket'>\" +\n \"<h1>Din biljett</h1>\"+\n \"<p>\" + booking.firstname + \" \" + booking.lastname + \"</p>\" +\n \"<p> Personnummer: \" + booking.personnr + \"</p>\" +\n \"<p> Plats: \" + booking.seat + \" Rad: \" + booking.row +\n \"<br>Biljetten avser resa i \" + getTravelClass(booking.seat).toLowerCase(); + \"</p>\" +\n \"</section>\"\n \"</body>\"+\n \"</html>\";\n\n win.document.write(html);\n}",
"function buyTicket() {\n window.open(movie_array[currentIndex].Trailer, \"_blank\");\n}",
"function shipping_costs(){\n\twindow.open(\"content/shippingcosts/index8124.html?blank=true\",\"Shipping\",\"height=580,width=710,menubar=no,location=no,resizable=false,scrollbars=yes,status=yes,toolbar=no,top=0\");\n}",
"function openPrinterFriendly(url){\r\n\tvar settings = \"width=800,height=600,scrollbars=yes,location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=yes\";\r\n\tpfLink = window.open(url, 'PrintPage', settings);\r\n\tpfLink.focus();\r\n}//",
"function caseWindow(URL) {\r\n caseWin = window.open(URL, 'caseWin', 'width=800,height=610,scrollbars=yes');\r\n caseWin.focus();\r\n}",
"function printerFriend(hrefTarget) {\n //Set Variables\n var name, width, height;\n name = \"printerVersion\";\n width = \"603\";\n height = \"500\";\n popWindow(hrefTarget, name, width, height, resizable = \"yes\");\n}",
"function openHowToPurchaseWindow()\n{\t\n\tNewWindow = window.open('how_To_Purchase.html','What is cvv','width=850,height=700,resizable=no,scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=no,colyhistory=no'); \n}",
"function storeIssuePrintPreview(issueId)\n{\n window.open(\"procurement/print/storeIssueDialog.jsp?operationType=find&output=HTML&issueId=\" + issueId,\n \"Store Issue Print Preview\",\n \"menubar=no,location=no,resizable=yes,scrollbars=yes,status=yes\");\n} //End of function storeIssuePrintPreview",
"function openBuyNow(url) {\n\tvar newWin = window.open(url,\"\",\"\");\n\treturn;\n}",
"function preview_flyer(id)\n{\n\twindow.open('generate.php?flyerid=' + id,null,'height=600,width=800,status=no,toolbar=no,menubar=no,location=no'); \n\tself.close();\n}",
"startOnboarding () {\n sessionStorage.setItem(REGISTRATION_IN_PROGRESS, true)\n this._openDownloadPage()\n this._openForwarder()\n }",
"function openPosterWindow()\r\n{\r\n if (!posterWindow || posterWindow.closed)\r\n posterWindow = window.open('about:blank', 'posterReport');\r\n if (posterWindow) {\r\n posterWindow.blur();\r\n window.focus();\r\n }\r\n}",
"function OpenSaferpayTerminalWindow() \r\n\t{\r\n\t\twindow.onerror = DoNothing;\r\n\r\n\t\t//reset the url for the next click\r\n\t\tif(strMode == \"LINK\") objRef.href = strUrl;\r\n\t\telse if(strMode == \"FORM\") objRef.action = strUrl;\r\n\t\t\r\n\t\t//add the standalone attribute to deliver the window state to the server\r\n\t\tif(strUrl.indexOf(\"WINDOWMODE=Standalone\") == -1) strUrl += \"&WINDOWMODE=Standalone\";\r\n\t\r\n\t\tw = window.open(\r\n\t\t\tstrUrl,\r\n\t\t\t'SaferpayTerminal',\r\n\t\t\t'scrollbars=1,resizable=0,toolbar=0,location=0,directories=0,status=1,menubar=0,width=580,height=400'\r\n\t\t);\r\n\t\t\r\n\t\tif (w)\r\n\t\t\tw.focus();\r\n\t\telse\r\n\t\t\twindow.location.href = strUrl;\r\n\t}",
"function openNewWindowForLocalBodyElection(){\r\n\tvar constituencyId = $('#constituencyList').val();\r\n\tvar constituencyName = $('#constituencyList option:selected').text();\r\n\tvar urlStr=\"localBodyElectionResultsAction.action?constituencyId=\"+constituencyId+\"&constituencyName=\"+constituencyName;\r\n\tvar updateBrowser = window.open(urlStr,\"localBodyElectionResultsAction\",\"scrollbars=yes,height=600,width=700,left=200,top=200\");\t\r\n\tupdateBrowser.focus();\r\n}",
"function reply_click(clicked_id){\n window.open('movie-details.html?'+clicked_id);\n}",
"function openWindow(batchno,AssQTY) {\n\t\twindow.open(\"viewBatchDetails.do?methodName=getBatchDetails&Batch_No=\"+batchno+\"&AssignedQTY=\"+AssQTY);\n\t\t\n\t}",
"function OnCmdPrintPrayerPlan()\r\n{\r\n window.openDialog(\"chrome://kneemail/content/print_prayer_plan.xul\", \"print_prayer_plan\", \"modal,centerscreen\", intPlans[intPlan]);\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Searches from back of array, until a 1 is found that can be swapped, then swaps it as far to the right as it can go Returns index of last 1 that can be swapped. Returns 1 if there aren't any 1's in the array that can be swapped (no 1's with a 0 to it's right) | function swapNext1AsFarAsItCanGo(array) {
const end = array.length - 1;
let i = findIndexOfLast1NotAtTheEnd(array);
if(i !== -1) {
for(let j = i; j < end; j++) {
if(array[j+1] === 1) { // If next number is a 1, stop swapping. So in this situation: [1,0,1,1] - it will find the first 1 and only swap once.
return {indexOfLast1: i, numbersAtTheEnd: end-j};
}
swapWithNext(array, j);
}
}
return {indexOfLast1: i, numbersAtTheEnd: 1};
} | [
"function minimumSwaps(arr) {\n\n if (arr.length < 1 || arr.length > 1000000) {\n return \"Invalid array length\"\n }\n\n let swaps = 0;\n\n for (let i = 0; i < arr.length; i++) {\n // at this position what is the right number to be here\n // for example at position 0 should be 1\n // add 1 to i if array starts with 1 (1->n)\n const right = i + 1;\n // is current position does not have the right number\n if (arr[i] !== right) {\n // find the index of the right number in the array\n // only look from the current position up passing i to indexOf\n const rightIdx = arr.indexOf(right, i);\n // replace the other position with this position value\n arr[rightIdx] = arr[i];\n // replace this position with the right number\n arr[i] = right;\n // increment the swap count since a swap was done\n swaps++;\n }\n }\n\n return swaps;\n\n}",
"function mirrorBinary(arr) {\n if (arr.length % 2 == 0) {\n let comparisons = arr.length / 2\n let low = comparisons - 1\n let high = comparisons\n return compare(comparisons, low, high, arr)\n } else {\n let comparisons = Math.floor(arr.length / 2)\n let low = comparisons - 1\n let high = comparisons + 1\n return compare(comparisons, low, high, arr)\n }\n}",
"function find_longest(arr){\n var swap_happened = true;\n var all_elements_not_same_length = true;\n\n for(i = 0; i < arr.length-2; i++){\n\n if(arr[i] == arr[i+1]){\n all_elements_not_same_length = false;\n // console.log(\"found elements that are the same length\");\n }\n else{\n all_elements_not_same_length = true;\n }\n }\n\n if(all_elements_not_same_length){\n while(swap_happened){\n\n for(index = 0; index < arr.length - 1; index++){\n\n if(arr[index].length > arr[index + 1].length){\n\n var_moving_backward = arr[index + 1];\n var_moving_forward = arr[index];\n arr[index] = var_moving_backward;\n arr[index + 1] = var_moving_forward;\n swap_happened = true;\n // console.log(\"swap happened this pass\")\n\n }\n else{\n swap_happened = false;\n // console.log (\"swap didn't happen this pass\")\n }\n }\n }\n }\n else{\n console.log(\"All elements are the same length. Function will return last element.\");\n }\n\n console.log(arr[arr.length-1]);\n return arr[arr.length-1];\n\n}",
"function reversSort(arr) {\n //defining variable temp for exchanging items\n var temp;\n //loop for decreasing part of array, which is checked\n for (var i = 0; i < arr.length; i++) {\n //loop for comparison items. Every loop iteration pushes max item to end of array\n //new iteration uses array without this item, thereby sorted items build up in the\n //end of array. After all iteration array is sorted\n for (var j = 0; j < arr.length - i - 1; j++) {\n //condition for comparison of current and next items\n if (arr[j] < arr[j + 1]) {\n //exchanging items if condition is executed\n temp = arr[j];\n arr[j] = arr[j + 1];\n arr[j + 1] = temp;\n }\n }\n }\n //returning array\n return arr;\n}",
"function minimumSwaps(arr) {\n var switchs = 0;\n var iterable = 0;\n\n for (var ii = 1; ii < arr.length; ii++){\n if(arr[ii - 1] == ii) {\n continue;\n }\n else {\n const memo = arr[ii - 1];\n const ii_index = arr.indexOf(ii);\n arr[ii - 1] = arr[ii_index];\n arr[ii_index] = memo;\n switchs++;\n }\n }\n\n return switchs\n}",
"function minimunConsecutiveFlips(arr){\n\n\tfor(let i=1;i<arr.length;i++){\n\n\t\tif(arr[i] != arr[i-1]){\n\t\t\tif(arr[i] != arr[0]){\n\t\t\t\tconsole.log(\"flip from \"+ i+ \" to \");\n\t\t\t}\n\t\t\telse{\n\t\t\t\tconsole.log(i-1);\n\t\t\t}\n\t\t}\n\t}\n\n\tif(arr[arr.length-1] != arr[0]){ // if last element needs to be flipped\n\t\tconsole.log(arr.length-1);\n\t}\n}",
"function switchSort(arr) {\n var swap = 0\n visited = Array(arr.length).fill(false)\n for (let i=0; i<arr.length; i++) {\n var j = i\n count = 0\n while (! visited[j]) {\n visited[j] = true\n j = arr[j] - 1\n count++\n }\n if (count != 0) {\n swap = swap + (count-1)\n }\n }\n return swap;\n}",
"function ChangingSequence(arr) {\n var increasing = arr[1] > arr[0] ? true : false;\n\n for (var i = 2; i < arr.length; i++) {\n // check direction of the sequence\n var seq = arr[i] > arr[i - 1];\n if (seq !== increasing) {\n return i - 1;\n }\n }\n return -1;\n}",
"function swapFirstLast(array1) {\n\n var holder;\n var isInt = true;\n\n // does array have at least one element?\n if (array1.length < 1) {\n console.log(\"Given array is too short. Array must contain one or more elements\")\n } else {\n\n //is every element an integer?\n for (i=0; i < array1.length; i ++) {\n if ((array1[i] % 1) !== 0)\n isInt = false\n \n }\n\n if (isInt == true) {\n \n holder = array1[0]\n array1[0] = array1[(array1.length)-1]\n array1[(array1.length)-1] = holder\n } else {console.log (\"At least one array element is not an integer.\")}\n \n } \nconsole.log(\"The array is now: \" + array1)\n}",
"function minimumSwaps(arr) {\n let swaps = 0;\n for(let i =0; i< arr.length; i++){\n let currentNumber = arr[i];\n let properIndexNumber = arr[currentNumber - 1];\n while(currentNumber !== properIndexNumber){\n arr[i] = properIndexNumber;\n arr[currentNumber - 1] = currentNumber;\n swaps++;\n currentNumber = properIndexNumber;\n properIndexNumber = arr[currentNumber - 1];\n } \n\n }\n return swaps;\n}",
"function almostSorted(arr) {\n if(arr.length === 0 || arr.length === 1) {\n console.log('yes');\n return;\n }\n\n const dips = [];\n const bumps = [];\n\n if(arr[0] > arr[1]) {\n bumps.push(new Element(0, arr[0]));\n }\n\n for(let i = 1; i < arr.length - 1; i++) {\n if(arr[i - 1] < arr[i] && arr[i + 1] < arr[i]) {\n bumps.push(new Element(i, arr[i]));\n }\n else if(arr[i - 1] > arr[i] && arr[i + 1] > arr[i]) {\n dips.push(new Element(i, arr[i]));\n }\n }\n\n if(arr[arr.length - 1] < arr[arr.length - 2]) {\n dips.push(new Element(arr.length - 1, arr[arr.length - 1]));\n }\n\n if(dips.length === 0 && bumps.length === 0) {\n console.log('yes');\n }\n else if(dips.length === 2 && bumps.length === 2) {\n console.log('yes');\n console.log(`swap ${bumps[0].index + 1} ${dips[1].index + 1}`);\n }\n else if(dips.length === 1 && bumps.length === 1) {\n if(dips[0].index - bumps[0].index === 1) {\n if((bumps[0].index === 0 || dips[0].value > arr[bumps[0].index - 1])\n && (dips[0].index === arr.length - 1 || bumps[0].value < arr[dips[0].index + 1])) {\n console.log('yes');\n console.log(`swap ${bumps[0].index + 1} ${dips[0].index + 1}`);\n }\n else {\n console.log('no');\n }\n }\n else {\n console.log('yes');\n console.log(`reverse ${bumps[0].index + 1} ${dips[0].index + 1}`);\n }\n }\n else {\n console.log('no');\n }\n \n}",
"function ChangingSequence(arr) {\n for (var i = 0; i < arr.length - 2; i++) {\n if (arr[i] < arr[i + 1] && arr[i + 1] > arr[i + 2] || arr[i] > arr[i + 1] && arr[i + 1] < arr[i + 2]) {\n return i + 1;\n }\n }\n return -1;\n}",
"function minimumSwaps(arr) {\n let swaps = 0, i = 0, len = arr.length, tmp;\n while (i < len) {\n if (arr[i] === i + 1) {\n i++;\n continue;\n }\n tmp = arr[arr[i] - 1]\n arr[arr[i] - 1] = arr[i];\n arr[i] = tmp;\n swaps++;\n }\n return swaps;\n}",
"function decreaseArr(arr) {\n let index;\n for(let i = 0; i < arr.length; i++) {\n if(arr[i+1] - arr[i] > 0) {\n index = i;\n break;\n } else {\n index = -1;\n }\n }\n return index;\n }",
"function minSwipes(arr){\n\n\tarr = arr.map(e=>{return {v:e,visited:false}})\n\n\tlet swap = 0;\n\n\tfor(let i=0;i<arr.length;i++){\n\n\t\tlet currentNode = arr[i]\n\t\tlet currentPos = i;\n\n\t\twhile(!currentNode.visited){\n\t\t\t\n\t\t\tcurrentNode.visited = true;\n\n\t\t\tif(currentPos != currentNode.v){\n\n\t\t\t\tcurrentNode = arr[currentNode.v-1]\n\t\t\t\tcurrentPos = currentNode.v-1;\n\t\t\t\tif(!currentNode.visited){\n\t\t\t\t\tswap+=1\n\t\t\t\t}else{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}else{\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t}\t\n\n\t}\n\n\t\n\treturn swap;\n\n}",
"function swapNums(array){\n var temp = array[0];\n array[0] = array[array.length-1];\n array[array.length-1] = temp;\n return array;\n}",
"function arrayChangePP2(a){\n var length=a.length;\n var move=0;\n var rs=0;\n for(var i=0; i<length; i++)\n {\n while(a[i+1]<=a[i])\n {\n move=a[i]-a[i+1]+1;\n rs+=move;\n a[i+1]+=move;\n }\n }\n return rs;\n}",
"function swapValues(arr) {\n temp = arr[0];\n arr[0] = arr[arr.length - 1];\n arr[arr.length - 1] = temp;\n}",
"function rotIndex1(arr) {\r\n if (arr[0] < arr[arr.length - 1]){\r\n return 0;\r\n }\r\n for (var i = 1; i < arr.length - 1; i++) {\r\n if (arr[i - 1] > arr[i] && arr[i + 1] > arr[i]) {\r\n return i;\r\n }\r\n }\r\n return i;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save current window's state to settingsStore `layout.windows.json` at `local` | _saveWindowStates () {
this.settingsStore.set("MainWindow", this.mainWinName)
this.settingsStore.set('managed', this.windowStates)
this.settingsStore.set("LastOpen", this.lastOpen)
} | [
"saveSettings() {\n localStorage.setItem(this.localStorageKey, JSON.stringify(this.getLayout()));\n }",
"function setWindowState() {\n\tchrome.windows.getCurrent(currWindow => {\n\t\tchrome.storage.sync.set({\n\t\t\twindowState: {\n\t\t\t\tstate: currWindow.state,\n\t\t\t\twidth: currWindow.width,\n\t\t\t\theight: currWindow.height\n\t\t\t}\n\t\t});\n\t});\n}",
"function saveAppState(mainWindow) {\n // Save window position and dimensions\n var bounds = mainWindow.getBounds();\n // Overwrite only the saved window position/dimensions\n var currentState = getSavedOrDefaultAppState();\n if (mainWindow.isMaximized()) {\n currentState.lastWindowState.maximized = true;\n }\n else {\n currentState.lastWindowState.maximized = false;\n currentState.lastWindowState.rect = bounds;\n }\n try {\n var storageFile = path.join(electron_1.app.getPath(\"userData\"), appStateFileName);\n fs.writeFileSync(storageFile, JSON.stringify(currentState));\n }\n catch (error) {\n console.error(\"An error occurred while saving current app state:\\n\" + error);\n }\n}",
"saveState() {\n const that = this;\n\n if (!that.id) {\n that.warn(that.localize('noId'));\n return;\n }\n\n //Save to LocalStorage\n window.localStorage.setItem('smartDockingLayout' + that.id, JSON.stringify(that.getJSONStructure()));\n }",
"saveState() {\n const that = this;\n\n if (!that.id) {\n that.warn(that.localize('noId'));\n return;\n }\n\n //Save to LocalStorage\n window.localStorage.setItem('jqxDockingLayout' + that.id, JSON.stringify(that.getJSONStructure()));\n }",
"function save(){\n\tchrome.storage.sync.set({'currentView': currentView}, function() {\n\t\tconsole.log('Settings saved');\n });\n}",
"function windowStateKeeper(windowName) {\n var window, windowState;\n function setBounds() {\n var electronScreen = electron_1.screen;\n var size = electronScreen.getPrimaryDisplay().workAreaSize;\n // Restore from appConfig\n if (appConfig.has(\"windowState.\" + windowName)) {\n windowState = appConfig.get(\"windowState.\" + windowName);\n return;\n }\n // Default\n windowState = {\n x: undefined,\n y: undefined,\n width: size.width,\n height: size.height\n };\n }\n function saveState() {\n if (!windowState.isMaximized) {\n windowState = window.getBounds();\n }\n windowState.isMaximized = window.isMaximized();\n appConfig.set(\"windowState.\" + windowName, windowState);\n }\n function track(win) {\n window = win;\n ['resize', 'move', 'close'].forEach(function (event) {\n win.on(event, saveState);\n });\n }\n setBounds();\n return ({\n x: windowState.x,\n y: windowState.y,\n width: windowState.width,\n height: windowState.height,\n isMaximized: windowState.isMaximized,\n track: track,\n });\n}",
"function saveState() {\n if (currentView) {\n currentView.checkpoint();\n }\n ConferenceApp.State.local.navigationState = WinJS.Navigation.history;\n }",
"static save(settings) { window.localStorage.setItem('settings', JSON.stringify(settings)); }",
"function storeSettings() {\n browser.storage.local.set({\n configs: {\n isAlert: isAlertBtn[0].checked || false,\n isDown: isDownBtn[0].checked || false,\n isCopy: isCopyBtn[0].checked || false,\n isOpenTab: isOpenTabBtn[0].checked || false,\n maxTabNum: tabNumOption[0].value\n }\n });\n}",
"function saveWindowOption() {\n chrome.storage.sync.get({currentWindowOnly: false}, function () {\n var checked = document.getElementById('current-window').checked;\n chrome.storage.sync.set({currentWindowOnly: checked}, function () {\n insertHTML('general', SUCCESS);\n });\n });\n}",
"function restoreWindowState() {\n\tchrome.storage.sync.get('windowState', result => {\n\t\tif (result != undefined) {\n\t\t\tchrome.windows.getCurrent(currWindow => {\n\t\t\t\tchrome.windows.update(currWindow.id, {\n\t\t\t\t\tstate: result.windowState.state,\n\t\t\t\t\twidth: result.windowState.width,\n\t\t\t\t\theight: result.windowState.height\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\t});\n}",
"function saveSettings() {\n localStorage.setItem('language', DATA.language)\n localStorage.setItem('gameMode', DATA.gameMode)\n localStorage.setItem('region', DATA.region)\n}",
"function storeSettings(){\n localStorage.setItem('settings', JSON.stringify(settings));\n}",
"function save(){\n\t\tlocalStorage.setItem(\n\t\t\tstorageKey, JSON.stringify(getSettings())\n\t\t);\n\t}",
"function save_window_position()\r\n{\r\n\tcurrentWindow = Titanium.UI.getMainWindow();\r\n\r\n\tif (position_saved == false && currentWindow.isMinimized() == false)\r\n\t{\r\n\t\tTitanium.App.Properties.setString('maximized', currentWindow.isMaximized().toString());\r\n\t\tTitanium.App.Properties.setString('user_height', currentWindow.height.toString());\r\n\t\tTitanium.App.Properties.setString('user_width', currentWindow.width.toString());\r\n\t\tTitanium.App.Properties.setString('user_x', currentWindow.x.toString());\r\n\t\tTitanium.App.Properties.setString('user_y', currentWindow.y.toString());\r\n\t\tposition_saved = true;\r\n\t\tcurrentWindow.hide();\r\n\t}\r\n}",
"function saveNotebookToLocal() {\n if (typeof autosaveEnabled !== 'undefined' && autosaveEnabled) {\n localStorage.setItem(notebookAutosaveKey(), JSON.stringify({\n timestamp: Date.now(),\n multiple_choice: gatherInputAnswersByType('multiple_choice'),\n codebox: gatherInputAnswersByType('codebox'),\n }));\n }\n}",
"setLocalSettings() {\n localStorage.setItem(this.storageKey,JSON.stringify(this.localSettings))\n }",
"function quickBarSaveLocal(){\n\n if(checkReffererProtocol()){\n var quickBarLayout = $('.ms-quick-bar-list')[0].innerHTML;\n storeToLocal('quickbar_layout', quickBarLayout);\n }\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
event listener for schedule button click | function schedule(event) {
// local constants
const scheduleText = 'schedule';
const scheduledText = 'scheduled';
const targetElementId = event.target.id;
const targetElement = document.getElementById(targetElementId);
const parentElement = targetElement.parentElement;
const newElement = targetElement.cloneNode(true);
newElement.classList.toggle('button-schedule-active');
if (targetElement.innerHTML === scheduleText) {
newElement.innerText = scheduledText;
} else {
newElement.innerText = scheduleText;
}
newElement.addEventListener('click', schedule);
parentElement.removeChild(targetElement);
parentElement.appendChild(newElement);
} | [
"function schedule(event) {\n let targetElementId = event.target.id;\n let targetElement = document.getElementById(targetElementId);\n let parentElement = targetElement.parentElement;\n let newElement = targetElement.cloneNode(true);\n newElement.classList.toggle('button-schedule-active');\n if (targetElement.innerHTML === 'schedule') {\n newElement.innerText = 'scheduled';\n } else {\n newElement.innerText = 'schedule';\n }\n newElement.addEventListener('click', schedule);\n parentElement.removeChild(targetElement);\n parentElement.appendChild(newElement);\n}",
"function btnGenerateSchedule() {\n\t\t\n\t\t$(\"#btnGenerate\").attr(\"disabled\", \"disabled\");\n\t\t$(\"#btnGenerate\").text(\"Running the process...\");\n\t\t$(\"#modal-schedule-configuration\").modal(\"hide\");\n\n\t\tsetTimeout(function(){ \n\t\t\tbeginGenerateSchedule (tmpAction, tmpActionOK); \n\t\t}, 250);\n\t\t\t\t\n\t\tevent.preventDefault();\n\t}",
"function schedule() {\n const mutateCursor = getCursorToMutate();\n if (mutateCursor) {\n clickTaskSchedule(mutateCursor);\n blurSchedulerInput();\n if (inBulkScheduleMode) {\n bulkScheduleCursorChanged();\n }\n } else {\n const query = 'button[data-action-hint=\"multi-select-toolbar-scheduler\"]';\n withUnique(document, query, (button) => {\n click(button);\n blurSchedulerInput();\n });\n }\n }",
"_calendarButtonClickHandler(event) {\n const that = this;\n\n that._highlightedTimePart = undefined;\n\n if (that.disabled || that.readonly) {\n return;\n }\n\n if (that.hasRippleAnimation) {\n Smart.Utilities.Animation.Ripple.animate(that.$.calendarButton, event.pageX, event.pageY);\n }\n\n if (that.opened) {\n that._close();\n }\n else {\n that._open();\n }\n }",
"onSchedule(){\n\n let list = this.getRandomItems();\n // this method fires every time the schedule is matched and activated\n console.log(`Schedule job with ID ${this.id} was activated at ${new Date()}`);\n // sending event to update widgets\n count++;\n this.sendEvent('list-of-items', list);\n }",
"_calendarButtonClickHandler(event) {\n const that = this;\n\n that._highlightedTimePart = undefined;\n\n if (that.disabled || that.readonly) {\n return;\n }\n\n if (that.hasRippleAnimation) {\n JQX.Utilities.Animation.Ripple.animate(that.$.calendarButton, event.pageX, event.pageY);\n }\n\n if (that.opened) {\n that._close();\n }\n else {\n that._open();\n }\n }",
"function buttonClicked(number) {\r\n \r\n // Deselect any other calendar day button that was previously selected\r\n for (var i = 0; i < calendarButtons.length; i += 1) {\r\n if (calendarButtons[i].disabled == true) {\r\n continue;\r\n }\r\n else {\r\n notHighlighedCalendarDay(i);\r\n }\r\n }\r\n \r\n // Select calendar day button user clicked on\r\n hightlightCalendarDay(number); \r\n \r\n // Set day\r\n day = monthDays[number];\r\n\r\n // Change title (day of week, month, day) on sidebar\r\n changeMonthAndDayName(number);\r\n \r\n /* Add events to sidebar */\r\n addEventsToSidebarList();\r\n}",
"dispatchEvent() {\n var event = new Event(Startbutton.BUTTON_PRESS);\n this.element.dispatchEvent(event);\n }",
"onDayDreamButtonClick() {\n this.dispatchEvent('button', event);\n }",
"function scheduleClick(t) {\n var osc = audioCtx.createOscillator();\n// osc.type = \"sine\";\n// osc.type = \"triangle\";\n// osc.type = \"sawtooth\";\n osc.type = \"square\";\n osc.frequency.value = clickFrequency;\n osc.connect(audioCtx.destination);\n osc.start(t);\n osc.stop(t + clickDuration);\n }",
"function buttonClick() {\n timestamp = duration[duration.length-1];\n console.log(timestamp + \"docReady: \" + docReady);\n if (docReady && timestamp !== undefined) {\n firepad.makeHeaderDialog_(timestamp);\n\n //Create buttons that take you to different parts of the video\n var button = document.createElement(\"input\");\n button.type = \"button\";\n button.value = timestamp.toFixed(2)+\"s\";\n button.onclick = function() {\n playerInstance.seek(timestamp);\n };\n document.querySelector(\"#annotatedNotes\").appendChild(button);\n }\n}",
"function saveToCalendarButton() {\n var newButton = document.createElement('BUTTON');\n newButton.setAttribute('class', 'button button-primary calendar-button');\n newButton.addEventListener('click', newEvent);\n newButton.innerHTML = 'Save + Calendar';\n document.getElementsByClassName('ynab-grid-actions')[0].appendChild(newButton);\n }",
"addAlarmButtonListeners() {\n let buttons = document.getElementsByClassName(\"clock__button-alarm\");\n for (let i = 0, length = buttons.length; i < length; i++) {\n buttons[i].addEventListener(\"mousedown\", (e) => { this.toggleAlarm(e) });\n }\n }",
"function startTimerByBtn(e) {\n const seconds = parseInt(this.dataset.time);\n timer.start(seconds);\n}",
"function onTaskStartButtonClick()\n{\n\tvar taskTimer = $(this).parent().parent().find(\".task-do\");\n\tvar taskTimerEnabled = $(this).parent().parent().find(\".task-do\").data(\"task-timer-enabled\");\n\n\tif ( !taskTimerEnabled )\n\t{\n\t\ttaskTimer.timer(\"resume\");\n\t\t$(this).addClass(\"btn-danger\").removeClass(\"btn-success\").text(\"Pause\");\n\t}\n\telse\n\t{\n\t\ttaskTimer.timer(\"pause\");\n\t\t$(this).removeClass(\"btn-danger\").addClass(\"btn-success\").text(\"Resume\");\n\t}\n\n\ttaskTimer.data(\"task-timer-enabled\", !taskTimerEnabled);\n}",
"function bindClickActions() {\n setAlarmBtn.addEventListener(\"click\", setAlarm);\n resetAlarmBtn.addEventListener(\"click\", resetAlarm);\n}",
"function clickedButton(e) {\n // WHEN DONE:\n if (listOfIds.length !== 0) {\n // each calibration button is popped out of the list one-by-one.\n // it is set to fade in.\n $('#' + listOfIds.pop()).show();\n } else {\n if (!dataIsSent) {\n activity.stopCollectingGazerData();\n }\n showVideoPage();\n }\n\n //hide progress after click\n $('#cal-progress').hide();\n }",
"function start_cal_listen()\n{\n\t\n\n\t//Listener for nexy / prev button\n\tjQuery('.loadCalMonth').on( 'click', function ( ) {\n\t\t// Get the ID of the button, turn to array with _ as split and second element is the quiz IDa\n\t\tvar month = this.id.split(\"_\")[1];\n\t\tvar year = this.id.split(\"_\")[2];\t\n\t\tvar tutorUsername = this.id.split(\"_\")[3];\t\t\n\t\t\n\t\t//console.log(\"Clicked month\"+month+\" and year \"+year);\n\t\tdrawCalendar(month, year, tutorUsername);\n\t});\t\n\t\n//\tdocument.getElementById('availableSlotsDiv').innerHTML = \"Loading...\";\t\t\n\n\t//Listener for nexy / prev button\n\tjQuery('.hasSlots').on( 'click', function ( ) {\n\t\t// Get the ID of the button, turn to array with _ as split and second element is the quiz IDa\n\t\tvar thisDate = this.id.split(\"_\")[1];\n\t\tvar tutorUsername = this.id.split(\"_\")[2];\t\t\n\t\t\n\t\t//console.log(\"Clicked thisDate = \"+thisDate+\" and tutorUsername \"+tutorUsername);\t\n\t\tdrawDaySlots(thisDate, tutorUsername);\n\t\t\n\t});\t\t\n\t\n\t\n}",
"function callbackButton() { console.log( 'BUTTONPRESS' ); }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
toggleMobileMenu(); Show and hide mobile menu by adding class "open" Change the burguer menu icon to "X" when clicked | function toggleMobileMenu() {
toggleIcon.addEventListener('click', function(){
this.classList.toggle("open");
mobileMenu.classList.toggle("open");
});
} | [
"function toggleMenu() {\n mobileMenu.classList.toggle('open');\n }",
"toggleMenu() {\n if(this.mobileMenuOpen) {\n document.body.classList.remove(\"mobile-menu-open\");\n this.mobileMenuOpen = false;\n } else {\n document.body.classList.add(\"mobile-menu-open\");\n this.mobileMenuOpen = true;\n }\n }",
"function mobileMenuIconToggle() {\r\n mobileMenuOpened = !mobileMenuOpened;\r\n if (mobileMenuOpened) {\r\n $('.mobile-menu-toggle').find('span').removeClass('fa-bars').addClass('fa-times');\r\n } else {\r\n $('.mobile-menu-toggle').find('span').addClass('fa-bars').removeClass('fa-times');\r\n }\r\n }",
"function showMobileMenu() {\n if(isMobileContactOpen) {\n hideContactMenu();\n }\n $(burgerIcon).addClass('active');\n isMobileMenuOpen = true;\n navContainer.css({left: 0});\n }",
"function toggleMobileMenu() {\n menuOpen ? menuOpen = false : menuOpen = true;\n menuOpen ? mobileMenuBtn.innerHTML = `<i class=\"fas fa-times\"></i>` : mobileMenuBtn.innerHTML = `<i class=\"fas fa-bars\"></i>`;\n menuOpen ? mobileMenu.classList.add(\"menu-open\") : mobileMenu.classList.remove(\"menu-open\");\n // toggles checkbox\n menuOpen ? document.querySelector(\"#players-choice-checkbox\").classList.add(\"mobile\") : document.querySelector(\"#players-choice-checkbox\").classList.remove(\"mobile\");\n}",
"function toggleMobileMenu() {\n if (mobileMenuVisible) {\n //close menu\n nav.style.removeProperty(\"top\");\n burgerMenuSpan.forEach(span => {\n span.style.removeProperty(\"background\");\n });\n } else {\n //open menu\n nav.style.top = \"0px\";\n burgerMenuSpan.forEach(span => {\n span.style.background = \"#e9e9e9\";\n });\n }\n mobileMenuVisible = !mobileMenuVisible;\n}",
"function clickOnMobileMenu() {\n /* toggle the mobile nav menu */\n $('.js--mobile-menu').click(function() {\n const mainNav = $('.js--main-nav');\n mainNav.slideToggle(200);\n\n /* toggle the mobile menu icon */\n if ($('.js--menu-outline').hasClass('icon-hidden')) {\n $('.js--menu-outline').removeClass('icon-hidden');\n $('.js--close-outline').addClass('icon-hidden');\n } else {\n $('.js--menu-outline').addClass('icon-hidden');\n $('.js--close-outline').removeClass('icon-hidden');\n }\n\n });\n}",
"function header_mobile_menu_toggle() {\r\n\t\t$(\".menu_toggle .fa-close\").hide();\r\n\t\t$(\"#mobile_header .menu_toggle\").on(\"click\", function() {\r\n\t\t\t$(\"#mobile_header .menu\").fadeToggle(200);\r\n\r\n\t\t\t$(\".menu_toggle .fa-bars\").toggle();\r\n\t\t\t$(\".menu_toggle .fa-close\").toggle();\r\n\t\t});\r\n\t}",
"function toggleMobileMenu() {\n if (mobileMenuVisible) {\n //close menu\n nav.style.removeProperty(\"top\");\n } else {\n //open menu\n nav.style.top = \"0px\";\n }\n mobileMenuVisible = !mobileMenuVisible;\n}",
"showMobilemenu() {\n\t\tdocument.getElementById('main-wrapper').classList.toggle('show-sidebar');\n\t}",
"function openHeaderMenuOnMobile() {\n $('#nav-icon-menu').click(function(){\n $(this).toggleClass('open');\n $('body').toggleClass('navigation-opened');\n });\n}",
"function hideMobileMenu() {\n isMobileMenuOpen = false;\n $(burgerIcon).removeClass('active');\n navContainer.css({left: -270});\n }",
"function openMenu() {\n $('.ham-button').toggleClass('open');\n $('.nav-mobile').slideToggle();\n}",
"function showHideMobileNav() {\n if ( $('#mobNavButton').hasClass('closed-nav') === true ) {\n\t$('#mobNavButton').removeClass('closed-nav').addClass('opened-nav');\n\t$('#mobNavIcon').removeClass('icon-navigation').addClass('icon-cross');\n\t$('#mobileMenu').slideDown(500);\n } else {\n\t$('#mobNavButton').removeClass('opened-nav').addClass('closed-nav');\n\t$('#mobNavIcon').removeClass('icon-cross').addClass('icon-navigation');\n\t$('#mobileMenu').slideUp(500);\n }\n}",
"showMobilemenu() {\n document.getElementById('main-wrapper').classList.toggle('show-sidebar');\n }",
"function expandMobileMenu() {\n gsap.to('.top--navbar', { height: 'fit-content', duration: 0.1 });\n gsap.to('.mobile--nav', { display: 'block', duration: 0.2 });\n open = true;\n\n}",
"function openMobileMenu(){\n if (breakPoint == 'xx' || breakPoint == 'xs' || breakPoint == 'sm') {\n $('.hamburger').attr('data-toggle', 'collapse');\n $('.hamburger').attr('aria-expanded', 'true');\n $('.hamburger').attr('data-target', '#mobile-wrap');\n $('.hamburger').addClass('collapsed');\n $('.mobile-wrap').addClass('collapse');\n\n } else {\n\n $('.hamburger').removeAttr('data-toggle', 'collapse');\n $('.hamburger').removeAttr('aria-expanded', 'true');\n $('.hamburger').removeAttr('data-target', '#mobile-wrap');\n $('.hamburger').removeClass('collapsed');\n $('.mobile-wrap').removeClass('collapse');\n }\n }",
"showMobilemenu() {\n document.getElementById(\"main-wrapper\").classList.toggle(\"show-sidebar\");\n }",
"function addMenuOpenClass(){\n removeClass(html, 'desktopMenu');\n\tremoveClass(html, 'mobileMenuClosed');\n\taddClass(html, 'mobileMenuOpen');\n menuHeight();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
unSelectMatchingOptions(select_object,regex) This function Unselects all options that match the regular expression passed in. | function unSelectMatchingOptions(obj,regex) {
selectUnselectMatchingOptions(obj,regex,"unselect",false);
} | [
"function unSelectMatchingOptions(obj,regex) {\n selectUnselectMatchingOptions(obj,regex,\"unselect\",false);\n }",
"function unSelectMatchingOptions(obj,regex) {\n\tselectUnselectMatchingOptions(obj,regex,\"unselect\",false);\n\t}",
"function selectOnlyMatchingOptions(obj,regex) {\n selectUnselectMatchingOptions(obj,regex,\"select\",true);\n }",
"function selectOnlyMatchingOptions(obj,regex) {\n selectUnselectMatchingOptions(obj,regex,\"select\",true);\n }",
"function selectMatchingOptions(obj,regex) {\n selectUnselectMatchingOptions(obj,regex,\"select\",false);\n }",
"function selectMatchingOptions(obj,regex) {\n selectUnselectMatchingOptions(obj,regex,\"select\",false);\n }",
"function selectOnlyMatchingOptions(obj,regex) {\n\tselectUnselectMatchingOptions(obj,regex,\"select\",true);\n\t}",
"function selectMatchingOptions(obj,regex) {\n\tselectUnselectMatchingOptions(obj,regex,\"select\",false);\n\t}",
"function clearOptions(theSelectObj) {\n\n // Clear all the dropdown fields\n if (bw.ns4 || bw.ns6) {\n theSelectObj.options.length = 0;\n } else {\n for (x = theSelectObj.length -1; x >= 0; x--) {\n theSelectObj.remove(x);\n }\n }\n}",
"function removeAllOptions(sel) {\r\n var len, groups, par;\r\n\r\n len = sel.options.length;\r\n for (var i=len; i; i--) {\r\n par = sel.options[i-1].parentNode;\r\n par.removeChild( sel.options[i-1] );\r\n }\r\n}",
"function selectRemoveAll(select_field) {\n\n var select_size = select_field.options.length\n\n while (select_field.options.length > 0) {\n select_field.options[0] = null;\n }\n\n}",
"function removeAllOptions(selectObj, keepFirst) {\n\t\tvar startIdx = selectObj.options.length-1;\n\t\tvar endIdx = (keepFirst) ? 1:0;\n\t\tfor (var j=startIdx; j>=endIdx; j--) {\n\t\t\tselectObj.remove(j);\n\t\t}\n\t}",
"function selectRemoveAll(select_input) {\n\n var linesNumber = select_input.options.length;\n for(i=0; i < linesNumber; i++) {\n\t\tselect_input.options[0] = null;\n }\n\tselect_input.selectedIndex = -1;\n}",
"function _removeSelectReplacement()\r\n\t{\r\n\t\tvar element = $(this),\r\n\t\t\tselect = element.data('replacement'),\r\n\t\t\tcloseFunc, blurFunc;\r\n\r\n\t\t// If not replaced\r\n\t\tif (!select)\r\n\t\t{\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t// If open\r\n\t\tcloseFunc = select.data('selectCloseFunction');\r\n\t\tif (closeFunc)\r\n\t\t{\r\n\t\t\tcloseFunc();\r\n\t\t}\r\n\r\n\t\t// If focused\r\n\t\tblurFunc = select.data('selectBlurFunction');\r\n\t\tif (blurFunc)\r\n\t\t{\r\n\t\t\tblurFunc();\r\n\t\t}\r\n\r\n\t\t// Tabindex\r\n\t\tthis.tabIndex = select[0].tabIndex;\r\n\r\n\t\t// Remove select from replacement and restore classes\r\n\t\telement.detach().insertBefore(select).css('display', '');\r\n\t\tthis.className = element.data('initial-classes');\r\n\t\telement.removeData('initial-classes');\r\n\r\n\t\t// Remove references\r\n\t\telement.removeData('replacement');\r\n\r\n\t\t// Stop scrolling\r\n\t\tif ($.fn.customScroll)\r\n\t\t{\r\n\t\t\tselect.children('.drop-down').removeCustomScroll();\r\n\t\t}\r\n\r\n\t\t// Delete select\r\n\t\tselect.remove();\r\n\t}",
"function DeselectAllOptions(campo_select) {\n if (!campo_select) {\n return;\n }\n var j = campo_select.options.length;\n for (var i = 0; i < j; i++) {\n campo_select.options[i].selected = false;\n }\n}",
"deselectAll() {\n this._setAllOptionsSelected(false);\n }",
"function doFiltering(pattern, list) \n{\n // fill cache with original select options\n if (typeof filterCache[list.id] == \"undefined\")\n { \n filterCache[list.id] = new Array();\n \n for(var i = 0; i < list.length; i++)\n {\n filterCache[list.id].push(new Array(\n list[i].text,\n list[i].value,\n list[i].getAttribute('class')\n ));\n }\n }\n // restore original select options from cache\n else\n {\n // remove all select options\n list.length = 0;\n for(var j = 0; j < filterCache[list.id].length; j++)\n {\n var option = new Option(\n filterCache[list.id][j][0],\n filterCache[list.id][j][1]\n );\n option.setAttribute('class', filterCache[list.id][j][2]);\n list[list.length] = option;\n }\n }\n \n // create list of options to be removed \n pattern = new RegExp(pattern,\"i\");\n removeList = new Array();\n i = 0;\n while(i < list.options.length) \n {\n // add options to remove list\n if (!pattern.test(list.options[i].text)) \n {\n removeList.push(list.options[i].text);\n }\n i++;\n }\n \n // remove select options\n for(var x = 0; x < removeList.length; x++)\n {\n for(i = 0; i < list.options.length; i++)\n {\n if(list.options[i].text == removeList[x])\n {\n list.options[i] = null;\n break;\n }\n }\n }\n}",
"function clearSelect(select) {\n var i = select.options.length;\n while(i > 0) {\n select.remove(i);\n i--;\n }\n}",
"function clearSelectOptions(select_array) {\n $.each(select_array, function() {\n $(this).empty();\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
VectorColorMapper.js Object for converting vector magnitude to color Developed by Wolfgang Christian | function VectorColorMap(lower, upper) {
this.lower =(lower === undefined) ? 0.5: lower;
this.upper =(upper === undefined) ? 1: upper;
} | [
"function colorPoly(ObjCol, LightColr , Normal, ColorVect ){\n\n var magNorm = Math.sqrt(Normal[0]*Normal[0] + Normal[1]*Normal[1]+ Normal[2]*Normal[2]);\n var magColV = Math.sqrt(ColorVect[0]*ColorVect[0] + ColorVect[1]*ColorVect[1]+ ColorVect[2]*ColorVect[2]);\n var unitVect = [Normal[0], Normal[1], Normal[2]];\n var dotProd = (unitVect[0]*ColorVect[0] + unitVect[1]*ColorVect[1] + unitVect[2]*ColorVect[2]);\n\n var costhet = ( dotProd / (magNorm+magColV) ) ;\n\n var r = ObjCol[0]*costhet*LightColr[0];\n var g = ObjCol[1]*costhet*LightColr[1];\n var b = ObjCol[2]*costhet*LightColr[2];\n\n if(r > 1){\n r =1;\n }\n else if (r < 0) {\n r = 0;\n }\n if(g > 1){\n g =1;\n }\n else if (g < 0) {\n g = 0;\n }\n if(b > 1){\n b = 1;\n }\n else if (b < 0) {\n b = 0;\n }\n return [r,g,b];\n}",
"function colorize(distanceList){\n console.log(distanceList)\n myMax = _.max(distanceList);\n myMin = _.min(distanceList);;\n console.log(\"min,max\" , myMin , myMax );\n var myRainbow = new Rainbow();\n myRainbow.setNumberRange(myMin, myMax);\n myRainbow.setSpectrum('#FF7F00' , '#FF0000' );\n // '#5d6ed9', '#5dd9ca', '#78d163', '#d2d95d' ,'#d9a95d' , '#d85c5c'\n //loop\n for (var k = 0 ; k < distanceList.length ; k++){\n var myHex = myRainbow.colorAt(distanceList[k]); \n\n colorList.push(myHex);\n // push three times in vertexColorOld\n vertexColorOld.push( hexToRgb( \"#\" + String(myHex) ) );\n vertexColorOld.push( hexToRgb( \"#\" + String(myHex) ) );\n vertexColorOld.push( hexToRgb( \"#\" + String(myHex) ) );\n\n }\n }",
"function vector(ctx, color, origin, vector, scale) {\n if (scale === void 0) { scale = 1.0; }\n var c = color ? color.toString() : 'blue';\n var v = vector.scale(scale);\n ctx.beginPath();\n ctx.strokeStyle = c;\n ctx.moveTo(origin.x, origin.y);\n ctx.lineTo(origin.x + v.x, origin.y + v.y);\n ctx.closePath();\n ctx.stroke();\n}",
"function VectorData(res, data, style) {\n var resolutions = res;\n \n // fix bounding box coordinates\n for(var d in data) {\n for(var b in data[d][0]) {\n data[d][0][b] /= 100;\n }\n }\n \n // get the index of the polygon at the given pixel coordinates (x,y)\n this.atCoord = function(x, y) {\n return null;\n }\n \n this.render = function(map, ctx, hObj) {//hObj: objects to highlight\n //var m = 0;\n //var colors = ['#FF0000', '#FF7700', '#FFFF00', '#00FF00', '#00FFFF', '#0000FF', '#FF00FF'];\n for(var s in style) {\n ctx[s] = style[s];\n }\n for(var d in data) {\n var bbox = data[d][0];\n if(bbox[1] > map.n || bbox[3] < map.s)\n continue\n for(var offset = Math.floor((map.w+180) / 360)*360; offset <= Math.floor((map.e+180) / 360)*360; offset+=360) {\n if(bbox[0] + offset > map.e || bbox[2] + offset < map.w) {\n continue\n }\n ctx.beginPath();\n for(var p in data[d][1]) { // parts of the polygon\n var polygon = data[d][1][p];\n var coords = map.coord(polygon[0][0]/100+offset, polygon[0][1]/100);\n ctx.moveTo(coords[0], map.height - coords[1]);\n for(var p = 1; p < polygon.length; p++) {\n coords = map.coord(polygon[p][0]/100+offset, polygon[p][1]/100);\n ctx.lineTo(coords[0], map.height - coords[1]);\n }\n }\n if(style.fillStyle) {\n ctx.fill();\n }\n if(style.strokeStyle) {\n ctx.stroke();\n }\n }\n }\n }\n}",
"function colormap(v) {\n const n = arbre.length / 6;\n const i = Math.min(Math.max(Math.floor(v * arbre.length / 6), 0), n - 1);\n // each bin is 6 characters, so\n return new Color(\"#\" + arbre.slice(i * 6, (i + 1) * 6));\n}",
"toColorLAB(){\n const rgb = [this.r, this.g, this.b].map((c) => {\n let color = c / 255;\n color = color > 0.04045 ? ((color + 0.055) / 1.055) ** 2.4 : color / 12.92;\n return color * 100;\n });\n const [xyzR,xyzG,xyzB] = rgb;\n const x = (xyzR * 0.4124 + xyzG * 0.3576 + xyzB * 0.1805) * 0.95047;\n const y = (xyzR * 0.2126 + xyzG * 0.7152 + xyzB * 0.0722) * 1;\n const z = (xyzR * 0.0193 + xyzG * 0.1192 + xyzB * 0.9505) * 1.08883;\n \n const labxyz = [x,y,z].map((c)=>{\n let color = c/100;\n return color > 0.008856 ? color ** (1/3) : (color * 7.787) + (16 /116);\n });\n \n const [labX, labY, labZ] = labxyz;\n const l = (labY * 116) - 16;\n const a = (labX - labY) * 500;\n const b = (labY - labZ) * 200;\n \n return new ColorLAB(l,a,b);\n }",
"function getColor (v) {\n\t\n}",
"function getForColorComponent () {\n from = new THREE.Color(dataFrom);\n to = new THREE.Color(dataTo);\n partialSetAttribute = function (value) {\n if (attributeSplit.length > 1) {\n el.setAttribute(attributeSplit[0], attributeSplit[1], rgbVectorToHex(value));\n }\n el.setAttribute(attribute, rgbVectorToHex(value));\n };\n }",
"GetVectorMagnitude()\n {\n return this.vectorMagnitude;\n }",
"function getColorForValueVec(v) {\n\t\tif(heatLimits.min < 0 && heatLimits.max > 0) {\n\t\t\tif(v >= 0) {\n\t\t\t\tvar prop = Math.log(v + 1) / Math.log(heatLimits.max + 1);\n\t\t\t\tvar r = zeroColorRGB[0] + prop * (hotColorRGB[0] - zeroColorRGB[0]);\n\t\t\t\tvar g = zeroColorRGB[1] + prop * (hotColorRGB[1] - zeroColorRGB[1]);\n\t\t\t\tvar b = zeroColorRGB[2] + prop * (hotColorRGB[2] - zeroColorRGB[2]);\n\t\t\t\tvar col = [r, g, b];\n\t\t\t\treturn col;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tvar prop = Math.log(1 - v) / Math.log(1 - heatLimits.min);\n\t\t\t\tvar r = zeroColorRGB[0] + prop * (coldColorRGB[0] - zeroColorRGB[0]);\n\t\t\t\tvar g = zeroColorRGB[1] + prop * (coldColorRGB[1] - zeroColorRGB[1]);\n\t\t\t\tvar b = zeroColorRGB[2] + prop * (coldColorRGB[2] - zeroColorRGB[2]);\n\t\t\t\tvar col = [r, g, b];\n\t\t\t\treturn col;\n\t\t\t}\n\t\t}\n\t\telse if(heatLimits.min < 0) {\n\t\t\tvar prop = Math.log(1 + (v - heatLimits.min)) / Math.log(1 + heatLimits.max - heatLimits.min);\n\t\t\tvar r = zeroColorRGB[0] + prop * (coldColorRGB[0] - zeroColorRGB[0]);\n\t\t\tvar g = zeroColorRGB[1] + prop * (coldColorRGB[1] - zeroColorRGB[1]);\n\t\t\tvar b = zeroColorRGB[2] + prop * (coldColorRGB[2] - zeroColorRGB[2]);\n\t\t\tvar col = [r, g, b];\n\t\t\treturn col;\n\t\t}\n\t\telse {\n\t\t\tvar prop = Math.log(1 + (v - heatLimits.min)) / Math.log(1 + heatLimits.max - heatLimits.min);\n\t\t\tvar r = zeroColorRGB[0] + prop * (hotColorRGB[0] - zeroColorRGB[0]);\n\t\t\tvar g = zeroColorRGB[1] + prop * (hotColorRGB[1] - zeroColorRGB[1]);\n\t\t\tvar b = zeroColorRGB[2] + prop * (hotColorRGB[2] - zeroColorRGB[2]);\n\t\t\tvar col = [r, g, b];\n\t\t\treturn col;\n\t\t}\n\t}",
"toLAB() {\r\n const x = this.x / XYZColor.D65.x;\r\n const y = this.y / XYZColor.D65.y;\r\n const z = this.z / XYZColor.D65.z;\r\n const xyz = [x, y, z].map((v) => {\r\n if (v > 0.008856451) {\r\n return v ** (1 / 3);\r\n }\r\n else {\r\n return 7.787037 * v + 16 / 116;\r\n }\r\n });\r\n return new LABColor_1.LABColor((116 * xyz[1] - 16) / 100, 5 * (xyz[0] - xyz[1]), 2 * (xyz[1] - xyz[2]));\r\n }",
"function Color( r, g, b, a ) { return vec4( r, g, b, a ); }",
"function _buildColorScale() {\n var hot = chroma.scale([ '#2E9A58', '#FBFF80', '#E06C1F', '#C83737', 'D7F4F4' ], // colors\n [ 0, .25, .50, .75, 1 ] // positions\n )\n return hot;\n}",
"constructor( _lon, _lat, _value, _scale){\n this.lon = _lon\n this.lat = _lat\n // value stands for the actual color of the pixel, the function brightness() extracts\n // the 'whiteness' of the pixel\n this.value = _value\n this.loc3D = createVector(0,0,0)\n this.scale = _scale\n this.radius = 400 + 5\n // declaring temporal x y z components\n let tX,tY,tZ\n // converting lat lon into spherical xyz components of the loc3D vector \n tX = this.radius * Math.cos(radians(this.lat) ) * Math.cos(radians(this.lon))\n tY = this.radius * Math.cos(radians(this.lat)) * Math.sin(radians(this.lon))\n tZ = this.radius * Math.sin(radians(this.lat))\n this.loc3D = createVector(\n tX,\n tY,\n tZ \n )\n\n }",
"toXYZ() {\r\n const [r, g, b] = this.values;\r\n const x = 0.4124 * r + 0.3576 * g + 0.1805 * b;\r\n const y = 0.2126 * r + 0.7152 * g + 0.0722 * b;\r\n const z = 0.0193 * r + 0.1192 * g + 0.9505 * b;\r\n return new XYZColor_1.XYZColor(x, y, z);\r\n }",
"function vec2f64_mag2(v = def_vec2f64) {\n return +(+(+v.x * +v.x) + +(+v.y * +v.y));\n}",
"function getColor(magnitude) {\n if (magnitude >= 6) {\n return '#A628FF';\n }\n if (magnitude >= 5) {\n return '#c675ff';\n }\n return '#d9a3ff';\n }",
"addVectorToArray(vector)\n {\n let vertices = this.vertices;\n let colors = this.colors;\n\n let heightVec = this.defineHeight(vector);\n\n vertices.push(vector[0] + heightVec[0]);\n vertices.push(vector[1] + heightVec[1]);\n vertices.push(vector[2] + heightVec[2]);\n }",
"function getSmoothColors(){\r\n var f = smoothNormz.length-1;\r\n for (var i=0; i<smoothNormz.length; i++){\r\n\r\n var Vnorm = new Vector3([smoothNormz[i].x, smoothNormz[i].y, smoothNormz[i].z]);\r\n\r\n var lightDir = new Vector3([1, 1, 1]);\r\n lightDir.normalize();\r\n\r\n //cos(theta) = dot product of lightDir and normal vector\r\n var SdotP = (lightDir.elements[0]*Vnorm.elements[0])+(lightDir.elements[1]*Vnorm.elements[1])+ (lightDir.elements[2]*Vnorm.elements[2]);\r\n\r\n //surface color = light color x base color x SdotP (DIFFUSE)\r\n var R = 1.0 * 0.0 * SdotP;\r\n var G = 1.0 * 1.0 * SdotP;\r\n var B = 1.0 * 0.0 * SdotP;\r\n\r\n smoothColor.push(R,G,B); \r\n }\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
======== XYZ vector operations. ======== Returns a new 3vector of floats (Float32Array), initially all zero. | static make3Vec() {
return new Float32Array(3);
} | [
"create(x, y, z) {\n var size = 3;\n var vector3x1 = new Float32Array(size);\n this.set(vector3x1, x, y, z);\n return vector3x1;\n }",
"function vector_98(x, y, z)\n{\n return float3_119 // [(Func Float Float Float Float3) | (Func (Array Float) Float3)]\n (x // Float\n ,y // Float\n ,z // Float\n ) // Float3\n ;\n}",
"function genVel3D(X, Y, Z, vectorField3D) {\n var vecs = [];\n for (var i=0; i<X.length; i++) {\n for (var j=0; j<Y.length; j++) {\n for (var k=0; k<Z.length; k++) {\n vecs.push(vectorField3D(X[i],Y[j],Z[k]))\n }\n }\n }\n return vecs\n}",
"function gl_vector3_list(vectors) {\n var size = vectors.length * 3;\n var return_value = new Float32Array(size);\n vectors.forEach(function(vector, index) {\n for (var i = 0; i < 3; i++){\n return_value[index * 3 + i] = vector[i];\n }\n }, this);\n return return_value;\n}",
"toVector() {\n\n // Return a new Vector\n return new Vector([this.x, this.y, this.z]);\n }",
"function sc_F32vector() {\n var sz = arguments.length;\n var a = new sc_Vector(sz);\n //var a = (\"Float32Array\" in window) ? new Float32Array(sz):new sc_Vector(sz);\n \n for (var i = 0; i < arguments.length; i++) {\n\n\n a[i] = arguments[i];\n }\n \n return a;\n}",
"toVector() {\n return new Vector(this.x, this.y, this.z);\n }",
"function vec3FromEcef(x, y, z) {\n return new WorldWind.Vec3(y, z, x);\n }",
"toVector3() {\n\t\treturn new THREE.Vector3(...this.coordinates);\n\t}",
"multiplyInverseXYZAsVector3d(x, y, z, result) {\n this.computeCachedInverse(true);\n if (this.inverseCoffs) {\n return Point3dVector3d_1.Vector3d.create((this.inverseCoffs[0] * x + this.inverseCoffs[1] * y + this.inverseCoffs[2] * z), (this.inverseCoffs[3] * x + this.inverseCoffs[4] * y + this.inverseCoffs[5] * z), (this.inverseCoffs[6] * x + this.inverseCoffs[7] * y + this.inverseCoffs[8] * z), result);\n }\n return undefined;\n }",
"function toVec(posn_array) {\n var result = new pk_mineflayer.vec3();\n result.x = posn_array[0];\n result.y = posn_array[1];\n result.z = posn_array[2];\n return result;\n}",
"function gl_vector_list(vectors) {\n var size = vectors.length * 4;\n var return_value = new Float32Array(size);\n vectors.forEach(function(vector, index) {\n for (var i = 0; i < 4; i++){\n return_value[index * 4 + i] = vector[i];\n }\n }, this);\n return return_value;\n}",
"toVector3() {\n return new Vector3(this.x, this.y, 0);\n }",
"multiplyByFloats(x, y, z) {\n return new Vector3(this.x * x, this.y * y, this.z * z);\n }",
"toVector3() {\n return new Vector3(this.x, this.y, this.z);\n }",
"function Vec3() {\n switch ( arguments.length ) {\n case 1:\n // array or VecN argument\n var argument = arguments[0];\n this.x = argument.x || argument[0] || 0.0;\n this.y = argument.y || argument[1] || 0.0;\n this.z = argument.z || argument[2] || 0.0;\n break;\n case 3:\n // individual component arguments\n this.x = arguments[0];\n this.y = arguments[1];\n this.z = arguments[2];\n break;\n default:\n this.x = 0.0;\n this.y = 0.0;\n this.z = 0.0;\n break;\n }\n }",
"function vec3 (vec4) {\r\n\treturn [vec4[0], vec4[1], vec4[2]];\r\n}",
"get Vector3() {}",
"Sphere3(x, y, z, r) {\n return new Float32Array([x, y, z, r]);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cast waterline types into SQL data types | function sqlTypeCast(type) {
type = type.toLowerCase();
switch (type) {
case 'string':
return 'TEXT';
case 'int':
case 'integer':
return 'INT';
case 'float':
case 'double':
return 'FLOAT';
case 'date':
return 'DATE';
}
} | [
"function _toDbType (value) {\n\t\tlet type = typeof value\n\t\tlet primitive = null // for container types (objects, arrays) primitive stay's as null\n\t\tif (value === null) return { primitive, type }\n\t\tswitch (value.constructor) {\n\t\tcase Array: type = 'array'; break\n\t\tcase Object: break\n\t\tcase Buffer: type = 'buffer'; primitive = value; break\n\t\tcase Function: primitive = value.toString(); break\n\t\tcase Date: type = 'date'; primitive = value.toISOString(); break\n\t\tcase Boolean: type = 'boolean'; primitive = (value) ? 1 : 0; break\n\t\tcase String:\n\t\tcase Number: primitive = value\n\t\t}\n\t\treturn { primitive, type }\n\t}",
"function sqlTypeCast(type, attrName) {\r\n type = type && type.toLowerCase();\r\n\r\n switch (type) {\r\n case 'string':\r\n return 'VARCHAR2(255)';\r\n\r\n case 'text':\r\n case 'array':\r\n case 'json':\r\n return 'VARCHAR2(255)';\r\n\r\n case 'boolean':\r\n return 'NUMBER(1) CHECK(\"' + attrName + '\" IN (0,1))';\r\n\r\n case 'int':\r\n case 'integer':\r\n return 'NUMBER';\r\n\r\n case 'float':\r\n case 'double':\r\n return 'FLOAT';\r\n\r\n case 'date':\r\n return 'DATE';\r\n\r\n case 'datetime':\r\n return 'TIMESTAMP';\r\n\r\n case 'binary':\r\n return 'BLOB';\r\n\r\n default:\r\n console.error(\"Unregistered type given: \" + type);\r\n return \"TEXT\";\r\n }\r\n}",
"function SqlTypes () {\n const SQL_UNKNOWN_TYPE = 0\n const SQL_DECIMAL = 3\n // var SQL_INTERVAL = 10;\n // var SQL_TIMESTAMP = 11;\n const SQL_BINARY = -2\n // var SQL_WCHAR = -8;\n // var SQL_SS_VARIANT = -150;\n // var SQL_SS_UDT = -151;\n // var SQL_SS_XML = -152;\n const SQL_SS_TABLE = -153\n const SQL_CHAR = 1\n const SQL_NUMERIC = 2\n const SQL_INTEGER = 4\n const SQL_SMALLINT = 5\n const SQL_FLOAT = 6\n const SQL_REAL = 7\n const SQL_DOUBLE = 8\n const SQL_VARCHAR = 12\n // var SQL_LONGVARCHAR = -1;\n const SQL_VARBINARY = -3\n const SQL_LONGVARBINARY = -4\n const SQL_BIGINT = -5\n const SQL_TINYINT = -6\n const SQL_BIT = -7\n const SQL_WVARCHAR = -9\n const SQL_WLONGVARCHAR = -10\n const SQL_TYPE_DATE = 91\n const SQL_TYPE_TIMESTAMP = 93\n const SQL_SS_TIME2 = -154\n const SQL_SS_TIMESTAMPOFFSET = -155\n\n // currently mapped in the driver either through a guess by looking at type or explicitly from user\n\n class ConcreteColumnType {\n parseHHMMSS (s) {\n const rehhmmss = /(\\d?\\d):(\\d?\\d):(\\d?\\d)$/g\n if (typeof s === 'string') {\n const match = rehhmmss.exec(s)\n if (match) {\n const [, hh, mm, ss] = match\n this.value = new Date(Date.UTC(1900, 0, 1,\n parseInt(hh),\n parseInt(mm),\n parseInt(ss)))\n return true\n }\n return false\n }\n }\n\n parseMMSS (s) {\n const rehhmmss = /(\\d?\\d):(\\d?\\d)$/g\n if (typeof s === 'string') {\n const match = rehhmmss.exec(s)\n if (match) {\n const [, mm, ss] = match\n this.value = new Date(Date.UTC(1900, 0, 1,\n 0,\n parseInt(mm),\n parseInt(ss)))\n return true\n }\n return false\n }\n }\n\n parseSS (s) {\n const rehhmmss = /(\\d?\\d)$/g\n if (typeof s === 'string') {\n const match = rehhmmss.exec(s)\n if (match) {\n const [, ss] = match\n this.value = new Date(Date.UTC(1900, 0, 1,\n 0,\n 0,\n parseInt(ss)))\n return true\n }\n return false\n }\n }\n\n parse (s) {\n if (!this.parseHHMMSS(s) && !this.parseMMSS(s) && !this.parseSS(s)) {\n this.value = s\n }\n }\n\n calcFraction (value, fraction) {\n if (!fraction && value) {\n fraction = 0\n if (Array.isArray(value)) {\n if (value.length > 0) {\n const s = value.find(o => !!o)\n if (s) {\n fraction = s.getUTCMilliseconds()\n }\n }\n } else {\n fraction = value.getUTCMilliseconds()\n }\n }\n return fraction\n }\n\n constructor (sqlType, value, precision, scale, offset, fraction) {\n precision = precision > 0\n ? precision\n : 0\n scale = scale > 0\n ? scale\n : 0\n\n this.sql_type = sqlType\n this.value = value\n this.precision = precision\n this.scale = scale\n this.offset = offset\n this.isDateTime = sqlType === SQL_TYPE_TIMESTAMP\n if (this.isDateTime) {\n this.fraction = this.calcFraction(value, fraction)\n }\n this.isTime2 = sqlType === SQL_SS_TIME2\n if (this.isTime2) {\n this.precision = this.precision || 16\n this.scale = this.scale || 7\n }\n this.money = false\n }\n }\n\n function Bit (p) {\n return new ConcreteColumnType(SQL_BIT, p)\n }\n\n // sql.BigInt(value)\n\n function BigInt (p) {\n return new ConcreteColumnType(SQL_BIGINT, p)\n }\n\n // sql.Float(value)\n\n function Float (p) {\n return new ConcreteColumnType(SQL_FLOAT, p)\n }\n\n // sql.Real(value)\n\n function Real (p) {\n return new ConcreteColumnType(SQL_REAL, p)\n }\n\n // sql.Int(value)\n\n function Int (p) {\n return new ConcreteColumnType(SQL_INTEGER, p)\n }\n\n // sql.SmallInt(value)\n\n function SmallInt (p) {\n return new ConcreteColumnType(SQL_SMALLINT, p)\n }\n\n // sql.TinyInt(value)\n\n function TinyInt (p) {\n return new ConcreteColumnType(SQL_TINYINT, p)\n }\n\n // sql.Numeric(value, [precision], [scale]) -- optional precision and scale definition\n\n function Numeric (p, precision, scale) {\n return new ConcreteColumnType(SQL_NUMERIC, p, precision, scale)\n }\n\n function Decimal (p, precision, scale) {\n return new ConcreteColumnType(SQL_DECIMAL, p, precision, scale)\n }\n\n // sql.Money(value) - uses underlying numeric type with driver computed precision/scale\n\n function Money (p) {\n const c = new ConcreteColumnType(SQL_NUMERIC, p, 0, 0)\n c.money = true\n return c\n }\n\n // sql.SmallMoney(value)\n\n function Binary (p) {\n return new ConcreteColumnType(SQL_BINARY, p, 0, 0)\n }\n\n function VarBinary (p) {\n return new ConcreteColumnType(SQL_VARBINARY, p, 0, 0)\n }\n\n function Unknown (p) {\n return new ConcreteColumnType(SQL_UNKNOWN_TYPE, p, 0, 0)\n }\n\n function LongVarBinary (p) {\n return new ConcreteColumnType(SQL_LONGVARBINARY, p, 0, 0)\n }\n\n function WVarChar (p) {\n return new ConcreteColumnType(SQL_WVARCHAR, p, 0, 0)\n }\n\n function WLongVarChar (p) {\n return new ConcreteColumnType(SQL_WLONGVARCHAR, p, 0, 0)\n }\n\n // sql.DateTimeOffset(value, [scale]) -- optional scale definition\n\n function DateTimeOffset (p, scale, offset) {\n return new ConcreteColumnType(SQL_SS_TIMESTAMPOFFSET, p, undefined, scale, offset)\n }\n\n function Double (p) {\n return new ConcreteColumnType(SQL_DOUBLE, p)\n }\n\n // sql.Char(value, [length]) -- optional length definition\n\n function Char (p, precision) {\n return new ConcreteColumnType(SQL_CHAR, p, precision)\n }\n\n // sql.VarChar(value, [length]) -- optional length definition\n\n function VarChar (p, precision) {\n return new ConcreteColumnType(SQL_VARCHAR, p, precision)\n }\n\n // sql.Time(value, [scale]) -- optional scale definition\n\n function Time2 (p, scale, offset) {\n return new ConcreteColumnType(SQL_SS_TIME2, p, undefined, scale, offset)\n }\n\n function MyDate (p, offset) {\n return new ConcreteColumnType(SQL_TYPE_DATE, p, undefined, undefined, offset)\n }\n\n function DateTime (p, offset) {\n return new ConcreteColumnType(SQL_TYPE_TIMESTAMP, p, undefined, undefined, offset)\n }\n\n // fraction is not yet used by driver, this is a placeholder for potential use given\n // a JS date only holds MS resolution. Also presents an issue of how to pass this\n // additional information back to the client.\n\n // sql.DateTime2(value, [scale]) -- optional scale definition\n\n function DateTime2 (p, scale, fraction, offset) {\n return new ConcreteColumnType(SQL_TYPE_TIMESTAMP, p, undefined, scale, offset, fraction)\n }\n\n // datetime Date round to 10 ms as fraction is not guaranteed\n\n function DateRound (d, scale) {\n if (!d) {\n d = new Date()\n }\n if (!scale) {\n scale = 10\n }\n const rms = Math.ceil(d.getUTCMilliseconds() / scale) * scale\n return new Date(Date.UTC(\n d.getUTCFullYear(),\n d.getUTCMonth(),\n d.getUTCDate(),\n d.getUTCHours(),\n d.getUTCMinutes(),\n d.getUTCSeconds(),\n rms\n ))\n }\n\n function TzOffsetQuery (s, offsetMinutes) {\n const offset = offsetMinutes || -new Date().getTimezoneOffset()\n return {\n query_str: s,\n query_timeout: 0,\n query_polling: false,\n query_tz_adjustment: offset\n }\n }\n\n function PollingQuery (s) {\n return {\n query_str: s,\n query_timeout: 0,\n query_polling: true,\n query_tz_adjustment: 0\n }\n }\n\n function TimeoutQuery (s, tSecs) {\n return {\n query_str: s,\n query_timeout: tSecs,\n query_polling: false,\n query_tz_adjustment: 0\n }\n }\n\n function fromRow (rows, c) {\n let v\n if (rows.length === 1) {\n v = rows[0][c]\n } else {\n v = []\n for (let r = 0; r < rows.length; ++r) {\n v[v.length] = rows[r][c]\n }\n }\n return v\n }\n\n function Table (typeName, cols) {\n const rows = []\n const columns = []\n let schema = 'dbo'\n let unqualifiedTableName = typeName\n const schemaIndex = typeName.indexOf('.')\n if (schemaIndex > 0) {\n schema = typeName.substring(0, schemaIndex)\n unqualifiedTableName = typeName.substring(schemaIndex + 1)\n }\n\n if (cols && Array.isArray(cols)) {\n cols.forEach(c => {\n columns.push(c)\n if (Object.prototype.hasOwnProperty.call(c, 'schema_name')) {\n schema = c.schema_name\n }\n })\n }\n\n function addRowsFromObjects (vec) {\n vec.forEach(v => {\n addRowFromObject(v)\n })\n }\n\n function addRowFromObject (o) {\n const row = []\n columns.forEach(col => {\n row.push(o[col.name])\n })\n rows.push(row)\n }\n\n return {\n schema,\n name: unqualifiedTableName,\n rows,\n columns,\n addRowsFromObjects\n }\n }\n\n function TvpFromTable (p) {\n const tp = {\n sql_type: SQL_SS_TABLE,\n table_name: p.name,\n type_id: p.name,\n is_user_defined: true,\n is_output: false,\n value: p,\n table_value_param: [],\n row_count: 1,\n schema: p.schema || 'dbo'\n }\n if (Object.prototype.hasOwnProperty.call(p, 'columns') &&\n Object.prototype.hasOwnProperty.call(p, 'rows')) {\n const cols = p.columns\n const rows = p.rows\n tp.row_count = rows.length\n for (let c = 0; c < cols.length; ++c) {\n const v = rows.length > 0 ? fromRow(rows, c) : []\n const { scale, precision, type: ty } = cols[c]\n tp.table_value_param[c] = getSqlTypeFromDeclaredType({\n scale,\n precision,\n ...ty\n }, v)\n }\n }\n\n return tp\n }\n\n function getSqlTypeFromDeclaredType (dt, p) {\n const type = dt.declaration || dt.type || dt.type_id\n switch (type) {\n case 'char':\n case 'nchar':\n return Char(p)\n\n case 'varchar':\n case 'uniqueidentifier':\n return VarChar(p)\n\n case 'nvarchar':\n return WVarChar(p)\n\n case 'text':\n return VarChar(p)\n\n case 'int':\n return Int(p)\n\n case 'bigint':\n return BigInt(p)\n\n case 'tinyint':\n return TinyInt(p)\n\n case 'smallint':\n return SmallInt(p)\n\n case 'bit':\n return Bit(p)\n\n case 'float':\n return Float(p)\n\n case 'numeric':\n return Numeric(p, dt.precision, dt.scale)\n\n case 'decimal':\n return Decimal(p, dt.precision, dt.scale)\n\n case 'real':\n return Real(p)\n\n case 'date':\n return MyDate(p, dt.offset)\n\n case 'datetime':\n return DateTime(p, dt.offset)\n\n case 'datetimeoffset':\n return DateTimeOffset(p, dt.scale, dt.offset)\n\n case 'datetime2':\n return DateTime2(p, dt.scale, 0, dt.offset)\n\n case 'smalldatetime':\n return DateTime2(p, dt.scale, 0, dt.offset)\n\n case 'time':\n return Time2(p, dt.scale, dt.offset)\n\n case 'money':\n return Money(p)\n\n case 'smallmoney':\n return Money(p)\n\n case 'binary':\n return Binary(p)\n\n case 'varbinary':\n case 'image':\n case 'hierarchyid':\n return VarBinary(p)\n\n default:\n return Unknown(p)\n }\n }\n\n return {\n TzOffsetQuery,\n TimeoutQuery,\n PollingQuery,\n Bit,\n BigInt,\n Int,\n TinyInt,\n Numeric,\n Money,\n SmallMoney: Money,\n Binary,\n VarBinary,\n Unknown,\n UniqueIdentifier: WVarChar,\n LongVarBinary,\n Image: LongVarBinary,\n WVarChar,\n Double,\n Decimal,\n SmallInt,\n Float,\n Real,\n Char,\n VarChar,\n WLongVarChar,\n NChar: Char,\n NVarChar: WVarChar,\n Text: VarChar,\n NText: WVarChar,\n Xml: WVarChar,\n Time2,\n Time: Time2,\n MyDate,\n DateTime,\n DateTime2,\n DateRound,\n SmallDateTime: DateTime2,\n DateTimeOffset,\n TvpFromTable,\n Table,\n getSqlTypeFromDeclaredType\n }\n }",
"cast(value, datatype) {\n switch (datatype) {\n case 'number': return Number(value);\n case 'boolean': return Boolean(value);\n case 'string': return String(value);\n }\n\n return value;\n }",
"function data_type_to_sql(type) {\n var size = get_type_size(type);\n\n if (type.startsWith('varchar')) {\n if (!Number.isInteger(+size) || size > MAX_VARCHAR || size < 1) {\n throw new Error(`VARCHAR size must be between 1 and ${MAX_VARCHAR}. Actual: ${type}`);\n }\n\n return `VARCHAR(${size})`;\n } else if (type.startsWith('int')) {\n if (INT_BYTES_TO_NAME[size]) {\n return INT_BYTES_TO_NAME[size];\n } else if (/u[1-8]{0,1}$/.test(size) && INT_BYTES_TO_NAME[size.charAt(1)]) {\n return INT_BYTES_TO_NAME[size.charAt(1)] + ' UNSIGNED';\n }\n throw new Error(`Integer must be a valid integer size in bytes: 1, 2, 3, 4, or 8. Actual: ${type}`);\n } else {\n throw new Error(`Data type is invalid or not yet supported. Actual: ${type}`);\n }\n}",
"function convertToTypes(row) {\n\n var converted = {};\n _.forEach(row, function (v,k){\n\n // if no type return existing value.\n if(!schema[k] || !schema[k].type){\n converted[k] = v;\n }\n\n // get the type and convert.\n else {\n var type = schema[k].type;\n converted[k] = schema.cast(type, v);\n }\n\n });\n return converted;\n }",
"static toSchemaType(value,schema,options){if(null==value)return null;if(null==schema)return null;if(options&&options.resolveFunctionWriteValue&&schema.writeValue)return this.toSchemaType(value,schema.writeValue,options.convertDirection?{convertDirection:options.convertDirection}:void 0);let typeOfValue=typeof value;if(options&&options.convertDirection===ValueConverter.ConvertDirection.Backward){let rules=TcHmi.System.Type.Schema.resolveTypeConversionRules(schema);if(rules){let res,keys=[];rules.forEach((value,key)=>{keys.push(key)});for(let i=0,ii=keys.length;i<ii;i++){let key=keys[i];if(!key)continue;let rule=rules.get(key);if(\"string\"===key){if(res=ValueConverter.toString(value),rule.enum&&rule.enum.includes(res))break;res=void 0}}if(void 0!==res)return res}}else{let rules=TcHmi.System.Type.Schema.resolveTypeConversionRules(schema);if(rules&&rules.has(typeOfValue)){switch(rules.get(typeOfValue).convert){case\"number\":return ValueConverter.toNumber(value);case\"string\":return ValueConverter.toString(value);case\"boolean\":return ValueConverter.toBoolean(value)}}}let schemaType=TcHmi.System.Type.Schema.resolveType(schema);if(\"string\"!=typeof schemaType&&!Array.isArray(schemaType))return null;if(Array.isArray(schemaType)){if(\"string\"===typeOfValue||\"number\"===typeOfValue||\"boolean\"===typeOfValue||\"object\"===typeOfValue){if(-1!==schemaType.indexOf(typeOfValue))return value;for(let i=0,ii=schemaType.length;i<ii;i++){let res;switch(schemaType[i]){case\"object\":case\"array\":res=ValueConverter.toObject(value);break;case\"string\":res=ValueConverter.toString(value);break;case\"integer\":case\"number\":res=ValueConverter.toNumber(value);break;case\"boolean\":res=ValueConverter.toBoolean(value);break;default:res=null}if(null!==res)return res}}}else switch(schemaType){case\"object\":case\"array\":return ValueConverter.toObject(value);case\"string\":return ValueConverter.toString(value);case\"integer\":case\"number\":return ValueConverter.toNumber(value);case\"boolean\":return ValueConverter.toBoolean(value)}return null}",
"function DatatypeBird() {}",
"getSqType(fieldObj, attr) {\r\n const attrValue = fieldObj[attr];\r\n if (!attrValue.toLowerCase) {\r\n console.log(\"attrValue\", attr, attrValue);\r\n return attrValue;\r\n }\r\n const type = attrValue.toLowerCase();\r\n const length = type.match(/\\(\\d+\\)/);\r\n const precision = type.match(/\\(\\d+,\\d+\\)/);\r\n let val = null;\r\n let typematch = null;\r\n if (type === \"boolean\" || type === \"bit(1)\" || type === \"bit\" || type === \"tinyint(1)\") {\r\n val = 'DataTypes.BOOLEAN';\r\n // postgres range types\r\n }\r\n else if (type === \"numrange\") {\r\n val = 'DataTypes.RANGE(DataTypes.DECIMAL)';\r\n }\r\n else if (type === \"int4range\") {\r\n val = 'DataTypes.RANGE(DataTypes.INTEGER)';\r\n }\r\n else if (type === \"int8range\") {\r\n val = 'DataTypes.RANGE(DataTypes.BIGINT)';\r\n }\r\n else if (type === \"daterange\") {\r\n val = 'DataTypes.RANGE(DataTypes.DATEONLY)';\r\n }\r\n else if (type === \"tsrange\" || type === \"tstzrange\") {\r\n val = 'DataTypes.RANGE(DataTypes.DATE)';\r\n }\r\n else if (typematch = type.match(/^(bigint|smallint|mediumint|tinyint|int)/)) {\r\n // integer subtypes\r\n val = 'DataTypes.' + (typematch[0] === 'int' ? 'INTEGER' : typematch[0].toUpperCase());\r\n if (/unsigned/i.test(type)) {\r\n val += '.UNSIGNED';\r\n }\r\n if (/zerofill/i.test(type)) {\r\n val += '.ZEROFILL';\r\n }\r\n }\r\n else if (type === 'nvarchar(max)' || type === 'varchar(max)') {\r\n val = 'DataTypes.TEXT';\r\n }\r\n else if (type.match(/n?varchar|string|varying/)) {\r\n val = 'DataTypes.STRING' + (!lodash_1.default.isNull(length) ? length : '');\r\n }\r\n else if (type.match(/^n?char/)) {\r\n val = 'DataTypes.CHAR' + (!lodash_1.default.isNull(length) ? length : '');\r\n }\r\n else if (type.match(/^real/)) {\r\n val = 'DataTypes.REAL';\r\n }\r\n else if (type.match(/text$/)) {\r\n val = 'DataTypes.TEXT' + (!lodash_1.default.isNull(length) ? length : '');\r\n }\r\n else if (type === \"date\") {\r\n val = 'DataTypes.DATEONLY';\r\n }\r\n else if (type.match(/^(date|timestamp)/)) {\r\n val = 'DataTypes.DATE' + (!lodash_1.default.isNull(length) ? length : '');\r\n }\r\n else if (type.match(/^(time)/)) {\r\n val = 'DataTypes.TIME';\r\n }\r\n else if (type.match(/^(float|float4)/)) {\r\n val = 'DataTypes.FLOAT' + (!lodash_1.default.isNull(precision) ? precision : '');\r\n }\r\n else if (type.match(/^(decimal|numeric)/)) {\r\n val = 'DataTypes.DECIMAL' + (!lodash_1.default.isNull(precision) ? precision : '');\r\n }\r\n else if (type.match(/^money/)) {\r\n val = 'DataTypes.DECIMAL(19,4)';\r\n }\r\n else if (type.match(/^smallmoney/)) {\r\n val = 'DataTypes.DECIMAL(10,4)';\r\n }\r\n else if (type.match(/^(float8|double)/)) {\r\n val = 'DataTypes.DOUBLE' + (!lodash_1.default.isNull(precision) ? precision : '');\r\n }\r\n else if (type.match(/^uuid|uniqueidentifier/)) {\r\n val = 'DataTypes.UUID';\r\n }\r\n else if (type.match(/^jsonb/)) {\r\n val = 'DataTypes.JSONB';\r\n }\r\n else if (type.match(/^json/)) {\r\n val = 'DataTypes.JSON';\r\n }\r\n else if (type.match(/^geometry/)) {\r\n const gtype = fieldObj.elementType ? `(${fieldObj.elementType})` : '';\r\n val = `DataTypes.GEOMETRY${gtype}`;\r\n }\r\n else if (type.match(/^geography/)) {\r\n const gtype = fieldObj.elementType ? `(${fieldObj.elementType})` : '';\r\n val = `DataTypes.GEOGRAPHY${gtype}`;\r\n }\r\n else if (type.match(/^array/)) {\r\n const eltype = this.getSqType(fieldObj, \"elementType\");\r\n val = `DataTypes.ARRAY(${eltype})`;\r\n }\r\n else if (type.match(/(binary|image|blob|bytea)/)) {\r\n val = 'DataTypes.BLOB';\r\n }\r\n else if (type.match(/^hstore/)) {\r\n val = 'DataTypes.HSTORE';\r\n }\r\n else if (type.match(/^inet/)) {\r\n val = 'DataTypes.INET';\r\n }\r\n else if (type.match(/^cidr/)) {\r\n val = 'DataTypes.CIDR';\r\n }\r\n else if (type.match(/^oid/)) {\r\n val = 'DataTypes.INTEGER';\r\n }\r\n else if (type.match(/^macaddr/)) {\r\n val = 'DataTypes.MACADDR';\r\n }\r\n else if (type.match(/^enum(\\(.*\\))?$/)) {\r\n const enumValues = this.getEnumValues(fieldObj);\r\n val = `DataTypes.ENUM(${enumValues})`;\r\n }\r\n return val;\r\n }",
"function _fromDbType ({ type, value, id }) {\n\t\tswitch (type) {\n\t\tcase 'array': return createNode(id, [])\n\t\tcase 'object': return createNode(id, {})\n\t\tcase 'buffer': return Buffer.from(value)\n\t\tcase 'date': return new Date(value)\n\t\tcase 'function': return String(value) // -- dummy\n\t\tcase 'boolean':\treturn Boolean(value)\n\t\tcase 'string': return String(value)\n\t\tdefault: return value\n\t\t}\n\t}",
"function castNewtypePower() {\n \n }",
"function fixFieldDataTypes(record) {\n\tif ((record.stampTime !== null) && (record.stampTime !== undefined)) {\n\t\trecord.stampTime = String(record.stampTime);\n\t}\n\tif ((record.localId !== null) && (record.localId !== undefined)) {\n\t\trecord.localId = String(record.localId);\n\t}\n\tif ((record.refId !== null) && (record.refId !== undefined)) {\n\t\trecord.refId = String(record.refId);\n\t}\n\tif ((record.type !== null) && (record.type !== undefined)) {\n\t\trecord.type = String(record.type);\n\t}\n\tif ((record.facilityCode !== null) && (record.facilityCode !== undefined)) {\n\t\trecord.facilityCode = String(record.facilityCode);\n\t}\n}",
"function inferSqlType(value) {\n\tvar type = typeof value;\t\n\tswitch (type) {\n\t\tcase \"string\":\n\t\t\treturn TYPES.VarChar;\n\t\tcase \"number\":\n\t\t\tif (isFloat(value)) {\n\t\t\t\treturn TYPES.Decimal;\n\t\t\t}\n\n\t\t\treturn TYPES.Int;\n\n\t\tdefault:\n\t\t\tthrow new Exception(\"Cannot infer SQL type for: \" + type);\n\t}\n}",
"function fixFieldDataTypes(record) {\n\tif ((record.stampTime !== null) && (record.stampTime !== undefined)) {\n\t\trecord.stampTime = String(record.stampTime);\n\t}\n\tif ((record.birthDate !== null) && (record.birthDate !== undefined)) {\n\t\trecord.birthDate = String(record.birthDate);\n\t}\n\tif ((record.deceased !== null) && (record.deceased !== undefined)) {\n\t\trecord.deceased = String(record.deceased);\n\t}\n\tif ((record.localId !== null) && (record.localId !== undefined)) {\n\t\trecord.localId = String(record.localId);\n\t}\n\tif ((record.ssn !== null) && (record.ssn !== undefined)) {\n\t\trecord.ssn = String(record.ssn);\n\t}\n\tif ((record.last4 !== null) && (record.last4 !== undefined)) {\n\t\trecord.last4 = String(record.last4);\n\t}\n\tif ((record.last5 !== null) && (record.last5 !== undefined)) {\n\t\trecord.last5 = String(record.last5);\n\t}\n}",
"function FieldTypes_castDBType(dbType, notFromRS, notSMSpecific) {\r\n\tvar retVal = -1;\r\n\tif (dbType && dbType.match && dbType.match(/^\\w/gi)) {\r\n\t\tdbType = dwscripts.getDBColumnTypeEnum(dbType);\r\n\t}\r\n\tdbType = dbType ? dbType.toString() : \"\";\r\n\tif (dbType && FieldTypes.castingHash[dbType]) {\r\n\t\tretVal = FieldTypes.castingHash[dbType];\r\n\t\tretVal = parseInt(retVal);\r\n\t\tif (notFromRS) {\r\n\t\t\tif (retVal == 200) {\r\n\t\t\t\tretVal = 201;\r\n\t\t\t}\r\n\t\t\tif (retVal == 11) {\r\n\t\t\t\tretVal = 5;\r\n\t\t\t}\r\n\t\t\tif (dbType.toString() == \"130\") {\r\n\t\t\t\tretVal = 203;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tvar dom = dw.getDocumentDOM();\r\n\tvar smName = dom.serverModel.getServerName();\r\n\tif ((smName = \"PHP\") && (retVal == 11)) {\r\n\t\tretVal = 5;\r\n\t}\r\n\r\n\tif (!notSMSpecific) {\r\n\t\tvar dom = dw.getDocumentDOM();\r\n\t\tvar smName = dom.serverModel.getServerName();\r\n\t\tretVal = FieldTypes.smCastingHash[smName][retVal];\r\n\t}\r\n\treturn retVal;\r\n}",
"function driverTypeConverter(field, next) {\n var type = field.type;\n var name = field.name;\n var value;\n switch (type) {\n case 'DATE':\n value = field.string();\n return value;\n case 'TIMESTAMP':\n value = field.string();\n if (value === null) {\n return null;\n }\n return value;\n case 'DATETIME':\n value = field.string();\n if (value === null) {\n return null;\n }\n return value;\n default:\n return next();\n }\n}",
"function Column_FLOAT() {}",
"function fixFieldDataTypes(record) {\n\tif ((record.stampTime !== null) && (record.stampTime !== undefined)) {\n\t\trecord.stampTime = String(record.stampTime);\n\t}\n\tif ((record.lastUpdateTime !== null) && (record.lastUpdateTime !== undefined)) {\n\t\trecord.lastUpdateTime = String(record.lastUpdateTime);\n\t}\n\tif ((record.arrivalDateTime !== null) && (record.arrivalDateTime !== undefined)) {\n\t\trecord.arrivalDateTime = String(record.arrivalDateTime);\n\t}\n\tif ((record.dischargeDateTime !== null) && (record.dischargeDateTime !== undefined)) {\n\t\trecord.dischargeDateTime = String(record.dischargeDateTime);\n\t}\n\tif ((record.facilityCode !== null) && (record.facilityCode !== undefined)) {\n\t\trecord.facilityCode = String(record.facilityCode);\n\t}\n\tif ((record.principalDx !== null) && (record.principalDx !== undefined)) {\n\t\trecord.principalDx = String(record.principalDx);\n\t}\n\tif ((record.drg !== null) && (record.drg !== undefined)) {\n\t\trecord.drg = String(record.drg);\n\t}\n}",
"function getDBColumnTypeAsString(typeNum)\n{\n// todo: should store dbtype array somewhere like in dwscripts?\n var retVal = null;\n var a = new Array();\n\n a[0] = \"Empty\";\n a[2] = \"CF_SQL_SMALLINT\";\n a[3] = \"CF_SQL_INTEGER\";\n a[4] = \"CF_SQL_FLOAT\";\n a[5] = \"CF_SQL_FLOAT\";\n a[6] = \"CF_SQL_MONEY\";\n a[7] = \"CF_SQL_DATE\";\n a[8] = \"CF_SQL_CHAR\"; //?\n a[9] = \"IDispatch\";\n a[10] = \"Error\";\n a[11] = \"CF_SQL_BIT\"; //Boolean\n a[12] = \"Variant\";\n a[13] = \"IUnknown\";\n a[14] = \"CF_SQL_DECIMAL\"; //Decimal\n a[16] = \"CF_SQL_TINYINT\"; //TinyInt\n a[17] = \"CF_SQL_TINYINT\"; //UnsignedTinyInt\n a[18] = \"CF_SQL_SMALLINT\"; //UnsignedSmallInt\n a[19] = \"CF_SQL_INTEGER\"; //UnsignedInt\n a[20] = \"CF_SQL_BIGINT\"; //BigInt\n a[21] = \"CF_SQL_BIGINT\"; //UnsignedBigInt\n a[72] = \"GUID\";\n a[128] = \"Binary\";\n a[129] = \"CF_SQL_CHAR\"; //Char\n a[130] = \"CF_SQL_CHAR\"; //WChar\n a[131] = \"CF_SQL_NUMERIC\"; //Numeric\n a[132] = \"UserDefined\";\n a[133] = \"CF_SQL_DATE\"; //DBDate\n a[134] = \"CF_SQL_TIME\"; //DBTime\n a[135] = \"CF_SQL_TIMESTAMP\"; //DBTimeStamp\n a[200] = \"CF_SQL_VARCHAR\"; //VarChar\n a[201] = \"CF_SQL_LONGVARCHAR\"; //LongVarChar\n a[202] = \"CF_SQL_VARCHAR\"; //VarWChar\n a[203] = \"CF_SQL_LONGVARCHAR\"; //LongVarWChar\n a[204] = \"VarBinary\";\n a[205] = \"LongVarBinary\";\n //Defined for CF support\n a[400] = \"CF_SQL_REAL\";\n a[401] = \"CF_SQL_FLOAT\";\n a[402] = \"CF_SQL_LONGVARCHAR\";\n a[403] = \"CF_SQL_MONEY4\";\n a[900] = \"REF CURSOR\" // Special case for Oracle\n a[901] = \"CF_SQL_BIT\";\n\n if (a[typeNum])\n {\n retVal = a[typeNum];\n }\n\n return retVal;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Scalar product between two velocities | function innerProduct(vel1, vel2) {
output = vel1['x'] * vel2['x'] + vel1['y'] * vel2['y']
return output;
} | [
"applyVelocity() {\n\t\tvectors.forEach(vector => {\n\t\t\tthis.position[vector] += this.velocity[vector];\n\t\t});\n\t}",
"updateVelocity() {\n vec3.scale(this.v, this.v, Math.pow((1 - drag), step));\n var increment = vec3.create();\n vec3.scale(increment, this.a, step);\n vec3.add(this.v, this.v, increment);\n }",
"getVelocity() {\n var velocity = scale(this.m_speed, this.m_direction);\n\n return velocity;\n }",
"getVelocity() {\n return this.canTrackVelocity ? (\n // These casts could be avoided if parseFloat would be typed better\n velocityPerSecond(parseFloat(this.current) - parseFloat(this.prev), this.timeDelta)\n ) : 0;\n }",
"updateVelocities() {\n this.model.scene.forEach(\n /** @arg m_1 {Celestial} */\n (m_1) =>\n m_1 instanceof Celestial &&\n m_1.physical &&\n // Add to the velocity\n m_1.velocity.add(\n this.model.scene\n // Total acceleration\n .reduce(\n /**\n * @arg {Vector} acc Total acceleration (accumulator)\n * @arg {Celestial} m_2 Celestial applying acceleration\n */\n (acc, m_2) =>\n // Add gravitational acceleration if not same celestial\n m_2 instanceof Celestial && m_2.physical && m_1 !== m_2\n ? acc.add(this.gravitate(m_1, m_2))\n : acc,\n // Initialize an zero acceleration vector\n new Vector(0, 0)\n )\n // Velocity from acceleration\n .scale(Physics.TIME_SCALE)\n )\n );\n }",
"function calculateVelocity(pressure) {\n return Math.sqrt((2 * pressure) / airDensity);\n}",
"updateVelocity() {\n let w = this.markers.map(marker => {\n let m = new THREE.Vector3().subVectors(this.pos, marker.v);\n let g = new THREE.Vector3().subVectors(this.pos, this.goal);\n let m_mag = m.length();\n let g_mag = g.length();\n let weight = (1 + m.dot(g) / (m_mag * g_mag)) / (1 + m_mag)\n return weight;\n })\n let sum_w = w.reduce((acc, val) => {\n return acc + val;\n }, 0);\n this.vel = this.markers.map((marker, i) => {\n let displacement = new THREE.Vector3().subVectors(marker.v, this.pos);\n return displacement.multiplyScalar(w[i] / sum_w);\n }).reduce((acc, val) => {\n return acc.add(val);\n }, v3()).clampLength(MIN_VEL, MAX_VEL);\n }",
"function velocity(L){\n//L= 1/2*t^2*g*(Math.sin(alpha) -F_d*Math.cos(alpha) + F1_x) //position at the end of the trajectory L\n//from eq. above we can get t at the end of the trajectory as\nt= Math.sqrt(2*L/a);\n//acquired velocity\n//v = v_0 + a*t =\nv = t*a; //this is v_0 for the second motion\nreturn v}",
"getVelocity() {\n // This could be isFloat(this.prev) && isFloat(this.current), but that would be wasteful\n return this.canTrackVelocity\n ? // These casts could be avoided if parseFloat would be typed better\n velocityPerSecond(parseFloat(this.current) -\n parseFloat(this.prev), this.timeDelta)\n : 0;\n }",
"r(u, v) { return (u[0] * v[0] + u[1] * v[1]) / (this.m(u) * this.m(v)); }",
"updateVelocityVectors() {\n this.bodies.forEach(body => {\n body.vx += body.ax * this.dt;\n body.vy += body.ay * this.dt;\n body.vz += body.az * this.dt;\n });\n return this;\n }",
"getAngularVelocity () { return Angle.PI_2/FPS.target; }",
"get relativeVelocity() {}",
"static scalarProduct(v1,v2){\n\t\tif(v1.constructor === Vector && v2.constructor === Vector){\n\t\t\treturn (v1.x*v2.x + v1.y*v2.y);\n\t\t}else{\n\t\t\tthrow {error:-1,message: \"v1 or v2 is not a Vector.\"};\n\t\t}\n\t}",
"doVelocities() {\n this.x += this.velocity.x; //X value equal to velocity x value\n this.y += this.velocity.y //Y value equal to velocity y value\n this.velocity.add(this.acceleration.x, this.acceleration.y);\n this.velocity.limit(this.maxSpeed); //Limit velocities magnitude to the maximum speed\n }",
"get velocity() {}",
"function ImpulseWithBall(i, j)\n{\n var ball1 = table.ballBag.balls[i];\n var ball2 = table.ballBag.balls[j];\n var v1 = ball1.velocity;\n var v2 = ball2.velocity;\n\n //u \n var u = vec2((ball1.position[0] - ball2.position[0]) * (ball1.position[0] - ball2.position[0]), (ball1.position[1] - ball2.position[1]) * (ball1.position[1] - ball2.position[1])) ;\n var d = Math.sqrt(u[0] * u[0] + u[1] + u[1]);\n var n = vec2(u[0] * 1.0/d, u[1] * 1.0/d);\n var int_p = (v1[0] * n[0] + v1[1] + n[1]) - (v2[0] * n[0] + v2[1] + n[1]);\n console.log(int_p)\n var p = (2 * (int_p) / (ball1.mass + ball2.mass))\n console.log(\"Sup\")\n var p1 = p * ball1.mass\n var p2 = p * ball2.mass\n console.log(v1[0], p, p1[0], n[0])\n ball1.velocity = vec2(v1[0] - (p1 * n[0] + p1 * n[1]), v1[1] - (p1 * n[0] + p1 * n[1]))\n ball2.velocity = vec2(v2[0] - (p2 * n[0] + p2 * n[1]), v2[1] - (p2 * n[0] + p2 * n[1]))\n console.log(ball1.velocity[0])\n\n}",
"function calculateVelocity(vertex, t) {\n let dampening = 0.5;\n let a = vertex.acceleration.multiply(t);\n return a.multiply(dampening);\n}",
"function calculateVelocity() {\n\t\t\t\tcurrentTime = (new Date).getTime();\n\t\t\t\tperiod = currentTime - previousTime;\n\t\t\t\tpreviousTime = currentTime;\n\t\t\t\tif (numSamples++) {\n\t\t\t\t\tvelocityX = (velocityX * (numSamples - 1) + numSamples * (translationX - previousTranslationX) / period) / 2 / numSamples;\n\t\t\t\t\tvelocityY = (velocityY * (numSamples - 1) + numSamples * (translationY - previousTranslationY) / period) / 2 / numSamples;\n\t\t\t\t} else {\n\t\t\t\t\tvelocityX = (translationX - startTranslationX) / period;\n\t\t\t\t\tvelocityY = (translationY - startTranslationY) / period;\n\t\t\t\t}\n\t\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implementation of filtering by duration which takes in a list of adventures, the lower bound and upper bound of duration and returns a filtered list of adventures. | function filterByDuration(list, low, high) {
// TODO: MODULE_FILTERS
// 1. Filter adventures based on Duration and return filtered list
return list.filter( option => option.duration>=low && option.duration <= high)
} | [
"function filterByDuration(list, low, high) {\n\n // 1. Filter adventures based on Duration and return filtered list\n\n return list.filter(item => item.duration >= low && item.duration <= high)\n // TODO: MODULE_FILTERS\n // 1. Filter adventures based on Duration and return filtered list\n\n}",
"function filterByDuration(list, low, high) {\n // TODO: MODULE_FILTERS\n // 1. Filter adventures based on Duration and return filtered list\n return list.filter(data => data.duration>=low && data.duration<=high);\n}",
"function filterByDuration(list, low, high) {\n // TODO: MODULE_FILTERS\n // 1. Filter adventures based on Duration and return filtered list\n let filteredList = list.filter(item => item.duration > low && item.duration <= high)\n return filteredList\n}",
"function filterByDuration(list, low, high) {\n // TODO: MODULE_FILTERS\n // 1. Filter adventures based on Duration and return filtered list\n let res = list.filter(e=>{\n return e.duration>=low&&e.duration<=high;\n })\n return res;\n}",
"function filterByDuration(list, low, high) {\n // TODO: MODULE_FILTERS\n // 1. Filter adventures based on Duration and return filtered list\n // console.log(\"Inside Duration\", low, high)\n let filteredList = [];\n list.forEach((adventure) => {\n if(adventure.duration >= parseInt(low) && adventure.duration <= parseInt(high)){\n filteredList.push(adventure);\n }\n })\n \n return filteredList\n}",
"function filterByDuration(list, low, high) {\n // TODO: MODULE_FILTERS\n // 1. Filter adventures based on Duration and return filtered list\n // let durationlist = (list.filter((e)=> e.duration > low && e.duration < high));\n // return durationlist;\n let durationlist = list.filter((e) => {\n return e.duration > low && e.duration < high;\n });\n return durationlist;\n}",
"function filterByDuration(list, low, high) {\n // TODO: MODULE_FILTERS\n // 1. Filter adventures based on Duration and return filtered list\n\n console.log(\"by dur\",list,low,high)\n var activities = []//list.filter(activity => activity.duration>=low && activity.duration<=high);\n for (var i=0;i<list.length;i++){\n if (list[i].duration>=low && list[i].duration<=high){\n activities.push(list[i])\n }\n }\n console.log(\"Filtered\",activities)\n return activities\n}",
"static filterRange(list, key, lower, upper) {\n return list.filter(item => item[key] <= upper && item[key] >= lower);\n }",
"function filterBetween(array, min, max) {\n\n}",
"function filterByCategory(list, categoryList) {\n // TODO: MODULE_FILTERS\n // 1. Filter adventures based on their Category and return filtered list\n var activities=[]\n for (var i=0;i<list.length;i++){\n for(var j=0;j<list.length;j++){\n if (list[i].category==categoryList[j]){\n activities.push(list[i])\n break\n }\n }\n }\n return activities\n\n}",
"emotionListWithinRangeTime(state) {\n // return a function to accept parameters\n return ({ start, end }) => {\n // return an array according to the range of time\n return state.list.filter(emotion => {\n return emotion.created_at > start && emotion.created_at < end\n })\n }\n }",
"function filterByDateRange(tasks, daterange) {\n let filteredLeads = [];\n const timeMin = Date.parse(daterange.startDate);\n const timeMax = Date.parse(daterange.endDate);\n\n for (let i = 0; i < tasks.length; i++) {\n let createTime = Date.parse(tasks[i].date);\n if (createTime > timeMin && createTime < timeMax) {\n filteredLeads.push(tasks[i]);\n }\n }\n\n return filteredLeads;\n}",
"function filterEventsByAgeRange(flag) {\n console.log(\"\\n Events that only \"+flag+ \" are allowed:\")\n if(flag==\"adults\") flag=true;\n else flag=false;\n for(var i=0;i<Events.length;i++) {\n if(Events[i].onlyAdults==flag || (Events[i].onlyAdults==undefined && !flag)) {\n prettyVisualization(i);\n }\n }\n}",
"function filterRange(){\n return function(arr, a, b){\n return arr.filter(function(value){\n return value >= a && value <= b;\n });\n }\n }",
"function itemsBetween14and18() {\n //filter the items to find the subset of items and return the array\n return items.filter(function(item) {\n return (item.price >= 14.00 && item.price <= 18.00)\n })\n\n}",
"function filterByAgeOfDriver(vehicles, ageOfDriver) {\r\n var filteredAge = [];\r\n $.each(vehicles, function (i, vehicle) {\r\n if (ageOfDriver >= vehicle.minDriverAge && ageOfDriver <= vehicle.maxDriverAge) {\r\n filteredAge, push(vehicle);\r\n }\r\n });\r\n return filteredAge;\r\n }",
"filterByRange(array,start,end){\n let a = array;\n let b = [];\n \n for(var i = 0;i<a.length;i++){\n if(this.stringToDate(a[i].date)>=this.stringToDate(start) && this.stringToDate(a[i].date)<=this.stringToDate(end)){\n b.push(a[i])\n }\n }\n return b;\n }",
"function filterForRangeObjects(dataArray, rangeObjectsArray) {\n\n //get the date filter object\n let dateObj = _.findWhere(rangeObjectsArray, { identifier: 'date' });\n\n //filter for the fibroValue object\n if (dateObj) {\n let startDate = new Date(dateObj.value.split('~~')[0]),\n endDate = new Date(dateObj.value.split('~~')[1]);\n\n dataArray = _.filter(dataArray, function(rec) {\n let admitDate = new Date(rec.admissionDate);\n return admitDate >= startDate && admitDate <= endDate;\n });\n }\n\n //get the age filter object\n let ageObj = _.findWhere(rangeObjectsArray, { identifier: 'age' });\n\n //filter for the age object\n if (ageObj) {\n let ageRange = ageObj.value.split('-'),\n minAge, maxAge = 0;\n minAge = ageRange[0].replace('+', '')\n maxAge = ageRange.length > 1 ? ageRange[1].replace('+', '') : 150;\n\n dataArray = _.filter(dataArray,(rec)=> rec.age >= ~~minAge && rec.age <= ~~maxAge);\n }\n\n //get the meldscore filter object\n let meldObj = _.findWhere(rangeObjectsArray, { identifier: 'meldscore' });\n\n //filter for the age object\n if (meldObj) {\n let valueRange = meldObj.value.split('-'),\n minValue, maxValue = 0;\n minValue = valueRange[0].replace('>', '')\n maxValue = valueRange.length > 1 ? valueRange[1].replace('>', '') : 150;\n\n //console.log(minValue,maxValue);\n\n dataArray = _.filter(dataArray, function(rec) {\n return rec.labs_meld >= parseFloat(minValue) && rec.labs_meld <= parseFloat(maxValue)\n });\n }\n\n //get the age fibroValue filter object\n let fibroObj = _.findWhere(rangeObjectsArray, { identifier: 'fibrovalue' });\n\n //filter for the fibroValue object\n if (fibroObj) {\n let valueRange = fibroObj.value.split('-'),\n minValue, maxValue = 0;\n minValue = valueRange[0].replace('+', '')\n maxValue = valueRange.length > 1 ? valueRange[1].replace('+', '') : 150;\n\n dataArray = _.filter(dataArray, function(rec) {\n return rec.fibro_Value >= parseFloat(minValue) && rec.fibro_Value <= parseFloat(maxValue)\n });\n }\n\n \n\n //get the apri filter object\n let apriObj = _.findWhere(rangeObjectsArray, { identifier: 'apri' });\n if (apriObj) {\n let isGreater = apriObj.value.indexOf('>') > -1 ? true : false;\n dataArray = dataArray.filter((d) => d['APRI'] != null);\n\n dataArray = _.filter(dataArray, function(rec) {\n let apri = new Date(rec.APRI);\n if (isGreater) {\n return apri >= 1;\n } else {\n return apri < 1;\n }\n });\n }\n\n\n //filter based on svr\n //get the meldscore filter object\n\n let svrObj = _.findWhere(rangeObjectsArray, { identifier: 'svr' });\n\n //filter for the age object\n if (svrObj) {\n let valueRange = svrObj.value.split('-'),\n minValue, maxValue = 0;\n minValue = parseFloat(valueRange[0].replace('<', '').replace('M', '').replace('+', '')) * 1000000;\n maxValue = parseFloat(valueRange.length > 1 ? valueRange[1].replace('<', '').replace('M', '').replace('+', '') : 150) * 1000000;\n\n if (valueRange.length == 1) {\n if (minValue <= 200000) {\n dataArray = _.filter(dataArray,(rec)=> rec.viralLoad <= ~~minValue)\n } else {\n dataArray = _.filter(dataArray,(rec)=> rec.viralLoad >= ~~minValue);\n }\n } else {\n dataArray = _.filter(dataArray,(rec)=> rec.viralLoad >= ~~minValue && rec.viralLoad < ~~maxValue);\n }\n }\n\n return dataArray;\n}",
"function filterByCategory(list, categoryList) {\n // TODO: MODULE_FILTERS\n // 1. Filter adventures based on their Category and return filtered list\n let arr = []\n for(let category of categoryList){\n let filterarr = list.filter(option => option.category === category)\n arr = [...arr,...filterarr]\n }\n return arr;\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Maps the group name to its event name | function groupToEventNameSpace(group) {
if (exports.NonSnakeCaseGroup.includes(group)) {
return group.toUpperCase();
}
return camelCaseToSnakeCase(group).toUpperCase();
} | [
"onName () {\n const group = get(this, 'group');\n this._validateGroupName(group);\n }",
"function groupToEventNameSpace(group) {\n switch (group) {\n case types_2.Group.ContextualSaveBar:\n return camelCaseToSnakeCase(group).toUpperCase();\n default:\n return group.toUpperCase();\n }\n}",
"function handle_get_group_name(event, callback, context) {\n let gid = get_event_property(event,'group_id', context);\n\n let statement = SqlString.format(\n 'SELECT groups.name FROM groups WHERE groups.id = (?);',\n [gid]\n );\n\n return handle_statement({statement:statement}, callback, context);\n}",
"function nameGroup(groupID,label){\n groups[groupID].name=label;\n storeGroups();\n}",
"function addEventGroup(evName, events) {\n var eventsMap = this._eventsMap;\n var map = eventsMap[evName] || {};\n checkGroupExist.call(this, evName, events);\n if (!isEventsExists.call(this, evName, events)) {\n for (var key in events) {\n map[key] = evName + GROUP_DELIMITER + events[key];\n }\n eventsMap[evName] = map;\n }\n }",
"setGroupName(event) {\n this.props.setGroupName(event.target.value);\n }",
"function getEventNameSpace(group, eventName, component) {\n if (eventName.startsWith(\"\" + constants_1.PREFIX + constants_1.SEPARATOR)) {\n return eventName;\n }\n var eventNameSpace = groupToEventNameSpace(group);\n if (component) {\n var subgroups_1 = component.subgroups, type = component.type;\n if (subgroups_1 && subgroups_1.length > 0) {\n eventNameSpace += eventNameSpace.length > 0 ? constants_1.SEPARATOR : '';\n subgroups_1.forEach(function (subgroup, index) {\n eventNameSpace += \"\" + subgroup.toUpperCase() + (index < subgroups_1.length - 1 ? constants_1.SEPARATOR : '');\n });\n }\n if (type !== group && type) {\n eventNameSpace += \"\" + (eventNameSpace.length > 0 ? constants_1.SEPARATOR : '') + type.toUpperCase();\n }\n }\n if (eventNameSpace) {\n eventNameSpace += \"\" + (eventNameSpace.length > 0 ? constants_1.SEPARATOR : '') + eventName.toUpperCase();\n }\n return \"\" + constants_1.PREFIX + constants_1.SEPARATOR + eventNameSpace;\n}",
"function camelizeEvent(name) {\n return 'on' + name.charAt(0).toUpperCase() + name.substring(1);\n}",
"function getEventName(match, prefix, eventName) {\n\t return eventName.toUpperCase();\n\t }",
"function getEventName(match, prefix, eventName) {\n return eventName.toUpperCase();\n }",
"function getEventName ( match, prefix, eventName ) {\n return eventName.toUpperCase();\n }",
"function InitEventGroupMapping() {\n TCEventConfigureCtrl.ePage.Masters.EventGroup = {};\n\n TCEventConfigureCtrl.ePage.Masters.EventGroup.OnEventGroupClick = OnEventGroupClick;\n }",
"getEventName(eventType, funcName) {\n return `sls-${eventType}-${funcName}`.replace(/-/g, '_');\n }",
"function checkGroupExist(evName, events) {\n var map = {};\n for (var key in events) {\n var val = events[key];\n if (map[val]) {\n var msg = 'problems with \"' + evName + '\". event ' + val + ' trying to define already existed event name';\n showError.call(this, msg);\n }\n map[val] = true;\n }\n map = null;\n }",
"getEventNames() {\n\t\t\tlet eventNames = {};\n\t\t\tObject.keys(this.events)\n\t\t\t\t.forEach(event => {\n\t\t\t\t\teventNames[utils.camelToUnderscore(event)] = event;\n\t\t\t\t});\n\t\t\treturn eventNames;\n\t\t}",
"function fnGroupName (argName) {\n fnLog (\"3d: GroupName: Set to \" + argName);\n sGroupName = \"group-\" + argName; // Global :(\n}",
"function renameGroup(group, name)\n {\n console.debug(\"renameGroup:\", group, name);\n // DI02 – Rename a group\n track('Sugar', 'Rename a group', name, group.tabs().length);\n // 1. The user renames a group in the dashboard (already done)\n //&2. The dashboard sends a request to the background page\n var gid = group.uid();\n chrome.extension.sendRequest({\n action: 'DI02', // Rename a group\n gid: gid,\n name: name\n },\n function (response)\n {\n });\n\n if (localStorage.debug == \"true\") {\n $('.debug', group).html('#' + gid + ' / ' + name);\n }\n return name;\n }",
"function getEventName(event_id) {\n for(var i in event_reference) {\n var obj = event_reference[i];\n if(obj.id === event_id)\n return obj.name;\n }\n return undefined;\n}",
"getName(event) {\n return parseStrFormat(event, this.title, this.isHTML);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
where current rank 0 to account for zero level modifier | levelZeroPassCalc(Rank) {
this.progUp = 10 * ((this.rank + Rank - 1) ** 2);
if (this.rank + Rank - 1 === 0) {
this.progUp = 10 * ((this.rank + Rank + 1) ** 2);
}
return this.levelProgressCalc();
} | [
"similarLevelCalc(Rank) {\n if (this.rank === Rank) {\n this.progUp = 3;\n }\n if (this.rank === (this.Rank - 1)) {\n this.progUp = 1;\n }\n return this.levelProgressCalc();\n }",
"checkZero() {\n\t\tif(this.rank<0) {\n\t\t\tthis.rank = 0;\n\t\t\tvar msg4 = (`Error! minimom star rank is zero`);\n\t\t\tconsole.log(`${msg4}`);\n\t\t\tthis.msg.push(msg4);\n\t\t\tthis.msg.push(`\\n`);\n\t\t}\n\t}",
"function getPowerLevel(rankObj, level) {\n\t\tvar valWithoutBonus = rankObj.value + level * 10;\n\t\treturn valWithoutBonus + getBonusPoints(level);\n\t}",
"function decodeRank(rank) {\n if (rank == -1)\n return ;\n else if (rank == 26)\n return 1;\n else if (rank == 25)\n return 1;\n else\n return 5 - rank % 5;\n}",
"function normalizeRanks(g) {\n\t var min = _.min(_.map(g.nodes(), function (v) {\n\t return g.node(v).rank;\n\t }));\n\n\t _.forEach(g.nodes(), function (v) {\n\t var node = g.node(v);\n\n\t if (_.has(node, \"rank\")) {\n\t node.rank -= min;\n\t }\n\t });\n\t }",
"function initRank(g){var sorted=topsort(g);sorted.forEach(function(u){var inEdges=g.inEdges(u);if(inEdges.length===0){g.node(u).rank=0;return;}var minLens=inEdges.map(function(e){return g.node(g.source(e)).rank+g.edge(e).minLen;});g.node(u).rank=util.max(minLens);});}",
"function rankCard(card) {\n switch(card.cardNumber) {\n /* MUST HAVE */\n case 142: return -22; /* Remove the guard */\n case 151: return -21; /* Kill a monster */\n case 143: return -20; /* Remove all abilities */\n case 149: return -19; /* Remove all abilities and draw a card */\n case 148: return -19; /* Remove all abilities and 2 damage */\n case 118: return -18; /* 0/+3 */\n case 128: return -17; /* Boost +4/3 */\n case 122: return -16; /* Boost +1/3 G */\n case 125: return -15; /* Boost +2/1 Drain */\n case 124: return -14; /* Boost +2/1 Drain */\n case 124: return -13; /* Boost +3/3 */\n case 126: return -12; /* Boost +2/3 */\n case 127: return -12; /* Boost +0/6 */\n case 129: return -11; /* Boost +2/5 */\n case 123: return -10; /* Boost +4/0 */\n case 134: return -9; /* Boost +2/2 draw+1 */\n case 133: return -8; /* Boost +4/0 ward */\n case 131: return -7; /* Boost +4/1 */\n case 132: return -6; /* Boost +3/3 B */\n case 154: return -5; /* Damage 2 - Draw 1 */\n case 156: return -4; /* Damage 3 and heal 3 */\n case 160: return -3; /* Damage 2 and heal 2 */\n case 153: return -2; /* Damage 2 and heal 2 */\n case 157: return -1; /* Damage 1 - heal 1 - Draw 1 */\n case 141: return -1; /* M0 -1/-1 */\n \n case 51: return 1; /* M4 3/5 L */\n case 52: return 2; /* M4 2/4 L */\n case 53: return 3; /* M4 1/1 CL */\n case 50: return 4; /* M3 3/2 L */\n case 49: return 5; /* M2 1/2 GL */\n case 54: return 6; /* M3 2/2 L */\n case 48: return 7; /* M1 1/1 lethal */\n case 70: return 8; /* M4 6/3 B */\n case 72: return 9; /* M4 5/3 B */\n case 101: return 10; /* M4 3/4 G */\n case 42: return 11; /* M4 4/2 D */\n case 40: return 12; /* M3 2/3 DG */\n case 104: return 13; /* M4 4/4 G */\n case 73: return 14; /* M4 4/4 B/H+4 */\n case 96: return 15; /* M2 3/2 G */\n case 47: return 16; /* M2 1/5 D */\n case 38: return 17; /* M1 1/3 drain */\n case 103: return 18; /* M4 3/6 G */\n case 14: return 19; /* M4 9/1 */\n case 18: return 20; /* M4 7/4 */\n case 16: return 21; /* M4 6/2 */\n case 11: return 22; /* M3 5/2 */\n case 41: return 23; /* M3 2/2 CD */\n case 10: return 24; /* M3 3/1 D */\n case 65: return 25; /* M2 2/2 W */\n case 7: return 26; /* M2 2/2 W */\n case 13: return 27; /* M4 5/3 H+1/-1 */\n case 87: return 28; /* M4 2/5 CG */\n case 99: return 29; /* M3 2/5 G */\n case 98: return 30; /* M3 2/4 G */\n case 102: return 31; /* M4 3/3 G H-1 */\n case 69: return 32; /* M3 4/4 B */\n case 97: return 33; /* M3 3/3 G */\n case 95: return 34; /* M2 2/3 G */\n case 9: return 35; /* M3 3/4 */\n case 6: return 36; /* M2 3/2 */\n case 39: return 37; /* M1 2/1 Drain */\n case 100: return 38; /* M3 1/6 G */\n case 15: return 39; /* M4 4/5 */\n case 17: return 39; /* M4 4/5 */\n case 33: return 40; /* M4 4/3 Draw+1 */\n case 30: return 41; /* M3 4/2 H-2 */\n case 8: return 42; /* M2 2/3 */\n case 64: return 43; /* M2 1/1 GW */\n case 5: return 44; /* M2 4/1 */\n case 63: return 45; /* M2 0/4 GW */\n case 71: return 46; /* M4 3/2 CB */\n case 26: return 47; /* M2 3/2 H-1 */\n case 32: return 48; /* M3 3/2 Draw+1 */\n case 12: return 49; /* M3 2/5 */\n case 25: return 50; /* M2 3/1 H-2 */\n case 31: return 51; /* M3 3/1 H-1 */\n case 57: return 52; /* M4 1/8 */\n case 94: return 53; /* M2 1/4 G */\n case 93: return 54; /* M1 2/1 G */\n case 3: return 55; /* M1 2/2 */\n case 84: return 56; /* M2 1/1 CDW */\n case 91: return 57; /* M0 1/2 GH+1 */\n case 27: return 58; /* M2 2/2 H+2 */\n case 1: return 59; /* M1 2/1 H+1 */\n case 86: return 60; /* M3 1/5 C */\n case 4: return 61; /* M2 1/5 */\n case 2: return 62; /* M1 1/2 H-1 */\n case 29: return 63; /* M2 2/1 Draw+1 */\n case 83: return 64; /* M0 1/1 Charge */\n case 28: return 65; /* M2 1/2 Draw+1 */\n case 92: return 66; /* M1 0/1 G H+2 */\n case 24: return 67; /* M1 1/1 H-1 */\n case 55: return 68; /* M2 0/5 G */\n \n \n /* 5 Mana */\n case 106: return 500; /* M5 5/5 G */\n case 74: return 501; /* M5 5/4 BG */\n case 66: return 502; /* M5 5/1 W */\n case 20: return 503; /* M5 8/2 */\n case 75: return 504; /* M5 6/5 B */\n case 21: return 505; /* M5 6/5 */\n case 105: return 506; /* M5 4/6 G */\n case 109: return 507; /* M5 5/6 */\n case 19: return 508; /* M5 5/6 */\n case 88: return 509; /* M5 4/4 C */\n case 108: return 510; /* M5 2/6 G */\n case 34: return 511; /* M5 3/5 Draw+1 */\n case 89: return 512; /* M5 4/1 C */\n case 107: return 513; /* M5 3/3 G H+3 */\n case 109: return 514; /* M5 5/6 */\n case 110: return 514; /* M5 0/9 G */\n \n /* Super Card */\n case 116: return 1000; /* M12 8/8 BCDGLW */\n case 82: return 1001; /* M7 7/7 BDW */\n case 62: return 1002; /* 12/12 BG */\n case 61: return 1003; /* 10/10 */\n case 80: return 1004; /* M8 8/8 BG Draw 1 */\n case 79: return 1005; /* M8 8/8 B */\n case 23: return 1006; /* M7 8/8 */\n case 76: return 1007; /* M6 5/5 BD */\n case 44: return 1008; /* M6 3/7 DL */\n case 114: return 1009; /* M7 7/7 G */\n case 77: return 1010; /* M7 7/7 B */\n case 45: return 1011; /* M6 6/5 BD H-3 */\n case 111: return 1012; /* M6 6/6 G */\n case 112: return 1013; /* M6 4/7 G */\n case 68: return 1014; /* M6 7/5 W */\n case 43: return 1015; /* M6 5/5 D */\n case 59: return 1016; /* 7/7 H+1/H-1 */ \n case 22: return 1017; /* M6 7/5 */\n case 81: return 1018; /* 6/6 BC */\n case 78: return 1019; /* M8 5/5 B H-5 */\n case 36: return 1020; /* M6 4/4 Draw 2 cards */\n case 35: return 1021; /* M6 5/2 B Draw 1 */\n case 37: return 1022; /* M6 5/7 Draw 1 */\n case 67: return 1023; /* M6 5/5 WH-2 */\n case 58: return 1024; /* M6 5/6 B */\n case 115: return 1025; /* M8 5/5 GW */\n case 60: return 1026; /* 4/8 */\n case 90: return 1027; /* 5/5 C */\n case 113: return 1028; /* M6 2/4 G H+4 */\n }\n return 10000;\n}",
"function calculateRank(rank) {\n var tempRank = 0;\n\n if (rank >= 0 && rank < 0.2) {\n tempRank = 1;\n } else if (rank >= 0.2 && rank < 0.4) {\n tempRank = 2;\n } else if (rank >= 0.4 && rank < 0.6) {\n tempRank = 3;\n } else if (rank >= 0.6 && rank < 0.8) {\n tempRank = 4;\n } else if (rank >= 0.8 && rank <= 1.0) {\n tempRank = 5;\n }\n\n return tempRank;\n}",
"function resetLevel() {\n current_level = 1;\n }",
"function normalizeRanks(g){var min=_.min(_.map(g.nodes(),function(v){return g.node(v).rank}));_.forEach(g.nodes(),function(v){var node=g.node(v);if(_.has(node,\"rank\")){node.rank-=min}})}",
"setRank(rank) {\n // use this to simplify rank number\n if (rank <= 0) {\n this.rank = 1\n } else if (rank < 1000 && rank > 0) {\n this.rank = int(rank);\n } else if (rank >= 1000 && rank <= 9999) {\n let temp = rank.toString()[0];\n this.rank = temp + \"K\";\n } else if (rank >= 10000 && rank <= 99999) {\n let temp = rank.toString().substring(0, 2);\n this.rank = temp + \"K\";\n } else if (rank >= 100000 && rank <= 999999) {\n let temp = rank.toString().substring(0, 3);\n this.rank = temp + \"K\";\n } else if (rank >= 1000000 && rank <= 9999999) {\n let temp = rank.toString()[0];\n this.rank = temp + \"M\";\n } else if (rank >= 10000000) {\n let temp = rank.toString().substring(0, 2);\n this.rank = temp + \"M\";\n }\n }",
"firstLevel() {\n this.level = 1;\n this.lostPenalty = this.baseLostPenalty;\n this.playerSpeed = this.baseSpeed;\n this.itemSpeed = this.baseSpeed / 4;\n this.reset();\n }",
"function normalizeRanks(g){var min=_.minBy(_.map(g.nodes(),function(v){return g.node(v).rank}));_.forEach(g.nodes(),function(v){var node=g.node(v);if(_.has(node,\"rank\")){node.rank-=min}})}",
"rank(i) { return this.#rank[i]; }",
"function masteryTierFull(tree, index) {\n var tier = data[tree][index].tier;\n\tfor (var i in data[tree])\n\t\tif (i != index && data[tree][i].tier == tier && (state[tree][i] || 0) + (state[tree][index] || 0) >= data[tree][i].ranks) \n\t\t\treturn i;\n return -1;\n}",
"findKthZero(k){ // K>=1\n if(k>this.totalZeroes)\n return -1\n if(this.l===this.r)\n return this.l\n if(this.leftChild.totalZeroes>=k)\n return this.leftChild.findKthZero(k)\n else\n return this.rightChild.findKthZero(k-this.leftChild.totalZeroes)\n }",
"getRank() {\n return this.rank;\n }",
"function calculate_level( score ) \n{\n var result = null;\n \n result = Math.round( score / 10 ) + 1;\n \n return result;\n}",
"function getScoreModifier(actor) { // Used to help calculate arena score points\r\n\tvar ranks = [\"Unranked\",\"Conscript\",\"Scout\",\"Soldier\",\"Second Squadman\",\"Squadman\",\"File Leader\",\"Patrolman\",\"Patrol Leader\",\"Second Bannerman\",\"Bannerman\",\"Hundredman\",\"Second Sergeant\",\"Sergeant\",\"First Sergeant\",\"Under-Lieutenant\",\"Lieutenant\",\"Senior Lieutenant\",\"Second Captain\",\"Captain\",\"First Captain\",\"Lord Captain\",\"General\",\"Banner-General\",\"Lieutenant-General\",\"Captain-General\",\"Marshal-General\",\"Lord General\",\"King\",\"King of Kings\",\"Godlike\"];\r\n\tfor (i=0; i<ranks.length; i++) {\r\n\t\tif (getArenaRank(actor) == ranks[i]) {\r\n\t\t\tvar points = i;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tif (points == 0 || !points)\r\n\t\tpoints = 1;\r\n\treturn points;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return active pool profile | returnActivePoolProfile() {
return this.activePoolProfile
} | [
"activeProfile(state) {\n return state.profile;\n }",
"getActiveProfile() {\n const activeProfile = this.profiles.find(x => x.active === true);\n\n if (!activeProfile) {\n Log.error(chalk.red('\\nThere is no active profile in your configuration.'));\n throw new Error('No active profile');\n }\n\n return activeProfile;\n }",
"returnPoolProfiles() {\n\t\treturn this.poolProfiles\n\t}",
"getCurrentProfile() {\n return this.profile;\n }",
"setActivePoolProfile(profileID) {\n\t\tthis.activePoolProfile = profileID\n\t}",
"_setActivePool(profileID) {\n\t\tthis.activePool = profileID\n\t}",
"get profile() {\n\t\treturn this.__profile;\n\t}",
"getSamplingProfile() {\n return this._client.send(\"Memory.getSamplingProfile\");\n }",
"GetProfile() {\n return this.m_profile;\n }",
"get profile () {\n\t\treturn this._profile;\n\t}",
"getPoolStats() {\n if (!this.pool) {\n return {};\n }\n return {\n pending: this.pool.pending,\n max: this.pool.max,\n min: this.pool.min,\n };\n }",
"inspectPool() {\n this.info(`Pool status: ${inspect(this.pool.inspectPool())}`)\n }",
"function getCachedProfile() {\r\n return userProfile;\r\n }",
"function getCachedProfile() {\n return userProfile;\n }",
"async getProfile(identity) {\n this.log.trace(`Get profile by identity ${identity}`);\n return this.profileStorageContract.methods.profile(identity).call({\n from: this.config.wallet_address,\n });\n }",
"showPoolStatus() {\n this.info(`Pool status: ${inspect(this.inspectPool())}`)\n }",
"get instanceProfileName() {\n return this.getStringAttribute('instance_profile_name');\n }",
"whichProfile() {\n\t\tthis.profile = 'particle';\n\t\tthis.readProfileData();\n\t}",
"function getCurrentProfile() {\r\n if (localStorage.profiles) {\r\n var profiles = $.parseJSON(localStorage.profiles);\r\n if (!localStorage.selectedProfile) {\r\n localStorage.selectedProfile = 0;\r\n }\r\n return profiles[localStorage.selectedProfile];\r\n }\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
register a default handler | default(handler) {
this._default = handler || this._notfound;
return this;
} | [
"static addHandler(handler) {\n assert(handler.call, 'Handler must be a function');\n assert(handler.length === 2 || handler.length === 3, 'Handler function takes 2 (request handler) or 3 (response handler) arguments');\n this._default.push(handler);\n }",
"addDefaultHandler(commandHandler) {\n this.defaultHandlers = this.defaultHandlers.concat(commandHandler);\n }",
"registerHandler(prefix, handler) {\n this.handlers_.push({ prefix: prefix, fn: handler });\n }",
"addHandler(handler) {\n this.handlers.push(handler);\n }",
"function setAllDefaultHandlers() {\n\t\tsetGo();\n\t\tsetInspect();\n\t\tsetInventory();\n\t\tsetUse();\n\t\tsetGive();\n\t\tsetLookAt();\n\t\tsetTalkTo();\n\t\tsetOpen();\n\t\tsetClose();\n\t\tsetPush();\n\t\tsetPull();\n\t\tsetPickUp();\n\t}",
"static handler0() {\n return\n }",
"static addHandler(handler) {\n let { type, url } = this.getTypeUrl(handler),\n key = this.getKey(type, url),\n wrapper = wrappers[key];\n\n if (!wrapper) {\n wrapper = new RequestWrapper();\n this.getPretender()[type.toLowerCase()].call(\n pretender,\n url,\n wrapper,\n delay\n );\n wrappers[key] = wrapper;\n }\n\n let index = wrapper.addHandler(handler);\n this.assignMockId(type, url, index, handler);\n }",
"function overrideHttpHandler(fn) {\n activeHandler = fn;\n }",
"function registerDefaultActions() {\n\t\n}",
"static replaceHandler(handler) {\n this.removeHandler(handler);\n this.addHandler(handler);\n }",
"static registerHandler(handler) {\n this.handlers.push(handler);\n return this;\n }",
"handler(name) {\n return externals[name].getSpecificHandler(self);\n }",
"on(type, handler) {\n let map = this._handlers || (this._handlers = Object.create(null))\n map[type] = (type in map) ? map[type].concat(handler) : [handler]\n }",
"registerAuthHandler(name, handler) {\n //if (this.authHandlers instanceof HashProxy) {\n this.authHandlers[name] = handler\n //}\n }",
"registerFormHandlers() {\n this.registerSearchHandler();\n this.registerInsertHandler();\n this.registerGetByIDHandler();\n this.registerUpdateHandler();\n this.registerDeleteHandler();\n }",
"addInvokeRequestHandler (path, commandName, handler) {\n\t\tconst cmdid = SystemInterface.getCommandId (commandName);\n\t\tif (cmdid < 0) {\n\t\t\tthrow Error (`Failed to add invoke request handler, unknown commandName ${commandName}`);\n\t\t}\n\t\tthis.invokeRequestHandlerMap[`${cmdid}:${path}`] = handler;\n\t}",
"function addHandler(field_name, handler) {\n tryInitField(field_name);\n fields[field_name].handlers.push(handler);\n}",
"bindRouteHandler() {\n this.app.singleton('router.handler', _Handler.default);\n }",
"_addSysHandler(handler, ns, name, type, id) {\n const hand = new Strophe.Handler(handler, ns, name, type, id);\n hand.user = false;\n this.addHandlers.push(hand);\n return hand;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
duplicate :: Extend w => w a > w (w a) . . Adds one level of nesting to a comonadic structure. . . This function is derived from [`extend`](extend). . . ```javascript . > duplicate (Identity (1)) . Identity (Identity (1)) . . > duplicate ([1]) . [[1]] . . > duplicate ([1, 2, 3]) . [[1, 2, 3], [2, 3], [3]] . . > duplicate (reverse) ([1, 2]) ([3, 4]) . [4, 3, 2, 1] . ``` | function duplicate(extend_) {
return extend (identity, extend_);
} | [
"function duplicate(extend_) {\n return extend(identity, extend_);\n }",
"function deepDup(arr) {\n\n}",
"function duplicate(arr) {\n return arr.concat(arr);\n}",
"function deepDup(arr) {\n\n for (let i = 0; i < arr.length; i++) {\n if (Array.isArray(arr[i])) dup[i] = deepDup(arr[i]);\n };\n\n return dup;\n}",
"function deep_clone(source) {\n return jQuery.extend(true, {}, source);\n}",
"function dup() {\r\n this.stack.push(this.stack[this.stack.length - 1]);\r\n}",
"function deepDup(arr) {\n if (arr.length === 0) {\n return [];\n }\n\n if (arr.length === 1) {\n return [arr[0]];\n }\n\n return [arr[0]].concat(deepDup(arr.slice(1)));\n}",
"function createDuplicateAcyclical () {\n const duplicate = {\n example: 'value'\n };\n return {\n a: duplicate,\n b: duplicate,\n c: 'unique'\n };\n}",
"function createDuplicateAcyclical () {\n const duplicate = {\n example: 'value'\n };\n return {\n a: duplicate,\n b: duplicate,\n c: 'unique'\n };\n }",
"@action(\"duplicate <List>\", { types: [ List ], returns: List })\n\tstatic duplicate(list) {\n\t\tif (!(list instanceof List)) return false\n\t\tduplicate = List.create_empty(list)\n\t\tObject.assign(duplicate, list)\n\t\tList.set_items(list, list)\n\t\treturn duplicate\n\t}",
"function superExtend(dest, source) {\n if (_.isArray(dest)) {\n if (!source) {\n return dest;\n }\n var newArray = dest.slice();\n for (var i = 0; i < source.length; i++) {\n var el = source[i];\n if (newArray.indexOf(el) === -1) {\n newArray.push(el);\n }\n }\n return newArray;\n } else if (_.isObject(dest)) {\n dest = _.extend({}, dest); // shallow clone\n if(source) {\n for (var p in source) {\n if (source.hasOwnProperty(p)) {\n if (dest[p] === undefined) {\n dest[p] = source[p];\n } else {\n dest[p] = superExtend(dest[p], source[p]);\n }\n }\n }\n }\n return dest;\n } else {\n return dest !== undefined ? dest : source;\n }\n }",
"function nonMutatingPush(original, newItem) {\n // Add your code below this line\n return original.concat(newItem);\n\n // Add your code above this line\n}",
"function nonMutatingPush(original, newItem) {\n return original.concat(newItem);\n}",
"function deepcopy(x) {\n let y, val, key\n if (typeof x !== \"object\" || x === null) return x // base case\n y = listy(x) ? [] : {} // initialize the copy\n for (key in x) {\n val = x[key]\n y[key] = deepcopy(val) // recur!\n }\n return y\n}",
"function bi_dup(x) {\n var buff = new Array(x.length);\n bi_copy_(buff, x);\n return buff;\n}",
"clone(noodle, obj, clone, flatList = [], flatClone = []) {\n cloneCounter++;\n //flatClone.push(clone);\n if (obj == undefined)\n return obj;\n\n if (typeof obj == 'object') {\n //If clone is undefined, make it an empty array or object\n if (clone == undefined) {\n if (obj.constructor == Array) {\n clone = new Array(obj.length);\n }\n else {\n clone = {};\n }\n }\n flatList.push(obj);\n flatClone.push(clone);\n //Go through obj to clone all its properties\n for (var i in obj) {\n var flatInd = flatList.indexOf(obj[i]);\n //If we've found a new object, add it to flatList and clone it to clone and flatClone\n if (flatInd == -1) {\n //clone[i] = clone[i] || {};\n clone[i] = noodle.object.clone(noodle, obj[i], clone[i], flatList, flatClone); //This works because flatList gets updated\n }\n //If we've seen obj[i] before, add the clone of it to clone\n else {\n clone[i] = flatClone[flatInd];\n }\n }\n return clone;\n }\n return obj;\n }",
"function deepDup(arr) {\n if(!(arr instanceof Array)) // arr is not Array (primitive num)\n return arr;\n return arr.map(el => deepDup(el));\n}",
"function deep_extend() {\n // The first argument is the object to extend.\n // It gets extended by the properties of all other arguments in turn.\n var obj = arguments[0];\n for (var i=1; i<arguments.length; i++) {\n var extra = arguments[i];\n for (var k in extra) {\n if (extra.hasOwnProperty(k)) {\n var vObj = obj[k];\n var vExtra = extra[k];\n // If it's a non-object, overwrite on obj.\n // If it's an object, maybe try a recursive clone.\n if (typeof vObj !== \"object\" || typeof vExtra !== \"object\") {\n obj[k] = vExtra;\n } else {\n deep_extend(vObj, vExtra);\n }\n }\n }\n }\n return obj;\n}",
"duplicate() {\n return this[Extend.extend](Function[Category.id]);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
type letter only function input text | function letterinputFunction(inputletter){
var ltrinput = /[^a-z ]/gi;
inputletter.value = inputletter.value.replace(ltrinput, '');
} | [
"function inputAlphabet(inputtext) {\n var alphaExp = /^[a-zA-Z\\s]+$/;\n if (inputtext.match(alphaExp)) {\n //document.getElementById('p1').innerText = '';\n return true;\n } else {\n //document.getElementById('p1').innerText = \"* For your name please use alphabets only *\"; // This segment displays the validation rule for name.\n //inputtext.focus();\n return false;\n }\n}",
"function lettersOnly() {\n var textInput = document.getElementById('letter').value;\n textInput = textInput.replace(/[^A-Za-z]/g, '');\n document.getElementById('letter').value = textInput;\n}",
"function alp1(ele){\r\n\tvar val = ele.value;\r\n\tvar len = val.length;\r\n\tif(val.search(/[^a-zA-Z\\s]/) != -1){\t\t\t// \\d is for digits i.e [0-9]\r\n\t\talert(\"Enter Only Alphabets\");\r\n\t\tele.value = ele.value.substring(0,len-1);\r\n\t\tele.focus();\r\n\t}\r\n}",
"function validateText (inputText) {\r\n let letters = /^[a-zA-Z+\\s]+$/;\r\n if (inputText.value.match(letters))\r\n {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }",
"function allowAlphabet()\n{\n\tif (!SignUp.name.value.match(/^[a-zA-Z]+$/) && SignUp.name.value !=\"\")\n\t{\n\t\tSignUp.name.value=\"\";\n\t\tSignUp.name.focus();\n\t\talert(\"Prosze uzywać tylko liter\");\n\t}\n}",
"specialCharacterCheck(txtInput, emptyMessage) {\n var regex = /^[a-zA-Z ]+$/;\n // console.log(\"TXTInput-->\" + txtInput);\n\n if ((regex.test(txtInput))) {\n return true\n } else {\n Alert.alert(globals.appName, emptyMessage)\n return false\n }\n }",
"function inputText(e) {\n //arrow keys\n if ([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {\n e.stopPropagation();\n //enter key\n } else if(e.keyCode === 13 && this.innerText.length <= CHAR_LIMIT) {\n this.blur();\n\n MAP_DIV.style.cursor = '';\n\n e.preventDefault();\n //limit\n } else if (this.innerText.length >= CHAR_LIMIT && e.keyCode !== 8) {\n e.preventDefault();\n }\n}",
"function isLetter(input){\n\tvar letters = /^[A-Za-z]+$/;\n\t\tif(input.match(letters)){\n\t\t\treturn true;\n\t\t}\n\telse{\n\t\talert(\"Please type a letter.\");\n\t\treturn false;\n\t}\n}",
"function typeCharacter() {\n $element.html($element.html() + word[charIndex]);\n\n if (charIndex >= wordLenght-1) {\n wordCounter++;\n animateCode();\n } else {\n charIndex++;\n setTimeout(typeCharacter, 50);\n }\n }",
"function input(word){\n // Call matchChar on each letter\n word.forEach(letter => matchChar(letter));\n}",
"function allLettersAndSpaces(inputtxt)\n {\n var letters = /^[A-Za-z\\s]+$/;\n if(inputtxt.match(letters))\n {\n return true;\n }\n else\n {\n return false;\n }\n }",
"function letterCaseToggle(){\r\n if(magicTxt.value != magicTxt.value.toUpperCase()){\r\n magicTxt.value = magicTxt.value.toUpperCase();\r\n magicTxt.focus();\r\n }else{\r\n magicTxt.value = magicTxt.value.toLowerCase();\r\n magicTxt.focus();\r\n }\r\n}",
"function validateLetterInput(input) {\n var finalChar\n if (input.length > 0) {\n var lastChar = input.charAt(input.length - 1)\n if (lastChar.toUpperCase() != lastChar.toLowerCase() ) {\n finalChar = lastChar.toUpperCase() \n }\n else {\n finalChar = input.substring(0, input.length - 1)\n }\n\n setLetter(finalChar)\n }\n updateIndex()\n updateBinary()\n updateHexadecimal()\n updateMorse()\n updateBraille()\n updateSemaphore()\n updatePigpen()\n updateMaritime() \n}",
"function onlyAlphabets(e, t) {\n try {\n if (window.event) {\n var charCode = window.event.keyCode;\n }\n else if (e) {\n var charCode = e.which;\n }\n else { return true; }\n if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))\n return true;\n else\n return false;\n }\n catch (err) {\n alert(err.Description);\n }\n }",
"function allowOnlyAlphabets(element){\r\n var content=element.value;\r\n var regex = /^[a-zA-Z]*$/;\r\n\r\n if (regex.test(content)){\r\n \r\n return true;\r\n } else {\r\n\r\n return false;\r\n }\r\n\r\n}",
"function lettersOnly(input) {\n //let regex = /[^a-z]/gi //\n let regex = /[^a-z\\s]/gi\n // let regex = /^[a-z ,.'-]+$/i //\n input.value = input.value.replace(regex, \"\");\n}",
"function lowercaseInput() {\n\t\t$('.letter').each(function() {\n\t\t\t$(this).html($(this).html().toLowerCase());\n\t\t});\n\t}",
"function ValidateCharInput(input)\n{\n let szTemp = input.trim();\n\n if (szTemp.length === 0)\n {\n return \"You must enter a value.\";\n }\n\n let regex = /^[a-zA-Z]+$/;\n if(szTemp.match(regex))\n {\n return true;\n }\n else\n {\n return \"Please enter letters only.\";\n }\n}",
"function sinMayusculasNiEspacios(event){\n var inputValue = event.which;\n // allow letters and whitespaces only.\n if( (inputValue >= 65 && inputValue <= 90) ||\n (inputValue == 209) || (inputValue == 32)\n ){\n event.preventDefault();\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the data attribute using a TrustedResourceUrl | function setData(obj, v) {
obj.data = (0, resource_url_impl_1.unwrapResourceUrl)(v);
} | [
"setURL(value)\n {\n\t\tthis.getData().url = value;\n\t}",
"replaceURL(url/*:string*/) {\n const { link, options: { keepOriginalAttributes } } = this;\n const { from } = link;\n if (keepOriginalAttributes && from && from.element && from.attribute) {\n const { element, attribute } = from;\n const noteAttribute = `data-original-${from.attribute}`;\n // Multiple links may be contained in one attribute (e.g. a srcset); we must act\n // only at the first one, therefore we check for existence of the noteAttribute.\n // XXX This also means that if the document already had 'data-original-...' attributes,\n // we leave them as is; this may or may not be desirable (e.g. it helps toward idempotency).\n if (!element.hasAttribute(noteAttribute)) {\n const originalValue = from.element.getAttribute(attribute) || \"\";\n element.setAttribute(noteAttribute, originalValue);\n }\n }\n\n // Replace the link target with the data URL. Note that link.target is a setter that will update\n // the resource itself.\n link.target = url;\n\n // Remove integrity attribute, if any. (should only be necessary if the content of the\n // subresource has been modified, but we keep things simple and blunt)\n // TODO should this be done elsewhere? Perhaps the link.target setter?\n if (from && from.element && from.element.hasAttribute('integrity')) {\n from.element.removeAttribute('integrity');\n // (we could also consider modifying or even adding integrity attributes..)\n }\n }",
"set(data) {\n this.dc.ww.just('dataset-op', {\n id: this.id,\n type: 'set',\n data: data\n })\n }",
"putURL(value)\n {\n\t\tthis.getData().url = value;\n\t}",
"function set_data_site(img_site){\r\n data_site = img_site;\r\n}",
"_dataUrlChanged() {\n if (!this.dataUrl)\n return;\n this.makeAjaxCall(this.dataUrl, 'get', null, null, null, null, function (err, resp) {\n if (resp) {\n this.set('data', resp);\n } else {\n var errMsg = this.resolveError(err);\n this.set('_errors', [errMsg]);\n }\n }.bind(this));\n }",
"function setDataset(el, key, value) {\r\n\t if (el.dataset) {\r\n\t el.dataset[key] = value;\r\n\t }\r\n\t else {\r\n\t el.setAttribute('data-' + key, value);\r\n\t }\r\n\t}",
"setData(e, attrName, attrVal = '') {\n e.setAttribute('data-' + attrName, attrVal);\n }",
"setData() {\n\t\tthis.data = this.getData()\n\t}",
"setCustomData(data) {\n this.data.customData = data;\n }",
"function setSrc(script, v) {\n script.src = (0, resource_url_impl_1.unwrapResourceUrl)(v);\n setNonceForScriptElement(script);\n}",
"function setImageURLDataprovider(datasource, imageurldataprovider) {\n}",
"function setSrc(element, attribute){\n element.setAttribute(attribute, element.getAttribute('data-' + attribute));\n element.removeAttribute('data-' + attribute);\n }",
"function setSrc(element, attribute) {\n element.setAttribute(attribute, element.getAttribute('data-' + attribute));\n element.removeAttribute('data-' + attribute);\n }",
"set(data, alias, uri = \"\") {\r\n this.uris.set(alias, uri);\r\n this.data.set(alias, data);\r\n }",
"function setSrc(element, attribute){\r\n element.setAttribute(attribute, element.getAttribute('data-' + attribute));\r\n element.removeAttribute('data-' + attribute);\r\n }",
"static setExternalData(ticket, provider, title, data) {\n let ticketId = null;\n // Get the ticket's ID\n if (ticket && typeof ticket === 'object' && (typeof ticket.id === 'string' || typeof ticket.id === 'number')) {\n ticketId = ticket.id;\n }\n else {\n ticketId = ticket;\n }\n if (!ticketId || (typeof ticketId !== 'number' && typeof ticketId !== 'string')) {\n throw new Error(exports.ERROR_NO_TICKET_ID);\n }\n if (!provider || typeof provider !== 'string') {\n throw new Error('No provider specified. The provider has to be a string.');\n }\n if (!title || typeof title !== 'string') {\n throw new Error('No title specified. The title has to be a string.');\n }\n if (!data) {\n throw new Error('No data provided.');\n }\n const payload = {\n provider,\n title,\n data: JSON.stringify(data),\n };\n return api_base_1.default.request(`tickets/${ticketId}/external`, payload, 'POST')\n .then((response) => response.result);\n }",
"setCacheData(url, data, lastUpdated) {\n this.cachedData[url] = {\n lastUpdated: lastUpdated || new Date(),\n data,\n };\n log.debug(`Cache set for key: \"${url}\"`);\n this.saveCacheData();\n }",
"function changeImage(){\r\n //step1 - select the arrays lit\r\n //step2 - choose a random one\r\n //step3 - get the data- atribute\r\n //step4 - change the content/value of data to new src\r\n \r\n var arr = getAllThumbs();\r\n var element = arr[Math.floor(Math.random() * arr.length)];\r\n \r\n var newURL = \"https://cdn.britannica.com/78/3278-004-90D1CE49/Sea-otter-crab.jpg\";\r\n \r\n// element.setAttribute('href', newURL);\r\n \r\n element.setAttribute('data-image-url', newURL);\r\n \r\n \r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Closes no schedule warning modal, which is created when an admin adds data to a week where a resource was not working | closeNoScheduleWarningModal() {
this.setState({ openNoScheduleWarning: false });
} | [
"function DTReInitWarning(){\n \t$('#DTReInitWarnModal .DTReInitMsg').empty();\n $('#DTReInitWarnModal .DTReInitMsg').append(\"<p>A completed chain of custody is already on file.</p><p>Are you sure you wish to submit a new order?</p>\");\n $('#DTReInitWarnModal').modal('show');\n CONSTANTS.interviewResultsObj.promptStaticDraggable('DTReInitWarnModal');\t\n }",
"function warn() {\n modal.style.display = 'block';\n}",
"warningSave(){\n this.showModalSave=true\n }",
"function okAction() {\n if (userRole === \"Admin\") {\n let newStart = new Date(datePicker.value + \"T\" + startTimePicker.value + \"Z\");\n let newEnd = new Date(datePicker.value + \"T\" + endTimePicker.value + \"Z\");\n let newEmployee = undefined;\n if (employeeSelectShift.value !== \"\") {\n newEmployee = employeeSelectShift[employeeSelectShift.selectedIndex].getAttribute('data-employee');\n }\n let isUpdate = true;\n if ((selectedShiftEmployee !== undefined && newEmployee === undefined) ||\n (selectedShiftEmployee === undefined && newEmployee !== undefined)){\n //DO NOTHING\n }\n else if (selectedShiftEmployee === undefined && newEmployee === undefined\n && selectedShift.start === newStart.toISOString()\n && selectedShift.end === newEnd.toISOString()) {\n isUpdate = false;\n }\n else if (selectedShiftEmployee && newEmployee) {\n if (selectedShiftEmployee.name === newEmployee.name\n && selectedShift.start === newStart.toISOString()\n && selectedShift.end === newEnd.toISOString()) {\n isUpdate = false;\n }\n }\n\n if (isUpdate) {\n updates.push(createUpdate(selectedShift, newStart, newEnd, newEmployee));\n selectedShiftDiv.style.backgroundColor = \"#91A41C\";\n selectedShiftDiv.setAttribute(\"hasupdate\", \"changed\");\n selectedShiftDiv.onclick = undefined;\n }\n\n dayShift.style.display = \"inline-block\";\n shiftUpdate.style.display = \"none\";\n\n\n let info = selectedShiftDiv.getElementsByTagName(\"li\");\n if (newEmployee === undefined) {\n info[0].innerText = \"Ingen ansat\";\n } else {\n info[0].innerText = \"Ansat: \" + employeeSelectShift.options[employeeSelectShift.selectedIndex].innerHTML\n }\n info[1].innerText = \"Dato: \" + /[0-9]{4}-[0-9]{2}-[0-9]{2}/g.exec(newStart.toISOString());\n info[2].innerText = \"Starttid: \" + /[0-9]{2}:[0-9]{2}/g.exec(newStart.toISOString());\n info[3].innerText = \"Sluttid: \" + /[0-9]{2}:[0-9]{2}/g.exec(newEnd.toISOString());\n }\n checkShiftsOnclick();\n saveButtonEnable();\n}",
"function onShowSchedule(){\n\tvar restriction = new Ab.view.Restriction();\n\trestriction.addClause(\"wr.wr_id\",$(\"wr.wr_id\").value,'=');\n\t\n\tView.openDialog(\"ab-helpdesk-workrequest-scheduling.axvw\",restriction);\n}",
"closeReasonModal() {\n this.askReason = false;\n }",
"function toggleAlert(invalid) {\n if (invalid) {\n jQuery('#dateAlert').css('display', 'block');\n jQuery('#dateAlert').addClass('in');\n jQuery('.schedule-button').prop('disabled', true);\n } else {\n jQuery('#dateAlert').css('display', 'none');\n jQuery('#dateAlert').removeClass('in');\n jQuery('.schedule-button').prop('disabled', false);\n }\n}",
"function show_waiting_bar_l3_update(){\n\tif ($(\"#l3_update_popup #add_edit_ecr_form\").valid() == true){\n\t\t$('#myPleaseWait').modal('show');\n\t}\n}",
"function BGCReInitWarning(){\n \t$('#BGCReInitWarnModal .BGCReInitMsg').empty();\n $('#BGCReInitWarnModal .BGCReInitMsg').append(\"<p>A background check consent has already been initiated. A new consent should only be created if the candidate's personal information has been updated.</p><p>Are you sure you wish to initiate a new consent?</p>\");\n $('#BGCReInitWarnModal').modal('show');\n CONSTANTS.interviewResultsObj.promptStaticDraggable('BGCReInitWarnModal');\t\n }",
"hide() {\n helper.confirm(\"warning\", \"Cảnh báo\",\n \"Bạn có chắc muốn đóng modal? <br/>Những dữ liệu chưa lưu sẽ bị mất!\",\n () => {\n this.props.createRegisterActions.showCreateRegisterModal(false);\n this.props.createRegisterActions.updateFormData({});\n },\n );\n }",
"function cancelAddAppointment() {\n $('#appointment-add-row').hide();\n}",
"function cancelEditSchulde(e) {\n\n\topenView('schedule');\n}",
"function ShowFirtWarningWhenCourseLaunch() {\n if (trackObjects[SeqID].firstwarninghrs != null || trackObjects[SeqID].firstwarningmins != null || trackObjects[SeqID].firstwarningsecs != null) {\n var firstwarnHoursInSeconds = parseInt(trackObjects[SeqID].firstwarninghrs * 3600);\n var firstwarnMinutesInSeconds = parseInt(trackObjects[SeqID].firstwarningmins * 60);\n var firstwarnSeconds = parseInt(trackObjects[SeqID].firstwarningsecs);\n var FirstwarningTime = (firstwarnHoursInSeconds + firstwarnMinutesInSeconds + firstwarnSeconds) * 1000;\n if (FirstwarningTime != undefined && FirstwarningTime != 0) {\n setTimeout(function () {\n if (currPageObject.type != undefined && currPageObject.type != \"summary\") {\n WarningAlert(trackObjects[SeqID].warningmessage, 5000);\n }\n }, FirstwarningTime);\n }\n }\n}",
"static closeSaveNotification() {\n let e = document.getElementById(\"novel-save-notification\");\n e.style.display = 'none';\n }",
"function cancelUpdateTimingModal(){\n modalInstanceUpateTiming.dismiss('cancel');\n }",
"function _warningRemoveDashboard() {\n //hide top app bar\n topAppBar.winControl.hide();\n //preserve bottom app bar shown\n div_dashboards_bottomAppBar.winControl.sticky = true;\n //show popup\n Popup.showYesNoPopup(cmdDelete, MessagesHelper.MSG_REMOVE_DASHBOARD_TITLE, MessagesHelper.MSG_REMOVE_DASHBOARD_TEXT,\n MessagesHelper.buttonsLabel.delete,\n function () {\n _removeDashboard();\n div_dashboards_bottomAppBar.winControl.sticky = false;\n div_dashboards_bottomAppBar.winControl.hide();\n },\n MessagesHelper.buttonsLabel.cancel,\n function () {\n div_dashboards_bottomAppBar.winControl.sticky = false;\n },\n CDHelper.position.right);\n }",
"function openWarningModal() {\n // The instance of the app blocking modal used to let the user know\n // they've lost connectivity. It can only be dismissed by receiving a\n // successful pingback from the server\n $modal.open({\n templateUrl: 'modal/templates/modalcontainer.html',\n controller: 'ModalController',\n backdrop: 'static',\n resolve: {\n locals: function () {\n return {\n type: BG_DEV.MODAL_TYPES.offlineWarning,\n userAction: BG_DEV.MODAL_USER_ACTIONS.offlineWarning\n };\n }\n }\n }).result.then(function (data) {\n OFFLINE_WARNING_SHOWING = false;\n }, function (error) {\n // kill the modal on error - this should never happen though\n OFFLINE_WARNING_SHOWING = false;\n });\n }",
"function remove_l2_status(){\n\t$('#l2_status').remove();\n\tif ($('#l2_update_popup #ia_modal_form').valid() == true){\n\t\t$('#myPleaseWait').modal('show');\n\t}\n}",
"addCloseSchedule() {\n const self = this;\n let schedule = this.get('newSchedule');\n\n // if there is no schedule, this will do nothing\n if (!schedule)\n return;\n\n this.get('selectedSchedules').addObject(schedule);\n this.get('store').find('schedule', schedule.id).then((newSchedule) => {\n self.get('ap').get('alwaysCloseSchedules').addObject(newSchedule);\n self.set('newSchedule', null);\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
================== Search By Id ================== Searches through the catalog array and return a Promise containing the product that matches the id argument. The Promise will resolve in 1000 millisecond after the function has executed. The Promise will reject if an invalid id is searched. | function searchProductById(id){
var promise = new Promise(function(resolve,reject){
var i = 0;
setTimeout(function(){
while (i < catalog.length){
if (catalog[i].id == id){
resolve({id:id,price:catalog[i].price,type:catalog[i].type});
}
i++;
}
reject("Invalid ID: " + id);
},1000);
});
return promise;
} | [
"function searchProductById(id){\n var promise = new Promise(function(resolve, reject){\n var i = 0;\n setTimeout(function(){\n while(i < catalog.length){\n if(id == catalog[i].id){\n resolve(catalog[i]);\n }\n i++;\n }\n reject(\"Invalid ID: \"+id);\n }, 1000);\n });\n return promise;\n }",
"function searchProductById(id) {\n var promise = new Promise(function (resolve, reject) {\n var i = 0;\n setTimeout(function () {\n while (i < catalog.length) {\n if (catalog[id] === id) {\n resolve({ id: id, price: catalog[i].price, type: catalog[i].type });\n }\n i++;\n }\n reject(\"Invalid Id:\" + id);\n }, 1000);\n });\n return promise;\n }",
"function searchProductById(id) {\n\n var promise = new Promise(function (resolve, reject) {\n var i = 0;\n setTimeout(function () {\n while (i < catalog.length) {\n if (catalog[i].id == id) {\n resolve({\n id: id,\n price: catalog[i].price,\n type: catalog[i].type\n });\n }\n i++;\n }\n reject(\"Invalid ID: \" + id);\n }, 1000);\n });\n return promise;\n }",
"function findById(id) {\n let currentProduct = products.find((product) => {\n return product.id === id\n })\n return currentProduct\n}",
"searchProduct(id){\n\t\tfor (var i = this.state.cartProducts.length - 1; i >= 0; i--) {\n\t\t\tif(id === this.state.cartProducts[i].id)\n\t\t\t\treturn this.state.cartProducts[i];\n\t\t}\n\n\t\treturn false;\n\t}",
"function searchAllProducts() {\n var promise = new Promise(function (resolve, reject) {\n\n setTimeout(function () {\n resolve(catalog);\n }, 1000);\n\n });\n return promise;\n }",
"function searchAllProducts(){\n var promise = new Promise(function(resolve, reject) {\n setTimeout(function(){\n resolve(catalog);\n },1000);\n\n });\n return promise;\n }",
"function getProduct(id) {\n for (var i = 0; i < products.length; i++) {\n var product = products[i];\n if (product.id === id) {\n return product;\n }\n }\n}",
"function processSearchById(id) {\n api.searchProductById(id)\n .then(function(product) {\n return Promise.all([\n api.searchProductsByPrice(product.price, 50),\n api.searchProductsByType(product.type),\n product\n ]);\n })\n .then(function(data) {\n let similar = getSimilar(data[0], data[1], data[2].id);\n updateProductInfo(data[2]);\n updateTable('similarProducts', similar);\n })\n .catch(function(value) {\n console.error(value);\n })\n}",
"function findProduct(arr, id) {\n return arr.find(pro => pro.id==id);\n}",
"getProduct(products,id) {\n return products.find(prod=>prod.id===id)\n }",
"function getProductById (id) {\n\n}",
"function productQuery(prodId){\n for (var i = 1; i < data.length; i++){\n if (prodId === data[i][0]){\n return data[i]\n }\n }\n}",
"function findById(id) {\n return new Promise((resolve, reject) => {\n const sql = `SELECT * FROM shopping_list WHERE id = ?`;\n db.get(sql, id, (err, row) => {\n if (err) {\n let message = `Error reading from the database: ${err.message}`;\n logger.error(message, 'findById()');\n reject(message);\n } else if (row) {\n resolve({ data : JSON.stringify(row), statusCode: 200 });\n } else {\n resolve({ data : '{}', statusCode: 404 });\n }\n });\n });\n}",
"static async fetchProductById(productId) {\n\t\tconst product = storage\n\t\t\t.get(\"products\")\n\t\t\t.find({ id: Number(productId) })\n\t\t\t.value();\n\t\treturn product;\n\t}",
"function getByProductId(id) {\n return db('specs').where({ product_id: id });\n}",
"static async fetchProductById(productId) {\n\n // fetch a single product\n const product = storage\n .get(\"products\")\n .find({ id: Number(productId) })\n .value();\n return product;\n }",
"function getProductByID(productArray, id) {\r\n return productArray.find(function (product) {\r\n return product.id == id;\r\n });\r\n }",
"function findProductForUpdate(id) {\n return productData.find(product => product.id === id);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Elimina del archivo el objeto con el id buscado. | async deleteById(id){
let objetos = await this.getAll();
objetos = objetos.filter(producto => producto.id !== id)
await fs.promises.writeFile(this.nombreArchivo, JSON.stringify(objetos));
} | [
"async deleteById(id) {\n await this.readFile();\n const index = this.fileContent.findIndex((e) => {\n return e.id === id;\n });\n if (index > -1) {\n this.fileContent.splice(index, 1);\n this.writeFile();\n return true;\n } else {\n console.log(\"No se encontró el elemento en la base de datos\");\n return false;\n }\n }",
"function deleteFile(id, cb) {\n\t\tmodelFile.findById(id).exec(function (err, item) {\n\t\t\tif (err){\n\t\t\t\tcb(err, null);\n\t\t\t}\n else {\n\t\t\t\t\tmodelFile.remove(item, function (err, result) {\n\t\t\t\t\t\tcb(err, result);\n\t\t\t\t\t});\n }\n });\n\t}",
"function EliminarFila(campo_id){\n console.log('Eliminando fila...');\n $('#'+campo_id).remove();\n}",
"function eliminaRegistro(id) {\n borraArticulo(id);\n}",
"eliminartodo(id) {\n \n this.todos = this.todos.filter(todo => todo.id != id);\n this.saveLocalStorage();\n\n }",
"function excluir(id){\n //limpa os registros do controle de acesso\n limpaControleAcesso(id);\n //deleta o registro\n deletar(id);\n //captura a linha informada\n var linha = document.getElementById(\"linha\"+id);\n //remove a linha da tabela\n linha.remove();\n}",
"function excluirAditivo(id){\n var xhr = new XMLHttpRequest();\n xhr.open(\"DELETE\", BASE_URL_SERVICO + \"/processoAditivo/\"+id);//realiza uma chamada sincrona para receber o id gerado\n xhr.setRequestHeader('Content-Type', 'application/json');\n xhr.send();\n}",
"function remove(_id){\n fhir.delete({type: \"Patient\",id: _id})\n .then((res) => {\n //Implemente su función aqui\n console.log(res)\n // INICIO Código de ejemplo\n loadData()\n // FIN Código de ejemplo\n\n })\n .catch(function(res){\n //Error responses\n if (res.status){\n console.log('Error', res.status);\n }\n\n //Errors\n if (res.message){\n console.log('Error', res.message);\n }\n });\n}",
"eliminarTodo( id ) {\n this.todos = this.todos.filter( todo => todo.id != id );\n this.cantidadPendientes();\n this.guardarLocalStorage();\n }",
"function deleteFromStock(id){\n for( var i = 0; i < file_obj[\"stock\"].length; i++){\n if ( file_obj[\"stock\"][i] == String(id)) {\n file_obj[\"stock\"].splice(i, 1);\n i--;\n }\n }\n delete file_obj[\"obs\"][id]\n $('#tr'+id).remove()\n updateDOM()\n updateBanner();\n console.log(file_obj)\n}",
"function eliminarUser(id){\n for(i=0;i<arreglo.length;i++){\n if(arreglo[i].id==id)\n indice=i;\n }\n // console.log(indice);\n arreglo.splice(indice, 1);\n cargarUsuarios();\n}",
"delete(id) {\n let index = this.getIndexOf(id);\n if (index > -1) {\n this.data.splice(index, 1);\n return;\n }\n }",
"function remove_file(id)\n{\n // remove from arr\n FILES.splice(id, 1);\n // clear display but not all files\n clear(false, true);\n FILES.length > 0 ? refresh_display() : reset();\n}",
"function del(fileObj) {\n fileObj.remove(function() {\n console.log(\"File removed\");\n },\n function(error) {\n console.log(\"Couldn't remove file\", error);\n });\n }",
"function eliminar(id) {\n // llamamos a la funcion encargada de eliminar un registro\n eliminarGasto(id);\n\n ///Llamamos a nuestra funcion encargada de obtener de nuevo el listado\n obtenerGastos();\n}",
"detruire () {\n if (this.nom) { fs.unlinkSync(this.path) }\n }",
"function eliminarUploadImg(id) {\n $('#blq' + id).remove();\n eliminarElmentoArray(idsUploadImg, id);\n }",
"async function borrarFoto(req, res) {\n const { id } = req.params;\n const foto = await photo_1.default.findByIdAndRemove(id);\n //se elimina la información pero no el archivo por lo que tenemos que eliminarlo\n if (foto) {\n await fs_extra_1.default.unlink(path_1.default.resolve(foto.imagePath));\n }\n return res.json({\n message: 'Foto borrada',\n foto\n });\n}",
"onDeleteObject(id) {\n // delete an object by number (row)\n this.dataObjects.splice(id, 1);\n refreshObjectTable();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
if two consecutive clicks occur in less than CLICK_TIMEOUT miliseconds they will be classified as "double click". | static get CLICK_TIMEOUT() {
return 250; // miliseconds
} | [
"function checkclick(d){\n if (clickedOnce) {\n // If already clicked once then this is a double\n run_on_double_click(d);\n } else {\n // Save the first click and start a timer to \n // clear that state and perform a single click\n timerClickedOnce = setTimeout(run_on_simple_click, 300, d);\n clickedOnce = true;\n }\n }",
"function run_on_double_click(d) {\n clickedOnce = false;\n clearTimeout(timerClickedOnce);\n ConsoleLog(\"doubleclick\");\n dblclick(d);\n }",
"static get DOUBLE_CLICK_MILLIS() {\n return 250;\n }",
"function checkDoubleClick() {\r\n \r\n var d2 = new Date().getTime();\r\n var delta = d2 - clickTime; // Difference in time between two clicks\r\n console.log(delta);\r\n if (delta < 300) { // If the delta < 300 milliseconds, consider it a double click\r\n loadNodeDetails($(this).attr(\"id\")); // Display edit window for selected node\r\n }\r\n clickTime = d2; // Reset initial click time to the time of the second click\r\n}",
"function detectDoubleTouch() {\r\n // If a single click was detected, starts the timer.\r\n if (clickTimer == null) {\r\n clickTimer = setTimeout(function () {\r\n clickTimer = null;\r\n }, 3.00);\r\n } else {\r\n // A double tap was detected!\r\n clearTimeout(clickTimer);\r\n clickTimer = null;\r\n return true;\r\n }\r\n\r\n // No double tap.\r\n return false;\r\n}",
"function onDblClick(e) {\n if( e.target.parentElement.className === 'move' || e.target.querySelectorAll('.move').length > 0 || !rotatePieces ) {\n return;\n }\n\n if ( lastTarget === undefined || lastTarget !== e.target) {\n lastTarget = e.target;\n clickCount = 1;\n }else {\n clickCount++;\n }\n\n if (clickCount === 1) {\n singleClickTimer = setTimeout(function() {\n clickCount = 0;\n }, 300);\n } else if (clickCount === 2) {\n clearTimeout(singleClickTimer);\n clickCount = 0;\n turn.call(this);\n }\n}",
"muteDoubleTap(e) {\n let timeBetweenTaps = e.timeStamp - this.state.lastTap\n\n if (timeBetweenTaps < 500 && timeBetweenTaps > 0) {\n e.preventDefault()\n }\n this.setState({\n lastTap: e.timeStamp\n })\n }",
"function makeclick() {\n\tvar clicks = 1;\n\tconsole.log('sfe')\n\tfunction timesout(n) {\n\t\ti = n;\n\t\tconsole.log('wfwefw')\n\t\tvar val = setTimeout( \"call();\", 250 );\n\t\tif ( i == 2 ) {\n\t\t\tclearTimeout( val );\n\t\t\tconsole.log('intersects');\n\t\t};\n\t};\n\tfunction call() {\n\t\tif ( i == 1 ) {\n\t\t\tonsinclick;\n\t\t\tconsole.log('intersects');\n\t\t} else {\n\t\t\tif ( i == 2 ) {\n\t\t\t\tondblclicks;\n\t\t\t};\n\t\t};\n\t};\n}",
"function clickCounter() {\n if (startTimer) {\n if (timeDifference() > 3) {\n resetTimer();\n }\n }\n clickCount += 1;\n if (clickCount == 1) {\n startTimer = Date.now();\n }\n }",
"function click_dispatcher(d) {\n if (d3.event.defaultPrevented) return; // prevent drag from sending click event\n if (clickedOnce) {\n dblclick(d);\n }else {\n timer = setTimeout(function() {\n click(d);\n }, 300);\n clickedOnce = true; \n }\n}",
"function doubleTap(elem, speed, distance) {\n if (!('ontouchstart' in elem)) {\n // non-touch has native dblclick and no need for polyfill\n return;\n }\n // default dblclick speed to half sec\n speed = Math.abs(+speed) || 500;//ms\n // default dblclick distance to within 40x40 area\n distance = Math.abs(+distance) || 40;//px\n\n var taps, x, y;\n var reset = function() {\n // reset state\n taps = 0;\n x = NaN;\n y = NaN;\n };\n reset();\n\n elem.addEventListener('touchstart', function(e) {\n var touch = e.changedTouches[0] || {}, oldX = x, oldY = y;\n\n taps++;\n x = +touch.pageX || +touch.clientX || +touch.screenX;\n y = +touch.pageY || +touch.clientY || +touch.screenY;\n\n // NaN will always be false\n if (Math.abs(oldX-x) < distance && Math.abs(oldY-y) < distance) {\n // fire dblclick event\n var e2 = document.createEvent('MouseEvents');\n if (e2.initMouseEvent) {\n e2.initMouseEvent(\n 'dblclick',\n true, // dblclick bubbles\n true, // dblclick cancelable\n e.view, // copy view\n taps, // click count\n touch.screenX, // copy coordinates\n touch.screenY,\n touch.clientX,\n touch.clientY,\n e.ctrlKey, // copy key modifiers\n e.altKey,\n e.shiftKey,\n e.metaKey,\n e.button, // copy button 0: left, 1: middle, 2: right\n touch.target); // copy target\n }\n elem.dispatchEvent(e2);\n }\n setTimeout(reset, speed);\n }, false);\n\n elem.addEventListener('touchmove', function(e) {\n reset();\n }, false);\n}",
"function doubleTap(elem, speed, distance) {\n if (!('ontouchstart' in elem)) {\n // non-touch has native dblclick and no need for polyfill\n return;\n }\n \n // default dblclick speed to half sec\n speed = Math.abs(+speed) || 500;//ms\n // default dblclick distance to within 40x40 area\n distance = Math.abs(+distance) || 40;//px\n \n var taps, x, y,\n reset = function() {\n // reset state\n taps = 0;\n x = NaN;\n y = NaN;\n };\n \n reset();\n \n elem.addEventListener('touchstart', function(e) {\n var touch = e.changedTouches[0] || {},\n oldX = x,\n oldY = y;\n \n taps++;\n x = +touch.pageX || +touch.clientX || +touch.screenX;\n y = +touch.pageY || +touch.clientY || +touch.screenY;\n \n // NaN will always be false\n if (Math.abs(oldX-x) < distance &&\n Math.abs(oldY-y) < distance) {\n \n // fire dblclick event\n var e2 = document.createEvent('MouseEvents');\n if (e2.initMouseEvent) {\n e2.initMouseEvent(\n 'dblclick',\n true, // dblclick bubbles\n true, // dblclick cancelable\n e.view, // copy view\n taps, // click count\n touch.screenX, // copy coordinates\n touch.screenY,\n touch.clientX,\n touch.clientY,\n e.ctrlKey, // copy key modifiers\n e.altKey,\n e.shiftKey,\n e.metaKey,\n e.button, // copy button 0: left, 1: middle, 2: right\n touch.target); // copy target\n }\n elem.dispatchEvent(e2);\n }\n \n setTimeout(reset, speed);\n \n }, false);\n \n elem.addEventListener('touchmove', function(e) {\n reset();\n }, false);\n}",
"function preventDoubleClick() {\r\n if (_clickHold != undefined) return true;\r\n else {\r\n _clickHold = {};\r\n setTimeout(function () { _clickHold = undefined; }, 700);\r\n }\r\n return false;\r\n }",
"function __DOUBLE_CLICK__(obj, delegate, selector)\n{\n __REF__(obj, selector).dblclick(__CALLBACK__(obj, delegate));\n}",
"function jsDblClick() {\n if (!clicked) {\n clicked = true;\n return true;\n }\n else {\n return false;\n }\n }",
"function scheduleMousedown2(e) {\n pending_e = e;\n\n clickTimer = setTimeout(function () {\n triggerPendingMousedown2();\n }, dblclickDelay);\n }",
"function addDblClickListener(el, f) {\n var cnt = 0, pre = 0;\n el.addEventListener('mousedown', function(e) {\n e.preventDefault();\n var now = new Date().getTime();\n if (now - pre < 200) { cnt++ } // adjust me.\n else { cnt=1 }\n if (cnt == 2) {\n f(e);\n el.removeEventListener(e.type, arguments.callee, e.eventPhase == Event.CAPTURING_PHASE);\n }\n pre = now;\n }, false);\n }",
"doubleClick(element) {\n element.waitForDisplayed(constants.WAIT_FOR_DISPLAYED_5000);\n element.doubleClick();\n }",
"function validateDoubleTap() {\n if (doubleTapStartTime == null) {\n return false;\n }\n \n var now = getTimeStamp();\n return hasDoubleTap() && now - doubleTapStartTime <= options.doubleTapThreshold;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Folder Check (To check if the folder exists) | function folderCheck() {
if (!fs.existsSync(`${process.env.LOCALAPPDATA}/gamiTask`))
fs.mkdir(`${process.env.LOCALAPPDATA}/gamiTask`, err => {
if (err) console.log(err.message);
else console.log("Folder Successfully Created!");
});
} | [
"function CheckFolderExists (path)\r\n{\r\n\treturn FSO.FolderExists(path);\r\n}",
"function checkExists(folderName) {\r\n var folderExists = false;\r\n for (var i = 1; i <= app.project.numItems; i += 1) {\r\n var cItem = app.project.item(i);\r\n if (cItem instanceof FolderItem && cItem.name == folderName) {\r\n cItem.parentFolder = app.project.rootFolder;\r\n folderExists = true;\r\n return true;\r\n }\r\n }\r\n app.project.items.addFolder(folderName);\r\n }// End checkExists",
"function DataFolderExists(folder) {\n try {\n // Query the entry\n var DataFolder = fs.lstatSync(folder);\n\n // Is it a directory?\n if (DataFolder.isDirectory()) {\n return true;\n } else {\n return false;\n }\n} //end try\ncatch (error) {\n console.error(error.message);\n console.error('There was an error checking if the folder exists.');\n}\n\n} //end DataFolderExists",
"function dzn_checkFolderExists() {\n\tvar output = true;\n\tif (!(DriveApp.getFoldersByName(\"ARMA FSD Tools\").hasNext())) {\n\t\tSpreadsheetApp.getUi().alert('⊗ WARNING!\\n\\nThere is no \"ARMA FSD Tools\" folder on your Drive.\\n\\nPlease, create it via \"FSD Tools\" menu'); \n\t\toutput = false;\n\t}\n\treturn output\n}",
"checkFolder(folder) {\n if(fs.existsSync(folder)) {\n console.log(\"--> Folder Exists : \" + folder);\n } else {\n fs.mkdirSync(folder, (err) => {\n console.log(\"--> Create folder: \" + folder);\n if (err) {\n throw err;\n }\n });\n }\n }",
"checkBasicFolders() {\n const folders = [];\n try {\n for (let i = 0; i < folders.length; i++) {\n if (!fs.existsSync(\"./\" + folders[i])) {\n _self.debugging(\"Creating folder: \" + folders[i]);\n fs.mkdirSync(\"./\" + folders[i]);\n }\n }\n } catch (error) {\n app.logger.log(\n \"error\",\n \"config - utils - checkFolderExists - \" + error\n );\n console.error(error);\n }\n }",
"function _checkFolder() {\n if (!useFiles) return true;\n \n let folderPath = path.join(__dirname, \"..\", \"..\", \"logs\");\n if (!fs.existsSync(folderPath)) {\n try {\n fs.mkdirSync(folderPath);\n return true;\n } catch (e) {\n _logMessage(e, Level.ERROR, Colour.RED);\n return e;\n }\n } else return true;\n }",
"function DirExists() {\r\n}",
"function checkForFolder(folder) {\n if (!fs.existsSync(folder)) {\n fs.mkdirSync(folder)\n }\n}",
"function checkFolder(){\n if (!fs.existsSync(OUTPUT_DIR)) {\n fs.mkdirSync(OUTPUT_DIR, { recursive: true });\n console.log(`${OUTPUT_DIR.split(/[\\\\]+/).pop()} directory created!`)\n }\n}",
"function checkFolders() {\n const courseDataPath = './courseData';\n const htmlFilesPath = './htmlFiles';\n\n if (!fs.existsSync(courseDataPath))\n fs.mkdirSync(courseDataPath);\n\n if (!fs.existsSync(htmlFilesPath))\n fs.mkdirSync(htmlFilesPath);\n}",
"async function folderUsable(folder) {\n\n try {\n\n // fetch folder information\n let fInfo = await info(folder);\n\n // create folder if required\n if (!fInfo.isDir) {\n await fsPromise.mkdir(folder);\n fInfo = await info(folder);\n }\n\n // folder accessible?\n return (fInfo.isDir && fInfo.read && fInfo.write ? fInfo : false);\n\n }\n catch (err) {\n console.log('folderUsable error:', err);\n return false;\n }\n\n}",
"function folderExists( folderAsString ) {\r\n\tvar f = Folder(folderAsString);\r\n\tif (f.exists) return true;\r\n\tif (DialogModes.NO == app.playbackDisplayDialogs) return false;\r\n\tif (confirm(strCreateFolder + folderAsString)) {\r\n\t\tif (f.create()) {\r\n\t\t\treturn true;\r\n\t\t} else {\r\n\t\t\talert(strCouldNotCreate);\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}",
"function isFolderEmpty(root, name) {\n const validFiles = [\n '.DS_Store',\n '.git',\n '.gitattributes',\n '.gitignore',\n '.gitlab-ci.yml',\n '.hg',\n '.hgcheck',\n '.hgignore',\n '.idea',\n '.npmignore',\n '.travis.yml',\n 'LICENSE',\n 'Thumbs.db',\n 'docs',\n 'mkdocs.yml',\n 'npm-debug.log',\n 'yarn-debug.log',\n 'yarn-error.log',\n ];\n const conflicts = external_fs_default().readdirSync(root)\n .filter((file) => !validFiles.includes(file))\n // Support IntelliJ IDEA-based editors\n .filter((file) => !/\\.iml$/.test(file));\n if (conflicts.length > 0) {\n console.log(`The directory ${chalk_default().green(name)} contains files that could conflict:`);\n console.log();\n for (const file of conflicts) {\n try {\n const stats = external_fs_default().lstatSync(external_path_default().join(root, file));\n if (stats.isDirectory()) {\n console.log(` ${chalk_default().blue(file)}/`);\n }\n else {\n console.log(` ${file}`);\n }\n }\n catch (_a) {\n console.log(` ${file}`);\n }\n }\n console.log();\n console.log('Either try using a new directory name, or remove the files listed above.');\n console.log();\n return false;\n }\n return true;\n}",
"async _checkCacheDirExists () {\n const { exists, isDirectory } = await FileSystem.getInfoAsync(this._path)\n return exists && isDirectory\n }",
"function checkExists(dir) {\n fs.exists(dir, function(exists) {\n if (!exists) {\n mkdirp(dir, function(err) {\n if (err) console.error(err)\n else console.log('The uploads folder was not present, we have created it for you [' + dir + ']');\n });\n //throw new Error(dir + ' does not exists. Please create the folder');\n }\n });\n }",
"function searchTestFolder() {\n if (!fs.existsSync('test/')) {\n return false\n }\n return true\n}",
"checkBuildFolder() {\n\t\tthis.fs.mkdirSync(this.buildPath([BUILD_FOLDER]), {recursive: true});\n\t}",
"static isFolderDoesNotExistError(error) {\n return FileSystem.isErrnoException(error) && error.code === 'ENOTDIR';\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
SETS ARM AND BALL TO BE DRAGGABLE | function dragBall() {
_ballDrag = Draggable.create("#leverRedBall", {
type: "y",
edgeResistance: 0.4,
bounds: "#holderLever",
throwProps: true,
dragResistance: 0.002,
cursor: "pointer",
onDrag: checkDrag,
force3D: true,
onDragEnd: dragComplete
});
} | [
"setBreed (breed) { breed.setBreed(this) }",
"set armStretch(value) {}",
"function reset_brcalls() {\n // reset br calls for both teams\n settings.set('lastbrcall', 0);\n settings.set('lastbrcall_team', 0);\n settings.set('brcall_team1', false);\n settings.set('brcall_team2', false);\n settings.set('game_caps', []);\n settings.set('capDiff', 0);\n}",
"function UpdateRubberbandOnMove(loc) {\r\n // Stores changing height, width, x & y position of most \r\n // top left point being either the click or mouse location\r\n UpdateRubberbandSizeData(loc)\r\n\r\n // Redraw the shape\r\n drawRubberbandShape(loc)\r\n}",
"setBreed (a) { // change agent a to be in this breed\n // Return if `a` is already of my breed\n if (a.agentSet === this) return\n // Remove/insert breeds (not baseSets) from their agentsets\n if (a.agentSet.isBreedSet()) util.removeItem(a.agentSet, a, 'id')\n if (this.isBreedSet()) util.insertItem(this, a, 'id')\n\n // Make list of `a`'s vars and my ownvars.\n const avars = a.agentSet.ownVariables\n // First remove `a`'s vars not in my ownVariables\n for (const avar of avars)\n if (!this.ownVariables.includes(avar))\n delete a[avar]\n // Now add ownVariables to `a`'s vars, default to 0.\n // If ownvar already in avars, it is not modified.\n for (const ownvar of this.ownVariables)\n if (!avars.includes(ownvar))\n a[ownvar] = 0 // NOTE: NL uses 0, maybe we should use null?\n\n // Give `a` my defaults/statics\n return Object.setPrototypeOf(a, this.agentProto)\n }",
"function cvjs_drawRedline_Freehand_setValues(){\n\n\tcvjs_redline++;\n\tcvjs_setCurrentRedlineValues(\"RED_\"+cvjs_redline, \"redline\"+cvjs_redline, cvjs_redline, \"RedLineLayer\", \"unassigned\", \"#AA0055\", 3, cvjs_currentRotationAngle[cvjs_active_floorplan_div_nr]);\n\tcvjs_drawRedline_Freehand();\n}",
"function setupArms() {\n\n // start from the torso\n var last = torso;\n var p, anchor, db;\n\n // setup right arm\n for ( var i = 0; i < ARM_JOINT_COUNT; i++ ) {\n p = last.getPosition();\n db = world.createDynamicBody(Vec2(bodyXOffset + i, p.y));\n db.createFixture(arm, armFixtureDef);\n \n anchor = Vec2(bodyXOffset + i, p.y);\n world.createJoint(pl.RevoluteJoint(armJoint, last, db, anchor));\n \n last = db;\n rightArmPoints.push(db);\n }\n\n // setup left arm\n last = torso;\n for ( var i = 0; i < ARM_JOINT_COUNT; i++ ) {\n p = last.getPosition();\n db = world.createDynamicBody(Vec2(bodyXOffset - i, p.y));\n db.createFixture(arm, armFixtureDef);\n\n anchor = Vec2(bodyXOffset -i, p.y);\n world.createJoint(pl.RevoluteJoint(armJoint, last, db, anchor));\n \n last = db;\n leftArmPoints.push(db);\n }\n}",
"function drawBalancersAndAdaptiviters(x,y,width,height,shapeColor){\r\n //add code to create sprite\r\n this.Balancers=createSprite(x,y,width,height);\r\n\r\n //add code to add shape color to sprite\r\n this.Balancers.shapeColor=shapeColor;\r\n }",
"function setBoundaryConditions(b, x){\n\t\tfor(i=0;i<height;i++){\n\t\t\tu[i*width+width-1] = -speed;\n\t\t\t//u[i*width + width -1] = -speed;\n\t\t\tu[i*width] = speed;\n\t\t}\t\n\t\t\n\t\tfor(i=0;i<width;i++){\n\t\t\tu[i] = -u[i+width];//u[width+i];\n\t\t\tv[i] = -v[i+width];\n\t\t\t\n\t\t\tu[(size-width) + i] = -u[(size-width) + i - width]\n\t\t\tv[(size-width) + i] = -v[(size-width) + i - width]\n\t\t}\n\t\t\n\t\tfor (i =0 ; i < size; i++){\n\t\t\tif (walls[i] == 1){\n\t\t\t\trho[i] = 0;\n\t\t\t\tu[i] = 0; // -u[i+1];\n\t\t\t\tv[i] = 0;// -v[i+1];\n\t\t\t}else{\n\t\t\t\t//u[i] = 0.5;\n\t\t\t}\n\t\t}\n\t}",
"function magicShootBL(){\n magicArrowBL.alpha = 1;\n magicArrowBLActive = true;\n}",
"function PBRMaterialDefines() {\n var _this = _super.call(this) || this;\n _this.PBR = true;\n _this.MAINUV1 = false;\n _this.MAINUV2 = false;\n _this.UV1 = false;\n _this.UV2 = false;\n _this.ALBEDO = false;\n _this.ALBEDODIRECTUV = 0;\n _this.VERTEXCOLOR = false;\n _this.AMBIENT = false;\n _this.AMBIENTDIRECTUV = 0;\n _this.AMBIENTINGRAYSCALE = false;\n _this.OPACITY = false;\n _this.VERTEXALPHA = false;\n _this.OPACITYDIRECTUV = 0;\n _this.OPACITYRGB = false;\n _this.ALPHATEST = false;\n _this.DEPTHPREPASS = false;\n _this.ALPHABLEND = false;\n _this.ALPHAFROMALBEDO = false;\n _this.ALPHATESTVALUE = \"0.5\";\n _this.SPECULAROVERALPHA = false;\n _this.RADIANCEOVERALPHA = false;\n _this.ALPHAFRESNEL = false;\n _this.LINEARALPHAFRESNEL = false;\n _this.PREMULTIPLYALPHA = false;\n _this.EMISSIVE = false;\n _this.EMISSIVEDIRECTUV = 0;\n _this.REFLECTIVITY = false;\n _this.REFLECTIVITYDIRECTUV = 0;\n _this.SPECULARTERM = false;\n _this.MICROSURFACEFROMREFLECTIVITYMAP = false;\n _this.MICROSURFACEAUTOMATIC = false;\n _this.LODBASEDMICROSFURACE = false;\n _this.MICROSURFACEMAP = false;\n _this.MICROSURFACEMAPDIRECTUV = 0;\n _this.METALLICWORKFLOW = false;\n _this.ROUGHNESSSTOREINMETALMAPALPHA = false;\n _this.ROUGHNESSSTOREINMETALMAPGREEN = false;\n _this.METALLNESSSTOREINMETALMAPBLUE = false;\n _this.AOSTOREINMETALMAPRED = false;\n _this.ENVIRONMENTBRDF = false;\n _this.NORMAL = false;\n _this.TANGENT = false;\n _this.BUMP = false;\n _this.BUMPDIRECTUV = 0;\n _this.OBJECTSPACE_NORMALMAP = false;\n _this.PARALLAX = false;\n _this.PARALLAXOCCLUSION = false;\n _this.NORMALXYSCALE = true;\n _this.LIGHTMAP = false;\n _this.LIGHTMAPDIRECTUV = 0;\n _this.USELIGHTMAPASSHADOWMAP = false;\n _this.GAMMALIGHTMAP = false;\n _this.REFLECTION = false;\n _this.REFLECTIONMAP_3D = false;\n _this.REFLECTIONMAP_SPHERICAL = false;\n _this.REFLECTIONMAP_PLANAR = false;\n _this.REFLECTIONMAP_CUBIC = false;\n _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;\n _this.REFLECTIONMAP_PROJECTION = false;\n _this.REFLECTIONMAP_SKYBOX = false;\n _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;\n _this.REFLECTIONMAP_EXPLICIT = false;\n _this.REFLECTIONMAP_EQUIRECTANGULAR = false;\n _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;\n _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;\n _this.INVERTCUBICMAP = false;\n _this.USESPHERICALFROMREFLECTIONMAP = false;\n _this.USESPHERICALINVERTEX = false;\n _this.REFLECTIONMAP_OPPOSITEZ = false;\n _this.LODINREFLECTIONALPHA = false;\n _this.GAMMAREFLECTION = false;\n _this.RGBDREFLECTION = false;\n _this.RADIANCEOCCLUSION = false;\n _this.HORIZONOCCLUSION = false;\n _this.REFRACTION = false;\n _this.REFRACTIONMAP_3D = false;\n _this.REFRACTIONMAP_OPPOSITEZ = false;\n _this.LODINREFRACTIONALPHA = false;\n _this.GAMMAREFRACTION = false;\n _this.RGBDREFRACTION = false;\n _this.LINKREFRACTIONTOTRANSPARENCY = false;\n _this.INSTANCES = false;\n _this.NUM_BONE_INFLUENCERS = 0;\n _this.BonesPerMesh = 0;\n _this.NONUNIFORMSCALING = false;\n _this.MORPHTARGETS = false;\n _this.MORPHTARGETS_NORMAL = false;\n _this.MORPHTARGETS_TANGENT = false;\n _this.NUM_MORPH_INFLUENCERS = 0;\n _this.IMAGEPROCESSING = false;\n _this.VIGNETTE = false;\n _this.VIGNETTEBLENDMODEMULTIPLY = false;\n _this.VIGNETTEBLENDMODEOPAQUE = false;\n _this.TONEMAPPING = false;\n _this.TONEMAPPING_ACES = false;\n _this.CONTRAST = false;\n _this.COLORCURVES = false;\n _this.COLORGRADING = false;\n _this.COLORGRADING3D = false;\n _this.SAMPLER3DGREENDEPTH = false;\n _this.SAMPLER3DBGRMAP = false;\n _this.IMAGEPROCESSINGPOSTPROCESS = false;\n _this.EXPOSURE = false;\n _this.USEPHYSICALLIGHTFALLOFF = false;\n _this.USEGLTFLIGHTFALLOFF = false;\n _this.TWOSIDEDLIGHTING = false;\n _this.SHADOWFLOAT = false;\n _this.CLIPPLANE = false;\n _this.CLIPPLANE2 = false;\n _this.CLIPPLANE3 = false;\n _this.CLIPPLANE4 = false;\n _this.POINTSIZE = false;\n _this.FOG = false;\n _this.LOGARITHMICDEPTH = false;\n _this.FORCENORMALFORWARD = false;\n _this.SPECULARAA = false;\n _this.UNLIT = false;\n _this.rebuild();\n return _this;\n }",
"ballBarrierCollision(ball) {\n let d = dist(this.x, this.y, ball.x, ball.y);\n let barrierSize = ((this.h + this.w) * 2);\n if (d < (ball.size + barrierSize) / 6 && this.id === 1) {\n ball.opacity -= 51;\n this.id = 2;\n this.fillColor = 255;\n ball.healthPercent -= 20;\n }\n }",
"function barrier(){\n \n this.x= w+100;\n this.y= Math.floor(Math.random()*h);\n this.leftPull=0.4;\n this.velocity=5;\n this.width=100;\n this.height=100;\n \n\n this.show=function(){\n fill(color(\"orange\"));\n rect(this.x,this.y,this.width,this.height);\n }\n\n this.update=function(){//makes the ball fall down\n this.velocity+= this.leftPull;\n this.x-=this.velocity;\n if (this.x <0){\n \n this.velocity=0;\n this.x= w+100;\n this.y= Math.floor(Math.random()*h);\n \n }\n }\n \n\n}",
"set brakeTorque(value) {}",
"rebondSurRaquette(raquette){\r\n //zone pour la raquette de gauche\r\n if(raquette.gauche){\r\n if ((this.positionY >= raquette.positionY)&&(this.positionY <= raquette.bas)){\r\n //console.log(\"passage dans la raquette de gauche\");\r\n if (this.positionX<= raquette.droite){\r\n this.positionX = raquette.droite + 1\r\n this.vitesseXSens = this.vitesseXSens * (-1);\r\n /*console.log(\"rebond sur raquette de gauche\");\r\n changement de couleur lié a l'impact*/\r\n raquette.$element.addClass(\"raquetteFluo\");\r\n setTimeout(\r\n function(){\r\n raquette.$element.removeClass(\"raquetteFluo\");\r\n },200\r\n );\r\n this.calculVitesseX();\r\n this.vitesseYSens = raquette.calculRebond(this.positionY);\r\n }\r\n }\r\n }\r\n //zone pour la raquette de droite\r\n else{\r\n if ((this.positionY >= raquette.positionY)&&(this.positionY <= raquette.bas)){\r\n //console.log(\"passage dans la raquette de droite\");\r\n if (this.droite > raquette.positionX){\r\n this.droite = raquette.positionX- 1\r\n this.vitesseXSens = this.vitesseXSens * (-1);\r\n /*console.log(\"rebond sur raquette de droite\");\r\n changement de couleur lié a l'impact*/\r\n raquette.$element.addClass(\"raquetteFluo\");\r\n setTimeout(\r\n function(){\r\n raquette.$element.removeClass(\"raquetteFluo\");\r\n },200\r\n );\r\n this.calculVitesseX();\r\n this.vitesseYSens = raquette.calculRebond(this.positionY);\r\n }\r\n }\r\n }\r\n}",
"function moveRobber(robber, hex) {\n robber.hex = hex;\n}",
"function PBRMaterialDefines() {\r\n var _this = _super.call(this) || this;\r\n _this.PBR = true;\r\n _this.MAINUV1 = false;\r\n _this.MAINUV2 = false;\r\n _this.UV1 = false;\r\n _this.UV2 = false;\r\n _this.ALBEDO = false;\r\n _this.ALBEDODIRECTUV = 0;\r\n _this.VERTEXCOLOR = false;\r\n _this.AMBIENT = false;\r\n _this.AMBIENTDIRECTUV = 0;\r\n _this.AMBIENTINGRAYSCALE = false;\r\n _this.OPACITY = false;\r\n _this.VERTEXALPHA = false;\r\n _this.OPACITYDIRECTUV = 0;\r\n _this.OPACITYRGB = false;\r\n _this.ALPHATEST = false;\r\n _this.DEPTHPREPASS = false;\r\n _this.ALPHABLEND = false;\r\n _this.ALPHAFROMALBEDO = false;\r\n _this.ALPHATESTVALUE = \"0.5\";\r\n _this.SPECULAROVERALPHA = false;\r\n _this.RADIANCEOVERALPHA = false;\r\n _this.ALPHAFRESNEL = false;\r\n _this.LINEARALPHAFRESNEL = false;\r\n _this.PREMULTIPLYALPHA = false;\r\n _this.EMISSIVE = false;\r\n _this.EMISSIVEDIRECTUV = 0;\r\n _this.REFLECTIVITY = false;\r\n _this.REFLECTIVITYDIRECTUV = 0;\r\n _this.SPECULARTERM = false;\r\n _this.MICROSURFACEFROMREFLECTIVITYMAP = false;\r\n _this.MICROSURFACEAUTOMATIC = false;\r\n _this.LODBASEDMICROSFURACE = false;\r\n _this.MICROSURFACEMAP = false;\r\n _this.MICROSURFACEMAPDIRECTUV = 0;\r\n _this.METALLICWORKFLOW = false;\r\n _this.ROUGHNESSSTOREINMETALMAPALPHA = false;\r\n _this.ROUGHNESSSTOREINMETALMAPGREEN = false;\r\n _this.METALLNESSSTOREINMETALMAPBLUE = false;\r\n _this.AOSTOREINMETALMAPRED = false;\r\n _this.ENVIRONMENTBRDF = false;\r\n _this.ENVIRONMENTBRDF_RGBD = false;\r\n _this.NORMAL = false;\r\n _this.TANGENT = false;\r\n _this.BUMP = false;\r\n _this.BUMPDIRECTUV = 0;\r\n _this.OBJECTSPACE_NORMALMAP = false;\r\n _this.PARALLAX = false;\r\n _this.PARALLAXOCCLUSION = false;\r\n _this.NORMALXYSCALE = true;\r\n _this.LIGHTMAP = false;\r\n _this.LIGHTMAPDIRECTUV = 0;\r\n _this.USELIGHTMAPASSHADOWMAP = false;\r\n _this.GAMMALIGHTMAP = false;\r\n _this.REFLECTION = false;\r\n _this.REFLECTIONMAP_3D = false;\r\n _this.REFLECTIONMAP_SPHERICAL = false;\r\n _this.REFLECTIONMAP_PLANAR = false;\r\n _this.REFLECTIONMAP_CUBIC = false;\r\n _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;\r\n _this.REFLECTIONMAP_PROJECTION = false;\r\n _this.REFLECTIONMAP_SKYBOX = false;\r\n _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;\r\n _this.REFLECTIONMAP_EXPLICIT = false;\r\n _this.REFLECTIONMAP_EQUIRECTANGULAR = false;\r\n _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;\r\n _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;\r\n _this.INVERTCUBICMAP = false;\r\n _this.USESPHERICALFROMREFLECTIONMAP = false;\r\n _this.SPHERICAL_HARMONICS = false;\r\n _this.USESPHERICALINVERTEX = false;\r\n _this.REFLECTIONMAP_OPPOSITEZ = false;\r\n _this.LODINREFLECTIONALPHA = false;\r\n _this.GAMMAREFLECTION = false;\r\n _this.RGBDREFLECTION = false;\r\n _this.RADIANCEOCCLUSION = false;\r\n _this.HORIZONOCCLUSION = false;\r\n _this.INSTANCES = false;\r\n _this.NUM_BONE_INFLUENCERS = 0;\r\n _this.BonesPerMesh = 0;\r\n _this.BONETEXTURE = false;\r\n _this.NONUNIFORMSCALING = false;\r\n _this.MORPHTARGETS = false;\r\n _this.MORPHTARGETS_NORMAL = false;\r\n _this.MORPHTARGETS_TANGENT = false;\r\n _this.NUM_MORPH_INFLUENCERS = 0;\r\n _this.IMAGEPROCESSING = false;\r\n _this.VIGNETTE = false;\r\n _this.VIGNETTEBLENDMODEMULTIPLY = false;\r\n _this.VIGNETTEBLENDMODEOPAQUE = false;\r\n _this.TONEMAPPING = false;\r\n _this.TONEMAPPING_ACES = false;\r\n _this.CONTRAST = false;\r\n _this.COLORCURVES = false;\r\n _this.COLORGRADING = false;\r\n _this.COLORGRADING3D = false;\r\n _this.SAMPLER3DGREENDEPTH = false;\r\n _this.SAMPLER3DBGRMAP = false;\r\n _this.IMAGEPROCESSINGPOSTPROCESS = false;\r\n _this.EXPOSURE = false;\r\n _this.MULTIVIEW = false;\r\n _this.USEPHYSICALLIGHTFALLOFF = false;\r\n _this.USEGLTFLIGHTFALLOFF = false;\r\n _this.TWOSIDEDLIGHTING = false;\r\n _this.SHADOWFLOAT = false;\r\n _this.CLIPPLANE = false;\r\n _this.CLIPPLANE2 = false;\r\n _this.CLIPPLANE3 = false;\r\n _this.CLIPPLANE4 = false;\r\n _this.POINTSIZE = false;\r\n _this.FOG = false;\r\n _this.LOGARITHMICDEPTH = false;\r\n _this.FORCENORMALFORWARD = false;\r\n _this.SPECULARAA = false;\r\n _this.CLEARCOAT = false;\r\n _this.CLEARCOAT_DEFAULTIOR = false;\r\n _this.CLEARCOAT_TEXTURE = false;\r\n _this.CLEARCOAT_TEXTUREDIRECTUV = 0;\r\n _this.CLEARCOAT_BUMP = false;\r\n _this.CLEARCOAT_BUMPDIRECTUV = 0;\r\n _this.CLEARCOAT_TINT = false;\r\n _this.CLEARCOAT_TINT_TEXTURE = false;\r\n _this.CLEARCOAT_TINT_TEXTUREDIRECTUV = 0;\r\n _this.ANISOTROPIC = false;\r\n _this.ANISOTROPIC_TEXTURE = false;\r\n _this.ANISOTROPIC_TEXTUREDIRECTUV = 0;\r\n _this.BRDF_V_HEIGHT_CORRELATED = false;\r\n _this.MS_BRDF_ENERGY_CONSERVATION = false;\r\n _this.SHEEN = false;\r\n _this.SHEEN_TEXTURE = false;\r\n _this.SHEEN_TEXTUREDIRECTUV = 0;\r\n _this.SHEEN_LINKWITHALBEDO = false;\r\n _this.SUBSURFACE = false;\r\n _this.SS_REFRACTION = false;\r\n _this.SS_TRANSLUCENCY = false;\r\n _this.SS_SCATERRING = false;\r\n _this.SS_THICKNESSANDMASK_TEXTURE = false;\r\n _this.SS_THICKNESSANDMASK_TEXTUREDIRECTUV = 0;\r\n _this.SS_REFRACTIONMAP_3D = false;\r\n _this.SS_REFRACTIONMAP_OPPOSITEZ = false;\r\n _this.SS_LODINREFRACTIONALPHA = false;\r\n _this.SS_GAMMAREFRACTION = false;\r\n _this.SS_RGBDREFRACTION = false;\r\n _this.SS_LINKREFRACTIONTOTRANSPARENCY = false;\r\n _this.SS_MASK_FROM_THICKNESS_TEXTURE = false;\r\n _this.UNLIT = false;\r\n _this.DEBUGMODE = 0;\r\n _this.rebuild();\r\n return _this;\r\n }",
"bendArm( arm, length ) {\n var ret = true;\n var upperArm = this.skeleton.bones[arm.upper];\n var lowerArm = this.skeleton.bones[arm.lower];\n var scaling = this.rootMesh.scaling.x;\n\n if ( length > arm.lowerLength + arm.upperLength ) {\n length = arm.lowerLength + arm.upperLength\n ret = false;\n }\n\n // simplified math by using same length for both bones\n // it's right angle, hypotenuse is bone\n // length/2 is sinus of half of elbow angle\n var boneLength = (arm.lowerLength + arm.upperLength)/2;\n var innerAngle = Math.asin(length/2/boneLength);\n //this.log(\"Bone length: \"+boneLength+\" distance to target \"+length);\n var shoulderAngle = Math.PI/2-innerAngle;\n var elbowAngle = shoulderAngle*2;\n\n var fix = BABYLON.Quaternion.RotationAxis(arm.frontAxis.axis,-shoulderAngle*arm.frontAxis.sign);\n arm.upperRot = arm.upperRot.multiply(fix);\n\n arm.lowerRot = BABYLON.Quaternion.RotationAxis(arm.frontAxis.axis,elbowAngle*arm.frontAxis.sign);\n //this.log(\"Angle shoulder: \"+shoulderAngle+\" elbow: \"+elbowAngle+\" length: \"+length);\n return ret;\n }",
"function resetBall()\n{\n console.log(\"ball being set\");\n if(currentRod == rod2)\n {\n ball.style.top = container.clientHeight - currentRod.offsetHeight - ball.offsetHeight + \"px\";\n ball.style.left = currentRod.offsetLeft + (currentRod.offsetWidth)/2 - (ball.offsetWidth)/2 + \"px\";\n }\n else{\n ball.style.top = currentRod.offsetHeight + \"px\";\n ball.style.left = currentRod.offsetLeft + (currentRod.offsetWidth)/2 - (ball.offsetWidth)/2 + \"px\";\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get collections block. Used by child views. Result is copied, ready to be modified | getCollectionsBlock() {
if (this.loading || this.error !== '') {
return null;
}
const blocks = this.render();
return blocks !== null && blocks.collections !== null
? objects.cloneObject(blocks.collections)
: null;
} | [
"getCollectionsBlock() {\n\t if (this.loading || this.error !== '') {\n\t return null;\n\t }\n\t const blocks = this.render();\n\t return blocks !== null && blocks.collections !== null\n\t ? blocks.collections\n\t : null;\n\t }",
"get collections() { return new Promise((resolve, reject) => {\n require('./skyblock/base.js').collections().then((collections) => {\n resolve(collections)\n })\n })}",
"getCollection() {\n return null;\n }",
"getCollection(name) {\n return this.collections.get(name);\n }",
"getCollection (collectionName) {\n return this.collections[ collectionName ]\n }",
"get collections() {\n return this._collections.custom;\n }",
"collect () {\n return this.getCollection()\n }",
"function _mGetCollection(memo, next){\n\t\t\tCollection.getDefault(memo.user_id, \n\t\t\t\t(err, collection) => {\n\t\t\t\t\tif(err)return setImmediate(() => next(err));\n\t\t\t\t\t\n\t\t\t\t\tmemo.Collection = collection;\n\t\t\t\t\t\n\t\t\t\t\tsetImmediate(() => next(null, memo))\n\t\t\t\t}\n\t\t\t);\n\t\t}",
"function _getCollection()\n\t{\n\t\treturn _collListItem;\n\t}",
"async getCollectionItems(name) {\n const { fields, entries } = await this.cockpit.collectionGet(name);\n return { fields, entries, name };\n }",
"getCollection() {\n return this.nodeCollection;\n }",
"function getBlocks(){\n return blocks;\n }",
"_findSiblingCollections() {\n\t const collectionsBlock = this\n\t .parent.getCollectionsBlock();\n\t if (collectionsBlock === null) {\n\t return null;\n\t }\n\t const collections = collectionsList.collectionsPrefixesWithInfo(collectionsBlock);\n\t const match = collections.find((item) => item.prefix === this.prefix);\n\t if (match === void 0 || collections.length < 2) {\n\t return null;\n\t }\n\t // Get limit\n\t const registry = storage.getRegistry(this._instance);\n\t const config = registry.config;\n\t // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n\t const limit = config.ui.showSiblingCollections;\n\t // Get items before and after current prefix\n\t let display = [];\n\t if (collections.length < limit * 2 + 2) {\n\t // Display all collections\n\t display = collections.slice(0);\n\t }\n\t else {\n\t const index = collections.indexOf(match);\n\t // few items before current\n\t for (let i = index - limit; i < index; i++) {\n\t display.push(collections[(i + collections.length) % collections.length]);\n\t }\n\t // Current item\n\t display.push(match);\n\t // few items after current\n\t for (let i = index + 1; i <= index + limit; i++) {\n\t display.push(collections[i % collections.length]);\n\t }\n\t }\n\t // Create block\n\t const block = filters.defaultFiltersBlock();\n\t block.filterType = 'collections';\n\t block.active = this.prefix;\n\t display.forEach((item) => {\n\t const filter = filters.defaultFilter(item.name);\n\t filter.index = item.index;\n\t block.filters[item.prefix] = filter;\n\t });\n\t return block;\n\t }",
"function filterCollectionsBlock(block, callback, keepEmptyCategories = false) {\n\t const result = {\n\t type: 'collections-list',\n\t showCategories: block.showCategories,\n\t collections: collections.filterCollections(block.collections, callback, keepEmptyCategories),\n\t };\n\t return result;\n\t}",
"function get_collection(callback) {\n\n TRANSFER_INGEST.get_collection(sip_uuid, function (result) {\n\n if (result === null || result === undefined) {\n get_collection(callback);\n return false;\n }\n\n let obj = {};\n obj.pid = sip_uuid;\n obj.sip_uuid = sip_uuid;\n obj.is_member_of_collection = result;\n callback(null, obj);\n });\n }",
"async allButterCollections(actions) {\n const collection = await this.client.content.retrieve(this.options.collections)\n const { data } = collection.data;\n const contentType = actions.addCollection({\n typeName: this.createTypeName('collection')\n });\n contentType.addNode({\n data\n })\n }",
"static getCollection () {\n const name = this.collection\n return this.connection.collection(name)\n }",
"function getCollection(collection)\n{\n let collectionSelected = db.collection(collection); \n return collectionSelected.get(); \n}",
"getCollection(collection) {\n return this.connection.get(collection);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse .TPL and .PHP files | function parseTemplates() {
// Load paths in array containing PHP and TPL Files via src
return gulp.src([paths.locale.classes, paths.locale.templates])
// Pipe all files in generator (concat)
.pipe(phpParser.generatePOT(paths.locale.potName, {project: 'TestProject', company: 'BestCompany' }))
// Save the POT to the destination
.pipe(gulp.dest(paths.locale.dest))
.on('end', function(){ log('[Locale] Recompiling .POT, .PO and .MO files from sources'); })
// For each language, pick the original .PO file and update it against the POT
// Also automatically regenerates .MO machine files
.pipe(phpParser.mergeAndMake(paths.locale.dest + paths.locale.poMoNames.it))
.pipe(phpParser.mergeAndMake(paths.locale.dest + paths.locale.poMoNames.en))
} | [
"function processFile(text){\n var flows = JSON.parse(text);\n var servers = getServers(flows);\n var time_stats = generateTimeStats(flows);\n\n flow_map = buildFlowMap(flows, time_stats);\n //console.log(flow_map);\n\n\n //console.log(flows);\n //console.log(time_stats);\n\n /* TODO: I shouldn't need the flows in the setup, right?*/\n setup(servers, flows, time_stats, flow_map);\n}",
"function pages() {\n return gulp.src('src/templates/**/*.tpl.html')\n .pipe(panini({\n root: 'src/templates',\n layouts: 'src/layouts',\n partials: 'src/partials',\n helpers: 'src/helpers'\n }))\n .pipe(inky())\n .pipe($.extReplace('.php'))\n .pipe(gulp.dest('templates'))\n\n // Update compiled file timestamp.\n .pipe($.shell([\n 'touch <%= file.path %>'\n ]));\n}",
"function parseFile () {\n // var bodySnippet = `payload := &bytes.Buffer{}\\n${indent}writer := multipart.NewWriter(payload)\\n`;\n // isFile = true;\n // bodySnippet += `${indent}// add your file name in the next statement in place of path\\n`;\n // bodySnippet += `${indent}file, err := os.Open(path)\\n`;\n // bodySnippet += `${indent}defer file.Close()\\n`;\n // bodySnippet += `${indent}part, err := writer.CreateFormFile(\"file\", filepath.Base(path))\\n`;\n // bodySnippet += `${indent}_, err := io.Copy(part, file)\\n`;\n // bodySnippet += `${indent}err := writer.Close()\\n${indent}if err != nil {${indent}fmt.Println(err)}\\n`;\n var bodySnippet = 'payload := strings.NewReader(\"<file contents here>\")\\n';\n return bodySnippet;\n}",
"_parseHTML() {\n const contents = fs.readFileSync(this.filepath, 'utf-8');\n this.code = htmlLoader(contents);\n }",
"function parseInputFiles() {\n parseDomain(generateInputWindow);\n}",
"async loadAllFilesAST() {\n await this.logger.time(Logger_1.LogLevel.log, ['Parsing files'], async () => {\n let errorCount = 0;\n let files = await this.logger.time(Logger_1.LogLevel.debug, ['getFilePaths'], async () => {\n return util_1.util.getFilePaths(this.options);\n });\n this.logger.trace('ProgramBuilder.loadAllFilesAST() files:', files);\n const typedefFiles = [];\n const nonTypedefFiles = [];\n for (const file of files) {\n const srcLower = file.src.toLowerCase();\n if (srcLower.endsWith('.d.bs')) {\n typedefFiles.push(file);\n }\n else {\n nonTypedefFiles.push(file);\n }\n }\n //preload every type definition file first, which eliminates duplicate file loading\n await Promise.all(typedefFiles.map(async (fileObj) => {\n try {\n this.program.setFile(fileObj, await this.getFileContents(fileObj.src));\n }\n catch (e) {\n //log the error, but don't fail this process because the file might be fixable later\n this.logger.log(e);\n }\n }));\n const acceptableExtensions = ['.bs', '.brs', '.xml'];\n //parse every file other than the type definitions\n await Promise.all(nonTypedefFiles.map(async (fileObj) => {\n try {\n let fileExtension = path.extname(fileObj.src).toLowerCase();\n //only process certain file types\n if (acceptableExtensions.includes(fileExtension)) {\n this.program.setFile(fileObj, await this.getFileContents(fileObj.src));\n }\n }\n catch (e) {\n //log the error, but don't fail this process because the file might be fixable later\n this.logger.log(e);\n }\n }));\n return errorCount;\n });\n }",
"function loadTemplate() {\n var templatePattern = /@[[a-zA-Z0-9]+]/g;\n\n templateContent = _fs.readFileSync(templatePath, fileEncoding);\n templatePlaceholders = templateContent.match(templatePattern);\n\n }",
"function parse(files, nested, base) {\n\n base = base || ''\n var html = '', padding = nested * 16 + 6\n\n files.forEach(function (file) {\n var path = base + '/' + file.name\n var id = 'id' + path.replace(/[.\\/]/g, '-')\n\n html += (file.child !== undefined) ?\n template('folder-template', {\n id: id,\n name: file.name,\n content: parse(file.child, nested + 1, path),\n padding: padding\n }) :\n template('file-template', {\n id: id,\n icon: (icon = icons.getClass(file.name)) ? icon : 'text-icon',\n name: file.name,\n path: hashbang + '/' + path,\n padding: padding\n })\n })\n\n return html;\n }",
"parseFlsFile(baseFile) {\r\n this.extension.logger.addLogMessage('Parse fls file.');\r\n const rootDir = path.dirname(baseFile);\r\n const outDir = this.getOutDir(baseFile);\r\n const flsFile = path.resolve(rootDir, path.join(outDir, path.basename(baseFile, '.tex') + '.fls'));\r\n if (!fs.existsSync(flsFile)) {\r\n this.extension.logger.addLogMessage(`Cannot find fls file: ${flsFile}`);\r\n return;\r\n }\r\n this.extension.logger.addLogMessage(`Fls file found: ${flsFile}`);\r\n const ioFiles = this.parseFlsContent(fs.readFileSync(flsFile).toString(), rootDir);\r\n ioFiles.input.forEach((inputFile) => {\r\n // Drop files that are also listed as OUTPUT or should be ignored\r\n if (ioFiles.output.includes(inputFile) ||\r\n this.isExcluded(inputFile) ||\r\n !fs.existsSync(inputFile)) {\r\n return;\r\n }\r\n // Drop the current rootFile often listed as INPUT and drop any file that is already in the texFileTree\r\n if (baseFile === inputFile || inputFile in this.cachedContent) {\r\n return;\r\n }\r\n if (path.extname(inputFile) === '.tex') {\r\n // Parse tex files as imported subfiles.\r\n this.cachedContent[baseFile].children.push({\r\n index: Number.MAX_VALUE,\r\n file: inputFile\r\n });\r\n this.parseFileAndSubs(inputFile);\r\n }\r\n else if (this.fileWatcher && !this.filesWatched.includes(inputFile)) {\r\n // Watch non-tex files.\r\n this.fileWatcher.add(inputFile);\r\n this.filesWatched.push(inputFile);\r\n }\r\n });\r\n ioFiles.output.forEach((outputFile) => {\r\n if (path.extname(outputFile) === '.aux' && fs.existsSync(outputFile)) {\r\n this.parseAuxFile(fs.readFileSync(outputFile).toString(), path.dirname(outputFile).replace(outDir, rootDir));\r\n }\r\n });\r\n }",
"loadTemplates(dir, name, templateDir) {\n // Load in and compile the templates in the view's dir using dust.\n let files\n try {\n files = fs.readdirSync(path.join(dir, templateDir))\n } catch (e) {\n return false\n }\n if (files) {\n for (\n let file of files) {\n let content = util.file.readIfFile(path.join(dir, templateDir, file))\n let templateName = path.join(name, file)\n viewEngine.compileMethod(content, templateName)\n }\n return true\n } else {\n console.log('No Partials Found')\n }\n }",
"function parseFiles(fileNames) {\n var resultContent = \"\";\n // parse all the given files\n fileNames.forEach(function (definitionFile) {\n console.error(\"Processing \" + colors.cyan(definitionFile));\n var content = fs.readFileSync(definitionFile, {\n encoding: \"utf-8\"\n });\n var definitions = new parser.DefinitionParser().parseDefinitions(content);\n var modules = {};\n for (var i = 0; i < definitions.length; i++) {\n var def = definitions[i];\n for (var j = 0; j < def.modules.length; j++) {\n var moduleName = def.modules[i];\n var contentList = modules[moduleName];\n if (!contentList) {\n modules[moduleName] = contentList = [];\n }\n contentList.push(def.item);\n }\n }\n for (var k in modules) {\n resultContent += 'declare module ' + k + '{\\n';\n for (var i = 0; i < modules[k].length; i++) {\n resultContent += modules[k][i] + '\\n';\n }\n resultContent += '}\\n';\n }\n });\n return resultContent;\n}",
"function parseSourceFile(filename) {\n\t\tvar filenameArr = filename.split(/\\\\|\\//g);\n\t\tvar folder = filenameArr[filenameArr.length-2].toLowerCase(); ;\n\t\t\n var src = fs.readFileSync(filename, 'utf-8');\n var outPath = filename.replace('.xml', '.json');\n var entryTree = et.parse(src);\n var contentNodes = entryTree.findall('./CONTENT');\n var contentOut = {\"template\": \"v18\"};\n\n for (var node in contentNodes) {\n var type = contentNodes[node].findtext('./SHARED_DATA/TYPE');\n\n // also filter out nodes if ECMCC_MULTI_OPT2 JavaScript[==]js ?? or CSS?\n if (nodeTypes.indexOf(type) > -1) {\n var synkey = contentNodes[node].findtext('./SHARED_DATA/SYNDICATION_KEY');\n var title = contentNodes[node].findtext('./SHARED_DATA/TITLE');\n console.log('node type:' ,type, synkey, title);\n if (typeof contentOut[synkey] === 'undefined') contentOut[synkey] = {};\n if (title) contentOut[synkey].title = title;\n console.log('we have content synkey node:', contentOut[synkey]);\n contentOut = parseGroupNode(contentOut, folder, synkey, contentNodes[node], true, \"\");\n }\n }\n\n fs.writeFileSync(outPath, JSON.stringify(contentOut, null, \"\\t\"));\n}",
"parse() {\n const basePath = path.join(this.iotjs, 'docs/api');\n\n fs.readdir(basePath, (err, files) => {\n this.verboseLog(`Read '${basePath}' directory.`);\n\n if (err) {\n console.error(err.message);\n return false;\n }\n\n const promises = files.filter(file => !file.includes('reference')).map(file => {\n const name = file.slice(\n config.docname.pre.length,\n -config.docname.post.length\n ).toLowerCase().replace('file-system', 'fs');\n\n this.addModuleToOutput(name);\n\n return new Promise((resolve, reject) => {\n const filePath = path.join(basePath, file);\n\n fs.readFile(filePath, 'utf8', (error, data) => {\n this.verboseLog(`- Read '${filePath}' --> ${name} module`);\n\n if (error) {\n reject(error.message);\n } else {\n resolve({ name, data });\n }\n });\n });\n });\n\n Promise.all(promises).then((data) => {\n this.verboseLog('\\nParse each read file content to get their available functions list.');\n\n data.forEach((file) => {\n this.verboseLog(`- Parse ${file.name} module:`);\n\n let doc = false;\n let label = '';\n let detail = '';\n let insertText = '';\n let documentation = [];\n\n file.data.split('\\n').forEach(line => {\n // Prototype line match.\n if (!config.regex.new.test(line) && config.regex.proto.test(line)) {\n // Found a new prototype before an example, save the last known prototype if necessary.\n if (doc) {\n this.addFunctionToModule(file.name, {\n label: label,\n kind: 2,\n detail: detail,\n documentation: documentation.join('\\n'),\n insertText: insertText,\n });\n }\n\n const functionName = line.substring(4).replace(config.regex.args, '').split('.').pop();\n const functionDetail = line.substring(4);\n\n label = functionName;\n detail = functionDetail;\n insertText = functionName;\n documentation = [];\n doc = true;\n\n this.verboseLog(` = ${functionDetail}`);\n\n return;\n }\n\n // Documentation line match.\n if (!config.regex.event.test(line) &&\n !config.regex.exDef.test(line) &&\n !config.regex.exLess.test(line) &&\n !config.regex.proto.test(line) && doc) {\n documentation.push(line);\n } else {\n // Store the function documentation.\n if (doc) {\n this.addFunctionToModule(file.name, {\n label: label,\n kind: 2,\n detail: detail,\n documentation: documentation.join('\\n'),\n insertText: insertText,\n });\n }\n\n documentation = [];\n doc = false;\n }\n });\n });\n\n this.verboseLog('Modules are parsed.\\n');\n\n this.writeOutputToDestonation();\n }).catch((error) => {\n console.error(error);\n });\n });\n }",
"function parseAllFiles(files) {\n var totalTimeMillis = 0;\n var charsProcessed = 0;\n var failed = [];\n forEachAsync(files, function(pair, doNext) {\n var name = pair[0];\n var defaultDialect = myjs.getDialect(pair[1] || 'myjs.JavaScript');\n fs.readFile(name, 'utf8', function(error, rawSource) {\n // Strip any hashbangs.\n var source = rawSource.replace(/^\\#\\!.*/, '');\n var dialect = defaultDialect;\n var useClause = /'use\\s+(\\S+)';/.exec(source);\n if (useClause) {\n var dialectName = useClause[1];\n if (dialectName != 'strict') {\n dialect = new myjs.Dialect(dialectName).addFragment(dialectName);\n }\n }\n var origin = new myjs.tedir.SourceOrigin(name);\n var now = new Date();\n if (CATCH_ERRORS) {\n try {\n dialect.translate(source, origin);\n } catch (e) {\n failed.push(name);\n }\n } else {\n dialect.translate(source, origin);\n }\n var duration = new Date() - now;\n totalTimeMillis += duration;\n charsProcessed += source.length;\n console.log(\"Parsed \" + name + \" [\" + duration + \" ms.]\");\n doNext();\n });\n }, function() {\n if (failed.length == 0) {\n console.log('All files parsed successfully.');\n var megas = charsProcessed / (1024 * 1024);\n var megasPerMilli = megas / totalTimeMillis;\n var megasPerSec = megasPerMilli * 1000;\n console.log('Throughput: ' + megasPerSec.toPrecision(4) + \" M/s\");\n } else {\n console.log('Tests failed:');\n console.log(failed.map(function(name) { return \" '\" + name + \"': true,\"; }).join(\"\\n\"));\n }\n });\n}",
"parse_text() {\n\t\tlet start = this.pos, end = start;\n\t\t\n\t\twhile(end < this.src.length) {\n\t\t\tlet x = this.src.indexOf(\"{{\", end);\n\t\t\tif(x === -1) {\n\t\t\t\t// If there's no more templates, we're done.\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\t// Hit a template, no more text\n\t\t\tif(x === end) {\n\t\t\t\treturn this.src.slice(start, x);\n\t\t\t}\n\t\t\t\n\t\t\t// Try to eat a nowiki block\n\t\t\tNOWIKI.lastIndex = end;\n\t\t\tlet m = NOWIKI.exec(this.src);\n\t\t\tif(m) {\n\t\t\t\tend = NOWIKI.lastIndex;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Must keep incrementing\n\t\t\t\t++end;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn this.src.slice(start);\n\t}",
"parse_text() {\n\t\tlet start = this.pos, end = start;\n\t\t\n\t\twhile(end < this.src.length) {\n\t\t\tlet x = this.src.indexOf(\"{{\", end);\n\t\t\tif(x === -1) {\n\t\t\t\t// If there's no more templates, we're done.\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\t// Hit a template, no more text\n\t\t\tif(x === end) {\n\t\t\t\treturn this.src.slice(start, x);\n\t\t\t}\n\t\t\t\n\t\t\t// Try to eat a nowiki block\n\t\t\t// This can't use match() because it doesn't care if nowiki is\n\t\t\t// next.\n\t\t\tNOWIKI.lastIndex = end;\n\t\t\tlet m = NOWIKI.exec(this.src);\n\t\t\tif(m) {\n\t\t\t\tend = NOWIKI.lastIndex;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Must keep incrementing\n\t\t\t\t++end;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn this.src.slice(start);\n\t}",
"function parseTemplate(text, tpl) {\n\t\t\t\ttpl = tpl.replace(/[_ ]/g, '[_ ]');\n\t\t\t\tvar re = new RegExp('{{\\\\s*(template:)?' + tpl + '\\\\s*\\\\|([\\\\w\\\\W]+?)[^!]}}', 'gi');\n \n\t\t\t\tvar data = [];\n\t\t\t\tvar match;\n \n\t\t\t\twhile (match = re.exec(text)) {\n\t\t\t\t\t\tvar params = match[2].split('|');\n\t\t\t\t\t\tvar j = 1; // Unnamed parameter index\n\t\t\t\t\t\tvar tplData = new Array();\n\t\t\t\t\t\tfor (var k in params) {\n\t\t\t\t\t\t\t\tvar t = params[k].split('=');\n\t\t\t\t\t\t\t\tvar name = null;\n\t\t\t\t\t\t\t\tvar value = null;\n\t\t\t\t\t\t\t\tif (t.length == 1) { // Unnamed params\n\t\t\t\t\t\t\t\t\t\tname = (j++) + ''; // Cast to string\n\t\t\t\t\t\t\t\t\t\tvalue = t[0];\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tname = t[0];\n\t\t\t\t\t\t\t\t\t\tvalue = t[1];\n\t\t\t\t\t\t\t\t}\n \n\t\t\t\t\t\t\t\ttplData[$.trim(name)] = $.trim(value);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdata.push(tplData);\n\t\t\t\t}\n \n\t\t\t\treturn data;\n\t\t}",
"prepare_template(filename, callback) {\n\n fs.readFile(filename, 'utf-8', function(err, data){\n \n if(err) {\n callback(err, data);\n return;\n }\n \n var template = hogan.compile(data);\n\n callback(err, template);\n \n });\n }",
"function loadTemplates() {\n let templates = fs.readdirSync(options.templates);\n templates.forEach(function(template) {\n let templateName = template.split('.')[0];\n templateCache[templateName] = hbs.compile(fs.readFileSync(options.templates + '/' + template).toString());\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
public method, allow the parent clear varCache | clearVarCache() {
const { delta } = this;
delta.varCache = {};
delta.varLastCalcIndex = 0;
} | [
"static clearCache() {\n codeCache = new Storage();\n _cache = new Storage();\n }",
"updateAllVarCache() {\n const { delta: { varLastCalcIndex }, updateVariable } = this;\n updateVariable(varLastCalcIndex);\n }",
"updateAfterCache(index) {\n const { delta } = this;\n delta.varLastCalcIndex = index;\n Object.keys(delta.varCache).forEach((key) => {\n if (key - 0 > index) {\n delta.varCache[key] = null;\n }\n });\n }",
"clear() {\n this._cache.clear();\n }",
"resetCache() {\n this._cache.inputs = {};\n this._cache.procedureParamNames = {};\n this._cache.procedureDefinitions = {};\n this._cache._executeCached = {};\n this._cache._monitored = null;\n this._cache.scripts = {};\n this._cache.compiledScripts = {};\n this._cache.compiledProcedures = {};\n this._cache.proceduresPopulated = false;\n }",
"resetCache() {\n if (this.cacheEnabled) {\n this.cached();\n }\n }",
"clearTemporaryCache() {\n this.temporaryCache = {};\n }",
"resetCache() {\n this.cache = null;\n }",
"clearCache() {\n this.fileCache = {};\n }",
"function listCacheClear(){this.__data__=[];}",
"clearCache() {\n this.descriptorsCache_ = null;\n }",
"clearCache() {\n this.cache = {};\n this.locks = {};\n }",
"resetCache() {\n// console.log(this, \".resetCache()\");\n this.cache = {};\n }",
"function clean() {\n _cache = {};\n }",
"resetCache() {\n Wick.ObjectCache.removeUnusedObjects(this);\n }",
"clearCodeCache() {\n this.fastStorage.code = null;\n this.fastStorage.rebuildDate = 0;\n }",
"clearCache() {\n this.treeArray = [];\n }",
"function listCacheClear(){this.__data__=[]}",
"stopCaching() {\n delete this[symbol('cacheMap')];\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets up markers for the nearby cabins | function setupNearbyCabins(nearCabinsJson){
//create a marker for each cabin
var markers = new Array();
for(var i=0;i<nearCabinsJson.length;i++){
//get id
var id = nearCabinsJson[i].id;
//get point
var latlon = new GLatLng(nearCabinsJson[i].lat,nearCabinsJson[i].lon);
var name = nearCabinsJson[i].name;
//create marker
var marker = new GMarker(latlon,{icon:cabinMarker(),title:name});
//GLog.write(latlon);
//add the marker to marker array (used to populate MarkerManager)
markers.push(marker);
}
//return the markers
return markers;
} | [
"function initMarkers() {\n // creating marker from places\n for (var i = 0; i < markerList.length; i++) {\n var marker = new google.maps.Marker({\n position: markerList[i].location,\n map: map,\n title: markerList[i].title,\n animation: google.maps.Animation.DROP,\n id: i\n });\n\n markers.push(marker);\n\n bounds.extend(marker.position);\n\n // adding info window to marker\n marker.addListener('click', markerClickHandler);\n }\n\n // Filts bound as per markers\n map.fitBounds(bounds);\n }",
"function setMarkers(bicycles) {\n // First it calls our function that gets the coordinate values\n getAllCoordinates();\n\n for (var i = 0; i < bicycles.length; i++) {\n // The array bicycles is multidimentional, so we extract the respective coordinate array\n var bicycle = bicycles[i];\n // The object myLatLng is a reformated version of the bicycle array, in a way that is\n // compatible with GoogleMaps\n var myLatLng = new google.maps.LatLng(parseFloat(bicycle[1]), parseFloat(bicycle[2]));\n // A new marker is created with the previously defined map, icon, latitude and longitude.\n var marker = new google.maps.Marker({\n map: map,\n position: myLatLng,\n icon: icon,\n zIndex: Number(bicycle[2])\n });\n // add the new marker to the markers array.\n markers.push(marker);\n }\n}",
"function initMarker() {\n //Foreach iterating over all the locations and creating markers for each location\n locations.forEach(function(location) {\n marker = new google.maps.Marker({\n title: location.title,\n position: location.location,\n map: map,\n animation: google.maps.Animation.DROP,\n icon: icons[location.type].icon\n });\n //Event handler function listening for marker clicks and opens up InfoWindow\n marker.addListener('click', function() {\n initInfoWindow(this, viewInfoWindow);\n bounceMarker(this);\n });\n markers.push(marker);\n location.marker = marker;\n });\n //Creating bound variable for setting bounds in google maps\n var bounds = new google.maps.LatLngBounds();\n markers.forEach(function (marker) {\n bounds.extend(marker.position);\n });\n map.fitBounds(bounds);\n}",
"function placeCenterAndPin(){\n setCenterAndMarker();\n initMap();\n }",
"function placeMarkers() {\n for (var i = 0; i < markers.length; i++) {\n var marker = markers[i];\n marker.setMap(areasMap);\n }\n\n areasMap.fitBounds(markerBounds);\n }",
"function initCarMaps() {\n\t \tvar locations = carmarkers;\n\t \tvar wrappers = document.getElementsByClassName('map-container');\n\t\tvar marker, i;\n\t \tvar infowindow = new google.maps.InfoWindow();\n\t \tvar image = {\n\t \t\turl: \"img/carmarker.png\",\n\t \t\tscaledSize: new google.maps.Size(30, 30), // scaled size\n\t \t};\n\t \t//append map to each car element\n\t \tfor (i = 0; i < wrappers.length; i++) {\n\t \t\tlatlng = {lat: parseFloat(locations[i][0]), lng: parseFloat(locations[i][1])};\n\t \t\t//console.log(latlng);\n\t \t\tvar mapOptions = {\n\t center: latlng,\n\t scrollwheel: true,\n\t zoom: 15\n\t };\n\t map = new google.maps.Map(document.getElementById('map-' + (i + 1)), mapOptions);\n \t var marker = new google.maps.Marker({\n\t map: map,\n\t position: latlng,\n\t icon: image\n\t });\n\t google.maps.event.addListener(marker, 'click', (function(marker, i) {\n\t\t return function() {\n\t\t infowindow.setContent(locations[i][2] || \"On the road\");\n\t\t infowindow.open(map, marker);\n\t\t }\n\t })(marker, i));\n\t \t}\n }",
"function setMarkers(map) {\n// Building Info\n// Name, latitude, longitude\n\tlet buildings = [\n\t\t['QLC', 21.3003437, -157.8183039],\n\t\t['Webster', 21.3001962, -157.8185224],\n\t\t['Shindler', 21.3005778, -157.8204599],\n\t\t['Sinclair', 21.2986725, -157.8206569],\n\t\t['Webster', 21.3001962, -157.8185224],\n\t\t['Hamilton', 21.3005079, -157.816839],\n\t\t['Kennedy', 21.2985384, -157.8171935],\n\t\t['Kuykendall', 21.2976342, -157.8170038],\n\t\t['Sakamaki', 21.2966728, -157.8172046],\n\t\t['EXTRA', 21.3003437, -157.8183039]\n\t];\n\n\tfor (var i = 0; i < buildings.length; i++) {\n\t\tvar building = buildings[i];\n\t\tvar marker = new google.maps.Marker({\n\t\t\tposition: { lat: building[1], lng: building[2] },\n\t\t\tmap: map,\n\t\t\ttitle: building[0]\n\t\t});\n\t\tattachMessage(marker, building[0] + \" Waste: 420.69\")\n\t}\n}",
"function setMarkersGE() {\n markers =[\n ['Nukriani', 41.6091781,45.8947416],\n ['Kazbegi', 42.657029,44.6308047],\n ];\n \n }",
"function setCityLocs() {\n $.each(cities, function(key, value){\n var top = this.top,\n left = this.left,\n width = '1600',\n height = '824';\n value.topPos = ( $('#map').height() * (top / height) );\n value.leftPos = ( $('#map').width() * (left / width) );\n /* temp fn adding pins to help add cities\n var city = $('<div class=\"city-' + key + '\"></div>');\n $('#map-box').append(city);\n $(city).css({\n top : value.topPos,\n left : value.leftPos\n })\n */\n });\n }",
"function initMarkers() {\n\tmodel.museumsData.forEach(function(museum, id) {\n \tvar position = museum.location;\n \tvar title = museum.name;\n \tvar favStatus = viewModel.getMuseum(id).fav();\n \tvar icon, icons;\n\n \tif (storageAvailable && favStatus) {\n \t\ticon = markerIcons.fav.def;\n \t\ticons = markerIcons.fav;\n \t} else {\n \t\ticon = markerIcons.def.def;\n \t\ticons = markerIcons.def;\n \t}\n\n \tvar marker = new google.maps.Marker({\n \tposition: position,\n \ttitle: title,\n \tanimation: google.maps.Animation.DROP,\n \t// storing index is useful for identifying individually passed\n \t// marker objects and their corresponding Museum objects\n \tid: id,\n \ticon: icon,\n \t// used to update and revert icon appearance when `selectMarker`\n \t// and `deselectMarker` are called\n \ticons: icons\n \t});\n\n \t// set marker click functionality\n \tmarker.addListener('click', function() {\n \tselectMarker(this);\n \t});\n\n \t// add marker to `markers`\n \tmarkers.push(marker);\n\t});\n\n\t// for adjusting viewport to contain all visible markers\n\tbounds = new google.maps.LatLngBounds();\n\n markers.forEach(function(marker) {\n \t// add marker to map (make visible)\n\t\tmarker.setMap(map);\n\t\tbounds.extend(marker.position);\n\t});\n\n\t// adjust viewport bounds\n\tmap.fitBounds(bounds);\n}",
"function setMarkers(parkObjects) {\n for (var i = 0; i < parkObjects.length; i++) {\n\n var infowindow = [];\n var marker = [];\n\n var $infoWindowContent = $([\n '<div class=\"infoWindowContent\">',\n '<p><b>' + parkObjects[i].name + '</b></p>',\n '<p>' + parkObjects[i].streetNumber + \" \" + parkObjects[i].streetName + '</p>',\n '<p><a class=\"btn btn-dark\" href=\"#/park/' + parkObjects[i].name + '\">' + \"View this park!\" +'</a></p>',\n '<button class=\"btn btn-dark routeHere\">Route to here</button>',\n '</div>'\n ].join(''));\n $infoWindowContent.find(\".routeHere\").on('click', function() {\n calcRoute();\n });\n\n infowindow[i] = new google.maps.InfoWindow();\n infowindow[i].setContent($infoWindowContent.get(0));\n\n marker[i] = new google.maps.Marker({\n\n map: $scope.mymap,\n animation: google.maps.Animation.DROP,\n position: new google.maps.LatLng(parkObjects[i].lat, parkObjects[i].lon),\n title: parkObjects[i].name\n });\n\n google.maps.event.addListener(marker[i], \"click\", function () {\n latitude = this.position.lat();\n longitude = this.position.lng();\n }); //end addListener\n\n google.maps.event.addListener(marker[i], 'click', makeInfoWindow($scope.mymap, infowindow[i], marker[i]));\n markersArray.push(marker[i]);\n }\n }",
"function setMarkersTUR() {\n markers =[\n ['Istambul', 41.0055005,28.7319924],\n ['Ankara', 39.9035557,32.62268],\n ];\n \n }",
"function initMarkers() {\n for (var i = 0; i < locations().length; i++) {\n addMarkerWithAnimations(locations()[i],i * 100, i);\n\n }\n}",
"function placeMarkers() {\n\tfor (let i = 0; i < markers.length; i++) {\n\t\tmarkers[i].setMap(map);\n\t}\n\tmarkerEvents();\n}",
"function initialize() {\n indexOfMarket = -1\n geocoder = new google.maps.Geocoder();\n var mapOptions = {\n zoom: 14\n };\n map = new google.maps.Map(\n gId('map-canvas'),\n mapOptions);\n google.maps.event.addListener(map, 'click', function(event) {\n placeMarker(event.latLng);\n });\n\n // put markers if blocks has coordinates\n var blocks = document.getElementsByClassName(\"block_story\");\n for (i = 0; i < blocks.length; i++) {\n if (blocks[i].getAttribute(\"data-lng\")) {\n lng = +blocks[i].getAttribute(\"data-lng\")\n lat = +blocks[i].getAttribute(\"data-lat\")\n markerLocation = new google.maps.LatLng(lat, lng)\n indexOfMarket = i;\n placeMarker(markerLocation)\n indexOfMarket = -1;\n }\n }\n if (Markers.length === 0) {\n centerOnCurrPos(map); // Set centers map on current position or L'viv city center.\n } else {\n setBounds(map, Markers); // Sets the map zoom so that all the markers are visible.\n }\n addDrawingManager(map);\n}",
"function setMarkersUKR() {\n markers =[\n ['Crimea', 45.3042776,33.4419001],\n ['Kyiv', 50.4021368,30.2525089],\n ];\n \n }",
"function initMarkers() {\n\n var numLocs = locations.length;\n var markerTimer = function(i) {\n setTimeout(function() {\n createMarker(locations[i], i);\n }, 300 * i);\n };\n /* Creation of markers delayed by an appropriate interval so that\n * that Geocoder query rates are not exceeded\n */\n for (var i = 0; i < numLocs; i++) {\n markerTimer(i);\n }\n }",
"function CreatBarsMarkers(places) {\n for (let i = 0, place; place = places[i]; i++) {\n marker = new google.maps.Marker({\n map: map,\n icon: marker_bars_pos,\n title: place.name,\n animation: google.maps.Animation.DROP,\n position: place.geometry.location\n });\n google.maps.event.addListener(marker, 'click', function() {\n infowindow.setContent(place.name);\n infowindow.open(map, this);\n });\n bounds.extend(place.geometry.location);\n }\n /**\n * Fit map to bounds and center map including my location to bounds\n */\n bounds.extend(myLocation);\n map.fitBounds(bounds);\n }",
"function showMarkers() {\n setAllMap(map);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
make a 'comment builder' style function, and punch these in to the showsInfo array build the shows table based off of this, use the same stylings as the already existing table in the table builder, hard code the DATE, LOCATION, etc. headers change the classes given to the tds to IDs, then just use classlist.add to add the appropriate styles then, forEach through our array to create the table // Structures comments on bio page base on preexisting objects, new inputs | function buildTable(tableInput) {
// create date descriptor
const dateDescriptor = document.createElement('td');
dateDescriptor.classList.add('shows__descriptor');
dateDescriptor.innerText = "DATE";
// create date td
const showDate = document.createElement('td');
showDate.classList.add('shows__date');
showDate.innerHTML = tableInput.date;
// create venue descriptor
const venueDescriptor = document.createElement('td');
venueDescriptor.classList.add('shows__descriptor');
venueDescriptor.innerText = "VENUE";
// create venue td
const showVenue = document.createElement('td');
showVenue.classList.add('shows__details');
showVenue.innerHTML = tableInput.place;
// create location descriptor
const locationDescriptor = document.createElement('td');
locationDescriptor.classList.add('shows__descriptor');
locationDescriptor.innerText = "LOCATION";
// create location td
const showLocation = document.createElement('td');
showLocation.classList.add('shows__details');
showLocation.innerHTML = tableInput.location;
// create the button, append here
const showsButton = document.createElement('button');
showsButton.classList.add('shows__button');
showsButton.innerText = "BUY TICKETS";
// append the button into the shows__tickets div, then append
// to tableBuilder
const showsTickets = document.createElement('td');
showsTickets.classList.add('shows__tickets');
showsTickets.appendChild(showsButton);
// create shows__section tr
const showsSection = document.createElement('tr');
showsSection.classList.add('shows__section');
showsSection.appendChild(dateDescriptor);
showsSection.appendChild(showDate);
showsSection.appendChild(venueDescriptor);
showsSection.appendChild(showVenue);
showsSection.appendChild(locationDescriptor);
showsSection.appendChild(showLocation);
showsSection.appendChild(showsTickets);
return showsSection;
} | [
"function drawNotesTable(tableID,limitationSelectName,limitationNoteName,majorTextArea,majorRecommendationID,minorTextArea,minorRecommendationID,generalNote)\n{\n var body = [];\n var table = document.getElementById(tableID);\n var majorRecommendation = document.getElementById(majorRecommendationID).value;\n\n var minorRecommendation = document.getElementById(minorRecommendationID).value;\n var rowCount = table.rows.length;\n var limitationNo = rowCount - 9;\n //console.log(limitationNo);\n //1. get the first row\n var a = [\n {\n text:'Access Limitation',\n style:'tableHeader'\n //alignment:'center'\n\n },\n {\n text:'Access Notes',\n style:'tableHeader'\n //alignment:'center'\n }\n ];\n body.push(a);\n\n\n //2. get the limitation data\n for (var i=0;i<limitationNo;i++)\n {\n //console.log(i);\n var selectID = limitationSelectName + i;\n var selectedValue = document.getElementById(selectID).value;\n //console.log(selectedValue);\n var noteID = limitationNoteName + i;\n var note = document.getElementById(noteID).value;\n var b = [\n {\n text:selectedValue,\n style:'tableText'\n },\n {\n text:note,\n style:'tableText'\n }\n ];\n body.push(b);\n\n }\n\n //3.get the third header--> row major founds\n var c = [\n {\n text:'Major and Serious Structural Defects Found:',\n style:'tableHeader',\n colSpan: 2\n }\n\n ];\n body.push(c);\n\n var d = [\n {\n text:splitTextArea(getTextArea(majorTextArea)),\n style:'tableText',\n colSpan:2\n }\n ];\n body.push(d);\n\n //check major Recommendation value\n if (majorRecommendation.trim() === \"\")\n {\n majorRecommendation = \"NA\"\n }\n\n var e = [\n {\n text:\"Professional & Trade Recommendations:\",\n style:'tableHeader',\n color: 'black'\n\n },\n {\n text:majorRecommendation,\n style:'tableText'\n }\n ];\n body.push(e);\n\n\n\n var f = [\n {\n text:'Maintenance Items and Minor Defects Found:',\n style:'tableHeader',\n colSpan:2\n }\n ];\n body.push(f);\n\n var g = [\n {\n text:splitTextArea(getTextArea(minorTextArea)),\n style:'tableText',\n colSpan:2\n }\n ];\n body.push(g);\n\n\n //check minor Recommendation value\n if (minorRecommendation.trim() === \"\")\n {\n minorRecommendation = \"NA\"\n }\n var h = [\n {\n text:\"Professional & Trade Recommendations:\",\n style:'tableHeader',\n color: 'black'\n\n },\n {\n text:minorRecommendation,\n style:'tableText'\n }\n ];\n\n body.push(h);\n\n var i =[\n {\n text:'General Notes',\n style:'tableHeader',\n colSpan:2\n }\n ];\n body.push(i);\n\n var j = [\n {\n colSpan:2,\n text:splitTextArea(getTextArea(generalNote)),\n style:'tableText'\n }\n ];\n body.push(j);\n\n\n\n\n\n\n\n\n //final the table\n PDFtable = {\n table: {\n widths: ['*', '*'],\n body: body\n }\n };\n\n return PDFtable;\n}",
"function buildComments() {\n\n for (let i = 0; i < commentAry.length; i++) {\n displayComment(commentAry[i]);\n }\n\n likeButtonListeners();\n deleteButtonListeners();\n}",
"function generateInfoWindowHTML(restauraunt){\n var col = generateColorFromSafety(restauraunt.CrimeCost);\n if(!('Date' in restauraunt)){\n infoWindow.setContent(\"<div><h1>\"+restauraunt.Name +\"</h1>\"+\n '<div class=\"address\">'+restauraunt.Address+'</div>'+\n '<div class=\"safetyRating\">'+\n '<span class=\"safetyInfo\" style=\"background-color:'+col+'\"></span>'+\n 'Danger Rating: '+restauraunt.CrimeCost+'</div>');\n loadMoreInfoWindowHTML(restauraunt.Name, restauraunt.Address);\n }else{\n console.log(restauraunt.Crimes);\n infoWindow.setContent(\"<div><h1>\"+restauraunt.Name +\"</h1>\"+\n '<div><i>'+restauraunt.Description +', EST '+restauraunt.Date+'</i></div>'+\n '<div class=\"address\">'+restauraunt.Address+'</div>'+\n '<div class=\"safetyRating\">'+\n '<span class=\"safetyInfo\" style=\"background-color:'+col+'\"></span>'+\n 'Danger Rating: '+restauraunt.CrimeCost+'</div><hr />'+\n processCrimes(restauraunt.CrimeCost, restauraunt.Crimes));\n } \n}",
"function populateShowInfoWrap(shows) {\n\tvar divToPopulate = document.getElementById('showInfo');\n\tfor (showNum in shows) {\n\t\tvar wrap = document.createElement(\"div\");\n\t\twrap.className = \"showDiv\";\n\t\t\n\t\tvar col1 = document.createElement(\"div\");\n\t\tcol1.className = \"showCol\";\n\t\t\n\t\tvar col2 = document.createElement(\"div\");\n\t\tcol2.className = \"showCol\";\n\t\t\n\t\tvar name = document.createElement(\"p\");\n\t\tname.innerHTML = shows[showNum].name;\n\t\tname.className = \"show-name\";\n\t\t\n//\t\tvar description = document.createElement(\"p\");\n//\t\tdescription.innerHTML = shows[showNum].description;\n//\t\tdescription.className = \"show-description\";\n\t\t\n\t\t\n\t\tvar genres = document.createElement(\"p\");\n\t\tvar genresVal = shows[showNum].genres;\n\t\tgenres.innerHTML = genresVal.substring(1, genresVal.length - 1);\n\t\tgenres.className = \"show-genres\";\n\t\t\n\t\tvar image = document.createElement(\"IMG\");\n\t\timage.setAttribute(\"src\", shows[showNum].image);\n\t\timage.setAttribute(\"alt\", shows[showNum].name);\n\t\timage.className = \"show-image\";\n\t\t\n\t\tvar scheduleBtn = document.createElement('button');\n\t\t$(scheduleBtn).text('Watch together!');\n\t\t\n\t\tcol1.appendChild(image);\n\t\tcol1.appendChild(scheduleBtn);\n\t\twrap.appendChild(col1);\n\t\t\n\t\tcol2.appendChild(name);\n//\t\tcol2.appendChild(description);\n\t\tcol2.appendChild(genres);\n\t\twrap.appendChild(col2);\n\t\t\n\t\tdivToPopulate.appendChild(wrap);\n\t}\n}",
"function buildTable(meta_id, ethnicity, gender, age, location, bbtype, wfreq) {\n var table = d3.select(\"#sample-metadata\");\n d3.select(\"#sample-metadata\").html(\"\");\n table.append(\"tbody\").text(\"ID: \" + meta_id);\n if (ethnicity !== null) {\n table.append(\"tbody\").text(\"Ethnicity: \" + ethnicity);\n };\n if (gender !== null) {\n table.append(\"tbody\").text(\"Gender: \" + gender);\n };\n if (age !== null) {\n table.append(\"tbody\").text(\"Age: \" + age);\n };\n if (location !== null) {\n table.append(\"tbody\").text(\"Location: \" + location);\n };\n if (bbtype !== null) {\n table.append(\"tbody\").text(\"bbtype: \" + bbtype);\n };\n if (wfreq !== null) {\n table.append(\"tbody\").text(\"wfreq: \" + wfreq);\n };\n\n }",
"function noteMaker() {\r\n let date = new Date();\r\n let newdate = formatDate(date, 'DD.MM.YY hh:mm')//formats date\r\n color = colors[Math.floor(Math.random()*colors.length)]; //gets random color\r\n let noteObj = createMaketDiv(newdate) //creates html object of a note's layout\r\n\r\n Notes.forEach(note => {\r\n moveCol(note, 'r'); //moves each note into the next column to make space for a new one\r\n })\r\n\r\n id++ //increases id\r\n clearHTML(); //removes an old display\r\n drawNotes(); //draws a new one\r\n col1.insertAdjacentHTML('afterbegin', noteObj); //inserts the layout into the first column\r\n}",
"function tableBuilder(pollChoices, tableArray2, sSize, graphData, graphLabels, isFake, state, isFree, isReview)\n{ \n \n\t////CONSOLE.LOG(tableArray2);\n\tvar rowCounter = 0;\n\tvar cellCounter = 0;\n\tvar graphQuestions = [];\n\tvar h = 0;\n\n\tvar table = document.getElementById(\"pollTable\");\n\tvar tableHead = document.getElementById(\"tableHead\");\n\tvar headRow = tableHead.insertRow(0);\n\t\n\t\t//console.log(\"in\");\n\t//Makes the table headers based on the chose questions\n\tfor(var h = 0; h < pollChoices.length; h++)\n\t{\n\n\t\tif(pollChoices[h] != null)\n\t\t{\n\t\t\tif(h==0)\n\t\t\t{\n\t\t\t\tgraphQuestions.push(\"major\");\n\t\t\t\t//graphQuestions.push(\"class\");\n\t\t\t\tgraphQuestions.push(\"group\");\n\t\t\t}\n\t\t\tswitch(pollChoices[h])\n\t\t\t{\n\t\t\t\tcase \"issFav\":\n\t\t\t\t\tvar cell = headRow.insertCell();\n\t\t\t\t\tcell.innerHTML = globals.tableHeaders[0];\n\t\t\t\t\tgraphQuestions.push(\"issFav\");\n\t\t\t\tbreak;\n \n\t\t\t\tcase \"issOpp\":\n\t\t\t\t\t\tvar cell = headRow.insertCell();\n\t\t\t\t\t\tcell.innerHTML = globals.tableHeaders[1];\n\t\t\t\t\t\tgraphQuestions.push(\"issOpp\");\n\t\t\t\tbreak;\n\n\t\t\t\tcase \"candFav\":\n\t\t\t\t\t\tvar cell = headRow.insertCell();\n\t\t\t\t\t\tcell.innerHTML = globals.tableHeaders[2];\n\t\t\t\t\t\tgraphQuestions.push(\"candFav\");\n\t\t\t\tbreak;\n\n\t\t\t\tcase \"candOpp\":\n\t\t\t\t\t\tvar cell = headRow.insertCell();\n\t\t\t\t\t\tcell.innerHTML = globals.tableHeaders[3];\n\t\t\t\t\t\tgraphQuestions.push(\"candOpp\");\n\t\t\t\tbreak;\n\n\t\t\t\tcase \"fame\":\n\t\t\t\t\t\tvar cell = headRow.insertCell();\n\t\t\t\t\t\tcell.innerHTML = globals.tableHeaders[7];\n\t\t\t\t\t\tgraphQuestions.push(\"fame\");\n\t\t\t\tbreak;\n\n\t\t\t\tcase \"playTrust\":\n\t\t\t\t\t\tvar cell = headRow.insertCell();\n\t\t\t\t\t\tcell.innerHTML = globals.tableHeaders[8];\n\t\t\t\t\t\tgraphQuestions.push(\"playTrust\");\n\t\t\t\tbreak;\n\t\t\t}\n\n \n\t\t\tfor(var k = 0;k<globals.positions.length;k++)\n\t\t\t{\n\n\t\t\t\tif(pollChoices[h] == \"issue\" + globals.positionsLower[k])\n\t\t\t\t{\n switch(pollChoices[h])\n\t\t\t\t\t{\n\t\t\t\t\t\tcase \"issuetuition\":\n\t\t\t\t\t\t\tvar cell = headRow.insertCell();\n\t\t\t\t\t\t\tvar posInfo = globals.tableHeaders[9] + globals.positions[0];\n\t\t\t\t\t\t\tcell.innerHTML = posInfo;\n\t\t\t\t\t\t\tgraphQuestions.push(\"issuetuition\");\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase \"issuebudget\":\n\t\t\t\t\t\t\tvar cell = headRow.insertCell();\n\t\t\t\t\t\t\tvar posInfo = globals.tableHeaders[9] + globals.positions[1];\n\t\t\t\t\t\t\tcell.innerHTML = posInfo;\n\t\t\t\t\t\t\tgraphQuestions.push(\"issuebudget\");\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase \"issuefunctions\":\n\t\t\t\t\t\t\tvar cell = headRow.insertCell();\n\t\t\t\t\t\t\tvar posInfo = globals.tableHeaders[9] + globals.positions[2];\n\t\t\t\t\t\t\tcell.innerHTML = posInfo;\n\t\t\t\t\t\t\tgraphQuestions.push(\"issuefunctions\");\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase \"issuemedical\":\n\t\t\t\t\t\t\tvar cell = headRow.insertCell();\n\t\t\t\t\t\t\tvar posInfo = globals.tableHeaders[9] + globals.positions[3];\n\t\t\t\t\t\t\tcell.innerHTML = posInfo;\n\t\t\t\t\t\t\tgraphQuestions.push(\"issuemedical\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor(var k = 1;k<globals.candidates.length;k++)\n\t\t\t{\n\t\t\t\tif(pollChoices[h] == \"candFame\" + globals.candidates[k].name)\n\t\t\t\t{\n\t\t\t\t\t\tvar cell = headRow.insertCell();\n\t\t\t\t\t\tvar candInfo = globals.tableHeaders[10] + globals.candidates[k].name;\n\t\t\t\t\t\tcell.innerHTML = candInfo;\n\t\t\t\t\t\tgraphQuestions.push(\"candFame\" + globals.candidates[k].name);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor(var k = 1;k<globals.candidates.length;k++)\n\t\t\t{\n\t\t\t\tif(pollChoices[h] == \"candTrust\" + globals.candidates[k].name)\n\t\t\t\t{\n\t\t\t\t\t//////CONSOLE.LOG(h);\n\t\t\t\t\t\tvar cell = headRow.insertCell();\n\t\t\t\t\t\tvar candInfo = globals.tableHeaders[11] + globals.candidates[k].name;\n\t\t\t\t\t\tcell.innerHTML = candInfo;\n\t\t\t\t\t\tgraphQuestions.push(\"candTrust\" + globals.candidates[k].name);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(h==pollChoices.length-1)\n\t\t\t{\n\t\t\t\tvar cell = headRow.insertCell(0);\n\t\t\t\tcell.innerHTML = globals.tableHeaders[4];\n\n\t\t\t\t//var cell = headRow.insertCell(1);\n\t\t\t\t//cell.innerHTML = globals.tableHeaders[5];\n\n\t\t\t\tvar cell = headRow.insertCell(1);\n\t\t\t\tcell.innerHTML = globals.tableHeaders[6];\n\t\t\t}\n\t\t}\n\t}\n \n //Creates the contents of the table based on the results of PollCalc\n\tfor(var h = 0; h<sSize; h++)\n\t{\n //Inserts a row into the table for each member of the sample\n\t\trow = table.insertRow(h);\n\n\n\t\tfor(var i = 0; i < pollChoices.length+1;i++)\n\t\t{\n\t\t\tif(pollChoices[i] != null)\n\t\t\t{\n\t\t\t\tswitch(pollChoices[i])\n\t\t\t\t{\n \n\t\t\t\t\tcase \"issFav\":\n\t\t\t\t\t\t\tvar cell = row.insertCell();\n\t\t\t\t\t\t\tcell.innerHTML = tableArray2[0][h];\n\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"issOpp\":\n\t\t\t\t\t\t\t\tvar cell = row.insertCell();\n\t\t\t\t\t\t\t\tcell.innerHTML = tableArray2[1][h];\n\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"candFav\":\n\t\t\t\t\t\t\t\tvar cell = row.insertCell();\n\t\t\t\t\t\t\t\tcell.innerHTML = tableArray2[2][h];\n\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"candOpp\":\n\t\t\t\t\t\t\t\tvar cell = row.insertCell();\n\t\t\t\t\t\t\t\tcell.innerHTML = tableArray2[3][h];\n\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"fame\":\n\t\t\t\t\t\t\t\tvar cell = row.insertCell();\n\t\t\t\t\t\t\t\tif(parseFloat(tableArray2[7][h]).toFixed(2) <= 0.2)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Candidate Unknown\";\n\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[7][h]).toFixed(2);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse if(parseFloat(tableArray2[7][h]).toFixed(2)>0.20 && parseFloat(tableArray2[7][h]).toFixed(2)<0.41)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Slightly Aware of Candidate\";\n\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[7][h]).toFixed(2);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse if(parseFloat(tableArray2[7][h]).toFixed(2)>0.40 && parseFloat(tableArray2[7][h]).toFixed(2)<0.61)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Aware of Candidate\";\n\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[7][h]).toFixed(2);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse if(parseFloat(tableArray2[7][h]).toFixed(2)>0.60 && parseFloat(tableArray2[7][h]).toFixed(2)<0.81)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Very Aware of Candidate\";\n\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[7][h]).toFixed(2);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Candidate Known\";\n\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[7][h]).toFixed(2);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"playTrust\":\n\t\t\t\t\t\t\t\tvar cell = row.insertCell();\n\t\t\t\t\t\t\t\tif(parseFloat(tableArray2[8][h]).toFixed(2) <= 0.2)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Very Trustworthy\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[8][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if(parseFloat(tableArray2[8][h]).toFixed(2)>0.2 && parseFloat(tableArray2[8][h]).toFixed(2)<0.41)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Fairly Trustworthy\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[8][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if(parseFloat(tableArray2[8][h]).toFixed(2)>0.4 && parseFloat(tableArray2[8][h]).toFixed(2)<0.61)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Sort Of Trustworthy\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[8][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if(parseFloat(tableArray2[8][h]).toFixed(2)>0.6 && parseFloat(tableArray2[8][h]).toFixed(2)<0.81)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Untrustworthy\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[8][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Very Untrustworthy\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[8][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tfor(var k = 0;k<globals.positions.length;k++)\n\t\t\t\t{\n\t\t\t\t\tif(pollChoices[i] == \"issue\" + globals.positionsLower[k])\n\t\t\t\t\t{\n let issueOpinion;\n\t\t\t\t\t\tswitch(pollChoices[i])\n\t\t\t\t\t\t{\n \n\t\t\t\t\t\t\tcase \"issuetuition\":\n\t\t\t\t\t\t\t\t\tvar cell = row.insertCell();\n\t\t\t\t\t\t\t\t\tif(tableArray2[9][h] <= -3)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Issue Hated\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[9][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if(tableArray2[9][h]>-3 && tableArray2[9][h]<-1)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Issue Disliked\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[9][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if(tableArray2[9][h]>-1 && tableArray2[9][h]<1)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Issue Neutral\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[9][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if(tableArray2[9][h]>1 && tableArray2[9][h]<3)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Issue Liked\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[9][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Issue Loved\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[9][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tcase \"issuebudget\":\n\t\t\t\t\t\t\t\t\tvar cell = row.insertCell();\n\t\t\t\t\t\t\t\t\tif(tableArray2[10][h] <= -3)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Issue Hated\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[9][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if(tableArray2[10][h]>-3 && tableArray2[10][h]<-1)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Issue Disliked\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[9][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if(tableArray2[10][h]>-1 && tableArray2[10][h]<1)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Issue Neutral\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[9][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if(tableArray2[10][h]>1 && tableArray2[10][h]<3)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Issue Liked\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[9][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Issue Loved\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[9][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tcase \"issuefunctions\":\n\t\t\t\t\t\t\t\t\tvar cell = row.insertCell();\n\t\t\t\t\t\t\t\t\tif(tableArray2[12][h] <= -3)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Issue Hated\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[9][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if(tableArray2[12][h]>-3 && tableArray2[12][h]<-1)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Issue Disliked\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[9][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if(tableArray2[12][h]>-1 && tableArray2[12][h]<1)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Issue Neutral\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[9][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if(tableArray2[12][h]>1 && tableArray2[12][h]<3)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Issue Liked\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[9][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Issue Loved\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[9][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tcase \"issuemedical\":\n var cell = row.insertCell();\n\t\t\t\t\t\t\t\t\tif(tableArray2[13][h] <= -3)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Issue Hated\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[9][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if(tableArray2[13][h]>-3 && tableArray2[13][h]<-1)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Issue Disliked\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[9][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if(tableArray2[13][h]>-1 && tableArray2[13][h]<1)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Issue Neutral\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[9][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if(tableArray2[13][h]>1 && tableArray2[13][h]<3)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Issue Liked\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[9][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Issue Loved\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[9][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\n\t\t\t\tcanCounter = 14;\n\t\t\t\tfor(var k = 1;k<globals.candidates.length;k++)\n\t\t\t\t{\n\n\t\t\t\t\tif(pollChoices[i] == \"candFame\" + globals.candidates[k].name)\n\t\t\t\t\t{\n\n\t\t\t\t\t\t\t\tvar cell = row.insertCell();\n\t\t\t\t\t\t\t\tvar counter = canCounter;\n\t\t\t\t\t\t\t\t\tif(parseFloat(tableArray2[counter][h]).toFixed(2) <= 0.2)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Candidate Unknown\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[counter][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if(parseFloat(tableArray2[counter][h]).toFixed(2)>0.2 && parseFloat(tableArray2[counter][h]).toFixed(2)<0.41)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Slightly Aware of Candidate\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[counter][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if(parseFloat(tableArray2[counter][h]).toFixed(2)>0.4 && parseFloat(tableArray2[counter][h]).toFixed(2)<0.61)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Aware of Candidate\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[counter][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if(parseFloat(tableArray2[counter][h]).toFixed(2)>0.6 && parseFloat(tableArray2[counter][h]).toFixed(2)<0.81)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Very Aware of Candidate\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[counter][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Candidate Known\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[counter][h]).toFixed(2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\tcanCounter++;\n\t\t\t\t}\n\t\t\t\tfor(var k = 1;k<globals.candidates.length;k++)\n\t\t\t\t{\n\t\t\t\t\tif(pollChoices[i] == \"candTrust\" + globals.candidates[k].name)\n\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvar cell = row.insertCell();\n\t\t\t\t\t\t\t\tvar counter = canCounter;\n\t\t\t\t\t\t\t\tif(parseFloat(tableArray2[counter][h]).toFixed(2) <= 0.2)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Very Trustworthy\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[counter][h]).toFixed(2);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse if(parseFloat(tableArray2[counter][h]).toFixed(2)>0.2 && parseFloat(tableArray2[counter][h]).toFixed(2)<0.41)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Fairly Trustworthy\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[counter][h]).toFixed(2);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse if(parseFloat(tableArray2[counter][h]).toFixed(2)>0.4 && parseFloat(tableArray2[counter][h]).toFixed(2)<0.61)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Sort Of Trustworthy\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[counter][h]).toFixed(2);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse if(parseFloat(tableArray2[counter][h]).toFixed(2)>0.6 && parseFloat(tableArray2[counter][h]).toFixed(2)<0.81)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Untrustworthy\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[counter][h]).toFixed(2);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcell.innerHTML = \"Very Untrustworthy\";\n\t\t\t\t\t\t\t\t\t\t//cell.innerHTML += \"Score: \" + parseFloat(tableArray2[counter][h]).toFixed(2);\n\t\t\t\t\t\t\t\t}\t\t\n\t\t\t\t\t}\n\n\t\t\t\t\tcanCounter++;\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n \n\t\tvar cell = row.insertCell(0);\n\t\tcell.innerHTML = capitalStr(tableArray2[4][h]);\n\n\t\t//var cell = row.insertCell(1);\n\t\t//cell.innerHTML = tableArray2[5][h];\n\n\t\tvar cell = row.insertCell(1);\n\t\tcell.innerHTML = capitalStr(tableArray2[6][h]);\n\t}\n\t\n\t\n\tsorttable.makeSortable(document.getElementById('tab'));\n\tdocument.getElementById(\"next\").innerHTML += \"<div id = 'filterArea'></div>\"\n\tdocument.getElementById(\"centerDisplay\").innerHTML += \"<div id = 'barChartDiv' style = 'display:block'></div>\";\n\tdocument.getElementById(\"centerDisplay\").innerHTML += \"<div id = 'pieChartDiv' style = 'display:none'></div>\";\n \n \n //Only display the filters if this isn't fake data\n //Quick fix for a bug when changing filter options\n if(!isFake){\n document.getElementById(\"centerDisplay\").innerHTML += \"<div id = 'chartFilters' style = 'display:block'> Filters: </div>\";\n document.getElementById(\"chartFilters\").innerHTML += \"<br>Major: <select class = 'graphFilters' id = 'majorSelect'></select> Social Group: <select class = 'graphFilters' id = 'groupSelect'></select>\";\n\n var noneOp = document.createElement(\"option\");\n noneOp.text = \"None\";\n noneOp.value = \"None\";\n var noneOp2 = document.createElement(\"option\");\n noneOp2.text = \"None\";\n noneOp2.value = \"None\";\n\n var majors = document.getElementById('majorSelect');\n majors.options.add(noneOp2);\n for(var i =0; i<globals.majorList.length; i++)\n {\n var newOp = document.createElement(\"option\");\n newOp.text = capitalStr(globals.majorList[i]);\n newOp.value = globals.majorList[i];\n majors.options.add(newOp);\n }\n\n var groups = document.getElementById('groupSelect');\n groups.options.add(noneOp);\n for(var i =0; i<globals.groupList.length; i++)\n {\n var newOp = document.createElement(\"option\");\n newOp.text = capitalStr(globals.groupList[i]);\n newOp.value = globals.groupList[i];\n groups.options.add(newOp);\n }\n }\n\t\n\tdocument.getElementById(\"next\").innerHTML += \"<button id = 'barButton' class='otherBtn' onclick = 'changeDataDisplay(2,\"+isFake+\")' style = 'display:none'>Show Bar Graphs</button>\";\n\tdocument.getElementById(\"next\").innerHTML += \"<button id = 'pieButton' class='otherBtn' onclick = 'changeDataDisplay(3,\"+isFake+\")'>Show Pie Graphs</button>\";\n\tdocument.getElementById(\"next\").innerHTML += \"<button id = 'dataButton' class='otherBtn' onclick = 'changeDataDisplay(1,\"+isFake+\")'>Show Data Table</button><br>\";\n\tfor (var x = 0; x < globals.groupList.length; x++){\n\t\tdocument.getElementById('filterArea').innerHTML += \"<input type = 'checkbox' class = 'filterChecklist' rel = '\"+ globals.groupList[x] +\"'> \"+ globals.groupList[x] +\" \";\n\t}\n\tdocument.getElementById('filterArea').innerHTML +='<br>'\n\tdocument.getElementById('filterArea').innerHTML +='<br>'\n\tfor (var x = 0; x < globals.groupList.length; x++){\n\t\tdocument.getElementById('filterArea').innerHTML += \"<input type = 'checkbox' class = 'filterChecklist' rel = '\"+ globals.majorList[x] +\"'> \"+ globals.majorList[x] +\" \";\n\t}\n\tdocument.getElementById('filterArea').innerHTML +='<br>'\n\tdocument.getElementById('filterArea').style.display = \"none\";\n\n\tmakeGraphs(graphData, graphQuestions,graphLabels);\n\t\t//if(state == POLL_STATES.FIRST)\n\t\t//{\n\t\t//\tglobals.candidates.splice(0,1);\n\t\t//}\n\tdocument.getElementById('table').style.display = 'none';\n\tif (state == POLL_STATES.TUTORIAL){\n document.getElementById('back').innerHTML += \"<button onclick = 'drawPoll(\"+state+\",false, true)'>Back to Start</button>\" ;\n\t}\n //If the data isn't fake and it isn't a past poll report\n\tif(!isFake && !isReview)\n\t{\n console.log(\"pushing\");\n\t\tglobals.pastPollResults.push(tableArray2);\n\t\tglobals.pastPollSizes.push(sSize);\n\t\tglobals.pastPollChoices.push(pollChoices);\n\t\tglobals.pastGraphData.push(graphData);\n\t\tglobals.pastGraphLabels.push(graphLabels);\n\t\tglobals.tableArrays = [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [ ], [ ], [ ], [ ], [ ], [ ], [ ], [ ], [ ], [ ], [ ], [ ], [ ], [ ], [ ], [ ], [ ], [ ], [ ], [ ], [ ], [ ]];\n\t\tif(!isFree)\n\t\t\tpollTime(sSize, pollChoices);\n\t\tglobals.currentPoll = (globals.pastPollResults.length - 1);\n\t}\n else if(isFake){\n //Result the fake data back to normal\n globals.candidates = globals.currentCandidateArrayHolder;\n }\n\n}",
"function generateReviewTable() {\n\t\td3.select(\"#table2\")\n\t\t\t\t.selectAll(\"tr\").remove();\n\n\t\tvar rows = d3.select(\"#table2\")\n\t\t\t\t\t.selectAll(\"tr\")\n\t\t\t\t\t.data(getReviewsForCurrentCleaner())\n\t\t\t\t\t.enter().append(\"tr\")\n\t\t\t\t\t\t.selectAll(\"td\")\n\t\t\t\t\t\t.data(function(row, i) {\n\t\t\t\t\t\t\tvar cleaningDate = new Date(Date.parse(row[\"Cleaning Time\"]));\n\t\t\t\t\t\t\tvar options = { \n\t\t\t\t\t\t\t\tyear: '2-digit', \n\t\t\t\t\t\t\t\tmonth: 'short', \n\t\t\t\t\t\t\t\tday: 'numeric', \n\t\t\t\t\t\t\t\thour: 'numeric', \n\t\t\t\t\t\t\t\tminute: 'numeric' };\n\t\t\t\t\t\t\tvar cleaningDateString = cleaningDate.toLocaleDateString(\"en-US\", options);\n\t\t\t\t\t\t\treturn [row[\"Cleanliness\"],\n\t\t\t\t\t\t\t\t\tcleaningDateString, \n\t\t\t\t\t\t\t\t\trow[\"Listing\"],\n\t\t\t\t\t\t\t\t\trow[\"Cleanliness Comments\"]];\n\t\t\t\t\t\t}).enter().append(\"td\")\n\t\t\t\t\t\t\t.text(function(d) {return d;})\n\n\t\t\n\t\t// Reset collapsible container height to accomodate new data\n\t\tvar coll = document.getElementsByClassName(\"collapsible\");\n\t\tfor (var i = 0; i < coll.length; i++) {\n\t\t var content = coll[i].nextElementSibling;\n\t\t if (content.style.maxHeight){\n\t\t content.style.maxHeight = content.scrollHeight + \"px\";\n\t\t }\n\t\t}\n\t\t\n\t}",
"function load_bioinfo_table() {\n\n // Hide the application-specific columns\n var app_classes = {\n 'rnaseq': ['RNA-seq (total RNA)', 'RNA-seq (RiboZero)', 'RNA-seq (mRNA)', 'stranded RNA-seq (total RNA)', 'cDNA', 'stranded RNA-seq (RiboZero)'],\n 'exome': ['Exome capture'],\n 'customCap': ['Custom capture'],\n 'WGreseq': ['WG re-seq', 'WG re-seq (IGN)'],\n 'denovo': ['de novo', 'Mate-pair', 'Mate-pair (short insert)', 'Mate-pair (long insert)']\n };\n $('[class^=bioinfo-app-]').hide();\n\n return $.getJSON(bioinfo_api_url, function (data) {\n\n // Show the columns that we need\n // Hacky, sorry. Page doesn't update fast enough sometimes.\n setTimeout(function(){\n if($('#type').text() == 'Application'){\n $('.bioinfo-app-applications').show();\n }\n var thisapp = $('#application').text();\n $.each(app_classes, function(key, arr){\n if(arr.indexOf(thisapp) != -1){\n $('.bioinfo-app-'+key).show();\n }\n });\n }, 100);\n\n // Hide the loading row and build the real runs based on the template\n if(Object.keys(data).length > 0){\n $('#bioinfo-noruns').hide();\n } else {\n $('#bioinfo-noruns').html('<td colspan=\"26\" class=\"text-muted\">No runs found</td>');\n $('#bioinfo-show-history').hide();\n }\n\n // Build the history dump\n $.getJSON(bioinfo_api_url+'?history=true', function (data_dump) {\n $('#bioinfo-history-dump').text(JSON.stringify(data_dump, null, ' '));\n });\n\n // Build the table\n var templaterow = $('#bioinfo-template-row').attr('id', '').show().detach();\n $.each(data, function(key, vals){\n // Start by copying the template row\n var tr = templaterow.clone();\n\n // Flowcell and status\n var url_key = key.replace(/_.+_/g, '_');\n tr.find('th.bioinfo-status-runid samp').html('<a href=\"../flowcells/'+url_key+'\">'+key+'</a>');\n tr.find('td.bioinfo-status-runstate span').text(vals.status);\n var bsi = bioinfo_states.indexOf(vals.status);\n if(bsi != -1){\n tr.find('td.bioinfo-status-runstate span').removeClass('label-default').addClass(bioinfo_states_classes[bsi]);\n }\n\n // User and date\n try {\n tr.find('th.bioinfo-status-runid samp').after(' <span class=\"glyphicon glyphicon-info-sign\" data-toggle=\"tooltip\" title=\"Last updated by '+vals.user+'<br>'+formatDateTime(vals.timestamp, true)+'\"></span>');\n } catch(e){\n tr.find('th.bioinfo-status-runid samp').after(' <span class=\"glyphicon glyphicon-info-sign\" data-toggle=\"tooltip\" title=\"No last update information found\"></span>');\n }\n\n // UPPNEX id confirmed\n if(vals.uppnex_confirmed == 'true'){\n $('#uppnex_id_confirmed').attr('checked', true);\n } else if(vals.uppnex_confirmed == 'false'){\n $('#uppnex_id_confirmed').attr('checked', false);\n }\n\n // Set the values for the row\n tr.children('td').each(function(i){\n if(field_names[i] in vals){\n if($(this).hasClass('bioinfo-status-pfw')){\n var state = vals[field_names[i]];\n $(this).text(state);\n var si = bioinfo_texts.indexOf(state);\n if(si != -1){\n $(this).removeClass('unknown').addClass(bioinfo_classes[si]);\n }\n } else {\n if($(this).find('input').length > 0){\n $(this).find('input').val(vals[field_names[i]]);\n }\n }\n }\n });\n // Add to table\n $('.table-bioinfo-status').append(tr);\n });\n\n var forceDisabledState = false;\n // Disable everything if the project is closed\n if($('#project_status_alert').text() == 'Closed'){\n forceDisabledState = true;\n $('.bioinfo-savespan').html('<p class=\"text-muted\"><em>Project is closed - not editable</em></p>');\n }\n // Set rows as disabled if they're not ready yet\n var editable = 0;\n $('.table-bioinfo-status tr:has(td)').each(function(){\n editable += reset_editable($(this), forceDisabledState);\n });\n if(editable > 0){\n $('#bioinfo-status-saveButton').attr('disabled', false);\n }\n\n }).fail(function( jqxhr, textStatus, error ) {\n var numcols = 0; // I doubt that anyone will notice this. But I'm OCD.\n $(\".bioinfo-field-names th\").each(function(){ numcols += $(this).css('display') != 'none' ? 1 : 0; });\n $('#bioinfo-noruns').addClass('danger');\n $('#bioinfo-noruns td').attr('colspan', numcols).html(\"Error loading bioinfo analysis data: <code>\"+textStatus+\"</code>, <code>\"+error+'</code>');\n });\n}",
"function createBioCol(section_target, index, bio_data){\n\n //create a dictionary to hold these pairs\n var dict = {};\n for (var i = 1; i < bio_data.length; i++){\n var nl_index = bio_data[i].indexOf('\\n');\n var key = bio_data[i].substring(0, nl_index);\n var value = bio_data[i].substring(nl_index + 1);\n \n dict[key.trim()] = value;\n }\n bios.push(dict);\n //create and store new column\n var tmpl = document.getElementById('bio-template').content.cloneNode(true);\n \n //update column id\n tmpl.querySelector('.item').id = section_target + \"-bio-\" + String(index);\n \n //offset professor row \n if (index == 0 && String(section_target).trim() === \"Personnel\"){\n tmpl.querySelector('.item').className += \" offset-lg-2\";\n }\n\n //set name\n tmpl.querySelector('.name').innerHTML = dict.name;\n \n //set subtitle\n tmpl.querySelector('.subtitle').innerHTML = dict.subtitle;\n \n //set description\n tmpl.querySelector('.description').innerHTML = dict.description;\n \n //set image\n tmpl.querySelector('.portrait').src = dict.image;\n \n //set link if exists\n if (dict.link != undefined)\n tmpl.querySelector('.link').href = dict.link;\n else\n tmpl.querySelector('.link').remove();\n \n //set facebook if exists\n if (dict.facebook != undefined)\n tmpl.querySelector('.facebook').href = dict.facebook;\n else\n tmpl.querySelector('.facebook').remove();\n \n //set instagram if exists\n if (dict.instagram != undefined)\n tmpl.querySelector('.instagram').href = dict.instagram;\n else\n tmpl.querySelector('.instagram').remove();\n \n //set twitter if exists\n if (dict.twitter != undefined)\n tmpl.querySelector('.twitter').href = dict.twitter;\n else\n tmpl.querySelector('.twitter').remove();\n \n //set linkedin if exists\n if (dict.linkedin != undefined)\n tmpl.querySelector('.linkedin').href = dict.linkedin;\n else\n tmpl.querySelector('.linkedin').remove();\n \n //append finished column to the DOM\n document.getElementById(\"section-\" + section_target).appendChild(tmpl);\n}",
"function createCommentsHTMLString(commentList) {\n // re-write all html for entire comments table\n var commentsCountdown = commentList.length;\n var needShowAllButton = \"hide-load-comments-button\";\n var showStatus = \"show-comment\";\n var commentsHTMLString = \"\";\n var commentTimeStamp;\n \n for(var j=0; j<commentList.length; j++) {\n commentTimeStamp = commentList[j].date.toFuzzyElapsedTime();\n \n if(commentsCountdown < 3) {\n showStatus = \"show-comment\";\n } else {\n showStatus = \"hide-comment\";\n needShowAllButton = \"show-load-comments-button\";\n }\n commentsCountdown--;\n\n if(commentsCountdown == commentList.length-1) {\n commentsHTMLString +=\n \"<div class='show-all-comments-button \" + needShowAllButton + \"'>\" +\n \"View all \" + commentList.length + \" comments.\" +\n \"</div>\";\n }\n \n // comments here\n commentsHTMLString +=\n \"<div class='single-comment \" + showStatus + \"'>\" +\n \"<div class='commenter-pic'>\" +\n \"<img src='https://graph.facebook.com/\" + commentList[j].fbid + \"/picture' class='ui-corner-all'>\" +\n \"</div>\" +\n \"<div class='comment-wrapper-text'>\" +\n \"<div class='comments-content'>\" +\n \"<b>\" +\n commentList[j].firstName + \" \" + commentList[j].lastName +\n \"</b><br>\" +\n commentList[j].comment +\n \"</div>\" +\n \"<div class='comment-date time-stamp'>\" +\n commentTimeStamp +\n \"</div>\" +\n \"</div>\";\n \n if (myUID == commentList[j].uid) {\n commentsHTMLString +=\n \"<button id='remove-comment-button-cid--\" + commentList[j].cid + \n \"' class='remove-comment-button' data-cid=\" + commentList[j].cid +\n \"></button>\";\n }\n \n commentsHTMLString = commentsHTMLString +\n \"</div>\";\n }\n return commentsHTMLString;\n}",
"function fnFormatDetailsFAQs(oTable, nTr) {\r\n\r\n\t\tvar propertyFound = 0;\r\n\t\tvar sOut = \"\";\r\n\t\tvar eventType = \"\";\r\n\r\n\t\t/* Grab the event type for use in detail window */\r\n $.each(typeInfo, function(property, value) {\r\n if (value != \"\") {\r\n if (property.indexOf(\"Type\") >= 0) {\r\n eventType = value;\r\n }\r\n }\r\n });\r\n\t\t\r\n\t\t/* Add the header for the Table and the information for the State */\r\n $.each(titleInfo, function(property, value) {\r\n\r\n if (value != \"\") {\r\n\r\n if (property.indexOf(\"Title\") >= 0) {\r\n sOut += \"\\t\\t<h1 align='center'>\" + eventType + \" Details for \" + value + \"</h2>\\n\";\r\n\t\t\t\t\tsOut += \"\\t\\t<table id='hor-minimalist-b' summary=\"+ value + \">\\n\";\r\n\t\t\t\t\tsOut += \"\\t\\t\\t<thead>\\n\\t\\t\\t\\t<tr>\\n\\t\\t\\t\\t\\t<th scope='col' nowrap>Item</th>\\n\\t\\t\\t\\t\\t<th scope='col' nowrap>Detail</th>\\n\\t\\t\\t\\t\\t<th scope='col' nowrap>Type</th>\\n\\t\\t\\t\\t</tr>\\n\\t\\t\\t</thead>\\n\";\r\n\t\t\t\t\tsOut += \"\\t\\t\\t<tbody>\\n\\t\\t\\t\\t<tr>\\t\\t\\t\\t\\t<td colspan='1'>Questions</td>\\n\\t\\t\\t\\t\\t<td colspan='1'>\" + value + \"</td>\\n\\t\\t\\t\\t\\t<td colspan='1'>\" + eventType + \"</td>\\n\\t\\t\\t\\t</tr>\\n\\t\\t\\t\\t<tr>\";\r\n }\r\n }\r\n });\r\n\t\t\r\n\t\t/* Add the State Plan Information */\r\n $.each(detailedRowInfo[0], function(property, value) {\r\n\r\n if (value != \"\") {\r\n\t\t\t\tif (property.indexOf(\"Description\") >= 0) {\r\n\t\t\t\t\tsOut += \"\\n\\t\\t\\t\\t\\t<td colspan='1'>Answers</td>\";\r\n\t\t\t\t\tsOut += \"\\n\\t\\t\\t\\t\\t<td colspan='2'>\" + value + \"</td>\\n\\t\\t\\t\\t</tr>\";\r\n\t\t\t\t}\r\n }\r\n\t\t});\r\n\t\t\r\n\t\tsOut += \"\\n\\t\\t\\t\\t\\t<tr>\";\r\n\t\t\r\n\t\t/* Process the Detail Rows */\r\n $.each(detailedRowInfo[0], function(property, value) {\r\n\t\t\tif(property != \"\") {\r\n if (property.indexOf(\"Download\") >= 0 && property.indexOf(\"Name\") >= 0) {\r\n\t\t\t\t\tif (value != \"\") {\r\n\t\t\t\t\t fieldName = value;\r\n\t\t\t\t\t\tpropertyFound = 1;\r\n\t\t\t\t\t}\r\n } \r\n\t\t\t\telse if (property.indexOf(\"Download\") >= 0 && property.indexOf(\"Path\") >= 0) {\r\n\t\t\t\t\tif (value == \"\" && propertyFound == 1){\r\n\t\t\t\t\t\tsOut += \"\\n\\t\\t\\t\\t\\t<td colspan='1'>\" + fieldName + \"</td>\";\r\n\t\t\t\t\t} \r\n\t\t\t\t\telse if (propertyFound == 1 && value != \"\" ){\r\n\t\t\t\t\t\tsOut += \"\\n\\t\\t\\t\\t\\t<td colspan='1'>\" + fieldName + \"</td>\";\r\n\t\t\t\t\t\tsOut += \"\\n\\t\\t\\t\\t\\t<td colspan='2'> <a href='\" + value + \"' target='_blank'>\" + value + \"</a></td>\\n\\t\\t\\t\\t</tr>\";\r\n\t\t\t\t\t}\r\n\t\t\t\t\tpropertyFound = 0;\r\n\t\t\t\t\tfieldName=null;\r\n\t\t\t\t} \r\n\t\t\t}\r\n }); \r\n\r\n sOut += \"\\n\\t\\t\\t\\t\\t\\t</ul>\\n\\t\\t\\t\\t\\t</td>\\n\\t\\t\\t\\t</tr>\\n\\t\\t\\t</tbody>\\n\\t\\t</table>\\n\";\r\n\r\n jQuery(\".main-body-content\").css(\"height\", tmpContentSize);\r\n\r\n jQuery(\".main-body-content\").css(\"height\", tmpContentSize); \r\n\t\tjQuery(\".main-body\").css(\"padding\",\"10px;\");\r\n jQuery(\".main-body-content\").addClass(\"iefooterfix\")\r\n\r\n return sOut;\r\n\r\n }",
"build() {\n const rows = this.data.split('\\n'); // the rows of the table\n let marker = 0; // a flag that is used to indicate on which set of the table I am\n\n if (rows.length > 1) {\n for (let i = 0; i < rows.length - 1; i++) {\n\n // +=====+======+ ... + is checked\n // before the third occurrence of this pattern we are in set S\\Sigma\n // after that we are in set S\n if (new RegExp('^(\\\\+\\\\=+)+\\\\+$').test(rows[i])) {\n marker++;\n continue;\n }\n\n // only check each second row because all others are only separators\n if (i % 2 === 1) {\n\n //remove column separators and white spaces around the entry content\n rows[i] = rows[i].split('|');\n rows[i].shift();\n rows[i].pop();\n for (let j = 0; j < rows[i].length; j++) {\n rows[i][j] = rows[i][j].trim();\n }\n\n // fill the table\n if (i === 1) {\n this.table.header = rows[i];\n } else {\n\n // depending on which set of the table i am\n if (marker === 2) {\n this.table.body.s1.push(rows[i]);\n } else {\n this.table.body.s2.push(rows[i]);\n }\n }\n }\n }\n }\n }",
"function tableGenerating() {\n tableWrapper.innerHTML = '';\n const newTable = document.createElement('table');\n newTable.style.width = `${tableWidth.value}%`;//no need for + ;\n newTable.style.border = `${borderWidth.value}px solid ${borderColor.value}`; // ` ` open and close for the whole string, NOT for each\n tableWrapper.style.backgroundColor = tableColor.value;\n newTable.style.color = fontColor.value;\n newTable.style.textAlign = textAlign.value;\n newTable.style.fontFamily = fontType.value;\n newTable.style.fontWeight = fontWeight.value;\n tableWrapper.appendChild(newTable);\n\n //create rows:\n for (let i = 0; i < rowNumber.value; i++) {\n const tableRow = document.createElement('tr');\n newTable.appendChild(tableRow);\n }\n\n //create heads:\n const tableAllRows = document.querySelectorAll('tr');\n \n for (let i = 0; i < columnNumber.value; i++) {\n const tableHead = document.createElement('th');\n tableAllRows[0].appendChild(tableHead);\n\n tableHead.textContent = 'Head';\n tableHead.style.border = `${borderWidth.value}px solid ${borderColor.value}`;\n tableHead.style.backgroundColor = headColor.value;\n }\n\n for (let row = 1; row < rowNumber.value; row++) {\n for (let column = 0; column < columnNumber.value; column++) {\n const data = document.createElement('td');\n data.textContent = 'data';\n tableAllRows[row].appendChild(data);\n data.style.backgroundColor = bodyColor.value;\n data.style.border = `${borderWidth.value}px solid ${borderColor.value}`;\n\n }\n }\n}",
"function constructGuestBill(currency,date,amount,details){\n var self = this;\n self.constructBill = function(){\n $('.guest-bill-info').each(function(){\n var parentId = $(this).parent().attr('id');\n var html ='',htmlres ='';\n var cur = encode_utf8(currency);\n var line_color = $('#'+ parentId+' .guest-bill-info .guest-bill-line').attr('style');\n var display_items = $('#'+ parentId+' .guest-bill-info').attr('bill_item');\n\n // $('#'+ parentId +' .guest-bill-info #guest-name-info').text(name);\n $('#'+ parentId +' .guest-bill-info #invoice-date-info').text(date);\n $('#'+ parentId +' .guest-bill-info #total-amount-info').text(cur +' '+ amount);\n\n if(display_items == \"1\"){\n //fetching the style of table head and table body style\n var thStyle = $('#'+ parentId+' .guest-bill-info table thead tr').attr('style');\n var tdStyle = $('#'+ parentId+' .guest-bill-info table tbody tr').attr('style');\n\n //constructing the each bill item into table\n jQuery.each(details.BillItems,function(key1,value1){\n htmlres += '<tr style=\"'+tdStyle+';\" class=\"details\"><td>' + encode_utf8(value1[\"BillItemDisplayName\"]) + '</td><td style=\"text-align:center;\">' + value1[\"BillItemDate\"] + '</td><td style=\"text-align:right;\">' + value1[\"BillItemAmount\"] + '</td></tr>';\n })\n\n html = '<div class=\"guest-bill-details hide_details\"><table id=\"bill-details-breakdown\" border = \"0\"><thead><tr class=\"bill-info-title\" style=\"'+thStyle+';\"><th >Description</th><th style=\"text-align:center;\">Date</th><th style=\"text-align:right;\">Amount</th></tr></thead><tbody>';\n html += htmlres;\n html += '<tr><td colspan=\"3\"><div class=\"guest-bill-line\" style=\"'+line_color+'\"></div></td></tr>';\n html += '<tr><td colspan=\"2\" style=\"'+thStyle+';\" class=\"bill-info-title\">Total</td><td class=\"details\" style=\"'+tdStyle+';\">'+cur +' '+ amount+'</td></tr>'\n html+= \"</tbody></table></div>\"\n $('#'+ parentId +' .guest-bill-info .guest-bill-details').replaceWith(html);\n }\n\n });\n\n }\n}",
"function decorateTables() {\n document.querySelectorAll('main div.post-body table').forEach(($table) => {\n const $cols=$table.querySelectorAll('thead tr th');\n const cols=Array.from($cols).map((e) => toClassName(e.innerHTML));\n const $rows=$table.querySelectorAll('tbody tr');\n let $div={};\n\n if (cols.length==1 && $rows.length==1) {\n $div=createTag('div', {class:`${cols[0]}`});\n $div.innerHTML=$rows[0].querySelector('td').innerHTML;\n } else {\n $div=turnTableIntoCards($table, cols)\n }\n $table.parentNode.replaceChild($div, $table);\n });\n}",
"function displayComment (arrayofObjects) {\n // Create the outermost Div comments-pre\n let outerDiv = makeElement(\"div\", \"comments-pre\");\n outerDiv.classList.add(arrayofObjects.class)\n // Create the Ininer Div comments-pre-top\n let innerDiv = makeElement(\"div\", \"comments-pre-top\");\n outerDiv.append(innerDiv)\n // comments-pre__circle \n let innerCircle = makeElement(\"div\", arrayofObjects.pictureClass);\n innerDiv.append(innerCircle)\n // Create the inner P tags\n let innerP = makeElement(\"p\", \"comments-pre-top__name\")\n innerP.innerText = arrayofObjects.name\n innerDiv.append(innerP)\n // Create the second inner P \n let innerP2 = makeElement(\"p\", \"comments-pre-top__date\")\n innerP2.innerText = arrayofObjects.date\n innerDiv.append(innerP2)\n //Create the outer p, for comment\n let innerP3 = makeElement(\"p\", \"comments-pre-bottom__loaded\")\n innerP3.innerText = arrayofObjects.comment\n outerDiv.append(innerP3)\n \n section.appendChild(outerDiv)\n return outerDiv\n}",
"function addTable(){\n alienData.forEach(aliens =>{\n\t\t// Creating the rows for each line\n var row = tbody.append(\"tr\");\n\t\t// Creating the cells and appending values \n columns.forEach(column => {\n\t\t\t// Formating the entries for City, State and Country to show them in upper case\n if(column ==\"city\" || column ==\"state\" ||column == \"country\"){\n row.append(\"td\").text(aliens[column].toUpperCase());\n }\n\t\t\t // Append the shape, duration and comment values\n else row.append(\"td\").text(aliens[column]); \n })\n })\n}",
"function buildTaskList()\n{\n\tconst body = $(\"body\");\n const spoonTypes = body.data(\"spoonTypes\");\n const spoonEmoji = body.data(\"spoonEmoji\"); // will need this to account for emoji mode on page load\n const spoonDifficulties = body.data(\"spoonDifficulties\");\n\t// create the task list\n\tconst taskList = makeTable();\n\ttaskList.attr(\"id\",\"tasklist\");\n body.append(taskList);\n\t// make the header row and append to the table\n\tconst headerRow = makeTaskHeaderRow(\"tasklist\",spoonTypes); // will probably need header emojis later\n\ttaskList.append(headerRow);\n\t// make the new task row and append to the table\n\tconst newTaskRow = makeNewTaskRow(spoonTypes,spoonDifficulties);\n\ttaskList.append(newTaskRow);\n const spoons = $(newTaskRow.children().filter(\".spoon\"));\n\tspoons.outerWidth(setSpoonWidths(taskList));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checksum creates a checksum for a string and returns the checksum value in a string (or as an integer). Originally found at And modified by | function checksum(s, type = 'i')
{
var chk = 0x5F378EA8;
var len = s.length;
for (var i = 0; i < len; i++) chk += (s.charCodeAt(i) * (i + 1));
if(type === 's') return (chk & 0xffffffff).toString(16);
else return (chk & 0xffffffff);
} | [
"function checksum(s) {\n var hash = 0, strlen = s.length, i, c;\n if ( strlen === 0 ) {\n return hash;\n }\n for ( i = 0; i < strlen; i++ ) {\n c = s.charCodeAt( i );\n hash = ((hash << 5) - hash) + c;\n hash = hash & hash; // Convert to 32bit integer\n }\n return hash;\n}",
"function checksum(s) {\n\tvar chk = 0x12345678;\n\tfor (var i = 0; i < s.length; i++) {\n\t\tchk += (s.charCodeAt(i) * (i + 1));\n\t}\n\treturn chk;\n}",
"function computeChecksum(inString) {\n var MOD_ADLER = 65521;\n var a = 1;\n var b = 0;\n for (var i = 0; i < inString.length; i++) {\n a = (a + inString.charAt(i).charCodeAt()) % MOD_ADLER;\n b = (b + a) % MOD_ADLER;\n }\n return (b ^ a) % 100;\n }",
"function computeChecksum(inString) {\n let MOD_ADLER = 65521;\n let a = 1;\n let b = 0;\n for (let i = 0; i < inString.length; i++) {\n a = (a + inString.charAt(i).charCodeAt()) % MOD_ADLER;\n b = (b + a) % MOD_ADLER;\n }\n return (b ^ a) % 100;\n }",
"function checksum(text)\n {\n var a = 1, b = 0;\n for (var index = 0; index < text.length; ++index) {\n a = (a + text.charCodeAt(index)) % 65521;\n b = (b + a) % 65521;\n }\n return (b << 16) | a;\n }",
"function checksum(s)\n{\n\t// console.log(\"DEBUT CHECK\");\n\ts = s.replace(/^(.(..)*)$/, \"0$1\"); // add a leading zero if needed\n\n\tvar a = s.match(/../g); // split number in groups of two\n\n\tvar C1 = a[0].charAt(0);\n\tvar C2 = a[0].charAt(1);\n\tfor( var i=1; i<a.length;i++ )\n\t{\n\t\tC1 = xor (C1,a[i].charAt(0).toString(16));\n\t\tC2 = xor (C2,a[i].charAt(1).toString(16));\n\t}\n\t// console.log(\"result :\"+C1.toString(16)+C2.toString(16));\n\t// console.log(\"FIN CHECK\");\n\n\treturn ''+C1.toString(16)+C2.toString(16);\n}",
"function checksum(text) {\n var a = 1, b = 0;\n for (var index = 0; index < text.length; ++index) {\n a = (a + text.charCodeAt(index)) % 65521;\n b = (b + a) % 65521;\n }\n return (b << 16) | a;\n }",
"computeChecksum(s) {\n s = s || '';\n if (s.lastIndexOf('*') >= 0) {\n s = s.substr(0, s.lastIndexOf('*'));\n }\n\n let cs = 0;\n for (let i = 0; i < s.length; ++i) {\n const c = s[i].charCodeAt(0);\n cs ^= c;\n }\n return cs;\n }",
"function calculateChecksum(sval) {\n var checksum = 0;\n for (var i = 0; i < sval.length; ++i) {\n checksum += parseInt(sval.charAt(i)) * (ACCOUNT_NUMBER_LENGTH - i);\n }\n return checksum;\n }",
"getAddressChecksumString () {\n return secUtil.toChecksumAddress(this.getAddressString())\n }",
"function checksum(data) {\n\tvar result = 0;\n\n\tfor (var i = 0; i < 13; i++) {\n\t\tresult += parseInt(data[i]) * (3 - i % 2 * 2);\n\t}\n\n\treturn Math.ceil(result / 10) * 10 - result;\n}",
"function checksum(data) {\n\t\tvar result = 0;\n\n\t\tfor (var i = 0; i < 13; i++) {\n\t\t\tresult += parseInt(data[i]) * (3 - i % 2 * 2);\n\t\t}\n\n\t\treturn Math.ceil(result / 10) * 10 - result;\n\t}",
"function calculateChecksum(data) {\n return crypto\n .createHash('sha256')\n .update(data, 'utf8')\n .digest('hex')\n}",
"function checksum$4(data) {\n\tvar result = 0;\n\n\tfor (var i = 0; i < 13; i++) {\n\t\tresult += parseInt(data[i]) * (3 - i % 2 * 2);\n\t}\n\n\treturn Math.ceil(result / 10) * 10 - result;\n}",
"function checkSumString(str) {\n var sum = 0;\n for(var i = 0; i < str.length; i+=2) {\n var n1 = str.charCodeAt(i);\n\n //Set n2 to zero in case string is not any longer\n var n2 = 0;\n if(i + 1 < str.length) {\n n2 = str.charCodeAt(i+1);\n }\n //Shift n1 8 bits since this is most significant byte\n var n = (n1 << 8) + n2;\n if(i + 1 < str.length) {\n console.log(str[i] + str[i+1] + \":\\t\\t\" + toBin(n,16));\n } else {\n //No more chars so just write null-char \n console.log(str[i] + \"\\\\0:\\t\\t\" + toBin(n,16));\n }\n \n sum += n;\n //Wrap around if there is overflow\n if(sum > Math.pow(2, 16)) {\n //Subtract 2^16 to remove the 17th bit, then add the carry in the\n // least significant bit\n sum = sum - Math.pow(2,16) + 1;\n }\n }\n console.log(\"___________________________________\")\n console.log(\"Sum:\\t\\t\" + toBin(sum, 16)); \n //This is the checksum\n console.log(\"1s compliment:\\t\" + toBin(~sum, 16) + \n \" (this is the checksum)\");\n \n}",
"static checksumFromBytes(bytes) {\n let checksum = 0x00\n\n for (let i = 0; i < bytes.length; i++) {\n let byte = bytes[i] \n checksum = checksum ^ byte\n }\n\n return checksum\n }",
"function checksum(number){\nvar result=0;\n\nvar i;\nfor(i=1;i<11;i+=2){\nresult+=parseInt(number[i]);\n}\nfor(i=0;i<11;i+=2){\nresult+=parseInt(number[i])*3;\n}\n\nreturn (10-result%10)%10;\n}",
"function appendChecksum(data) {\n var result = 0;\n var arrData = data.split('');\n arrData.forEach(function (entry) {\n var entryBuffer = new Buffer(entry, 'ascii');\n var entryRepHex = entryBuffer.toString('hex');\n var entryHex = parseInt(entryRepHex, 16);\n result = result + parseInt(entryHex, 10);\n });\n data = data + (parseInt(result, 10).toString(16).toUpperCase().slice(-2) + \"\\r\\n\");\n return data;\n}",
"toChecksumAddress (address) { \n address = address.toLowerCase().replace('0x','');\n var addressHash = web3.sha3(address);\n var checksumAddress = '0x';\n\n for (var i = 0; i < address.length; i++ ) { \n // If ith character is 9 to f then make it uppercase \n if (parseInt(addressHash[i], 16) > 8) {\n checksumAddress += address[i].toUpperCase();\n } else {\n checksumAddress += address[i];\n }\n }\n return checksumAddress;\n \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
se crean la cantidad de cohortes por sede y la lista de sus cohortes | function getCohorts() {
for (var i = 0; i < centers.length; i++) {
// cohortes por sede
keys = Object.keys(data[centers[i].key]);
// numero de cohortes
centers[i].cohorts = keys.length;
// cohortes
centers[i].cohortsList = keys;
}
} | [
"function getCohorts() {\n for (var i = 0; i < centers.length; i++) {\n // cohortes por sede\n keys = Object.keys(data[centers[i].key]);\n // numero de cohortes\n centers[i].cohortLength = keys.length;\n // cohortes\n centers[i].cohortList = keys;\n }\n}",
"function getCohortNumbers(){\n\treturn new Promise(function(resolve, reject){\n\t\tCONSOLE_WITH_TIME('Getting cohorts from Canvas');\n\t\tvar start = Date.now();\n\t\trequest(`accounts/${KEYS.canvas.accountID}/courses?per_page=100&enrollment_type[]=student`, 'Canvas')\n\t\t \t.then(function (courses) {\n\t \t\tvar previous;\n\t\t \tvar cohorts = {};\n\t\t \tcourses.forEach(function (course) {\n\t\t\t\t\t/*parses cohortNumber from 'course name'. regex may be better\n\t\t\t\t\tif cohort naming changes format, cohort numbers will be incorrect\n\t\t\t\t\tmaybe look for better methods for retrieving cohort number*/\n\t\t\t\t\tvar nameArr = course.name.trim().split(' ');\n\t\t\t\t\tvar cohortNumber = nameArr[1];\n\t\t\t\t\tif(isNaN(cohortNumber) || nameArr[0].toLowerCase() !== 'cohort') return;\n\t\t\t\t\tif(!cohorts[cohortNumber]){\n\t\t\t\t\t\tcohorts[cohortNumber] = {};\n\t\t\t\t\t\tcohorts[cohortNumber].class_ids = [];\n\t\t\t\t\t\tcohorts[cohortNumber].closed_class_ids = [];\n\t\t\t\t\t}\n\t\t\t\t\tif(course.workflow_state==='available'){\n\t\t\t\t\t\tcohorts[cohortNumber].class_ids.push(course.id);\n\t\t\t\t\t} else if(course.workflow_state==='completed'){\n\t\t\t\t\t\tcohorts[cohortNumber].closed_class_ids.push(course.id);\n\t\t\t\t\t}\n\t\t\t\t\t/*For some cohorts, the courses are marked 'completed'. \n\t\t\t\t\tThese are closed courses. I've tallied them separately from open ones\n\t\t\t\t\tin the case that data needs to be handled differently from open\n\t\t\t\t\tcourses. Both lists of courses are concatenated in the end*/\n\t\t\t\t});\n\t\t\t\tObject.keys(cohorts).forEach(function(key){\n\t\t\t\t\tif(cohorts[key].class_ids.length == 0) delete cohorts[key];\n\t\t\t\t\telse cohortKeys.push(key);\n\t\t\t\t});\n\n\t\t\t\tvar timeTook = (Date.now()-start)/1000;\n\t\t\t\tCONSOLE_WITH_TIME(`Done. Took ${timeTook} seconds`);\n\t\t\t\tresolve(cohorts);\n\t\t\t}).catch(function(err){\n\t\t\t\tCONSOLE_WITH_TIME(`Error processing data from course list: ${err}`);\n\t\t\t});\n\t}).catch(errorHandler);\n}",
"function countCohorts(data) {\n\n return data.length;\n}",
"function getCohorts() {\n\treturn db('cohorts');\n}",
"function makeDataSets(array) {\n var yearmonth = []; //holds dates for labels\n var dataSets = []; //holds the line object\n\n for (x = 0; x < array.length; x++) {\n if (array[0][x + 1] !== undefined) {\n yearmonth[x] = array[0][x + 1]; //year month is on first row of array\n }\n }\n\n for (x = 1; x < array.length - 1; x++) {\n var label; //holds the cohort\n var data = []; //holds the cohort's data\n var c = 0; //counter for the data array\n var alive = false; //if cohort has arrived at site or not\n for (y = 0; y < array[array.length - 2].length; y++) { //remove the last element as it is an unremovable empty line for some reason\n if (y == 0) {\n label = array[x][y]; //first column of 2d array is the cohort\n } else {\n if (alive) { //if cohort exists yet\n if (isNaN(parseInt(array[x][y]))) {\n data[c] = 0; //if cohort exists and there is no data set to 0\n } else {\n data[c] = array[x][y]; //if cohort exists and there is data set to data value\n }\n } else {\n if (isNaN(parseInt(array[x][y]))) {\n data[c] = null; //if cohort doesn't exist and there is no data set to null\n } else {\n alive = true;\n data[c] = array[x][y]; //this will be the first value for any cohort, set to alive\n }\n }\n c++;\n }\n }\n\n dataSets.push({\n label: 'Cohort ' + label, //label for each cohort line\n data: data, //data for each cohort\n borderColor: randomColorGenerator(),\n borderWidth: 3,\n fill: false\n });\n }\n return [yearmonth, dataSets];\n\n}",
"async getCohorts() {\n const SQL = 'SELECT * FROM rs.cohorts;';\n\n try {\n const currentCohorts = await this.client.query(SQL);\n return currentCohorts.rows;\n } catch (error) {\n throw new Error(error);\n }\n }",
"function getCohorts(state) {\n return state.calculate.form.cohortVars.map(function (cohort) {\n return cohort\n .replace(/[^a-z\\d/]/gi, '_')\n .replace(/_{2,}/g, '_')\n .replace(/^[^a-z\\d/]*|[^a-z\\d/]*$/gi, '');\n });\n}",
"getAllCohortDataSets() {\n let self = this;\n\n let dataSets = [];\n if (self.mainDataSet) {\n dataSets.push(self.mainDataSet);\n }\n self.otherDataSets.forEach((dataSet) => {\n if (!dataSet.isSingleSample) {\n dataSets.push(dataSet);\n }\n })\n return dataSets;\n }",
"function getCohorts() {\n container.innerHTML = ' ';\n const httpRequest = new XMLHttpRequest();\n httpRequest.open('GET',`https://laboratoria-la-staging.firebaseapp.com/cohorts/`); \n httpRequest.onload = responseCohorts;\n httpRequest.onerror = handleError;\n httpRequest.send();\n}",
"function renderCohort(cohort) {\n\tconst ul = document.querySelector(\"#cohorts\");\n\tconst li = document.createElement(\"li\");\n\n\tli.innerText = cohort.name;\n\n\tul.appendChild(li);\n }",
"renderCohort(cohort) {\n const count = this.modal.getBody().find(SELECTORS.AREA_RESULTS).find(\".cohort\").length;\n let cohort_html = `<div class=\"cohort item clearfix\" rel=\"${cohort.id}\">\n <div class=\"count\">${count}</div>\n <div class=\"details\">\n <div class=\"fullname\">${cohort.name}</div>\n </div>\n <div class=\"options\">\n <select name=\"cohort_group\" rel=\"${cohort.id}\">`;\n\n for (let id in this.groups) {\n cohort_html += `<option value=\"${id}\">${this.groups[id]}</option>`;\n }\n\n cohort_html += `</select>\n <button class=\"btn btn-success\" data-toggle=\"enrol\" value=\"${cohort.id}\">\n ${this.strings[14]}</button>\n </div>\n </div>`;\n\n return cohort_html;\n }",
"function processCohorts() {\n //Get the spreadsheets and data from the spreadsheets\n var sa = SpreadsheetApp.getActiveSpreadsheet();\n var inputSS = sa.getSheetByName(\"Cohort\");\n var inputDT = getDataValues(inputSS.getName());\n var cols = inputDT[0].length;\n \n for(var i = 1; i < inputDT.length; i++) {\n var student = inputDT[i];\n student.splice(8, 2);\n var cohorts = student.slice(2, 10);\n var cohort = checkValue(cohorts);\n if(cohort.length > 1) {\n cohort = cohort.trim();\n cohort = cohort.slice(0, cohort.length-1);\n }\n inputSS.getRange(i+1, cols+1).setValue(cohort);\n }\n}",
"function getAllCohorts () {\n return db.raw(getAllCohortsQuery)\n}",
"function createClubDataArray() {\n let clubListArray = []\n wineClubs.forEach(winery => {\n let { wineClubs: clubs } = winery\n clubs.forEach(club => {\n clubListArray.push({\n ...club,\n winery: winery.name\n })\n })\n })\n updateClubList(clubListArray)\n updateFirstClub(clubListArray[0])\n updateSecondClub(clubListArray[1])\n }",
"function printCohort(arr){\n for (var i = 0; i < arr.length; i++){\n console.log(\"Name: \"+ arr[i].name + \" , Cohort : \" + arr[i].cohort)\n }\n}",
"function saveTables(cohorts, session, title, counts) {\n var cohorts_csv = [];\n\n // cohorts (plural) {'all': 'Number of employees', ...}\n // cohort (singular) 'all'\n for (var cohort in cohorts) {\n var tables_csv = [];\n\n // table is assigned object of roles\n // e.g. table is the key {\"Number of Employees\": {\"Adminis\": {\"afrf\": 200.00}}, \"Craft\":...,}\n var tables = cohorts[cohort];\n\n // sheet is \"Number of Employees\"\n for (var sheet in tables) {\n var cols = [];\n var sheet_csv = [];\n\n sheet_csv.push([sheet]);\n\n // row is \"Adminis\", ...\n for (var row in tables[sheet]) {\n // if a new sheet, then create the column headers\n if (sheet_csv.length === 1) {\n cols.push('row');\n\n // col is \"afrf\", ...\n for (var col in tables[sheet][row]) {\n cols.push(col);\n }\n\n // push the list of headers to the first row of the sheet\n sheet_csv.push(cols.join(','));\n }\n\n var row_csv = []\n\n // set the row name\n row_csv.push(row);\n\n // then populate the rest of the row with values\n for (var c = 1; c < cols.length; c++) {\n row_csv.push(tables[sheet][row][cols[c]]);\n }\n\n // push the list to the next row of the sheet\n sheet_csv.push(row_csv.join(','));\n }\n\n // push the sheet to the list of sheets\n tables_csv.push(sheet_csv.join('\\n'));\n }\n\n // combine the sheets into a csv with string concatenation\n var count = 'Number of participants ' + counts[cohort].length;\n if (cohort === 'all') {\n cohorts_csv[0] = 'All Cohorts -- ' + count + '\\n\\n' + tables_csv.join('\\n\\n');\n } else {\n cohorts_csv[cohort] = 'Cohort #' + cohort + ' -- ' + count + '\\n\\n' + tables_csv.join('\\n\\n');\n }\n }\n\n // Sort by cohorts, all appears first\n var joined = cohorts_csv[0];\n for (var i = 1; i < cohorts_csv.length; i++) {\n if (cohorts_csv[i] != null) {\n joined += '\\n\\n\\n\\n' + cohorts_csv[i];\n }\n }\n\n filesaver.saveAs(new Blob([joined], {type: 'text/plain;charset=utf-8'}), 'Aggregate_' + title + '_' + session + '.csv');\n }",
"function cargar(cohort){\n Promise.all([\n fetch(\"../data/cohorts/\"+ cohort + \"users.json\"),\n fetch(\"../data/cohorts/\"+ cohort + \"progress.json\"),\n fetch(\"../data/cohorts.json\")\n ]).then(//al cumplirse las promesas ejecutara lo siguiente\n (datos.Json) =>{\n return Promise.all(datos.Json.map((respuesta) =>{//crea un nuevo array con objetos json\n return respuesta.json()\n }))\n }\n ).then(\n (respuestaJson)=> {\n console.log(respuestaJson)\n var usuarios = computeUsersStats(respuestaJson[0], respuestaJson[1],respuestaJson[2])\n\n }\n )\n}",
"function setDiscipline(disc) {\n // console.log(resultPreferences);\n\n for (var i = 0; i < disc.length; i++) {\n var prof = disc[i].getProfessor();\n // Set Professors\n for (var index = 0; index < prof.length; index++) {\n prof[index] = professors.find(o => o.id === prof[index]);\n }\n // Set Course \n disc[i].setCourse(courses.find(o => o.id === disc[i].getCourse()));\n\n // Set Preferences \n for (var index = 0; index < prof.length; index++) {\n\n var prf = resultPreferences.find(o => o.idProf === prof[index].getId());\n if (prf != undefined) {\n disc[i].setPreferences(prf);\n }\n }\n }\n\n /**\n * NUMBER OF WEEK OF LESSONS\n */\n\n // i.e. 24/09/2018\n // var startWeek = moment(2018 + \"/\" + 09 + \"/\" + 24, 'YYYY-MM-DD');\n\n // // i.e 14/12/2018\n // var endWeeek = moment(2018 + \"/\" + 12 + \"/\" + 14, 'YYYY-MM-DD');\n // var numberOfWeek = endWeeek.diff(startWeek, 'week');\n // console.log(\"Numero di settimane di lezione \" + numberOfWeek);\n /**\n ******************************************************************\n */\n\n\n // for every query reset the timetable.length has resize\n timetable.tt.length = 0\n\n for (var i = 0; i < disc.length; i++) {\n\n var randomClassroom = classrooms[Math.floor(Math.random() * classrooms.length)];\n var randomDay = days[Math.floor(Math.random() * days.length)];\n // var subjectWeeksHours = disc[i].getWeeksHours();\n var subjectWeeksHours = Math.round(disc[i].getTotalHours()/11);\n //var subjectWeeksHours = DURATION_LESSON;\n if (subjectWeeksHours < 4) {\n timetable.tt.push(new Lesson(randomDay, disc[i], START_LESSONS, START_LESSONS + 2, randomClassroom));\n }\n if (subjectWeeksHours == 4) {\n timetable.tt.push(new Lesson(randomDay, disc[i], START_LESSONS, START_LESSONS + 2, randomClassroom));\n timetable.tt.push(new Lesson(randomDay, disc[i], START_LESSONS, START_LESSONS + 2, randomClassroom));\n }\n if (subjectWeeksHours == 5) {\n timetable.tt.push(new Lesson(randomDay, disc[i], START_LESSONS, START_LESSONS + 3, randomClassroom));\n timetable.tt.push(new Lesson(randomDay, disc[i], START_LESSONS, START_LESSONS + 2, randomClassroom));\n }\n if (subjectWeeksHours == 6) {\n\n if (disc[i].getSplitDuration(2)) {\n timetable.tt.push(new Lesson(randomDay, disc[i], START_LESSONS, START_LESSONS + 2, randomClassroom));\n timetable.tt.push(new Lesson(randomDay, disc[i], START_LESSONS, START_LESSONS + 2, randomClassroom));\n timetable.tt.push(new Lesson(randomDay, disc[i], START_LESSONS, START_LESSONS + 2, randomClassroom));\n }\n else if (disc[i].getSplitDuration(3)) {\n\n timetable.tt.push(new Lesson(randomDay, disc[i], START_LESSONS, START_LESSONS + 3, randomClassroom));\n timetable.tt.push(new Lesson(randomDay, disc[i], START_LESSONS, START_LESSONS + 3, randomClassroom));\n }\n else {\n timetable.tt.push(new Lesson(randomDay, disc[i], START_LESSONS, START_LESSONS + 2, randomClassroom));\n timetable.tt.push(new Lesson(randomDay, disc[i], START_LESSONS, START_LESSONS + 4, randomClassroom));\n }\n\n }\n if (subjectWeeksHours == 8) {\n timetable.tt.push(new Lesson(randomDay, disc[i], START_LESSONS, START_LESSONS + 3, randomClassroom));\n timetable.tt.push(new Lesson(randomDay, disc[i], START_LESSONS, START_LESSONS + 3, randomClassroom));\n timetable.tt.push(new Lesson(randomDay, disc[i], START_LESSONS, START_LESSONS + 2, randomClassroom));\n }\n if (subjectWeeksHours == 9) {\n timetable.tt.push(new Lesson(randomDay, disc[i], START_LESSONS, START_LESSONS + 3, randomClassroom));\n timetable.tt.push(new Lesson(randomDay, disc[i], START_LESSONS, START_LESSONS + 3, randomClassroom));\n timetable.tt.push(new Lesson(randomDay, disc[i], START_LESSONS, START_LESSONS + 3, randomClassroom));\n }\n\n }\n}",
"function createCohort (cohort) {\n return db.raw('INSERT INTO Cohorts (title, slug, isActive, startDate, endDate) VALUES (?, ?, true, ?, ?)', [cohort.title, cohort.slug, cohort.startDate, cohort.endDate])\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.