query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
sequencelengths
19
20
metadata
dict
Return a string containing a MySQL 5.6 `ALTER TABLE` statement
function alterTable(name, alterations) { // Loop through `alterations` a bunch of times, collecting a different part // of the `ALTER TABLE` statement each time. // There will be at most one comment change, but allow multiple. const commentChanges = alterations .filter(alt => alt.kind === 'alterDescription') .map(alt => `comment = ${quoteString(alt.description)}`); const modifyColumns = alterations .filter(alt => alt.kind === 'alterColumn') .map(({kind, ...column}) => 'modify column ' + column2tableClause(column)); const addColumns = alterations .filter(alt => alt.kind === 'appendColumn') .map(({kind, ...column}) => 'add column ' + column2tableClause({nullable: true, ...column})); // Foreign keys happen as part of "appendColumn," but require a separate // SQL clause, so we do them separately here. const foreignKeys = alterations .filter(alt => alt.kind === 'appendColumn' && alt.foreignKey) .map(({kind, ...column}) => 'add ' + column2foreignKeyTableClause(column)); const clauses = [ ...commentChanges, ...modifyColumns, ...addColumns, ...foreignKeys ]; return `alter table ${quoteName(name)} ${clauses.join(',\n')}`; }
[ "renameTable(from, to) {\n this.pushQuery(\n `alter table ${this.formatter.wrap(from)} rename to ${this.formatter.wrap(\n to\n )}`\n );\n }", "visitAlter_table(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function _addColumn(){\n self._visitingAlter = true;\n var table = self._queryNode.table;\n self._visitingAddColumn = true;\n var result='ALTER TABLE '+self.visit(table.toNode())+' ADD '+self.visit(alter.nodes[0].nodes[0]);\n for (var i= 1,len=alter.nodes.length; i<len; i++){\n var node=alter.nodes[i];\n assert(node.type=='ADD COLUMN',errMsg);\n result+=', '+self.visit(node.nodes[0]);\n }\n self._visitingAddColumn = false;\n self._visitingAlter = false;\n return [result];\n }", "function _renameColumn(){\n self._visitingAlter = true;\n var table = self._queryNode.table;\n var result = [\"EXEC sp_rename '\"+\n self.visit(table.toNode())+'.'+self.visit(alter.nodes[0].nodes[0])+\"', \"+\n self.visit(alter.nodes[0].nodes[1])+', '+\n \"'COLUMN'\"\n ];\n self._visitingAlter = false;\n return result;\n }", "function _dropColumn(){\n self._visitingAlter = true;\n var table = self._queryNode.table;\n var result=[\n 'ALTER TABLE',\n self.visit(table.toNode())\n ];\n var columns='DROP COLUMN '+self.visit(alter.nodes[0].nodes[0]);\n for (var i= 1,len=alter.nodes.length; i<len; i++){\n var node=alter.nodes[i];\n assert(node.type=='DROP COLUMN',errMsg);\n columns+=', '+self.visit(node.nodes[0]);\n }\n result.push(columns);\n self._visitingAlter = false;\n return result;\n }", "function getSql(tblName, tblData, alternateName) {\n tblData = tblData || getSqlTable();\n let altName = (alternateName || tblName);\n let sql;\n if (tblName.substr(0, 4) == \"idx_\") {\n // If this is an index, we need construct the SQL differently\n let idxTbl = tblData[tblName].shift();\n let idxOn = idxTbl + \"(\" + tblData[tblName].join(\",\") + \")\";\n sql = \"CREATE INDEX \" + altName + \" ON \" + idxOn + \";\";\n } else {\n sql = \"CREATE TABLE \" + altName + \" (\\n\";\n for (let [key, type] in Iterator(tblData[tblName])) {\n sql += \" \" + key + \" \" + type + \",\\n\";\n }\n }\n\n return sql.replace(/,\\s*$/, \");\");\n}", "function getAllSql(version) {\n let tblData = getSqlTable(version);\n let sql = \"\";\n for (let tblName in tblData) {\n sql += getSql(tblName, tblData) + \"\\n\\n\";\n }\n cal.LOG(\"Storage: Full SQL statement is \" + sql);\n return sql;\n}", "function renameTable(tblData, tblName, newTblName, db, overwrite) {\n if (overwrite) {\n dropTable(tblData, newTblName, db);\n }\n tblData[newTblName] = tblData[tblName];\n delete tblData[tblName];\n executeSimpleSQL(db, \"ALTER TABLE \" + tblName +\n \" RENAME TO \" + newTblName);\n}", "visitAlter_table_properties(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitAlter_database(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitAlter_tablespace(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function dbdiff2sql(dbdiff) {\n // keep 'em honest\n schemas.dbdiff.enforce(dbdiff);\n\n // Order of statements returned:\n // - create new tables\n // - alter existing tables\n // - update existing rows\n // - insert new rows\n //\n // I use this order, rather than everything-per-table, so that the DDL\n // statements are together at the top, and the DML statements are together\n // at the bottom.\n\n const creates = topologicallySortedTables(dbdiff.newTables)\n .map(createTable);\n\n // Return an array of just the part of `dbdiff.modifications` indicated,\n // one element for each table. Exclude tables where `what` is empty.\n function justThe(what) {\n return Object.entries(dbdiff.modifications)\n .map(([tableName, modifications]) => [tableName, modifications[what]])\n .filter(([_, whats]) => whats.length);\n }\n\n const alterations = justThe('alterations')\n .map(([tableName, alterations]) => alterTable(tableName, alterations));\n\n const updates = justThe('updates')\n .map(([tableName, updates]) =>\n updates.map(update =>\n updateRow(dbdiff.allTables[tableName], update)))\n .flat(); // Each row updated gets its own statement.\n\n // `INSERT` comes from two places: \"insertions\" and \"newTables\" with\n // nonempty \".rows\". Here is the latter, which is combined with the former\n // below.\n const newTablesWithRows = Object.entries(dbdiff.newTables)\n .filter(([name, table]) => (table.rows || []).length)\n .map(([name, table]) => [name, table.rows]);\n\n // This looks a tiny bit silly because we went from tables to table names\n // in `newTablesWithRows`, and now we're going back to tables, but that's\n // because `justThe` uses table names, so to keep things uniform here I\n // look up the tables by name in `allTables` again for the whole lot.\n const inserts = [...justThe('insertions'), ...newTablesWithRows]\n .map(([tableName, rows]) =>\n insertRows(dbdiff.allTables[tableName], rows));\n\n return [...creates, ...alterations, ...updates, ...inserts]\n .map(statement => statement + ';\\n')\n .join('\\n');\n}", "resetDatabase() {\n const stmt = this._db.prepare('DROP TABLE redeem')\n stmt.run()\n this.initDatabase()\n }", "visitUpgrade_table_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function getSqlTable(schemaVersion) {\n let version = \"v\" + (schemaVersion || DB_SCHEMA_VERSION);\n if (version in upgrade) {\n return upgrade[version]();\n } else {\n return {};\n }\n}", "visitAlter_table_properties_1(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "toString() {\n var statement = this._statement;\n this._applyHas();\n this._applyLimit();\n\n var parts = {\n fields: statement.data('fields').slice(),\n joins: statement.data('joins').slice(),\n where: statement.data('where').slice(),\n limit: statement.data('limit')\n };\n\n var noFields = !statement.data('fields');\n if (noFields) {\n statement.fields({ [this.alias()]: ['*'] });\n }\n var sql = statement.toString(this._schemas, this._aliases);\n\n for (var name in parts) {\n statement.data(name, parts[name]);\n }\n this._aliasCounter = {};\n this._aliases = {};\n this.alias('', this.schema());\n return sql;\n }", "toString(withComment = false) {\n let str = '';\n if (this.length > 0) {\n if (withComment) {\n str += '# Merkel migrations that need to run after checking out this commit:\\n';\n }\n for (const type of ['up', 'down']) {\n const tasks = this.filter(task => task.type === type);\n if (tasks.length === 0) {\n continue;\n }\n let command = `[merkel ${type} ${tasks.map(task => task.migration.name).join(' ')}]\\n`;\n if (command.length > 72) {\n command = `[\\n merkel ${type}\\n ${tasks.map(task => task.migration.name).join('\\n ')}\\n]\\n`;\n }\n str += command;\n }\n }\n return str.trim();\n }", "createCommentsTable() {\r\n const sql = `\r\n CREATE TABLE IF NOT EXISTS comments (\r\n CommentID integer primary key,\r\n comment text,\r\n time integer,\r\n date integer,\r\n is_Admin integer)`\r\n return this.DB.run(sql)\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Post multiples the modelview matrix with a scaling matrix and replaces the modelview matrix with the result
function gScale(sx,sy,sz) { modelMatrix = mult(modelMatrix,scale(sx,sy,sz)) ; }
[ "function gScale(sx,sy,sz) {\r\n modelViewMatrix = mult(modelViewMatrix,scale(sx,sy,sz)) ;\r\n}", "static scale(_matrix, _x, _y, _z) {\n return Mat4.multiply(_matrix, this.scaling(_x, _y, _z));\n }", "scale(scale) {\n const result = new Matrix();\n this.scaleToRef(scale, result);\n return result;\n }", "static mxScale(it,s) { \r\n\t\tvar res = new mx4(); \t\t\r\n\t\tfor (var i=0; i<16; ++i) { res.M[i] = it.M[i] *s; }\r\n\t\treturn res; \r\n\t}", "function setMV() {\r\n gl.uniformMatrix4fv(modelViewMatrixLoc, false, flatten(modelViewMatrix) );\r\n normalMatrix = inverseTranspose(modelViewMatrix) ;\r\n gl.uniformMatrix4fv(normalMatrixLoc, false, flatten(normalMatrix) );\r\n}", "function updateScale(increment) {\n var ctx = document.getElementById(\"canvas\").getContext(\"2d\");\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n //var viewportScale = document.getElementById(\"scale\").value;\n axes.scale += increment;\n draw();\n}", "static scale(v) {\r\n\t\tres = identity(); \t\tres.M[0] = v.x; \r\n\t\tres.M[5] = v.y; \t\tres.M[10] = v.z; \r\n\t\treturn res; \r\n\t}", "onTransformScaling() {\n const scale = this.getClosestScaleToFitExtentFeature();\n this.setScale(scale);\n }", "function scaleMatrix(sx,sy,sz) { // identidade\n return [\n [sx, 0, 0, 0],\n [0, sy, 0, 0],\n [0, 0, sz, 0],\n [0, 0, 0, 1]\n ]; //retorna matriz 4x4\n}", "function resetScaleTransform() {\n Data.Edit.Transform.Scale = 1;\n updateTransform();\n}", "scale(scale) {\n return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);\n }", "transform ( translationVector, theta, axis, scalingVector ) {\n \n modelViewMatrix = mat4.create();\n mat4.lookAt( modelViewMatrix, eye, at, up );\n\n var ctm = mat4.create();\n var q = quat.create();\n \n if ( axis === \"X\" ) {\n mat4.fromRotationTranslationScale( ctm, quat.rotateX( q, q, theta ), translationVector, scalingVector );\n } else if ( axis === \"Y\" ) {\n mat4.fromRotationTranslationScale( ctm, quat.rotateY( q, q, theta ), translationVector, scalingVector );\n } else if ( axis === \"Z\" ) {\n mat4.fromRotationTranslationScale( ctm, quat.rotateZ( q, q, theta ), translationVector, scalingVector );\n } else {\n throw Error( \"Axis isn't specified correctly.\" );\n }\n \n // calculates and sends the modelViewMatrix\n mat4.mul( modelViewMatrix, modelViewMatrix, ctm );\n this.gl.uniformMatrix4fv( modelViewLoc, false, modelViewMatrix );\n\n // calculates and sends the normalMatrix using modelViewMatrix\n normalMatrix = mat3.create();\n mat3.normalFromMat4( normalMatrix, modelViewMatrix );\n this.gl.uniformMatrix3fv( normalMatrixLoc, false, normalMatrix );\n\n }", "function setCurrentScale() {\n\t\tFloorPlanService.currentScale = $(FloorPlanService.panzoomSelector).panzoom(\"getMatrix\")[0];\n\t}", "set scale(newscale)\n\t{\n\t\tthis.myscale.x = newscale;\n\t\tthis.myscale.y = newscale;\n\n\t\tthis.container.style.transform = \"scale(\" + newscale + \",\" + newscale + \")\";\n \n\t\t//get width and height metrics\n\t\tthis.size.x = this.container.getBoundingClientRect().width;\n this.size.y = this.container.getBoundingClientRect().height;\n\n\t\t//adjust z order based on scale\n\t\tthis.container.style.zIndex = (100 * newscale).toString();\n\t}", "function _scaling ( /*[Object] event*/ e ) {\n\t\tvar activeObject = cnv.getActiveObject(),\n\t\tscale = activeObject.get('scaleY') * 100;\n\t\tif ( scale > 500 ) {\n\t\t\tactiveObject.scale(5);\n\t\t\tactiveObject.left = activeObject.lastGoodLeft;\n \tactiveObject.top = activeObject.lastGoodTop;\n\t\t}\n\t\tactiveObject.lastGoodTop = activeObject.top;\n \tactiveObject.lastGoodLeft = activeObject.left;\n\t\tif ( is_text(activeObject) ) {\n\t\t\teditTextScale.set( scale );\n\t\t\twindow.tmpTextProps && window.tmpTextProps.setNEW( 'scale', scale );\n\t\t\twindow.tmpTextProps && window.tmpTextProps.setNEW( 'top', activeObject.top );\n\t\t\twindow.tmpTextProps && window.tmpTextProps.setNEW( 'left', activeObject.left );\n\t\t}\n\t\telse {\n\t\t\teditImageScale.set(scale);\n\t\t}\n\t}", "function updateTransformationMatrixDisplay () {\n // Divide by 1 to remove trailing zeroes\n $('#matrixElemA').val(matrix.a.toFixed(decimalPlaces) / 1)\n $('#matrixElemB').val(matrix.b.toFixed(decimalPlaces) / 1)\n $('#matrixElemC').val(matrix.c.toFixed(decimalPlaces) / 1)\n $('#matrixElemD').val(matrix.d.toFixed(decimalPlaces) / 1)\n }", "function gPush() {\r\n MVS.push(modelViewMatrix) ;\r\n}", "function uploadModelViewMatrixToShader() \n{\n gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);\n}", "function gTranslate(x,y,z) {\r\n modelViewMatrix = mult(modelViewMatrix,translate([x,y,z])) ;\r\n}", "normalize(){\n for (var column = 0; column < 4; column++){\n for(var row = 0; row < 4; row++){\n this.matArray[column][row]\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A module that lets you easily switch to certain themes. the SSL themes are publicly offered as members.
function themeSwitcher(){ // this makes the LightWeightThemeManager resource available. // we need it to change the LightWeightThemes, also known as Personas. var {Cu} = require('chrome'); var sslStatus = require('./sslHandler').SSLHandler.SSL_STATUS; var PrefListener = require('./prefListener').PrefListener; var simpleStorage = require('sdk/simple-storage'); var simplePrefs = require('sdk/simple-prefs'); var data = require('sdk/self').data; var cleanupReasons = { standardActive : 'standardActive' }; // these Ids are going to be cleaned up whenever we switch to the default theme. // the reason is that we don't want them to appear in the extensions list. var sslPersonasThemeIds = ['ev','sv','http','https','sslp_standard']; var self = this; var themeChangedListener = new PrefListener( "lightweightThemes.", function(branch, name) { switch (name) { case "lightweight-theme-changed": case "persisted.headerURL": case "isThemeSelected": self.ensureCustomTheme(); break; case "lightweight-theme-change-requested": break; case "usedThemes": break; default: break; } } ); // Implitctly declared: var LightWeightThemeManger Cu.import('resource://gre/modules/LightweightThemeManager.jsm'); /** * Constants for available themes. */ this.theme = {}; this.theme.defaultTheme = simpleStorage.storage.userTheme || new Theme(); this.theme[sslStatus.extendedValidation] = new Theme('ev','Extended Validation Certificate Theme', data.url('img/themes/extendedValidation.png')); this.theme[sslStatus.standardValidation] = new Theme('sv','Standard Validation Certificate Theme', data.url('img/themes/standardValidation.png')); // we need to allow people to deactivate the red theme because a lot of users complained about seeing red all the time. resetInsecureConnectionTheme(); this.theme[sslStatus.brokenCertificate] = new Theme('https','Broken Certificate Theme', data.url('img/themes/brokenCertificate.png')); this.theme[sslStatus.otherProtocol] = simpleStorage.storage.userTheme || new Theme(); /** * Wrapper for the LightweightThemeManager's themeChanged method. * Only thing we do is make sure to clean up the SSLPersonas themes * if we switch to the default theme. * @param theme object of type {id:?,name:?,headerURL:?} */ this.switchToTheme = function(theme){ if(theme && typeof theme != 'undefined'){ LightweightThemeManager.themeChanged(theme); // it doesn't happen that often, to switch to the // default theme. // let's use this opportunity to quickly clean up // after our add on. if(theme.id == this.theme.defaultTheme.id){ this.cleanUpSSLPersonasThemes(cleanupReasons.standardActive); } } }; /** * we do not want to leave any traces. * That's why we tell the theme manager * to forget all our themes. * This might be called onUninstall or even onClose. */ this.cleanUpSSLPersonasThemes = function(reason){ // console.log("Cleanup "+reason); // on each clean up we restore the default theme // is restoring the default theme. // don't do this with this.switchToTheme, because this might // lead to recursion! if(typeof reason == 'undefined' || reason != cleanupReasons.standardActive){ try{ LightweightThemeManager.themeChanged(simpleStorage.storage.userTheme); } catch(e){ // pokemon! // gotta catch 'em all. } } // iterate over all themes that are stored // in this.theme // do not remove: defaultTheme, otherProtool for(var i=0;i<sslPersonasThemeIds.length;i++){ (function(id){ if(typeof id != 'undefined'){ try{ LightweightThemeManager.forgetUsedTheme(id); } catch(e){ console.warn("SSLPersonas could not clean up properly because there was an error with forgetUsedTheme"); } } })(sslPersonasThemeIds[i]); } }; /** * this maintains the user selected theme when SSLPersonas is installed or activated. */ this.ensureCustomTheme = function(){ var previousTheme = LightweightThemeManager.currentTheme; // there was an active theme that was not the default theme if(previousTheme != null && typeof previousTheme != 'undefined'){ if(previousTheme.id == self.theme.defaultTheme.id){ // we already are using the custom theme. // getting here results most likely from another // callback to the themeChangeListener return; } // let's see if the theme is one of our own: if(sslPersonasThemeIds.indexOf(previousTheme.id) == -1){ // if we get here, we know that the user has chosen her own theme. // let's try to preserve it. We're going to activate it when none // of our statuses are needed. simpleStorage.storage.userTheme = previousTheme; self.theme.defaultTheme = previousTheme; self.theme[sslStatus.otherProtocol] = previousTheme; // console.log('Trying to use theme ' + previousTheme.name + ' by ' + previousTheme.author); } else{ // last theme was an SSLPersonas theme. We don't persist anything. } } // the previous theme is Null in case the user chooses not to use // any custom theme, i.e. deactivates themes. // in that case, we want to use the standard theme again. else{ delete simpleStorage.storage.userTheme; self.theme.defaultTheme = new Theme(); self.theme[sslStatus.otherProtocol] = new Theme(); } }; /** * An Object wrapper for a lightweight theme. * @param id a randomly chosen string that will not be shown to the user * @param name a name for the theme that will appear in the theme selection. * @param headerURL a path or URL to an image that's large enough to span the entire chrome. */ function Theme(id,name,headerURL){ var additionalInfo = 'SSLPersonas'; this.id = id || 'sslp_standard'; this.name = additionalInfo + ": " + (name || 'Standard Theme'); // if headerURL is null, the LightWeightThemeManager // reverts to Firefox's default theme! this.headerURL = headerURL; this.footerURL = headerURL; // for people who actually use the footer. this.author = additionalInfo; } function resetInsecureConnectionTheme(){ switch (simplePrefs.prefs.insecureTheme){ case 'white': self.theme[sslStatus.insecureConnection] = new Theme('http', 'Insecure Connection Theme', data.url('img/themes/insecureConnection_white.png')); break; case 'red': self.theme[sslStatus.insecureConnection] = new Theme('http', 'Insecure Connection Theme', data.url('img/themes/insecureConnection_red.png')); break; default: self.theme[sslStatus.insecureConnection] = simpleStorage.storage.userTheme || new Theme(); break; } } //this.ensureCustomTheme(); // we want to be notified in case the user changes the theme. themeChangedListener.register(true); simplePrefs.on("insecureTheme", function(preferenceName){ resetInsecureConnectionTheme(); }); }
[ "function switchThemes(){\n var entirePage = document.getElementById( 'document-body' );\n if( entirePage.classList.contains( 'lightTheme' ) ){\n entirePage.classList.remove( 'lightTheme' );\n entirePage.classList.add( 'darkTheme' );\n document.cookie = \"theme=darkTheme;path=/\";\n }\n else if( entirePage.classList.contains( 'darkTheme' ) ){\n entirePage.classList.remove( 'darkTheme' );\n entirePage.classList.add( 'lightTheme' );\n document.cookie = \"theme=lightTheme;path=/\";\n }\n}", "function applyTheme(themeName) {\n document.body.classList = '';\n document.body.classList.add(themeName);\n document.cookie = 'theme=' + themeName;\n }", "function setupTheme() {\n var theme = interactive.theme;\n\n if (arrays[\"a\" /* default */].isArray(theme)) {\n // [\"a\", \"b\"] => \"lab-theme-a lab-theme-b\"\n theme = theme.map(function (el) {\n return 'lab-theme-' + el;\n }).join(' ');\n } else if (theme) {\n theme = 'lab-theme-' + theme;\n } else {\n theme = '';\n }\n\n $interactiveContainer.alterClass('lab-theme-*', theme);\n }", "function changeTheme(){\n\tvar new_theme = $('#theme').val();\n\teditor.setTheme(\"ace/theme/\"+new_theme);\n}", "function RetroTheme() {\n if (localStorage.getItem('theme') === 'theme-dark') {\n setTheme('theme-retro');\n } else if (localStorage.getItem('theme') === 'theme-light') {\n setTheme('theme-retro');\n } else {\n setTheme('theme-light');\n }\n}", "function updateThemeWithAppSkinInfo(appSkinInfo) {\n // console.log(appSkinInfo)\n var panelBgColor = appSkinInfo.panelBackgroundColor.color;\n var bgdColor = toHex(panelBgColor);\n var fontColor = \"F0F0F0\";\n if (panelBgColor.red > 122) {\n fontColor = \"000000\";\n }\n \n var styleId = \"hostStyle\";\n addRule(styleId, \"body\", \"background-color:\" + \"#\" + bgdColor);\n addRule(styleId, \"body\", \"color:\" + \"#\" + fontColor);\n \n var isLight = appSkinInfo.panelBackgroundColor.color.red >= 127;\n if (isLight) {\n $(\"#theme\").attr(\"href\", \"css/topcoat-desktop-light.css\");\n } else {\n $(\"#theme\").attr(\"href\", \"css/topcoat-desktop-dark.css\");\n }\n }", "function DarkTheme() {\n var themeNumber = 1;\n /*\n 1 - Light\n 2 - Dark\n 3 - Nocturne\n 4 - Terminal\n 5 - Indigo\n */\n // Your code here\n switch (themeNumber) {\n case 1:\n console.log(\"Light\");\n break;\n case 2:\n console.log(\"Dark\");\n break;\n case 3:\n console.log(\"Nocturne\");\n break;\n case 4:\n console.log(\"Terminal\");\n break;\n case 5:\n console.log(\"Indigo\");\n break;\n }\n}", "function handleThemeChange() {\n\t\tsetTheme(theme === \"light\" ? \"dark\" : \"light\");\n\t}", "function addRestoreDefaultThemeHandler() {\r\n $(document).on(\"click\", \"#open-chrome-settings-url\", function (e) {\r\n e.preventDefault();\r\n chrome.tabs.create({\r\n url: 'chrome://settings/'\r\n });\r\n });\r\n $(document).on(\"click\", \"#restore-default-theme-dialog-body\", function (e) {\r\n e.preventDefault();\r\n openUrlInNewTab($(this).find(\"#restore-default-theme-description\").attr(\"src\"));\r\n });\r\n}", "async addTheme(){\n //If there is no page styling already\n if(!document.querySelector('.eggy-theme') && this.options.styles){\n //Create the style tag\n let styles = document.createElement('style');\n //Add a class\n styles.classList.add('eggy-theme');\n //Populate it\n styles.innerHTML = '{{CSS_THEME}}';\n //Add to the head\n document.querySelector('head').appendChild(styles);\n }\n //Resolve\n return;\n }", "function initStyleSwitcher() {\n var isInitialzed = false;\n var sessionStorageKey = 'activeStylesheetHref';\n var titlePrefix = 'style::';\n\n function handleSwitch(activeTitle) {\n var activeElm = document.querySelector('link[title=\"' + activeTitle +'\"]');\n setActiveLink(activeElm);\n }\n\n function setActiveLink(activeElm) {\n var activeHref = activeElm.getAttribute('href');\n var activeTitle = activeElm.getAttribute('title');\n var inactiveElms = document.querySelectorAll(\n 'link[title^=\"' + titlePrefix + '\"]:not([href*=\"' + activeHref +'\"]):not([title=\"' + activeTitle +'\"])');\n\n // CUSTOM OVERRIDE to allow all Simple Dark titled CSS to be activated together\n // so now all CSS tag with same activeTitle will all be activated together in group\n var activeElms = document.querySelectorAll('link[title=\"' + activeTitle +'\"]');\n activeElms.forEach(function(activeElm){\n // Remove \"alternate\" keyword\n activeElm.setAttribute('rel', (activeElm.rel || '').replace(/\\s*alternate/g, '').trim());\n\n // Force enable stylesheet (required for some browsers)\n activeElm.disabled = true;\n activeElm.disabled = false;\n })\n\n // Store active style sheet\n sessionStorage.setItem(sessionStorageKey, activeTitle);\n\n // Disable other elms\n inactiveElms.forEach(function(elm){\n elm.disabled = true;\n\n // Fix for browsersync and alternate stylesheet updates. Will\n // cause FOUC when switching stylesheets during development, but\n // required to properly apply style updates when alternate\n // stylesheets are enabled.\n if (window.browsersyncObserver) {\n var linkRel = elm.getAttribute('rel') || '';\n var linkRelAlt = linkRel.indexOf('alternate') > -1 ? linkRel : (linkRel + ' alternate').trim();\n\n elm.setAttribute('rel', linkRelAlt);\n }\n });\n\n // CSS custom property ponyfil\n if ((window.$docsify || {}).themeable) {\n window.$docsify.themeable.util.cssVars();\n }\n }\n\n // Event listeners\n if (!isInitialzed) {\n isInitialzed = true;\n\n // Restore active stylesheet\n document.addEventListener('DOMContentLoaded', function() {\n var activeTitle = sessionStorage.getItem(sessionStorageKey);\n\n if (activeTitle) {\n handleSwitch(activeTitle);\n }\n });\n\n // Update active stylesheet\n /** \n * @OPTIMIZE: this will add event listener on all click\n */\n document.addEventListener('click', function(evt) {\n var dataTitle = evt.target.getAttribute('title');\n if(!dataTitle){ return 0; }\n var dataTitleIncludePrefix = dataTitle.toLowerCase().includes(titlePrefix);\n if(!dataTitleIncludePrefix){ return 0; }\n\n dataTitle = dataTitle\n || evt.target.textContent\n || '_' + Math.random().toString(36).substr(2, 9); // UID\n\n handleSwitch(dataTitle);\n evt.preventDefault();\n });\n }\n }", "function changeColorTextTheme(value, colorDark, colorLight) {\r\n if (value === \"dark\") {\r\n return { color: colorDark };\r\n } else return { color: colorLight };\r\n }", "function hideThemesDisableDial() {\r\n $('.available-themes-block').addClass('hide-first-av-content');\r\n}", "function setTheme (theme, pageName)\n{\n\t// check to see if base page is in page list\n\tif (pageName.indexOf(gBASE_PAGE) >= 0)\n\t\tvar base = theme;\n\telse\n\t\tvar base = getTheme (gBASE_PAGE);\n\t\t\n\tpageName = pageName.split (\"<br>\");\n\tfor (var n = 0; n < pageName.length; n++)\n\t\tsetSiteEditorCfgField (pageName[n], gTHEME, theme, base)\t\t\t\n}", "function browseTheme() \n{\n\t//Set lib source folder\n\tvar libFolder = settings.cssType == SPLIT_CSS ? PREF_SPLIT_JQLIB_SOURCE_FOLDER : PREF_JQLIB_SOURCE_FOLDER;\n\t\n\t//Get selected theme folder.\n\tvar browseRoot = dw.getPreferenceString(PREF_SECTION, libFolder, dw.getConfigurationPath()+\"/\"+assetDir);\n\tvar themeFolder = dw.getPreferenceString(PREF_SECTION, PREF_CSS_FILE, browseRoot);\n\t\n\t//Strings for browse file dialog.\n\tvar browseCSS = dw.loadString(\"Commands/jQM/files/alert/browseCSS\");\n\tvar cssFiles = dw.loadString(\"Commands/jQM/files/alert/label/cssFiles\");\n\t\n\tvar jQMThemeFile = dw.browseForFileURL(\"select\", browseCSS, false, true, new Array(cssFiles + \" (*.CSS)|*.css||\"), themeFolder);\n\t\n\tif (jQMThemeFile != \"\") {\n\t\t//Some file was chosen.\n\t\tvar cssName = getFileName(jQMThemeFile);\n\t\tvar cssExt = '.css';\n\t\t\n\t\t//Check to see if it's a CSS file.\n\t\tvar nameSuffix = cssName.substr(-4);\n\t\tif (nameSuffix === cssExt) {\n\t\t\t//Update display input.\n\t\t\tsettings.themeInput.value = jQMThemeFile;\n\t\t\tdw.setPreferenceString(PREF_SECTION, PREF_CSS_FILE, jQMThemeFile);\n\t\t} else {\n\t\t\t//Bad file!\n\t\t\tvar invalidCSSFile = dw.loadString(\"Commands/jQM/files/alert/invalidCSSFile\");\n\t\t\talert(invalidCSSFile);\n\t\t}\n\t}\n}", "function updateThemeField() {\n\tvar linkTypeValue = settings.linkType;\n\tvar themePref, themeDef;\n\t\n\t//Get the correct theme preference and default.\n\tif (linkTypeValue == REMOTE) {\n\t\tthemePref = REMOTE_THEME;\n\t\tthemeDef = jQMThemeSource;\n\t} else {\n\t\tvar libPath = getTrueConfigurationPath() + assetDir;\n\t\tthemeDef = libPath + localThemeCSS;\n\t\tthemePref = PREF_CSS_FILE;\n\t}\n\t\n\t//Pre-populate select menu with CSS files.\n\tvar cssOpts = dw.getPreferenceString(PREF_SECTION, themePref, themeDef);\n\tsettings.themeInput.value = cssOpts;\n}", "function getTheme (pageName)\n{\n\tvar theme = doAction ('DATA_GETCONFIGDATA', 'ObjectName', gSITE_ED_FILE, 'RowName', \n\t\t\t\t\t\t\t\t\tpageName, 'ColName', gTHEME);\n\treturn (theme);\n}", "_onThemeChanged() {\n this._changeStylesheet();\n if (!this._disableRedisplay)\n this._updateAppearancePreferences();\n }", "function getThemeStyleList (bCustomOnly, bThemes, bStyles)\n{\n\tvar styles = new Array(), themes = new Array();\n\tvar supStyles = new Array(), supThemes = new Array();\n\tvar custStyles = new Array(), custThemes = new Array();\n\tvar out = new Array();\n\tif(bStyles)\n\t{\n\t\tvar dirList = doActionBDO (\"DATA_DIRECTORYLIST\", \"ObjectName\", gPUBLIC,\n\t\t\t\t\t\t\t\t\t\"SubDirectoryPath\", gSTYLES_DIR+\"*.css\");\n\t\tvar labels = dirList.GetLabels();\n\t\tfor (var n = 0; n < labels.length; n++)\n\t\t{\n\t\t\tif (dirList[labels[n]].indexOf (\"SC_\") == 0)\n\t\t\t\tcustStyles.push (dirList[labels[n]]);\n\t\t}\n\t\tif (!bCustomOnly)\n\t\t{\n\t\t\tvar globalDirList = doActionBDO (\"DATA_DIRECTORYLIST\", \"ObjectName\", gSTYLE_OBJ);\n\t\t\tvar globalLabels = globalDirList.GetLabels();\n\t\t\tfor (var n = 0; n < globalLabels.length; n++)\n\t\t\t\tif (globalDirList[globalLabels[n]].indexOf (\"SS_\") == 0)\n\t\t\t\t\tsupStyles.push (globalDirList[globalLabels[n]]);\n\t\t}\n\t}\n\tif (bThemes)\n\t{\n\t\tvar dirList = doActionBDO (\"DATA_DIRECTORYLIST\", \"ObjectName\", gPUBLIC,\n\t\t\t\t\t\t\t\t\t\"SubDirectoryPath\", gTHEMES_DIR+\"*.css\");\n\t\tvar labels = dirList.GetLabels();\n\t\tfor (var n = 0; n < labels.length; n++)\n\t\t{\n\t\t\tif (dirList[labels[n]].indexOf (\"TC_\") == 0)\n\t\t\t\tcustThemes.push (dirList[labels[n]]);\n\t\t}\n\t\tif (!bCustomOnly)\n\t\t{\n\t\t\tvar themeLevel = doActionEx(\"DATA_GETLITERAL\",\"Result\",\"ObjectName\",gLICENSE_CFG,\"LiteralID\",\"THEME_CHOICE\");\n\t\t\tif (themeLevel)\n\t\t\t{\n\t\t\t\tthemeLevel += \".txt\";\n\t\t\t\tvar themeList = doActionEx\t('DATA_READFILE',themeLevel, 'FileName', themeLevel,\n\t\t\t\t\t\t\t\t\t\t\t'ObjectName',gTHEME_OBJ, 'FileType', 'txt');\n\t\t\t\tif (themeList)\n\t\t\t\t{\n\t\t\t\t\tthemeList = themeList.replace (/\\r|\\f/g, \"\");\n\t\t\t\t\tvar themeArray = themeList.split (\"\\n\");\n\t\t\t\t\tfor (var n = 0; n < themeArray.length; n++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (themeArray[n].length > 0)\n\t\t\t\t\t\t\tsupThemes.push (themeArray[n]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tstyles [\"customStyles\"] = custStyles;\n\tstyles [\"suppliedStyles\"] = supStyles;\n\tout[\"styles\"] = styles;\n\tthemes [\"customThemes\"] = custThemes;\n\tthemes [\"suppliedThemes\"] = supThemes;\n\tout[\"themes\"] = themes;\n\treturn (out);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clone an existing response profile.
static cloneAction(id, profile){ let kparams = {}; kparams.id = id; kparams.profile = profile; return new kaltura.RequestBuilder('responseprofile', 'clone', kparams); }
[ "function copyDefaultProfile() {\n\n // Setup sample data for new user\n SampleData.setupFor(userId)\n .then(function getDefaultProfile() {\n return mongoUtils.getEntityById(DEFAULT_USER, USERPROFILE_COL_NAME, DEFAULT_USER, [DEFAULT_GROUP])\n })\n .then(function copyDefaultProfile(err, defaultProfile) {\n console.log('Creating new profile for: ' + userId);\n if (err) {\n sendResponse(res, 'Error while setting up user: ' + err.message, null);\n return;\n }\n defaultProfile._id = userId;\n defaultProfile.owner = userId;\n defaultProfile.group = userId;\n defaultProfile.ingroups = [userId, DEFAULT_GROUP];\n\n _saveOrUpdateUserProfile(defaultProfile)\n .then(_.partial(sendResponse, res))\n .fail(_.partial(sendResponse, res, 'Failed to get UserProfile ' + userId));\n\n })\n }", "toProfile(profile) {\n return { \"name\": profile.name, \"id\": profile.uuid, \"_msmc\": profile._msmc };\n }", "clone() {\n let stats = {};\n this.forEachStat((name, value) => stats[name] = value)\n return new BirdStats(stats);\n }", "function cloneStatus( targetResponse, sourceResponse ) {\n return targetResponse.status( sourceResponse.statusCode );\n}", "clone() {\n var clone = new Player();\n clone.brain = this.brain.clone();\n clone.fitness = this.fitness;\n clone.brain.generateNetwork();\n clone.gen = this.gen;\n clone.bestScore = this.score;\n return clone;\n }", "function cloneResponse(material) {\n return material_management_1.cloneMaterial(material);\n}", "cloneListing() {\n const clone = this.clone();\n clone.unset('slug');\n clone.unset('hash');\n clone.guid = this.guid;\n clone.lastSyncedAttrs = {};\n return clone;\n }", "function restoreProfileFromSession() {\n var params = storageService.getUserInfo();\n if (params) {\n profile = params;\n }\n return profile;\n }", "function cloneData(data) {\r\n\t// Convert the data into a string first\r\n\tvar jsonString = JSON.stringify(data);\r\n \r\n\t// Parse the string to create a new instance of the data\r\n\treturn JSON.parse(jsonString);\r\n }", "copy() {\n return new ActiveUser(this.id, this.caret, this.colour);\n }", "function copyGame(id) {\n\n\tconsole.log(\"Replaying game \" + id);\n\n\tconst game = getGame(id);\n\n\tif (game == null) {\n\t\tconsole.log(\"Game \" + id + \" not found\");\n\n\t\treturn getNextGameID();\n\t}\n\n\tgame.reset();\n\n\tconst reply = {};\n\treply.id = game.getID();\n\n\treturn reply;\n\n}", "clone() {\n return new Point(this.data);\n }", "clone() {\n return new RNPermission(this);\n }", "function clone (buffer) {\r\n return copy(buffer, shallow(buffer));\r\n}", "static add(addResponseProfile){\n\t\tlet kparams = {};\n\t\tkparams.addResponseProfile = addResponseProfile;\n\t\treturn new kaltura.RequestBuilder('responseprofile', 'add', kparams);\n\t}", "clone() {\n const newMetadata = new Metadata(this.options);\n const newInternalRepr = newMetadata.internalRepr;\n for (const [key, value] of this.internalRepr) {\n const clonedValue = value.map(v => {\n if (Buffer.isBuffer(v)) {\n return Buffer.from(v);\n }\n else {\n return v;\n }\n });\n newInternalRepr.set(key, clonedValue);\n }\n return newMetadata;\n }", "copy() {\n if (this.era) return new $625ad1e1f4c43bc1$export$ca871e8dbb80966f(this.calendar, this.era, this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);\n else return new $625ad1e1f4c43bc1$export$ca871e8dbb80966f(this.calendar, this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);\n }", "copy() {\n return new $625ad1e1f4c43bc1$export$680ea196effce5f(this.hour, this.minute, this.second, this.millisecond);\n }", "static cloneAction(id, entryId){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.entryId = entryId;\n\t\treturn new kaltura.RequestBuilder('cuepoint_cuepoint', 'clone', kparams);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract translatable messages from an html AST
function extractMessages(nodes, interpolationConfig, implicitTags, implicitAttrs) { var visitor = new _Visitor(implicitTags, implicitAttrs); return visitor.extract(nodes, interpolationConfig); }
[ "static parseHTML( content, target, messages ){\n\n let search = function( node, map ){\n let children = node.children;\n for( let i = 0; i< children.length; i++ ){\n if( children[i].id ) map[children[i].id] = children[i];\n if( messages ){\n [\"title\", \"placeholder\"].forEach( function( attr ){\n let matchattr = `data-${attr}-message`;\n if( children[i].hasAttribute( matchattr )){\n let msg = children[i].getAttribute( matchattr );\n children[i].setAttribute( attr, messages[msg] );\n }\n });\n if( children[i].hasAttribute( \"data-textcontent-message\" )){\n let msg = children[i].getAttribute( \"data-textcontent-message\" );\n children[i].textContent = messages[msg] ;\n }\n }\n search( children[i], map );\n }\n };\n\n let nodes = {};\n target.innerHTML = content;\n search( target, nodes );\n return nodes;\n\n }", "addTranslatedMessagesToDom_() {\n const elements = document.querySelectorAll('.i18n');\n for (const element of elements) {\n const messageId = element.getAttribute('msgid');\n if (!messageId)\n throw new Error('Element has no msgid attribute: ' + element);\n const translatedMessage =\n chrome.i18n.getMessage('switch_access_' + messageId);\n if (element.tagName == 'INPUT')\n element.setAttribute('placeholder', translatedMessage);\n else\n element.textContent = translatedMessage;\n element.classList.add('i18n-processed');\n }\n }", "function extractMessage(jmap) {\n // Not all emails contain a textBody so we do a cascade selection\n let body = jmap.textBody || jmap.strippedHtmlBody || '';\n\n return textUtilities.replaceURLsinText(textUtilities.trimEmailThreads(body), () => 'URL');\n}", "function parseTranslationsSection(section) {\n let tables = section.body.match(/^{{(?:check)?trans-top(?:-also)?(?:\\|.*?)?}}[\\s\\S]*?^{{trans-bottom}}/mg);\n\n if (!tables) {\n tables = section.body.match(/^{{trans-see\\|.*?}}/mg);\n\n if (!tables) {\n console.log(\"UNEXPECTED 1026\", section.body);\n }\n }\n\n const tablemap = tables.map(table => parseTranslationTable(table));\n\n return tablemap;\n}", "function STLangVisitor() {\n STLangParserVisitor.call(this);\n this.result = {\n \"valid\": true,\n \"error\": null,\n \"tree\": {\n \"text\": \"\",\n \"children\": null\n }\n };\n\treturn this;\n}", "convertHtml(htmlText, lnMode) {\n const docDef = [];\n this.lineNumberingMode = lnMode || LineNumberingMode.None;\n // Cleanup of dirty html would happen here\n // Create a HTML DOM tree out of html string\n const parser = new DOMParser();\n const parsedHtml = parser.parseFromString(htmlText, 'text/html');\n // Since the spread operator did not work for HTMLCollection, use Array.from\n const htmlArray = Array.from(parsedHtml.body.childNodes);\n // Parse the children of the current HTML element\n for (const child of htmlArray) {\n const parsedElement = this.parseElement(child);\n docDef.push(parsedElement);\n }\n return docDef;\n }", "function htmlToPassage(raw, isCorrect) {\n convertedPassage = '';\n\n for (let i = 0; i < raw.length; i ++) {\n if(raw[i] != '{') {\n convertedPassage += raw[i];\n } else {\n let string = getSpecialString(raw.substring(i)).specialString;\n convertedPassage += parseString(string, isCorrect).value;\n //change value of i to skip to the end of the parsed string\n i += getSpecialString(raw.substring(i)).charIndex;\n }\n }\n return convertedPassage;\n}", "function captureTomDoc(comments) {// collect lines up to first paragraph break\n const lines = [];for (let i = 0; i < comments.length; i++) {const comment = comments[i];if (comment.value.match(/^\\s*$/)) break;lines.push(comment.value.trim());} // return doctrine-like object\n const statusMatch = lines.join(' ').match(/^(Public|Internal|Deprecated):\\s*(.+)/);if (statusMatch) {return { description: statusMatch[2], tags: [{ title: statusMatch[1].toLowerCase(), description: statusMatch[2] }] };}}", "function getTranslationDeclStmts(variable, closureVar, message, meta, params, transformFn) {\r\n if (params === void 0) { params = {}; }\r\n var statements = [];\r\n statements.push.apply(statements, __spread(i18nTranslationToDeclStmt(variable, closureVar, message, meta, params)));\r\n if (transformFn) {\r\n statements.push(new ExpressionStatement(variable.set(transformFn(variable))));\r\n }\r\n return statements;\r\n }", "function substituteForTranslationFailures(translationResult) {\n var foundSubstitute = false;\n var substituteText;\n translationResult.targets.forEach(function(target) {\n if (target.success && target.language === 'en') {\n substituteText = target.text;\n foundSubstitute = true;\n }\n });\n if (!foundSubstitute) {\n substituteText = translationResult.source.text;\n }\n translationResult.targets.forEach(function(target) {\n if (!target.success) {\n target.text = substituteText;\n }\n });\n}", "function collectTextNodes($, $el) {\n let textNodes = [];\n $el.contents().each((ii, node) => {\n if (isTextNode(node)) {\n let $node = $(node);\n textNodes.push($node);\n } else {\n textNodes.push(...collectTextNodes($, $(node)));\n }\n });\n return textNodes;\n}", "static parseEvolutionTreeFromDexPage(evolutionTreeParser, html, dexIDMap) {\n const rootName = DexPageParser.getInfoFromDexPageHeader(html).name;\n const tree = html.find('.evolutiontree').eq(0);\n const flattened = evolutionTreeParser.parseEvolutionTree(rootName, tree, dexIDMap);\n return flattened;\n }", "getMessagesList() {\n return Object.keys(i18nMessages).map( (language) => {\n return bcp47normalize(language);\n });\n }", "function wikiparse( contents )\n{\n //global config;\n //patterns = [];\n //replacements = [];\n patterns = [];\n replacements = [];\n //contents = htmlspecialchars(contents, ENT_COMPAT, \"UTF-8\");\n contents = htmlspecialchars(contents.addSlashes());\n // webpage links\n patterns[0] = \"/\\\\[\\\\[([^\\\\[]*)\\\\]\\\\]/\";\n replacements[0] = \"\\\"+webpagelink( \\\"$1\\\" )+\\\"\"; \n\n // images\n patterns[1] = \"/{{([^{]*)}}/\";\n replacements[1] = \"\\\"+image( \\\"$1\\\" )+\\\"\"; \n\n // coloured text\n patterns[2] = \"/~~#([^~]*)~~/\";\n replacements[2] = \"\\\"+colouredtext( \\\"$1\\\" )+\\\"\"; \n \n patterns[3] = '/\\\\$/';\n replacements[3] = \"&DOLLAR;\";\n \n // verbatim text\n patterns[4] = \"/~~~(.*)~~~/\";\n replacements[4] = \"\\\"+verbatim( \\\"$1\\\" )+\\\"\";\n\n if ( config.SYNTAX.HTMLCODE )\n {\n patterns[5] = \"/%%(.*)%%/\";\n replacements[5] = \"\\\"+htmltag( \\\"$1\\\" )+\\\"\"; \n }\n\n // substitute complex expressions\n contents = wikiEval( contents.preg_replace( patterns, replacements ) );\n //contents = contents.preg_replace( patterns, replacements );\n //contents = wikiEval( contents );\n patterns = [];//[];\n replacements = [];//array();\n\n // h1\n patterns[0] = \"/==([^=]*[^=]*)==/\";\n replacements[0] = \"<h1>$1</h1>\";\n\n // italic\n patterns[1] = \"/''([^']*[^']*)''/\";\n replacements[1] = \"<i>$1</i>\";\n\n // bold\n patterns[2] = \"/\\\\*\\\\*([^\\\\*]*[^\\\\*]*)\\\\*\\\\*/\";\n replacements[2] = \"<b>$1</b>\";\n\n // underline\n patterns[3] = \"/__([^_]*[^_]*)__/\";\n replacements[3] = \"<span style=\\\\\\\"text-decoration: underline;\\\\\\\">$1</span>\"; \n\n // html shortcuts\n patterns[4] = \"/@@([^@]*)@@/\";\n replacements[4] = \"<a name=\\\\\\\"$1\\\\\\\"></a>\";\n \n // wiki words \n if ( config.SYNTAX.WIKIWORDS )\n {\n patterns[5] = \"/([A-Z][a-z0-9]+[A-Z][A-Za-z0-9]+)/\";\n replacements[5] = \"\\\"+wikilink( \\\"$1\\\" )+\\\"\"; \n }\n\n // substitute simple expressions & final expansion\n contents = wikiEval( contents.preg_replace( patterns, replacements ) );\n //contents = contents.preg_replace( patterns, replacements );\n patterns = [];//array();\n replacements = [];//array();\n\n // replace some whitespace bits & bobs \n patterns[0] = \"/\\t/\";\n replacements[0] = \"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\";\n patterns[1] = \"/ /\";\n replacements[1] = \"&nbsp;&nbsp;\";\n patterns[2] = \"/&DOLLAR;/\";\n replacements[2] = \"$\";\n patterns[3] = \"/\\n/\";\n replacements[3] = \"<br>\\n\";\n contents = contents.preg_replace( patterns, replacements );\n return contents;\n}", "function renderToMessage_Targets(html, messageData) {\n // Return cases\n if( game.settings.get(MOD_ID, \"targetsSendToChat\") === \"none\" ) { return; }\n if( !messageData.message.roll ) { return; }\n \n var rollDict = JSON.parse(messageData.message.roll);\n let targetedTokens = getTokenObjsFromIds(rollDict.selectedTargets);\n if(!targetedTokens) { return; }\n \n // Build targets message\n let targetNodes = getTokensHTML(targetedTokens);\n if( !targetNodes || targetNodes.length == 0 ) { return; }\n \n // Create Base Info\n let targetsDiv = document.createElement(\"div\");\n targetsDiv.classList.add(\"targetList\");\n \n let targetsLabel = document.createElement(\"span\");\n targetsLabel.classList.add(\"targetListLabel\");\n targetsLabel.innerHTML = `<b>TARGETS:</b>`;\n targetsDiv.append(targetsLabel);\n \n // Add targets\n for(let i = 0; i < targetNodes.length; i++) {\n targetNode = targetNodes[i];\n targetsDiv.append(targetNode);\n }\n \n // append back to the message html\n html[0].append(targetsDiv);\n \n // Add target all hover function\n if( game.settings.get(MOD_ID, \"chatIntegrationClick\") ) {\n let targetsLabelList = html.find(\".targetListLabel\");\n if(targetsLabelList) targetsLabelList.click(_onChatNameClick_all);\n }\n}", "toTokens(msg) {\n // remove the prefix\n let tokensString = msg.content.slice(1).trim();\n // parse the tokens into an array\n let tokens = parse(tokensString)['_'];\n return tokens;\n }", "rawHTML(html) {\n this.$messages.html(this.$messages.html() + html);\n return this.$messagesContainer.restoreScrollPosition();\n }", "getMessages(language) {\n let languageKey = Object.keys(i18nMessages).find( (currentLanauge) => {\n return language === bcp47normalize(currentLanauge);\n });\n \n return i18nMessages[languageKey];\n }", "function parse(html, shouldSort) {\n var $ = cheerio.load(html);\n\n return $('page').map((idx, pageElem) => {\n var $page = $(pageElem);\n\n return new Page(\n $page.attr('width'), $page.attr('height'),\n $page.children('word').map((idx, wordElem) => {\n var $word = $(wordElem);\n\n return new Text(\n $word.attr('xmin'), $word.attr('xmax'),\n $word.attr('ymin'), $word.attr('ymax'), $word.text().trim()\n );\n }).get()\n );\n }).get();\n}", "function extractSentences(raw) {\n return $.map(raw[0], (function(v) { return v[0]; })).join('');\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
initialize variables such as lastUpdate (important for gravity !)
init(){ this.speedX=0; this.speedY=-this.maxSpeed; this.speedZ=0; // these two components are used to know speed in the new coordinates after a rotation this.speedXAfterRotate=0; this.speedZAfterRotate=0; let now = (new Date).getTime(); this.lastUpdate=now; }
[ "initializeTimeProperties () {\r\n this.timeAtThisFrame = new Date().getTime();\r\n this.timeAtFirstFrame = new Date().getTime();\r\n this.timeAtLastFrame = this.timeAtFirstFrame;\r\n\r\n // time and deltaTime are local scene properties\r\n // we set the dynamically created t and dt in the update frame\r\n this.time = 0;\r\n this.deltatime = 0;\r\n }", "initDistTime () {\n this.eachDatum((x, y, status) => {\n const beta = this._ellipse.betaPoint(x, y) // { radians, ratio, rate, dist, time }\n this.set(x, y, new Location(beta.dist, beta.time, Unvisited, Unvisited))\n })\n }", "_initializeGameValues() {\n this.currentFPS = GameConfig.STARTING_FPS;\n this.scoreBoard.resetScore();\n\n this.player = new Player(this.gameView.getPlayerName(), \"white\");\n this.food = new Food(this.boardView.getRandomCoordinate(this.player.segments), \"lightgreen\");\n this.gameView.hideChangeNameButton();\n }", "updateTimeProperties () {\r\n this.timeAtThisFrame = new Date().getTime();\r\n\r\n // divide by 1000 to get it into seconds\r\n this.time = (this.timeAtThisFrame - this.timeAtFirstFrame) / 1000.0;\r\n\r\n this.deltaTime = (this.timeAtThisFrame - this.timeAtLastFrame) / 1000.0;\r\n this.timeAtLastFrame = this.timeAtThisFrame;\r\n\r\n // update and set our scene time uniforms\r\n this.t = this.time / 10;\r\n this.dt = this.deltaTime;\r\n }", "initPosition (position) {\n\t\tthis.init_x = parseFloat(position.coords.latitude);\n\t\tthis.init_z = parseFloat(position.coords.longitude);\n\t\tthis.lat = this.init_x;\n\t\tthis.long = this.init_z;\n\t\tthis.camera.setAttribute(\"position\", this.generatePosition(this.init_x, this.init_z));\n\t\tconsole.log(\"Home is: [\"+this.init_x + \",\" + this.init_z+\"]\");\n\t\tthis.emit(\"update\", {\n\t\t\tlat: this.init_x, \n\t\t\tlong: this.init_z\n\t\t});\n\t}", "loadZero()\n\t{\n\t\tthis._x = this._y = this._z = 0.0;\n\t}", "function resetVars(state) {\n keepBallAttached = false;\n ballIsUp = false;\n fired = false;\n }", "constructor(){\r\n this.points = []\r\n this.numpoints = 100\r\n this.gravity = 0.1;\r\n }", "notify_speed_update() {\n this.speed_update = true;\n }", "update() {\n //update coordinates so the droid will orbit the center of the canvas\n if (!this.sceneManager) {\n this.sceneManager = this.game.sceneManager;\n }\n this.calcMovement();\n\n /* droid shooting */\n this.secondsBeforeFire -= this.game.clockTick;\n //will shoot at every interval\n if (this.secondsBeforeFire <= 0 && (!this.fire)) {\n this.secondsBeforeFire = this.shootInterval;\n this.fire = true;\n this.shoot();\n }\n\n super.update();\n }", "reset(){\n this.setSpeed();\n this.setStartPosition();\n }", "function InitBoardVars()\n{\n\t//Initializing history table\n\tfor(let i = 0; i < MAXGAMEMOVES; i++) \n\t{\n\t\tGameBoard.history.push\n\t\t({\n\t\t\tmove: NOMOVE,\n\t\t\tcastlePerm: 0,\n\t\t\tenPas: 0,\n\t\t\tfiftyMove: 0,\n\t\t\tposKey: 0\n\t\t});\n\t}\t\n\t//Initializing Pv Table\n\tfor (let i = 0; i < PVENTRIES; i++)\n\t{\n\t\tGameBoard.PvTable.push\n\t\t({\n\t\t\tmove: NOMOVE,\n\t\t\tposKey: 0\n\t\t});\n\t}\n}", "resetPosition(){\n this.speed = 0;\n this.deltaT = 0;\n this.rotation = 0;\n this.position[0] = this.startingPos[0];\n this.position[1] = this.startingPos[1];\n this.position[2] = this.startingPos[2];\n }", "constructor(){\n this.started = false;\n this.score = 0;\n this.level = 1;\n this.grid = new Grid();\n this.active = new Block();\n }", "update() {\n let frameStart = (performance || Date).now();\n // track wall time for game systems that run when the ECS gametime\n // is frozen.\n let wallDelta = this.lastFrameStart != -1 ?\n frameStart - this.lastFrameStart :\n Constants.DELTA_MS;\n this.lastFrameStart = frameStart;\n // pre: start stats tracking\n this.updateStats.begin();\n // note: implement lag / catchup sometime later. need to measure\n // timing too if we want this.\n this.game.update(wallDelta, Constants.DELTA_MS);\n // post: tell stats done\n this.updateStats.end();\n // Pick when to run update again. Attempt to run every\n // `this.targetUpdate` ms, but if going too slow, just run as soon\n // as possible.\n let elapsed = (performance || Date).now() - frameStart;\n let nextDelay = Math.max(this.targetUpdate - elapsed, 0);\n setTimeout(update, nextDelay);\n }", "init(){\n\t\tthis.calcStats();\n\t\tthis.hpRem = this.getStatValue(Stat.HP);\n\n\t\tthis.poisoned = false;\n\t\tthis.regen = false;\n\t\tthis.shield = false;\n\n this.healableDamage = 0; //damage that can be healed through heart collection\n\n this.eventListenReg.clear();\n\n this.warriorSkills.forEach((skill)=>{\n skill.apply();\n });\n\t}", "function updateVariables() {\n secondNumber = null;\n firstNumber = displayValue;\n operation = null;\n}", "function initCannon(){\n\tworld = new CANNON.World;\n\tworld.gravity.set(0,-9.81, 0);\n\tworld.solver.iterations = 3;\n}", "function initialize(){\n seconds = 0;\n INITIALIZING = true;\n SAVE_DATA = false;\n GEN_PASSENGERS = false; //If true, we are waiting for Python to return from Generating Passengers\n READY_TO_INS_TRIPS = false; //If true, we have finished generating passengers and are ready to insert trips into the system\n INS_TRIPS = false; //If true, we are waiting for Python to return from inserting trips into the system\n \n initialize_simulation_data();\n if(master_interval == false){\n\tmaster_interval = setInterval(function(){master()},1000);}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Render the given partial content
render(partialName, content) { if (partialName != 'content' && !this.partials.has(partialName)) { throw new Error(`Call to unknown partial: ${partialName}`); } if (this.events.trigger(`loading.${partialName}`, content, this) === false) return; let selector = partialName == 'content' ? 'main' : this.partials.get(partialName).selector || partialName; this.container.find(selector).html(content); this.events.trigger(`${partialName}.load`, content, this); }
[ "function _render( options ) {\n\n\t\tvar template_id = options.template_id,\n\t\t\t$target = options.$target,\n\t\t\tdata_url = options.data_url\n\t\t;\n\n\t\t$.ajax({\n\t\t\t'url': data_url,\n\t\t\t'dataType': 'json',\n\t\t\t'success': function( data ) {\n\n\t\t\t\tvar html = $( template_id ).html(),\n\t\t\t\t\ttemplate = _.template( html )\n\t\t\t\t;\n\n\t\t\t\t_.find( data.items, function( index ) {\n\n\t\t\t\t\tvar html = template({\n\t\t\t\t\t\t'title': index.title,\n\t\t\t\t\t\t'body': index.body,\n\t\t\t\t\t\t'slug': index.urlId\n\t\t\t\t\t});\n\n\t\t\t\t\t$target.append( html );\n\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\n\t}", "function showTemplate(template, data){\r\n\tvar html = template(data);\r\n\t$('#content').html(html);\r\n}", "function getPartial(filename, req, type) {\n return new Promise(function (resolve, reject) {\n type = type ? type : \"partial\";\n let dir;\n if(type == \"partial\") {\n dir = \"partials\";\n }\n else if(type == \"page\") {\n dir = \"pages\";\n }\n\t\tif(filename) {\n\t\t\tif(filename.length - filename.lastIndexOf(\".html\") - 1 == 5) {\n\t\t\t\tfilename.slice(0, -5);\n\t\t\t}\n\t\t\tfs.readFile('public/html/' + dir + '/' + filename + \".html\", 'utf8', function(err, data) {\n\t\t\t\tif(!err) {\n\t\t\t\t\tif(req) {\n\t\t\t\t\t\tif(!req.renderData) {\n\t\t\t\t\t\t\treq.renderData = {};\n\t\t\t\t\t\t}\n if(type == \"partial\") {\n if(!req.renderData[filename])\n req.renderData[filename] = {};\n req.renderData[filename].partial = data;\n } else if(type == \"page\")\n req.renderData.pageContent = data;\n\t\t\t\t\t}\n return resolve(data);\n\t\t\t\t} else {\n\t\t\t\t\treturn reject(err);\n\t\t\t\t}\n\t\t\t});\n\t\t} else {\n\t\t\treturn reject(\"No filename provided\");\n\t\t}\n\t});\n}", "render(viewPath, data = {}, scope = this.app) {\r\n if (!this.views.has(viewPath)) {\r\n throw new Error(`Not Found view ${viewPath}`);\r\n }\r\n\r\n let content = this.get(viewPath);\r\n \r\n // let start = performance.now();\r\n\r\n let compiler = new ViewCompiler(viewPath, content, data, scope);\r\n\r\n // let end = performance.now();\r\n\r\n // echo(viewPath + ' -> ' + (end - start));\r\n\r\n return compiler.html;\r\n }", "render(){\n\t\tthis.loadStyle();\n\t\tthis.renderView();\n\t}", "render() {\n templateSettings.interpolate = /{{([\\s\\S]+?)}}/g;\n const temp = document.querySelector(`#${SETTINGS.Id.TOGGLE_TEMP}`).innerHTML;\n const tempFn = template(temp);\n const markup = tempFn({ data: this.data });\n this.container.insertAdjacentHTML('beforeend', markup)\n }", "function renderPreset(preset){\r\n\r\n var template = Handlebars.compile($('#'+preset+'PresetTemplate').html());\r\n Handlebars.registerPartial(\"assetEditor\", $('#assetEditorTemplate').html());\r\n\r\n data = new Object();\r\n data['assetId'] = \"1\";\r\n data['else'] = \"something\";\r\n\r\n $('#editorView').html(template(data));\r\n\r\n}", "function renderQuestion () {\n $('main').html(generateQuestion());\n}", "function render(items) {\n // LOOP\n // var item = ...\n // $(\"div#target\").append(\"<p>\" + item.message + \"</p>\")\n //\n }", "function renderContext() {\n var theTemplateScript = $(\"#list-card-template\").html();\n var theTemplate = Handlebars.compile(theTemplateScript);\n var theCompiledHtml = theTemplate(GLOBALS.userdata);\n $('#content-area').html(theCompiledHtml);\n applyJQuerySortable();\n }", "function renderMyActivities (user) {\n contentBody.innerHTML = formatActivities(user)\n }", "async render(documentId, viewName, viewData) {\n try {\n let html;\n try {\n const {data} = await this.localApi.request({\n url: `/view-engine/web-components/${viewName}.ejs`\n })\n html = ejs.render(data, viewData)\n } catch(e) {\n html = \"Ocurrió un error desconocido\"\n }\n document.getElementById(documentId).innerHTML = html\n } catch(e) {\n console.log(e)\n console.log('ERROR RENDERING %s', e.message)\n }\n }", "onRender() {}", "_render() {\n if (this._connected && !!this._template) {\n render(this._template(this), this, {eventContext: this});\n }\n }", "function renderByType() {\n\t\t\t\tswitch(templateEngineRequire.renderType()) {\n\t\t\t\t\tcase 'string':\n\t\t\t\t\t\trenderStringFromFile(templateEngineRequire, viewPath, view.data, function(err,data) {\n\t\t\t\t\t\t\tcallback(err,data);\n\t\t\t\t\t\t});\t\t\t\t\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'file':\n\t\t\t\t\t\trenderFile(templateEngineRequire, viewPath, view.data, function(err,data) {\n\t\t\t\t\t\t\tcallback(err,data);\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tcallback(new Error('The template engine has an unsupported renderType'));\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}", "function render(file, context, options, callback) {\n winston.verbose('rendering: ' + file);\n options = options || {};\n options.cache = options.cache || objCache;\n options.cacheKey = file;\n options.hoganOptions = options.hoganOptions || {};\n\n getTemplate(file, options, function(err, t) {\n callback(err, t ? t.template.render(context, t.partials) : err.message);\n });\n}", "function render(msg)\n{\n document.getElementById('feeds').innerHTML = msg;\n}", "renderAndReply(originalMessage, templateName, params = null) {\n var content = \"\";\n this.mu.compileAndRender(templateName, params)\n .on('data', function (data) {\n content += data.toString();\n })\n .on('end', () => {\n originalMessage.reply(content);\n });\n }", "build(basePath = this.defaultBasePath) {\r\n if (typeof this.container != 'undefined') {\r\n this.container.remove();\r\n }\r\n\r\n if (Is.callable(basePath)) {\r\n basePath = basePath();\r\n }\r\n\r\n this.container = $(basePath ? render(basePath) : this.view.render('core/layout/layout/base'));\r\n\r\n $('body').prepend(this.container);\r\n\r\n this.content = this.container.find('main');\r\n\r\n this.preparePartials();\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display the current list of feed URL items.
function displayFeedsUrlList() { const message = document.getElementById("feedsUrlMessage"); const headers = {"Authorization": getToken()}; apiRequest("GET", "get_feeds_url.php", null, headers, res => { const jsonRes = JSON.parse(res.responseText); for (const feed of jsonRes.feeds) addFeedUrlToList(feed.id, feed.url); message.innerHTML = ""; message.className = ""; }, err => handleRequestError(err.status, "Erreur lors de la récupération des flux.", message) ); }
[ "function getFeedItems(feed) {\n\t\t$.ajax({\n\t\t url: urlBase + 'articles/' + encodeURIComponent(feed.feed),\n\t\t\tdataType: \"json\",\n\t\t\tsuccess: function (data) {\n\t\t\t\tko.utils.arrayForEach(data, function(item) {\n\t\t\t\t\tvm.displayedItems.push( new Item(feed, item) );\n\t\t\t\t\t\n\t\t\t\t\tvar bool = containsId(vm.bookmarkedArray(), vm.displayedItems()[vm.displayedItems().length-1]);\n\t\t\t\t\t\n\t\t\t\t\tif(vm.displayedItems()[vm.displayedItems().length-1].favorite() == 'fav-icon' && bool)\n\t\t\t\t\t\tvm.bookmarkedArray.push(vm.displayedItems()[vm.displayedItems().length-1]);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}", "function Listing() {\n this.feeds = {}; \n this.sortIDs = {};\n this.folders = {};\n this.max = 1000;\n this.openFolders = {};\n this.scroll = false;\n this.show = 'all';\n this.init = true;\n}", "function fetchFeedItems(url, from, count, callback) {\n\t\tfrom = from || 0;\n\t\tcount = count || 20;\n\t\t\n\t\tvar feed = new google.feeds.Feed(FEED_URL);\n\t\tfeed.setResultFormat(google.feeds.Feed.JSON_FORMAT);\n\t\tfeed.setNumEntries(from + count);\n\t\tfeed.includeHistoricalEntries();\n\t\tlog('From ' + from + ' to ' + (from + count) + '\\n');\n\t\tfeed.load(function(result) {\n\t\t\tif (result.error) {\n\t\t\t\tret = false;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Set title\n\t\t\t\theader = '<a href=\"' + result.feed.link + '\" rel=\"external\" target=\"_blank\"><h1>' + result.feed.title + '</h1></a>';\n\t\t\t header += '<h2><small>' + result.feed.description + '</small></h2>';\n\t\t\t header += '<hr class=\"soften\">'; \n\t\t\t $('body > div.container-fluid > .title-wrapper').html(header);\n\t\t\t\t\n\t\t\t\tvar max = (count > result['feed'].entries.length) ? count : result['feed'].entries.length;\n\t\t\t\titems = [];\n\t\t\t\tfor (var i = from; i < max; i++) {\n\t\t\t\t\titem = result['feed'].entries[i];\n\t\t\t\t\titem.eid = i;\n\t\t\t\t\tENTRIES[i] = item;\n\t\t\t\t\titems.push(item);\n\t\t\t\t}\n\t\t\t\tret = items;\t\n\t\t\t}\t\n\t\t\t\n\t\t\tif (callback && $.isFunction(callback)) {\n\t\t\t\tcallback(ret);\n\t\t\t}\n\t\t});\n\t}", "function nextClicked() {\n if (currentFeed && currentItemIndex < currentFeed.items.size - 1) {\n currentItemIndex++;\n displayCurrentItem();\n }\n }", "fetch() {\n this._client.get(`/sales-channel-api/v1/sns/instagramfeed?media=${this.options.count}`, (responseText) => {\n this.el.outerHTML = responseText;\n });\n }", "function showItems() {\n\t\tvar itemlist = [];\n\t\n\t\tfor (var i = 0; i < room.items.length; i++) {\n\t\t\tif (room.items[i].specialdesc) {\n\t\t\t\toutput.before(room.items[i].specialdesc + \"<br />\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\titemlist.push(room.items[i].desc);\n\t\t\t}\n\t\t}\n\t\n\t\tif (itemlist.length === 1) {\n\t\t\toutput.before(\"There is a \" + itemlist[0] + \" here.<br /><br />\");\n\t\t}\n\t\telse if (itemlist.length > 1) {\n\t\t\tvar str = \"\";\n\t\t\tfor (var i = 0; i < itemlist.length; i++) {\n\t\t\t\tif (!itemlist[i + 1]) {\n\t\t\t\t\tstr.concat(itemlist[i]);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tstr.concat(itemlist[i] + \", \");\n\t\t\t\t}\n\t\t\t}\n\t\t\toutput.before(\"There is a \" + str + \" here.<br /><br />\");\n\t\t}\n\t\n\t\tscrollDown();\n\t\n\t}", "function loadOnScreen(){\n\tHeadingArray = getOnScreenHeadingArray();\n URLArray = getOnScreenURLArray();\n\t\n\tfor(var i = 0; i<HeadingArray.length; i++)\n\t getFeed(HeadingArray[i],URLArray[i]);\n}", "function _getNewFeeds() {\n\n let query = {\n tag: 'steemovie',\n limit: 21,\n };\n\n steem.api.getDiscussionsByCreated(query, function (err, result) {\n app.feeds = result;\n\n // Rendering process of image image\n renderingImagePaths(result)\n });\n\n}", "function fetch() {\n $http.get(resourceUrl + $scope.search + '&maxResults=20&orderBy=newest')\n .success(function(data) {\n $scope.data = data;\n $scope.bookFeed = data.items;\n });\n }", "async displayRecentSearches(){\n try{\n // load the recent search from the device database cache\n let recentSearchData = await utopiasoftware[utopiasoftware_app_namespace].databaseOperations.\n loadData(\"recent-searches\", utopiasoftware[utopiasoftware_app_namespace].model.appDatabase);\n\n let displayContent = \"<ons-list-title>Recent Searches</ons-list-title>\"; // holds the content of the list to be created\n // create the Recent Searches list\n for(let index = 0; index < recentSearchData.products.length; index++){\n displayContent += `\n <ons-list-item modifier=\"longdivider\" tappable lock-on-drag=\"true\">\n <div class=\"center\">\n <div style=\"width: 100%;\" \n onclick=\"utopiasoftware[utopiasoftware_app_namespace].controller.searchPageViewModel.\n recentSearchesItemClicked(${index})\">\n <span class=\"list-item__subtitle\">${recentSearchData.products[index].name}</span>\n </div>\n </div>\n <div class=\"right\" prevent-tap \n onclick=\"utopiasoftware[utopiasoftware_app_namespace].controller.searchPageViewModel.\n removeRecentSearchItem(${index}, this);\">\n <ons-icon icon=\"md-close-circle\" style=\"color: lavender; font-size: 18px;\"></ons-icon>\n </div>\n </ons-list-item>`;\n }\n // attach the displayContent to the list\n $('#search-page #search-list').html(displayContent);\n }\n catch(err){\n\n }\n }", "function getItems() {\n fetch('http://genshinnews.com/api')\n .then(response => response.text())\n .then(data => {\n discordHooks = JSON.parse(`[${data}]`)\n webhookLoop(discordHooks)\n });\n }", "ShowCurrentItems(){\n MyUtility.getInstance().sendTo('telegram.0', {\n chatId : MyUtility.getInstance().getState('telegram.0.communicate.requestChatId'/*Chat ID of last received request*/).val,\n text: 'Bitte Raum wählen:',\n reply_markup: {\n keyboard:\n this._telegramArray.getTelegramArray(this._currentIDX)\n ,\n resize_keyboard: true,\n one_time_keyboard: true\n }\n });\n\n this.emit(\"onItemChange\",this);\n }", "async loadPlaylists(url) {\n\t\tlet response = await utils.apiCall(url, this.props.access_token);\n\t\tthis.setState({ playlists: response.items, nplaylists: response.total, nextURL: response.next,\n\t\t\tprevURL: response.previous });\n\n\t\tplaylists.style.display = 'block';\n\t\tsubtitle.textContent = (response.offset + 1) + '-' + (response.offset + response.items.length) +\n\t\t\t' of ' + response.total + ' playlists\\n';\n\t}", "function showTermList() {\n scroll_list_ui.innerHTML = \"\"; // reset list contents\n for (var i = 0; i < term_list.length; i++) { // loop over list of terms\n scroll_list_ui.innerHTML = scroll_list_ui.innerHTML + term_list[i] + '<br>';\n // add term to list in UI\n }\n }", "function showFriendsFeedEvent(event){\n\n\t\tvar feedList = $('#friends-live-activity');\n\n\t\tif(feedList.length){\n\n\t\t\tautoScroll = true;\n\n\t\t\t// Agrego el item a la lista\n\t\t\tfeedList.prepend(tmpl('friendlist_item', event));\n\n\t\t\tif(!hoverOnHovercard && !hoverOnList) {\n\t\t\t\tfeedList.scrollTo(0, 500);\n\t\t\t}\n\n\t\t\t// Mantenemos el scroll para evitar sacar de hover el elemento actual\n\t\t\tfeedList[0].scrollTop += 42;\n\n\t\t\t// Hago aparecer lo nuevo con una simple animación\n\t\t\tfeedList.find('.list-item:hidden').fadeIn(400);\n\n\t\t\t// Remuevo los feeds más viejos // -1 debido al índice 0 que es tomado en cuenta\n\t\t\tfeedList.find('.list-item:gt('+(feedsLimit-1)+')').remove();\n\t\t}\n\n\t}", "function showStravaActivities(){\n var lengthActivities = activities.length;\n if (lengthActivities > 0) {\n var listHTML = '<ul>';\n\n for (var i = 0; i < lengthActivities; ++i) {\n console.log(activities[i].id); \n listHTML += '<li>' + activities[i].name + \" - \" + activities[i].date + \" - \" + activities[i].id + '</li>';\n }\n\n listHTML += '</ul>';\n $( \".listActivities\" ).append( listHTML );\n }\n}", "function EntryList() { }", "function seeAllStories() {\n vm.storyLimit = vm.newsDetails.length - 1;\n }", "function loadItemList() {\n removeEmptyItems() // cleanup\n db = getDBFromLocalStorage() // get the latest saved object from localStorage\n Object.keys(db).forEach(function(key) {\n if(db[key]['title'] !== \"\") {\n main.innerHTML = `<section data-key='${key}'>${db[key]['title'].substr(0, titleLimit)}</section>` + main.innerHTML\n } else { // if title is blank, then show the first couple characters of the content as the title\n main.innerHTML = `<section data-key='${key}'>${decodeURIComponent(db[key]['content']).substr(0, titleLimit)}</section>` + main.innerHTML\n }\n })\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Separate the controller to simplify testing Chart drilldown and recovery NOTE: Prototype approach gets messy in directives
function chartDirectiveCtrl($scope){ //Validates our click event and calls the parent drilldown function $scope.drilldown = function(points, evt){ if($scope.hasDrilldown && points.length > 0) { $scope.click(points, evt); } }; //Check if we have anything stored (toggles return button) $scope.hasPreviousChart = function(){ return ($scope.previousChart ? true : false); }; //Restores our previous chart, toggles our button and removes our saved chart $scope.restorePrevious = function(){ $scope.data = angular.copy($scope.previousChart.data); $scope.labels = angular.copy($scope.previousChart.labels); $scope.hasDrilldown = true; $scope.title = angular.copy($scope.previousChart.title); $scope.previousChart = false; } }
[ "function createChart() {\n getSettings();\n $scope.chart = picasso.chart({\n element: $element.find('.adv-kpi-chart')[0],\n data: ds,\n settings: picassoSettings,\n beforeRender() { qlik.resize(); }\n });\n }", "function sparklineChartCtrl() {\n\n /**\n * Inline chart\n */\n var inlineData = [34, 43, 43, 35, 44, 32, 44, 52, 25];\n var inlineOptions = {\n type: 'line',\n lineColor: '#f04544',\n fillColor: '#e35b5a'\n };\n\n /**\n * Bar chart\n */\n var barSmallData = [5, 6, 7, 2, 0, -4, -2, 4];\n var barSmallOptions = {\n type: 'bar',\n barColor: '#e35b5a',\n negBarColor: '#c6c6c6'\n };\n\n /**\n * Pie chart\n */\n var smallPieData = [1, 1, 2];\n var smallPieOptions = {\n type: 'pie',\n sliceColors: ['#e35b5a', '#b3b3b3', '#e4f0fb']\n };\n\n /**\n * Long line chart\n */\n var longLineData = [34, 43, 43, 35, 44, 32, 15, 22, 46, 33, 86, 54, 73, 53, 12, 53, 23, 65, 23, 63, 53, 42, 34, 56, 76, 15, 54, 23, 44];\n var longLineOptions = {\n type: 'line',\n lineColor: '#e35b5a',\n fillColor: '#ffffff'\n };\n\n /**\n * Tristate chart\n */\n var tristateData = [1, 1, 0, 1, -1, -1, 1, -1, 0, 0, 1, 1];\n var tristateOptions = {\n type: 'tristate',\n posBarColor: '#e35b5a',\n negBarColor: '#bfbfbf'\n };\n\n /**\n * Discrate chart\n */\n var discreteData = [4, 6, 7, 7, 4, 3, 2, 1, 4, 4, 5, 6, 3, 4, 5, 8, 7, 6, 9, 3, 2, 4, 1, 5, 6, 4, 3, 7, ];\n var discreteOptions = {\n type: 'discrete',\n lineColor: '#e35b5a'\n };\n\n /**\n * Pie chart\n */\n var pieCustomData = [52, 12, 44];\n var pieCustomOptions = {\n type: 'pie',\n height: '150px',\n sliceColors: ['#e35b5a', '#b3b3b3', '#e4f0fb']\n };\n\n /**\n * Bar chart\n */\n var barCustomData = [5, 6, 7, 2, 0, 4, 2, 4, 5, 7, 2, 4, 12, 14, 4, 2, 14, 12, 7];\n var barCustomOptions = {\n type: 'bar',\n barWidth: 8,\n height: '150px',\n barColor: '#e35b5a',\n negBarColor: '#c6c6c6'\n };\n\n /**\n * Line chart\n */\n var lineCustomData = [34, 43, 43, 35, 44, 32, 15, 22, 46, 33, 86, 54, 73, 53, 12, 53, 23, 65, 23, 63, 53, 42, 34, 56, 76, 15, 54, 23, 44];\n var lineCustomOptions = {\n type: 'line',\n lineWidth: 1,\n height: '150px',\n lineColor: '#e35b5a',\n fillColor: '#ffffff'\n };\n\n\n /**\n * Definition of variables\n * Flot chart\n */\n this.inlineData = inlineData;\n this.inlineOptions = inlineOptions;\n this.barSmallData = barSmallData;\n this.barSmallOptions = barSmallOptions;\n this.pieSmallData = smallPieData;\n this.pieSmallOptions = smallPieOptions;\n this.discreteData = discreteData;\n this.discreteOptions = discreteOptions;\n this.longLineData = longLineData;\n this.longLineOptions = longLineOptions;\n this.tristateData = tristateData;\n this.tristateOptions = tristateOptions;\n this.pieCustomData = pieCustomData;\n this.pieCustomOptions = pieCustomOptions;\n this.barCustomData = barCustomData;\n this.barCustomOptions = barCustomOptions;\n this.lineCustomData = lineCustomData;\n this.lineCustomOptions = lineCustomOptions;\n}", "function coveragesController() {\n\n }", "static directiveFactory (dataService) {\n return new ChartDirective(dataService)\n }", "function controller_by_user(){\n\t\ttry {\n\t\t\t\n//debug: all data\nconsole.log(data_quotess);\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"error: page quotes => custom controller\");\n\t\t\tconsole.log(e);\n\t\t}\n\t}", "function ExercisesCtrl($scope, $rootScope, authentication, exercisessrv, GetMyExercises){\n\t\tvar vm = this;\n\t\t$scope.title = 'Exercises';\n\t\t$rootScope.curPath = 'exercises';\n\n\t\tvm.exercises = {\n\t\t\ttitle: null,\n\t\t\tdescr: null,\n\t\t\tlink: null\n\t\t}\n\n\t\tvm.addExercise = function(){\n\t\t\treturn exercisessrv.addExercise(vm.exercises, vm.authInfo.uid);\n\t\t}\n\n\t\texercisessrv.getExercise().then(function(_data){\n\t\t\tconsole.log(_data);\n\t\t\tvm.exer = _data;\n\t\t});\n\t\t\n\t}", "function ParametersTabController(model, controller) {\n this.view = null;\n\n this.setView = function(view) {\n this.view = view;\n };\n\n this.resetOutput = function() {\n };\n\n this.reset = function() {\n model.apertureDiameter = model.defaultApertureDiameter;\n this.view.apertureDiameterEdit.text = format(\n model.formatApertureDiameter,\n model.scaleApertureDiameter * model.apertureDiameter\n );\n\n model.focalLength = model.defaultFocalLength;\n this.view.focalLengthEdit.text = format(\n model.formatApertureDiameter,\n model.scaleFocalLength * model.focalLength\n );\n\n model.detectorType = model.defaultDetectorType;\n this.view.detectorTypeComboBox.currentItem = model.detectorType;\n\n model.gain = model.defaultGain;\n this.view.gainEdit.text = format(\n model.formatGain,\n model.scaleGain * model.gain\n );\n\n model.pixelSize = model.defaultPixelSize;\n this.view.pixelSizeEdit.text = format(\n model.formatPixelSize,\n model.scalePixelSize * model.pixelSize\n );\n\n model.observationWavelength = model.defaultObservationWavelength;\n this.view.observationWavelengthEdit.text = format(\n model.formatObservationWavelength,\n model.scaleObservationWavelength * model.observationWavelength\n );\n\n model.rejectionMethod = model.defaultRejectionMethod;\n this.view.rejectionMethodComboBox.currentItem = model.rejectionMethod;\n\n model.rejectionScale = model.defaultRejectionScale;\n this.view.rejectionScaleEdit.text =\n model.rejectionMethod == model.noRejectionMethod ? \"-\" : format(\n model.formatRejectionScale,\n model.scaleRejectionScale * model.rejectionScale\n );\n\n model.identifierPrefix = model.defaultIdentifierPrefix;\n this.view.identifierPrefixEdit.text = model.identifierPrefix;\n\n model.fringeCountScale = model.defaultFringeCountScale;\n this.view.fringeCountScaleEdit.text =\n format(\n model.formatFringeCountScale,\n model.scaleFringeCountScale * model.fringeCountScale\n );\n\n model.generateViews = model.defaultGenerateViews;\n this.view.generateViewsCheckBox.checked = model.generateViews;\n };\n\n this.disableControls = function() {\n this.view.apertureDiameterEdit.enabled = false;\n this.view.focalLengthEdit.enabled = false;\n\n this.view.detectorTypeComboBox.enabled = false;\n this.view.gainEdit.enabled = false;\n this.view.pixelSizeEdit.enabled = false;\n\n this.view.observationWavelengthEdit.enabled = false;\n this.view.observationWavelengthTypicalValuesComboBox.enabled = false;\n\n this.view.rejectionMethodComboBox.enabled = false;\n this.view.rejectionScaleEdit.enabled = false;\n\n this.view.identifierPrefixEdit.enabled = false;\n this.view.fringeCountScaleEdit.enabled = false;\n this.view.generateViewsCheckBox.enabled = false;\n };\n\n this.enableControls = function() {\n this.view.apertureDiameterEdit.enabled = true;\n this.view.focalLengthEdit.enabled = true;\n\n this.view.detectorTypeComboBox.enabled = true;\n this.view.gainEdit.enabled = true;\n this.view.pixelSizeEdit.enabled = true;\n\n this.view.observationWavelengthEdit.enabled = true;\n this.view.observationWavelengthTypicalValuesComboBox.enabled = true;\n\n this.view.rejectionMethodComboBox.enabled = true;\n this.view.rejectionScaleEdit.enabled =\n model.rejectionMethod == model.scaleRejectionMethod;\n\n this.view.identifierPrefixEdit.enabled = true;\n this.view.fringeCountScaleEdit.enabled = true;\n this.view.generateViewsCheckBox.enabled = true;\n };\n\n this.apertureDiameterOnTextUpdated = function(text) {\n model.apertureDiameter = defaultNumeric(\n parseFloat(text) / model.scaleApertureDiameter,\n model.minimumApertureDiameter,\n model.maximumApertureDiameter,\n model.defaultApertureDiameter\n );\n controller.resetOutput();\n controller.enableControls();\n };\n\n this.focalLengthOnTextUpdated = function(text) {\n model.focalLength = defaultNumeric(\n parseFloat(text) / model.scaleFocalLength,\n model.minimumFocalLength,\n model.maximumFocalLength,\n model.defaultFocalLength\n );\n controller.resetOutput();\n controller.enableControls();\n };\n\n this.detectorTypeOnItemSelected = function(item) {\n model.detectorType = item;\n controller.resetOutput();\n controller.enableControls();\n };\n\n this.gainOnTextUpdated = function(text) {\n model.gain = defaultNumeric(\n parseFloat(text) / model.scaleGain,\n model.minimumGain,\n model.maximumGain,\n model.defaultGain\n );\n controller.resetOutput();\n controller.enableControls();\n };\n\n this.pixelSizeOnTextUpdated = function(text) {\n model.pixelSize = defaultNumeric(\n parseFloat(text) / model.scalePixelSize,\n model.minimumPixelSize,\n model.maximumPixelSize,\n model.defaultPixelSize\n );\n controller.resetOutput();\n controller.enableControls();\n };\n\n this.observationWavelengthOnTextUpdated = function(text) {\n model.observationWavelength = defaultNumeric(\n parseFloat(text) / model.scaleObservationWavelength,\n model.minimumObservationWavelength,\n model.maximumObservationWavelength,\n model.defaultObservationWavelength\n );\n controller.resetOutput();\n controller.enableControls();\n };\n\n this.observationWavelengthTypicalValuesOnItemSelected = function(item) {\n this.view.observationWavelengthTypicalValuesComboBox.currentItem = 0;\n if (item != 0) {\n model.observationWavelength =\n this.view.observationWavelengthTypicalValues[item][1];\n this.view.observationWavelengthEdit.text = format(\n model.formatObservationWavelength,\n model.scaleObservationWavelength * model.observationWavelength\n );\n controller.resetOutput();\n controller.enableControls();\n }\n };\n\n this.rejectionMethodOnItemSelected = function(item) {\n model.rejectionMethod = item;\n\n this.view.rejectionScaleEdit.text =\n model.rejectionMethod == model.noRejectionMethod ? \"-\" : format(\n model.formatRejectionScale,\n model.scaleRejectionScale * model.rejectionScale\n );\n this.view.rejectionScaleEdit.enabled =\n model.rejectionMethod == model.scaleRejectionMethod;\n controller.resetOutput();\n controller.enableControls();\n };\n\n this.rejectionScaleOnTextUpdated = function(text) {\n model.rejectionScale = defaultNumeric(\n parseFloat(text) / model.scaleRejectionScale,\n model.minimumRejectionScale,\n model.maximumRejectionScale,\n model.defaultRejectionScale\n );\n controller.resetOutput();\n controller.enableControls();\n };\n\n this.identifierPrefixOnTextUpdated = function(text) {\n model.identifierPrefix = text;\n controller.resetOutput();\n controller.enableControls();\n };\n\n this.fringeCountScaleOnTextUpdated = function(text) {\n model.fringeCountScale = defaultNumeric(\n parseFloat(text) / model.scaleFringeCountScale,\n model.minimumFringeCountScale,\n model.maximumFringeCountScale,\n model.defaultFringeCountScale\n );\n controller.resetOutput();\n controller.enableControls();\n };\n\n this.generateViewsOnCheck = function(checked) {\n model.generateViews = checked;\n controller.resetOutput();\n controller.enableControls();\n };\n}", "function marketController() {}", "function getTable(params, i){\n\t\tDashboardServices.GetDashboard(params).then(function(response){\n\t\t\tif(response.length == 0){\n\t\t\t\t$scope.peopleCategories[i] = null;\n\t\t\t\t//do other stuff\n\t\t\t}else{\n\t\t\t\t$scope.peopleCategories[i] = response;\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tvar p = {\ttable : params.tableId };\n\t\t\t\tCategoryServices.GetCategories(p).then(function(response){\n\t\t\t\t\t$scope.categories[i] = response;\n\t\t\t\t\tAspectServices.GetAspects(p).then(function(response){\n\t\t\t\t\t\t$scope.aspects[i] = response;\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t$scope.dataAspects[i] = [];\n\t\t\t\t\t\t$scope.dataCategories[i] = [];\n\t\t\t\t\t\t\n\t\t\t\t\t\t//This should be module\n\t\t\t\t\t\tfor(var u = 0; u< $scope.peopleCategories[i].length; u++){\n\t\t\t\t\t\t\tvar hasCategory = [];\n\t\t\t\t\t\t\tvar hasAspect = [];\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t$scope.dataAspects[i][u] = [];\n\t\t\t\t\t\t\t$scope.dataCategories[i][u] = [];\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tfor(var index = 0; index < $scope.peopleCategories[i][u].length; index++){\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tfor(var c = 0 ; c< $scope.categories[i].length;c++){\n\t\t\t\t\t\t\t\t\tif($scope.peopleCategories[i][u][index].categoryId == $scope.categories[i][c]._id){\n\t\t\t\t\t\t\t\t\t\tisInArray(hasCategory, $scope.categories[i][c]);\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tfor(var a = 0; a< $scope.aspects[i].length; a++){\n\t\t\t\t\t\t\t\t\tif($scope.peopleCategories[i][u][index].aspectId == $scope.aspects[i][a]._id){\n\t\t\t\t\t\t\t\t\t\tisInArray(hasAspect, $scope.aspects[i][a]);\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\t\t\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t$scope.dataAspects[i][u] = hasAspect;\n\t\t\t\t\t\t\t$scope.dataCategories[i][u] = hasCategory; \n\t\t\t\t\t\t}\n\t\t\t\t\t\t//End of module\n\t\t\t\t\t\t\n\t\t\t\t\t\t$scope.selectCategories[i] = [];\n\t\t\t\t\t\tfor(var u = 0 ; u<$scope.dataCategories[i].length; u++){\n\t\t\t\t\t\t\tfor(var c = 0; c<$scope.dataCategories[i][u].length; c++){\n\t\t\t\t\t\t\t\tisInArray($scope.selectCategories[i], $scope.dataCategories[i][u][c]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\n\t\t\t\t\t\t$scope.matrix[i] = [];\n\n\t\t\t\t\t\tfor(var u = 0; u< $scope.peopleCategories[i].length ; u++){\n\t\t\t\t\t\t\t$scope.matrix[i][u] = [];\n\t\t\t\t\t\t\tfor(var c = 0; c < $scope.dataCategories[i][u].length; c++){\n\t\t\t\t\t\t\t\t$scope.matrix[i][u][c] = [];\n\n\t\t\t\t\t\t\t\t//The formula below helps me convert the $scope.peopleCategories array into a matrix\n\t\t\t\t\t\t\t\t//arrayIndex = columnNumber * numberOfAspects this is equal to the number of columns the matrix will have\n\t\t\t\t\t\t\t\t//and each category will be a new row graphic example\n\t\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t\t\t$scope.peopleCategories[i][u] = [aspect11, ... ,aspect33]\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t \t\t\tASPECT 1 ASPECT 2 ASPECT 3\n\t\t\t\t\t\t\t\t\tCATEGORY 1 [ aspect11 , aspect12, aspect13]\n\t\t\t\t\t\t\t\t\tCATEGORY 2 [ aspect21 , aspect22, aspect23]\n\t\t\t\t\t\t\t\t\tCATEGORY 3 [ aspect31 , aspect32, aspect33]\n\n\t\t\t\t\t\t\t\t*/\n\n\t\t\t\t\t\t\t\tvar index = c * $scope.dataAspects[i][u].length;\n\t\t\t\t\t\t\t\tfor (var a = 0; a<$scope.dataAspects[i][u].length; a++ ){\n\t\t\t\t\t\t\t\t\t$scope.matrix[i][u][c].push($scope.peopleCategories[i][u][index].Results);\n\t\t\t\t\t\t\t\t\tindex++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//time to draw the graphs\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdrawMatrix($scope.matrix,i);\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\n\n\t\t\t\n\t\t});\n\t}", "function clientTeamPointsController(){\n return {\n restrict: 'E',\n scope: {},\n templateUrl: 'app/client/clientTeamPoints/client-team-points.html',\n controller: 'initTeamPointsController',\n controllerAs: 'teamPointsCtrl'\n };\n }", "function ControllerFactory(resourceName, options, extras) {\n\treturn function($scope, R, MESSAGES) {\n\t\t//Get resource by name. Usually it would be you API i.e. generated magically from your database table.\n\t\tvar Resource = R.get(resourceName);\n\n\t\t//Scope variables\n\t\t$scope.data = {};\n\t\t$scope.data.single = new Resource();\n\t\t$scope.data.list = [];\n\t\t$scope.errors = [];\n\t\t$scope.MODES = {\n\t\t\t'view': 'view',\n\t\t\t'edit': 'edit',\n\t\t\t'add': 'add'\n\t\t}\n\t\t$scope.mode = $scope.MODES.view;\n\n\t\t//Default error handler\n\t\tvar errorHandler = function(error) {\n\t\t\tif (error && error.status) {\n\t\t\t\tswitch (error.status) {\n\t\t\t\t\tcase 404:\n\t\t\t\t\t\t$scope.errors.push({\n\t\t\t\t\t\t\tmessage: MESSAGES.E404\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 400:\n\t\t\t\t\t\t$scope.errors.push({\n\t\t\t\t\t\t\tmessage: MESSAGES.E400\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 500:\n\t\t\t\t\t\t$scope.errors.push({\n\t\t\t\t\t\t\tmessage: MESSAGES.E500\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t$scope.errors.push({\n\t\t\t\t\t\t\tmessage: MESSAGES.E500\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\t\n\t\t//Initializa new single objetc\n\t\t$scope.initSingle = function(){\n\t\t\t$scope.data.single = new Resource();\t\n\t\t};\n\n\t\t//Get all rows from your API/table. Provide a query filter in case you want reduced dataset.\n\t\t$scope.query = function(q, callback) {\n\t\t\tif (!q) {\n\t\t\t\tq = {};\n\t\t\t}\n\t\t\tResource.query(q, function(result) {\n\t\t\t\tif (result) {\n\t\t\t\t\t$scope.data.list = result;\n\t\t\t\t}\n\t\t\t\tif (callback) {\n\t\t\t\t\tcallback(result);\n\t\t\t\t}\n\t\t\t}, errorHandler);\n\t\t};\n\n\t\t//Get specific record\n\t\t$scope.get = function(id, callback) {\n\t\t\tResource.get({\n\t\t\t\tid: id\n\t\t\t}, function(result) {\n\t\t\t\t$scope.data.single = result;\n\t\t\t\tif (callback) {\n\t\t\t\t\tcallback(result);\n\t\t\t\t}\n\t\t\t}, errorHandler);\n\t\t};\n\n\t\t//Delete specific record\n\t\t$scope.delete = function(obj, callback) {\n\t\t\tif (obj && obj.$delete) {\n\t\t\t\tobj.$delete();\n\t\t\t\tif (callback) {\n\t\t\t\t\tcallback();\n\t\t\t\t}\n\t\t\t} else if (!isNaN(obj)) {\n\t\t\t\t$scope.get(obj, function(result){\n\t\t\t\t\tif(result && result.$delete){\n\t\t\t\t\t\tresult.$delete();\n\t\t\t\t\t\tif (callback) {\n\t\t\t\t\t\t\tcallback();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t};\n\n\t\t//Save a record\n\t\t$scope.save = function(obj, callback) {\n\t\t\t\n\t\t\tif (obj && obj.$save) {\n\t\t\t\tvar promise = obj.$save();\n\t\t\t\tpromise.then(function(){\n\t\t\t\t\tif (callback) {\n\t\t\t\t\t\tcallback();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} else if ($scope.data.single) {\n\t\t\t\tvar promise = $scope.data.single.$save();\n\t\t\t\tpromise.then(function(){\n\t\t\t\t\tif (callback) {\n\t\t\t\t\t\tcallback();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t};\n\n\t\t//Clear errors\n\t\t$scope.clearErrors = function() {\n\t\t\t$scope.errors = [];\n\t\t};\n\t\t\n\t\t//Refresh data\n\t\t$scope.refreshData = function(){\n\t\t\t$scope.query();\n\t\t};\n\n\t\t/*Define options\n\t\t\tinit:true -> Load all records when the controller loads\n\t\t*/\n\t\tif (options) {\n\t\t\t$scope.options = options;\n\t\t\tif ($scope.options.init) {\n\t\t\t\t$scope.query();\n\t\t\t}\n\t\t}\n\n\t\t//Any extra stuff you might want to merge into the data object\n\t\tif (extras) {\n\t\t\tfor (var e in extras) {\n\t\t\t\t$scope.data[e] = extras[e];\n\t\t\t}\n\t\t}\n\n\t};\n}", "function NewInvoiceController($scope, $location, $http, $modal, $toaster) {\n\tvar NJS_API = jQuery(\"#NJS_API_URL\").val();\n\tvar PARAMS = $location.search();\n\t//customize Invoice Class to have database connection\n\tInvoice.prototype.getTaxInvoiceNo = function() {\n\t\tvar me = this;\n\t\tsetTimeout(function() {\n\t\t\tvar data = {\n\t\t\t\tid : me.client.client_id\n\t\t\t};\n\n\t\t\t$http.post(NJS_API + \"/clients/get-new-tax-invoice-no/\", data).success(function(response) {\n\t\t\t\tme.tax_invoice_no = response.tax_invoice_no;\n\t\t\t});\n\n\t\t}, 500);\n\n\t\t//collect all commissions for the selected client\n\t\tsetTimeout(function() {\n\n\t\t\t$http.get(NJS_API + \"/commission/get-commision-by-leads-id?leads_id=\" + me.client.client_id).success(function(response) {\n\t\t\t\t$scope.commissions = response.result;\n\t\t\t\tsetTimeout(function() {\n\t\t\t\t\tjQuery(\".commissions\").trigger(\"chosen:updated\");\n\t\t\t\t}, 500);\n\t\t\t});\n\n\t\t}, 500);\n\n\t};\n\n\t/**\n\t * Sync invoice to database\n\t */\n\tInvoice.prototype.sync = function() {\n\t\tvar new_history;\n\t\tif (this.due_date==null){\n\t\t\talert(\"Due Date is required\");\n\t\t\treturn;\n\t\t}\n\t\t//add history check\n\t\tif (moment(this.original_due_date).format() != moment(this.due_date).format()) {\n\t\t\tnew_history = new History();\n\t\t\tnew_history.timestamp = new Date();\n\t\t\tnew_history.timestamp_unix = moment(new_history.timestamp).unix();\n\t\t\tnew_history.changes = \"Changed due date from \" + moment(this.original_due_date).format() + \" to \" + moment(this.due_date).format();\n\t\t\tnew_history.by = jQuery(\"#ADMIN_NAME\").val() + \" :\" + jQuery(\"#ADMIN_ID\").val();\n\t\t\tthis.addHistory(new_history);\n\t\t}\n\t\tif (moment(this.original_invoice_date).format() != moment(this.invoice_date).format()) {\n\t\t\tnew_history = new History();\n\t\t\tnew_history.timestamp = new Date();\n\t\t\tnew_history.timestamp_unix = moment(new_history.timestamp).unix();\n\t\t\tnew_history.changes = \"Changed due date from \" + moment(this.original_invoice_date).format() + \" to \" + moment(this.invoice_date).format();\n\t\t\tnew_history.by = jQuery(\"#ADMIN_NAME\").val() + \" :\" + jQuery(\"#ADMIN_ID\").val();\n\t\t\tthis.addHistory(new_history);\n\t\t}\n\t\tvar item_changes = [];\n\t\tfor (var j = 0; j < this.original_items.length; j++) {\n\t\t\tfor (var i = 0; i < this.items.length; i++) {\n\t\t\t\tvar item = this.items[i];\n\t\t\t\tvar original_item = this.original_items[i];\n\t\t\t\tvar change_found = false;\n\t\t\t\tvar description = \"Changes found on item number \" + item.item_no + \"<br/>\";\n\t\t\t\ttry{\n\t\t\t\t\tif (item.item_no == original_item.item_no) {\n\t\t\t\t\t\tif (item_changes.indexOf(item.item_no)===-1){\n\t\t\t\t\t\t\tif (item.description != original_item.description) {\n\t\t\t\t\t\t\t\tchange_found = true;\n\t\t\t\t\t\t\t\tdescription += \"Description from <strong>\" + original_item.description + \"</strong> to <strong>\" + item.description + \"</strong><br/>\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (item.item_type != original_item.item_type) {\n\t\t\t\t\t\t\t\tchange_found = true;\n\t\t\t\t\t\t\t\tdescription += \"Item Type from <strong>\" + original_item.item_type + \"</strong> to <strong>\" + item.item_type + \"</strong>\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconsole.log(item);\n\t\t\t\t\t\t\tif (item.quantity != original_item.quantity) {\n\t\t\t\t\t\t\t\tchange_found = true;\n\t\t\t\t\t\t\t\tdescription += \"Quantity from <strong>\" + original_item.quantity + \"</strong> to <strong>\" + item.quantity + \"</strong>\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (item.unit_price != original_item.unit_price) {\n\t\t\t\t\t\t\t\tchange_found = true;\n\t\t\t\t\t\t\t\tdescription += \"Unit Price from <strong>\" + original_item.unit_price + \"</strong> to <strong>\" + item.unit_price + \"</strong>\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (item.selected_date!=undefined){\n\t\t\t\t\t\t\t\tif (moment(item.selected_date.startDate).format()!=moment(original_item.selected_date.startDate).format()){\n\t\t\t\t\t\t\t\t\tchange_found = true;\n\t\t\t\t\t\t\t\t\tdescription += \"Start Date from <strong>\" + moment(original_item.selected_date.startDate).format() + \"</strong> to <strong>\" + moment(item.selected_date.startDate).format() + \"</strong>\";\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (moment(item.selected_date.endDate).format()!=moment(original_item.selected_date.endDate).format()){\n\t\t\t\t\t\t\t\t\tchange_found = true;\n\t\t\t\t\t\t\t\t\tdescription += \"End Date from <strong>\" + moment(original_item.selected_date.endDate).format() + \"</strong> to <strong>\" + moment(item.selected_date.endDate).format() + \"</strong>\";\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (change_found) {\n\t\t\t\t\t\t\t\tnew_history = new History();\n\t\t\t\t\t\t\t\tnew_history.timestamp = new Date();\n\t\t\t\t\t\t\t\tnew_history.timestamp_unix = moment(new_history.timestamp).unix();\n\t\t\t\t\t\t\t\tnew_history.changes = description;\n\t\t\t\t\t\t\t\tnew_history.by = jQuery(\"#ADMIN_NAME\").val() + \" :\" + jQuery(\"#ADMIN_ID\").val();\n\t\t\t\t\t\t\t\tthis.addHistory(new_history);\n\t\t\t\t\t\t\t\titem_changes.push(item.item_no);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t}catch(e){\n\n\t\t\t\t}\n\n\n\t\t\t}\n\t\t}\n var invoice = this.toJSON();\n if(typeof new_history != \"undefined\" || invoice.items.length != $scope.initialInvoice.items.length) {\n\n var me = this;\n $http({\n method : 'POST',\n url : NJS_API + \"/invoice/save/\",\n data : invoice\n }).success(function(response) {\n\n if (response.success) {\n $http.get(NJS_API + \"/invoice/sync-daily-rates?order_id=\" + invoice.order_id).success(function(response) {\n alert(\"Successfully save invoice \" + invoice.order_id);\n var sync_mod_data = {\n \"invoice_number\" : invoice.order_id,\n \"date_updated\" : new Date(),\n \"updated_by_admin_id\" : $(\"#ADMIN_ID\").val(),\n \"updated_by_admin_name\" : invoice.added_by,\n \"status\" : \"Pending\"\n };\n $http.post(NJS_API + \"/invoice-versioning/sync-modification\", sync_mod_data).success(function (response) {\n if(response.success && response.result == \"Invoice inserted\"){\n window.location.href = \"/portal/accounts_v2/#/invoice/client-account/\" + invoice.client_id;\n } else {\n alert(\"Error syncing Invoice Versioning Sync Modification\");\n }\n });\n });\n } else {\n alert(\"Something went wrong! Please try again\");\n }\n });\n\t\t} else {\n\t\t\talert(\"No changes made.\")\n\t\t}\n\n\t};\n\n\tInvoice.prototype.cancel = function(){\n\t\tif (this.client==null){\n\t\t\twindow.location.href = \"/portal/accounts_v2/#/invoice/clients\";\n\t\t}else{\n\t\t\twindow.location.href = \"/portal/accounts_v2/#/invoice/client-account/\" + this.client.client_id;\t\n\t\n\t\t}\n\t};\n\n\t//item types\n\t$scope.item_types = [\"Bonus\", \"Placement Fee\", \"Commission\", \"Reimbursement\", \"Gifts\", \"Office Fee\", \"Service Fee\", \"Training Room Fee\", \"Currency Adjustment\", \"Regular Rostered Hours\", \"Adjustment Credit Memo\", \"Adjustment Over Time Work\", \"Over Payment\", \"Final Invoice\", \"Others\", \"Referral Program\"];\n\n\t//package selections\n\t$scope.package_selections = [];\n\t$scope.package_selections.push({\n\t\tvalue : \"weekly_fulltime\",\n\t\tlabel : \"Full Time Weekly or 40 working hours\",\n\t\tqty : 40,\n\t\twork_status : \"Full-Time\"\n\t});\n\t$scope.package_selections.push({\n\t\tvalue : \"weekly_parttime\",\n\t\tlabel : \"Part Time Weekly or 20 working hours\",\n\t\tqty : 20,\n\t\twork_status : \"Part-Time\"\n\t});\n\t$scope.package_selections.push({\n\t\tvalue : \"fortnightly_fulltime\",\n\t\tlabel : \"Full Time Fortnightly or 80 working hours\",\n\t\tqty : 80,\n\t\twork_status : \"Full-Time\"\n\t});\n\t$scope.package_selections.push({\n\t\tvalue : \"fortnightly_parttime\",\n\t\tlabel : \"Part Time Fortnightly or 40 working hours\",\n\t\tqty : 40,\n\t\twork_status : \"Part-Time\"\n\t});\n\t$scope.package_selections.push({\n\t\tvalue : \"monthly_fulltime\",\n\t\tlabel : \"Full Time 22 working Days or 176 working hours\",\n\t\tqty : 176,\n\t\twork_status : \"Full-Time\"\n\t});\n\t$scope.package_selections.push({\n\t\tvalue : \"monthly_parttime\",\n\t\tlabel : \"Part Time 22 working Days or 88 working hours\",\n\t\tqty : 88,\n\t\twork_status : \"Part-Time\"\n\t});\n\t$scope.package_selections.push({\n\t\tvalue : \"trial1week_fulltime\",\n\t\tlabel : \"Full Time 1 week trial or 40 working hours\",\n\t\tqty : 40,\n\t\twork_status : \"Full-Time\"\n\t});\n\t$scope.package_selections.push({\n\t\tvalue : \"trial1week_parttime\",\n\t\tlabel : \"Part Time 1 week trial or 20 working hours\",\n\t\tqty : 20,\n\t\twork_status : \"Part-Time\"\n\t});\n\t$scope.package_selections.push({\n\t\tvalue : \"trial2week_fulltime\",\n\t\tlabel : \"Full Time 2 week trial or 80 working hours\",\n\t\tqty : 80,\n\t\twork_status : \"Full-Time\"\n\t});\n\t$scope.package_selections.push({\n\t\tvalue : \"trial2week_parttime\",\n\t\tlabel : \"Part Time 2 week trial or 40 working hours\",\n\t\tqty : 40,\n\t\twork_status : \"Part-Time\"\n\t});\n\n\t//work status\n\t$scope.work_statuses = [\"Full-Time\", \"Part-Time\"];\n\n\t//invoice types\n\t$scope.invoice_types = [];\n\t$scope.invoice_types.push({\n\t\tvalue : \"regular\",\n\t\tlabel : \"Regular Invoicing\"\n\t});\n\n\t/**\n\t * Event for Handling Adding Item from Staff List\n\t */\n\t$scope.addItemFromStaffList = function() {\n\t\tif ($scope.invoice.client == null) {\n\t\t\talert(\"Please select client!\");\n\t\t\treturn;\n\t\t}\n\t\tif ($scope.invoice.client.active_subcons.length == 0) {\n\t\t\talert(\"The selected client has no active subcons!\");\n\t\t\treturn;\n\t\t}\n\n\t\tvar modalInstance = $modal.open({\n\t\t\ttemplateUrl : 'views/common/new-invoice/add-item-from-staff-list.html',\n\t\t\tcontroller : AddItemFromStaffListModalController,\n\t\t\tsize : \"lg\",\n\t\t\tresolve : {\n\t\t\t\t$invoker : function() {\n\t\t\t\t\treturn $scope;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t};\n\n\t/**\n\t * Event for handling Adding Items from Timesheet\n\t */\n\t$scope.addItemsFromTimesheet = function() {\n\t\tif ($scope.invoice.client == null) {\n\t\t\talert(\"Please select client!\");\n\t\t\treturn;\n\t\t}\n\t\tif ($scope.invoice.client.active_subcons.length == 0) {\n\t\t\talert(\"The selected client has no active subcons!\");\n\t\t\treturn;\n\t\t}\n\t\tvar modalInstance = $modal.open({\n\t\t\ttemplateUrl : 'views/common/new-invoice/add-item-from-timesheet.html',\n\t\t\tcontroller : AddItemFromTimesheetModalController,\n\t\t\tsize : \"lg\",\n\t\t\tresolve : {\n\t\t\t\t$invoker : function() {\n\t\t\t\t\treturn $scope;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t};\n\n\t$scope.addItemsCurrencyAdjustment = function(){\n\t\tif ($scope.invoice.client == null) {\n\t\t\talert(\"Please select client!\");\n\t\t\treturn;\n\t\t}\n\t\tif ($scope.invoice.client.active_subcons.length == 0) {\n\t\t\talert(\"The selected client has no active subcons!\");\n\t\t\treturn;\n\t\t}\n\t\tvar modalInstance = $modal.open({\n\t\t\ttemplateUrl : 'views/common/new-invoice/add-item-currency-adjustment.html',\n\t\t\tcontroller : AddItemCurrencyAdjustmentModalController,\n\t\t\tsize : \"lg\",\n\t\t\tresolve : {\n\t\t\t\t$invoker : function() {\n\t\t\t\t\treturn $scope;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\t\n\t}\n\n\t//initialize Invoice Instance\n\t$scope.invoice = new Invoice();\n\tsetTimeout(function() {\n\t\tif ($scope.invoice.due_date == null) {\n\t\t\tjQuery(\"#due_date\").val(\"\");\n\t\t}\n\t}, 5000);\n\n\tif ( typeof PARAMS.order_id != \"undefined\") {\n\t\t//load invoice details when updating invoice\n\t\tvar order_id = PARAMS.order_id;\n\t\t$scope.invoice.tax_invoice_no = PARAMS.order_id;\n\t\t$http.get(NJS_API + \"/invoice/get-invoice-details/?order_id=\" + order_id).success(function(response) {\n\t\t\tif (response.result.status == \"paid\" || response.result.status == \"cancelled\") {\n\t\t\t\twindow.location.href = \"/portal/accounts_v2/#/invoice/details/\" + PARAMS.order_id;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (var i = 0; i < response.result.items.length; i++) {\n\t\t\t\tvar item = $scope.invoice.getBlankItem(i + 1);\n\t\t\t\tvar result_item = response.result.items[i];\n\t\t\t\titem.description = result_item.description;\n\t\t\t\titem.item_type = result_item.item_type;\n\t\t\t\titem.selected_date = {\n\t\t\t\t\tstartDate : result_item.start_date,\n\t\t\t\t\tendDate : result_item.end_date\n\t\t\t\t};\n\t\t\t\titem.quantity = result_item.qty;\n\t\t\t\titem.subcontractors_id = result_item.subcontractors_id;\n\t\t\t\titem.unit_price = result_item.unit_price;\n\t\t\t\titem.commission_id = result_item.commission_id;\n\t\t\t\t$scope.invoice.addItem(item);\n\t\t\t}\n\t\t\tfor (var i = 0; i < response.result.history.length; i++) {\n\t\t\t\tvar result_history = response.result.history[i];\n\t\t\t\tvar history = new History();\n\t\t\t\thistory.timestamp = new Date(result_history.timestamp);\n\t\t\t\thistory.timestamp_unix = moment(history.timestamp).unix();\n\t\t\t\thistory.changes = result_history.changes;\n\t\t\t\thistory.by = result_history.by;\n\t\t\t\t$scope.invoice.addHistory(history);\n\t\t\t}\n\n\t\t\t$scope.invoice.copyItems();\n\t\t\t$scope.invoice.due_date = new Date(response.result.pay_before_date);\n\t\t\t$scope.invoice.invoice_date = new Date(response.result.added_on);\n\n\t\t\t$scope.invoice.original_due_date = new Date(response.result.pay_before_date);\n\t\t\t$scope.invoice.original_invoice_date = new Date(response.result.added_on);\n\t\t\t$scope.initialInvoice = angular.copy($scope.invoice);\n\n\t\t\tPARAMS.client_id = parseInt(response.result.client_id);\n\t\t\t//console.log($scope.invoice.items);\n\t\t\t//collect all commissions for the selected client\n\t\t\tsetTimeout(function() {\n\n\t\t\t\t$http.get(NJS_API + \"/commission/get-commision-by-leads-id?leads_id=\" + response.result.client_id).success(function(response) {\n\t\t\t\t\t$scope.commissions = response.result;\n\t\t\t\t\tsetTimeout(function() {\n\t\t\t\t\t\tjQuery(\".commissions\").trigger(\"chosen:updated\");\n\t\t\t\t\t}, 500);\n\t\t\t\t});\n\n\t\t\t}, 500);\n\t\t\tsyncClients();\n\n\t\t});\n\t}\n\n\t$scope.invoice.selected_from_params = false;\n\n\t$scope.update_commission_item = function(item, commission){\n\t\tfor(var i=0;i<$scope.commissions.length;i++){\n\t\t\tvar commission = $scope.commissions[i];\n\t\t\tif (commission.commission_id == item.commission_id){\n\t\t\t\titem.unit_price = commission.commission_amount;\n\t\t\t\titem.description = commission.commission_title;\n\t\t\t\titem.item_type = \"Commission\";\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t};\n\t/**\n\t * Update forex rate from Server\n\t */\n\tfunction updateForexRateFromServer() {\n\t\t$http({\n\t\t\tmethod : 'GET',\n\t\t\turl : NJS_API + \"/currency-adjustments/get-all-active-forex-rate/\"\n\t\t}).success(function(response) {\n\t\t\tconsole.log(response.result);\n\t\t\twindow.localStorage.setItem(\"currency_rate\", JSON.stringify(response.result));\n\t\t});\n\t}\n\n\n\t/**\n\t * Sync all clients from DB\n\t */\n\tfunction syncClients() {\n\n\t\tvar clients = window.localStorage.getItem(\"clients\");\n\t\tif ( typeof clients == \"undefined\" || clients == null || clients == \"\") {\n\t\t\t$http({\n\t\t\t\tmethod : 'POST',\n\t\t\t\turl : NJS_API + \"/clients/get-all-clients/\"\n\t\t\t}).success(function(response) {\n\t\t\t\tconsole.log(response);\n\t\t\t\tif (response.success) {\n\t\t\t\t\t$scope.clients = response.clients;\n\t\t\t\t\tfor (var i = 0; i < response.clients.length; i++) {\n\t\t\t\t\t\tvar client = response.clients[i];\n\t\t\t\t\t\tif ( typeof PARAMS.client_id != \"undefined\" && parseInt(PARAMS.client_id) == client.client_id) {\n\t\t\t\t\t\t\t$scope.invoice.client = client;\n\t\t\t\t\t\t\t$scope.invoice.selected_from_params = true;\n\t\t\t\t\t\t\tif ( typeof PARAMS.order_id == \"undefined\") {\n\t\t\t\t\t\t\t\t$scope.invoice.getTaxInvoiceNo();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tclient.awaiting_invoices = [];\n\t\t\t\t\t\twindow.localStorage.setItem(\"client_\" + client.client_id, JSON.stringify(client));\n\t\t\t\t\t\tclient.awaiting_invoices = [];\n\t\t\t\t\t}\n\n\t\t\t\t\twindow.localStorage.setItem(\"clients\", \"\");\n\t\t\t\t\twindow.localStorage.setItem(\"clients\", JSON.stringify(response.clients));\n\t\t\t\t\tsetTimeout(function() {\n\t\t\t\t\t\tjQuery(\"#leads_id\").trigger(\"chosen:updated\");\n\t\t\t\t\t}, 500);\n\n\t\t\t\t}\n\t\t\t});\n\t\t} else {\n\t\t\tclients = jQuery.parseJSON(clients);\n\t\t\t$scope.clients = clients;\n\n\t\t\tfor (var i = 0; i < $scope.clients.length; i++) {\n\t\t\t\tvar client = $scope.clients[i];\n\t\t\t\tif ( typeof PARAMS.client_id != \"undefined\" && parseInt(PARAMS.client_id) == client.client_id) {\n\t\t\t\t\t$scope.invoice.client = client;\n\t\t\t\t\t$scope.invoice.selected_from_params = true;\n\t\t\t\t\tif ( typeof PARAMS.order_id == \"undefined\") {\n\t\t\t\t\t\t$scope.invoice.getTaxInvoiceNo();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tsetTimeout(function() {\n\t\t\t\tjQuery(\"#leads_id\").trigger(\"chosen:updated\");\n\t\t\t}, 500);\n\n\t\t\t$http({\n\t\t\t\tmethod : 'POST',\n\t\t\t\turl : NJS_API + \"/clients/get-all-clients/\"\n\t\t\t}).success(function(response) {\n\t\t\t\tconsole.log(response);\n\t\t\t\tif (response.success) {\n\n\t\t\t\t\tfor (var i = 0; i < response.clients.length; i++) {\n\t\t\t\t\t\tvar client = response.clients[i];\n\n\t\t\t\t\t\twindow.localStorage.setItem(\"client_\" + client.client_id, JSON.stringify(client));\n\t\t\t\t\t\tclient.awaiting_invoices = [];\n\t\t\t\t\t}\n\t\t\t\t\tsetTimeout(function() {\n\t\t\t\t\t\tjQuery(\"#leads_id\").trigger(\"chosen:updated\");\n\t\t\t\t\t}, 500);\n\t\t\t\t\twindow.localStorage.setItem(\"clients\", \"\");\n\t\t\t\t\twindow.localStorage.setItem(\"clients\", JSON.stringify(response.clients));\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t};\n\tif ( typeof PARAMS.order_id == \"undefined\") {\n\t\tsyncClients();\n\t}\n\tupdateForexRateFromServer();\n}", "function gras_chart_factory_make(registry, args)\n{\n //create containers\n var chart_box = $('<table />').attr({class:'chart_container'});\n var tr = $('<tr />');\n var td = $('<td />');\n tr.append(td);\n\n //call into the factory\n try\n {\n var chart = new registry.chart_factories[args.chart_type](args, td.get(0));\n }\n catch(err)\n {\n return;\n }\n\n //setup the title\n var tr_title = $('<tr />');\n var th_title = $('<th />');\n tr_title.append(th_title);\n th_title.text(chart.title);\n\n //register the chart\n var chart_info = {chart:chart,args:args,panel:chart_box};\n registry.active_charts.push(chart_info);\n $('#charts_panel').append(chart_box);\n\n //close button\n var close_div = $('<div/>').attr({class:'chart_designer_block_close'});\n var close_href = $('<a />').attr({href:'#', class:\"ui-dialog-titlebar-close ui-corner-all\", role:\"button\"});\n var close_span = $('<span />').attr({class:\"ui-icon ui-icon-closethick\"}).text('close');\n close_div.append(close_href);\n close_href.append(close_span);\n th_title.append(close_div);\n $(close_href).click(function()\n {\n var index = $.inArray(chart_info, registry.active_charts);\n registry.active_charts.splice(index, 1);\n chart_box.remove();\n gras_chart_save(registry);\n });\n gras_chart_save(registry);\n\n //finish gui building\n chart_box.append(tr_title);\n chart_box.append(tr);\n\n //implement draggable and resizable from jquery ui\n var handle_stop = function(event, ui)\n {\n args['width'] = chart_box.width();\n args['height'] = chart_box.height();\n args['position'] = chart_box.offset();\n chart.gc_resize = false;\n chart.update(registry.point);\n gras_chart_save(registry);\n };\n\n if ('default_width' in chart) chart_box.width(chart.default_width);\n chart_box.resizable({stop: handle_stop, create: function(event, ui)\n {\n if ('width' in args) chart_box.width(args.width);\n if ('height' in args) chart_box.height(args.height);\n },\n start: function(event, ui)\n {\n chart.gc_resize = true;\n chart.update(registry.point);\n }});\n\n chart_box.css('position', 'absolute');\n chart_box.draggable({stop: handle_stop, create: function(event, ui)\n {\n if ('position' in args) chart_box.offset(args.position);\n }, cursor: \"move\"});\n\n //set the cursor on the title bar so its obvious\n tr_title.hover(\n function(){$(this).css('cursor','move'); close_div.show();},\n function(){$(this).css('cursor','auto'); close_div.hide();}\n );\n close_div.hide();\n}", "function pieChart() {\n\t$('.design-abilities').css('display', 'inline-block');\n\tvar designCount = 0;\n\t$('.design-abilities .ability').each(function(){\n\t\tdesignCount++;\n\t});\n\tfunction displayDesign(){\n\t\tvar ability = '.design-abilities li:nth-last-of-type(' + designCount + ')'\n\t\tvar barFill = $(ability + ' .fill').attr('value') + '%';\n\t\t$(ability).fadeIn('fast');\n\t\t$(ability + ' .bar-graph .fill').css('width', barFill);\n\t\tdesignCount--;\n\t\tif(designCount != 0){\n\t\t\tsetTimeout(function(){\n\t\t\t\tdisplayDesign();\n\t\t\t}, 100);\n\t\t}\n\t\telse{\n\t\t\treturn;\n\t\t}\n\t};\n\tdisplayDesign();\n\n\t$('.pie').click(function(){\n\t\tvar abilitiesDiv = '.' + this.id.split('-')[0] + '-abilities';\n\t\t$('.pie').removeClass('selected');\n\t\t$(this).addClass('selected');\n\t\t$('.abilities').hide();\n\t\t\n\t\t$('.abilities').css('display', 'none');\n\t\t$('.ability').css('display', 'none');\n\t\t$('.fill').css('width', '0');\n\t\tvar abilityCount = 0;\n\t\t$(abilitiesDiv + ' .ability').each(function(){\n\t\t\tabilityCount ++;\n\t\t})\n\t\t$(abilitiesDiv).css('display', 'inline-block');\n\n\t\tfunction displayAbility() {\n\t\t\tvar ability = abilitiesDiv + ' li:nth-last-of-type(' + abilityCount + ')'\n\t\t\tvar barFill = $(ability + ' .fill').attr('value') + '%';\n\t\t\t$(ability).fadeIn('fast');\n\t\t\t$(ability + ' .bar-graph .fill').css('width', barFill);\n\t\t\tabilityCount--;\n\t\t\tif(abilityCount != 0){\n\t\t\t\tsetTimeout(function(){\n\t\t\t\t\tdisplayAbility();\n\t\t\t\t}, 100);\n\t\t\t}\n\t\t\telse{\n\t\t\t\treturn;\n\t\t\t}\t\n\t\t}\n\t\tdisplayAbility();\n\t});\n\n}", "function makeGraphs(data) {\n \n var ndx = crossfilter(data);\n \n has_website(ndx);\n pieChart(ndx);\n barChart(ndx);\n table(ndx, 10);\n \n dc.renderAll();\n $(\".dc-select-menu\").addClass(\"custom-select\");\n\n}", "function enableChartView() {\n for (let element of defaultViewElements) element.style.display = \"none\";\n for (let element of chartViewElements) element.style.display = \"block\";\n }", "updateRadarDiagram(domain, code) {\n\n // return;\n\n // let cardBodyHeight = $('#radar-diagram-card-body').height();\n // $('#radar-diagram-chart-container').height(cardBodyHeight - 50);\n\n this.setSeries(domain, code);\n\n this.config.data.datasets[0].label = radarContainerViewModel.title;\n this.config.data.labels = this.sortedLabels;\n this.config.data.datasets[0].data = this.sortedValues;\n this.config.data.datasets[1].label = radarContainerViewModel.baseTitle;\n this.config.data.datasets[1].data = this.sortedAverageValues;\n\n this.radarDiagram.update();\n\n }", "function mainViewCtrl(viewToShow, data) {\n switch(viewToShow){\n // if course+/edit was clicked\n case 'add-course':\n $('#count').hide();\n emptyDetails(\"course\");\n studentDetails.addClass(\"hidden\");\n studentForm.addClass(\"hidden\");\n courseDetails.addClass(\"hidden\");\n // show course add form\n courseForm.removeClass(\"hidden\");\n showListForSelection('course');\n\n if (typeof data === 'object' && data != null){\n fillDetails(data);\n }\n break;\n // if student+/edit was clicked\n case 'add-student':\n $('#count').hide();\n emptyDetails(\"student\");\n studentDetails.addClass(\"hidden\");\n courseForm.addClass(\"hidden\");\n courseDetails.addClass(\"hidden\");\n // show student add form\n studentForm.removeClass(\"hidden\");\n // show all available courses for new student\n showListForSelection('student');\n\n if (typeof data === 'object' && data != null){\n fillDetails(data);\n }\n break;\n // if clicked on the specific student\n case 'show-student':\n $('#count').hide();\n studentForm.addClass(\"hidden\");\n courseForm.addClass(\"hidden\");\n courseDetails.addClass(\"hidden\");\n // show details view\n studentDetails.removeClass(\"hidden\");\n\n if (data.s_ID !== null || data.s_ID !== false){\n showStudentDetails(data);\n }\n break;\n // if clicked on the specific course\n case 'show-course':\n $('#count').hide();\n studentForm.addClass(\"hidden\");\n courseForm.addClass(\"hidden\");\n studentDetails.addClass(\"hidden\");\n // show details view\n courseDetails.removeClass(\"hidden\");\n\n if (data.c_ID !== null || data.c_ID !== false){\n showCourseDetails(data);\n }\n break;\n }\n }", "function savingsImpCtrlFn($scope, $http, $filter, PPSTService) {\n $scope.savingsPopup = false;\n $scope.selectedSavingsFlag = false;\n $scope.savingsSubtype = \"\";\n $scope.selectSavings = function () {\n $scope.savingsPopup = true;\n }\n $scope.savingsPopupOnHideCallback = function (e) {\n $scope.savingsPopup = false;\n };\n $scope.savingsImpactData = PPSTService.savingsImpactData;\n $scope.savingsImpactDataColumns = PPSTService.savingsImpactDataColumns;\n var selectedSavings = 0, selectedSavingsType;\n $scope.selectedSavings = $scope.selectedSavingsCount = selectedSavings;\n $scope.selectedSavingsList = [];\n $scope.updateOtfm = function (index, value) {\n $scope.savingsImpactData[index].otfmValue = value;\n selectedSavingsType = $scope.savingsImpactData[index].title;\n var foundItem = $filter('filter')($scope.selectedSavingsList, { title: $scope.savingsImpactData[index].title }, true)[0];\n\n if (value) {\n if ($scope.selectedSavingsList.indexOf(foundItem) < 0)\n $scope.selectedSavingsList.push($scope.savingsImpactData[index]);\n selectedSavings++;\n if ($scope.savingsImpactData[index].recurringValue) {\n selectedSavings--;\n $scope.savingsImpactData[index].recurringValue = false;\n }\n }\n else {\n $scope.itemIndex = $scope.selectedSavingsList.indexOf(foundItem);\n $scope.selectedSavingsList.splice($scope.itemIndex, 1);\n selectedSavings--;\n }\n if (selectedSavings == 1)\n $scope.savingsSubtype = \" (One Time - First Month)\";\n else\n $scope.savingsSubtype = \"\";\n $scope.selectedSavingsCount = selectedSavings;\n }\n $scope.updateOtlm = function (index, value) {\n $scope.savingsImpactData[index].otlmValue = value;\n selectedSavingsType = $scope.savingsImpactData[index].title;\n var foundItem = $filter('filter')($scope.selectedSavingsList, { title: $scope.savingsImpactData[index].title }, true)[0];\n if (value) {\n if ($scope.selectedSavingsList.indexOf(foundItem) < 0)\n $scope.selectedSavingsList.push($scope.savingsImpactData[index]);\n selectedSavings++;\n }\n else {\n $scope.itemIndex = $scope.selectedSavingsList.indexOf(foundItem);\n $scope.selectedSavingsList.splice($scope.itemIndex, 1);\n selectedSavings--;\n }\n if (selectedSavings == 1)\n $scope.savingsSubtype = \" (One Time - Last Month)\";\n else\n $scope.savingsSubtype = \"\";\n $scope.selectedSavingsCount = selectedSavings;\n }\n $scope.updateRecurring = function (index, value) {\n $scope.savingsImpactData[index].recurringValue = value;\n selectedSavingsType = $scope.savingsImpactData[index].title;\n var foundItem = $filter('filter')($scope.selectedSavingsList, { title: $scope.savingsImpactData[index].title }, true)[0];\n if (value) {\n if ($scope.selectedSavingsList.indexOf(foundItem) < 0)\n $scope.selectedSavingsList.push($scope.savingsImpactData[index]);\n selectedSavings++;\n if ($scope.savingsImpactData[index].otfmValue) {\n $scope.savingsImpactData[index].otfmValue = false;\n selectedSavings--;\n }\n }\n else {\n $scope.itemIndex = $scope.selectedSavingsList.indexOf(foundItem);\n $scope.selectedSavingsList.splice($scope.itemIndex, 1);\n selectedSavings--;\n }\n if (selectedSavings == 1)\n $scope.savingsSubtype = \" (Recurring)\";\n else\n $scope.savingsSubtype = \"\";\n $scope.selectedSavingsCount = selectedSavings;\n }\n $scope.doneCallBack = function () {\n if (selectedSavings > 0) {\n $scope.selectedSavingsFlag = true;\n $scope.selectedSavings = selectedSavings;\n $scope.selectedSavingsType = selectedSavingsType;\n }\n $scope.savingsPopup = false;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
to get existing device types
function getDeviceTypes() { }
[ "function getDeviceType(axios$$1, token) {\n return restAuthGet(axios$$1, '/devicetypes/' + token);\n }", "get supportedRootDeviceTypes() {\n return this.getListAttribute('supported_root_device_types');\n }", "getAvailableDevices(controllerId) {\n\n var _thisSvc = this;\n\n var deviceList = [];\n\n var controllerInfo =\n _thisSvc.controllerInfoCollection[controllerId];\n\n for(var deviceId in controllerInfo.deviceInfoCollection) {\n\n var deviceInfo =\n controllerInfo.deviceInfoCollection[deviceId];\n\n deviceList.push({\n connected: deviceInfo.connected,\n deviceId: deviceInfo.deviceId,\n address: deviceInfo.address,\n name: deviceInfo.name\n });\n }\n\n return deviceList;\n }", "function getRoomTypes() {\n const results = hotel.getRoomTypes();\n domUpdates.populateRoomTypeSelector(results);\n}", "function queryCommandTypes() {\n server.getCommandTypes().then(function(res) {\n vm.commandTypes = res.data.commandTypes;\n }, function(res) {\n gui.alertBadResponse(res);\n });\n }", "function discoverTTSDevices() {\n console.log('[TTS] Discovering resources on TTS...');\n var json = JSON.stringify({\n path: '/api/v1/device/list',\n requestID: '1',\n options: {depth: 'all'}\n });\n manageWS.send(json);\n}", "scan(){\n // TODO : scan for new devices\n let ret=\"\", dev=[], device=null,re=null,id=null;\n\n this.count = 0;\n if(this.Bridges.ADB.isReady()){\n dev = this.Bridges.ADB.listDevices();\n this.count += dev.length;\n\n for(let i in dev){\n this.devices[dev[i].id] = dev[i];\n }\n ut.msgBox(\"Android devices\", Object.keys(this.devices));\n }\n\n // TODO : add SDB and others type of bridge\n \n if(this.count==1){\n this.setDefault(dev[0].id);\n }\n }", "function getHasDevNameOnArray(){\n\tvar str =[];\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\tfor(var a=0; a<devices.length; a++){\n\t\tif (devices[a].DeviceName!=\"\"){\n\t\t\tvar name = devices[a].DeviceName;\n\t\t\tstr.push(name);\n\t\t}\t\n\t}\n\treturn str;\n}", "function createDeviceType(axios$$1, payload) {\n return restAuthPost(axios$$1, '/devicetypes', payload);\n }", "function onDeviceTypeChange(inst, ui)\n{\n if(inst.deviceType === \"zc\" || inst.deviceType === \"zr\"\n || inst.deviceType === \"znp\")\n {\n ui.nwkMaxDeviceList.hidden = false;\n if(inst.deviceType === \"zc\" || inst.deviceType === \"znp\")\n {\n ui.zdsecmgrTcDeviceMax.hidden = false;\n inst.zdsecmgrTcDeviceMax = 40;\n }\n else /* zr */\n {\n ui.zdsecmgrTcDeviceMax.hidden = true;\n inst.zdsecmgrTcDeviceMax = 3;\n }\n if(inst.deviceType === \"zc\")\n {\n ui.distributedGlobalLinkKey.hidden = true;\n }\n else /* znp or zr */\n {\n ui.distributedGlobalLinkKey.hidden = false;\n }\n }\n else /* zed */\n {\n ui.distributedGlobalLinkKey.hidden = false;\n ui.nwkMaxDeviceList.hidden = true;\n ui.zdsecmgrTcDeviceMax.hidden = true;\n inst.zdsecmgrTcDeviceMax = 3;\n }\n}", "function getDeviceObject(){\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\tfor(var a=0; a<devices.length; a++){\n\t\tif (devices[a].ObjectPath == glblDevMenImg){\n\t\t\treturn devices[a];\n\t\t}\n\t}\n}", "function getSupportingEntries(mime, device) {\n\tvar builtin = false;\n\tfor (var di in deviceTypes) {\n\t\tvar dt = deviceTypes[di];\n\t\tif ((device===undefined || dt.term==device) && dt.supportsMime.indexOf(mime)>=0) {\n\t\t\tconsole.log('Mime type '+mime+' built-in on device '+options.device);\n\t\t\tbuiltin = true;\n\t\t}\n\t}\n\tvar apps = [];\n\tfor (var ei in entries) {\n\t\tvar entry = entries[ei];\n\t\tif (entry.supportsMime && entry.supportsMime.indexOf(mime)>=0) {\n\t\t\tif (!entry.requiresDevice || device===undefined || device=='any' || entry.requiresDevice.indexOf(device)>=0) {\n\t\t\t\t// ok\n\t\t\t\tapps.push(entry);\n\t\t\t\tconsole.log('Mime type '+mime+' supported on device '+options.device+' by '+entry.title);\n\t\t\t}\n\t\t}\n\t}\n\tif (!builtin && apps.length==0) {\n\t\tconsole.log('Mime type '+mime+' unsupported on device '+options.device);\n\t\treturn null;\n\t}\n\treturn apps;\n}", "function updateDeviceType(axios$$1, token, payload) {\n return restAuthPut(axios$$1, '/devicetypes/' + token, payload);\n }", "function targetDevices(targetOS) {\n for (var key in _platformDeviceMap) {\n if (targetOS.contains(key))\n return _platformDeviceMap[key];\n }\n}", "getDataTypes(moduleType) {\n return this._resources.modules[moduleType];\n }", "function checkDeviceIfExist(devName,type){\n\tvar myReturn = false;\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\tif(devName == \"\"){\n\t\tfor(var a=0; a < window['variable' + dynamicLineConnected[pageCanvas]].length;a++){\n\t\t\tif(pageCanvas == window['variable' + dynamicLineConnected[pageCanvas]][a].Page){\n\t\t\t\tmyReturn = true;\n\t\t\t}\n\t\t}\t\n\t}else{\n\t\tfor(var a=0; a<devices.length;a++){\n\t\t\tif (devName == devices[a].DeviceName && type != \"createdev\"){\n\t\t\t\tmyReturn = true;\n\t\t\t}else if(devName == devices[a].DeviceName && type == \"createdev\"){ \n\t\t\t\tmyReturn = true;\n\t\t\t}\t\n\t\t}\n\t}\n\treturn myReturn;\n}", "getBaseTypes() {\r\n return this.getType().getBaseTypes();\r\n }", "function findImageDevice(type,manu,model){\n\tvar st = \"\";\n\ttype = type.toLowerCase();\n\tmanu = manu.toLowerCase();\n\tmodel = model.toLowerCase();\n\tif(type.toLowerCase() == \"dut\"){\n/*\t\tif(manu == \"cisco\"){\n\t\t\tvar mtch = model.match(/asr/g);\n\t\t\tif(mtch ==\"\" || mtch != \"asr\"){\n\t\t\t\tst = '/device/cisco_vivid_blue_40.png';\n\t\t\t}else{\t\t\t\t\t\t\t\n\t\t\t\tst= '/device/asr-1k-40px.png';\n\t\t\t}\n\t\t}else if(manu == \"ixia\"){\n\t\t\tst= '/testtool/ixia-40px.png';\n\t\t}*/\n\t}else if(type == \"testtool\"){\n\t\tif(manu == \"ixia\"){\n\t\t\tst= '/model_icons/ixia-40px.png';\n\t\t}\n\t}\n\treturn st;\n\t\t\n}", "function listDeviceStatuses(axios$$1, options) {\n var query = '';\n query += options.deviceTypeToken ? '?deviceTypeToken=' + options.deviceTypeToken : '';\n return restAuthGet(axios$$1, '/statuses' + query);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the AWS CloudFormation properties of an `AWS::AppMesh::VirtualNode.VirtualNodeHttpConnectionPool` resource
function cfnVirtualNodeVirtualNodeHttpConnectionPoolPropertyToCloudFormation(properties) { if (!cdk.canInspect(properties)) { return properties; } CfnVirtualNode_VirtualNodeHttpConnectionPoolPropertyValidator(properties).assertSuccess(); return { MaxConnections: cdk.numberToCloudFormation(properties.maxConnections), MaxPendingRequests: cdk.numberToCloudFormation(properties.maxPendingRequests), }; }
[ "function cfnVirtualGatewayVirtualGatewayHttpConnectionPoolPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_VirtualGatewayHttpConnectionPoolPropertyValidator(properties).assertSuccess();\n return {\n MaxConnections: cdk.numberToCloudFormation(properties.maxConnections),\n MaxPendingRequests: cdk.numberToCloudFormation(properties.maxPendingRequests),\n };\n}", "function cfnVirtualNodeVirtualNodeHttp2ConnectionPoolPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_VirtualNodeHttp2ConnectionPoolPropertyValidator(properties).assertSuccess();\n return {\n MaxRequests: cdk.numberToCloudFormation(properties.maxRequests),\n };\n}", "function cfnVirtualNodeVirtualNodeGrpcConnectionPoolPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_VirtualNodeGrpcConnectionPoolPropertyValidator(properties).assertSuccess();\n return {\n MaxRequests: cdk.numberToCloudFormation(properties.maxRequests),\n };\n}", "function cfnVirtualNodeVirtualNodeConnectionPoolPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_VirtualNodeConnectionPoolPropertyValidator(properties).assertSuccess();\n return {\n GRPC: cfnVirtualNodeVirtualNodeGrpcConnectionPoolPropertyToCloudFormation(properties.grpc),\n HTTP: cfnVirtualNodeVirtualNodeHttpConnectionPoolPropertyToCloudFormation(properties.http),\n HTTP2: cfnVirtualNodeVirtualNodeHttp2ConnectionPoolPropertyToCloudFormation(properties.http2),\n TCP: cfnVirtualNodeVirtualNodeTcpConnectionPoolPropertyToCloudFormation(properties.tcp),\n };\n}", "function cfnVirtualNodeVirtualNodeTcpConnectionPoolPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_VirtualNodeTcpConnectionPoolPropertyValidator(properties).assertSuccess();\n return {\n MaxConnections: cdk.numberToCloudFormation(properties.maxConnections),\n };\n}", "function cfnVirtualGatewayVirtualGatewayHttp2ConnectionPoolPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_VirtualGatewayHttp2ConnectionPoolPropertyValidator(properties).assertSuccess();\n return {\n MaxRequests: cdk.numberToCloudFormation(properties.maxRequests),\n };\n}", "function cfnVirtualGatewayVirtualGatewayConnectionPoolPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_VirtualGatewayConnectionPoolPropertyValidator(properties).assertSuccess();\n return {\n GRPC: cfnVirtualGatewayVirtualGatewayGrpcConnectionPoolPropertyToCloudFormation(properties.grpc),\n HTTP: cfnVirtualGatewayVirtualGatewayHttpConnectionPoolPropertyToCloudFormation(properties.http),\n HTTP2: cfnVirtualGatewayVirtualGatewayHttp2ConnectionPoolPropertyToCloudFormation(properties.http2),\n };\n}", "function cfnVirtualGatewayVirtualGatewayGrpcConnectionPoolPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_VirtualGatewayGrpcConnectionPoolPropertyValidator(properties).assertSuccess();\n return {\n MaxRequests: cdk.numberToCloudFormation(properties.maxRequests),\n };\n}", "function CfnVirtualGateway_VirtualGatewayHttpConnectionPoolPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('maxConnections', cdk.requiredValidator)(properties.maxConnections));\n errors.collect(cdk.propertyValidator('maxConnections', cdk.validateNumber)(properties.maxConnections));\n errors.collect(cdk.propertyValidator('maxPendingRequests', cdk.validateNumber)(properties.maxPendingRequests));\n return errors.wrap('supplied properties not correct for \"VirtualGatewayHttpConnectionPoolProperty\"');\n}", "function CfnVirtualNode_VirtualNodeHttp2ConnectionPoolPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('maxRequests', cdk.requiredValidator)(properties.maxRequests));\n errors.collect(cdk.propertyValidator('maxRequests', cdk.validateNumber)(properties.maxRequests));\n return errors.wrap('supplied properties not correct for \"VirtualNodeHttp2ConnectionPoolProperty\"');\n}", "function CfnVirtualNode_VirtualNodeTcpConnectionPoolPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('maxConnections', cdk.requiredValidator)(properties.maxConnections));\n errors.collect(cdk.propertyValidator('maxConnections', cdk.validateNumber)(properties.maxConnections));\n return errors.wrap('supplied properties not correct for \"VirtualNodeTcpConnectionPoolProperty\"');\n}", "function CfnVirtualNode_VirtualNodeConnectionPoolPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('grpc', CfnVirtualNode_VirtualNodeGrpcConnectionPoolPropertyValidator)(properties.grpc));\n errors.collect(cdk.propertyValidator('http', CfnVirtualNode_VirtualNodeHttpConnectionPoolPropertyValidator)(properties.http));\n errors.collect(cdk.propertyValidator('http2', CfnVirtualNode_VirtualNodeHttp2ConnectionPoolPropertyValidator)(properties.http2));\n errors.collect(cdk.propertyValidator('tcp', CfnVirtualNode_VirtualNodeTcpConnectionPoolPropertyValidator)(properties.tcp));\n return errors.wrap('supplied properties not correct for \"VirtualNodeConnectionPoolProperty\"');\n}", "function CfnVirtualNode_VirtualNodeGrpcConnectionPoolPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('maxRequests', cdk.requiredValidator)(properties.maxRequests));\n errors.collect(cdk.propertyValidator('maxRequests', cdk.validateNumber)(properties.maxRequests));\n return errors.wrap('supplied properties not correct for \"VirtualNodeGrpcConnectionPoolProperty\"');\n}", "function cfnVirtualNodeHttpTimeoutPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_HttpTimeoutPropertyValidator(properties).assertSuccess();\n return {\n Idle: cfnVirtualNodeDurationPropertyToCloudFormation(properties.idle),\n PerRequest: cfnVirtualNodeDurationPropertyToCloudFormation(properties.perRequest),\n };\n}", "function CfnVirtualGateway_VirtualGatewayHttp2ConnectionPoolPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('maxRequests', cdk.requiredValidator)(properties.maxRequests));\n errors.collect(cdk.propertyValidator('maxRequests', cdk.validateNumber)(properties.maxRequests));\n return errors.wrap('supplied properties not correct for \"VirtualGatewayHttp2ConnectionPoolProperty\"');\n}", "function CfnVirtualGateway_VirtualGatewayConnectionPoolPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('grpc', CfnVirtualGateway_VirtualGatewayGrpcConnectionPoolPropertyValidator)(properties.grpc));\n errors.collect(cdk.propertyValidator('http', CfnVirtualGateway_VirtualGatewayHttpConnectionPoolPropertyValidator)(properties.http));\n errors.collect(cdk.propertyValidator('http2', CfnVirtualGateway_VirtualGatewayHttp2ConnectionPoolPropertyValidator)(properties.http2));\n return errors.wrap('supplied properties not correct for \"VirtualGatewayConnectionPoolProperty\"');\n}", "function cfnVirtualNodeTcpTimeoutPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_TcpTimeoutPropertyValidator(properties).assertSuccess();\n return {\n Idle: cfnVirtualNodeDurationPropertyToCloudFormation(properties.idle),\n };\n}", "function CfnVirtualGateway_VirtualGatewayGrpcConnectionPoolPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('maxRequests', cdk.requiredValidator)(properties.maxRequests));\n errors.collect(cdk.propertyValidator('maxRequests', cdk.validateNumber)(properties.maxRequests));\n return errors.wrap('supplied properties not correct for \"VirtualGatewayGrpcConnectionPoolProperty\"');\n}", "function cfnVirtualNodeHealthCheckPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_HealthCheckPropertyValidator(properties).assertSuccess();\n return {\n HealthyThreshold: cdk.numberToCloudFormation(properties.healthyThreshold),\n IntervalMillis: cdk.numberToCloudFormation(properties.intervalMillis),\n Path: cdk.stringToCloudFormation(properties.path),\n Port: cdk.numberToCloudFormation(properties.port),\n Protocol: cdk.stringToCloudFormation(properties.protocol),\n TimeoutMillis: cdk.numberToCloudFormation(properties.timeoutMillis),\n UnhealthyThreshold: cdk.numberToCloudFormation(properties.unhealthyThreshold),\n };\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return true if alertA is worse than alertB Neither alertA nor alertB can be 'notice'
_statusIsWorseThan(alertA, alertB) { const statusRank = {}; statusRank[SystemStatuses.ok] = 0; statusRank[SystemStatuses.pending] = 1; statusRank[SystemStatuses.attention] = 2; // to be greater than is to be worse than return statusRank[alertA] > statusRank[alertB]; }
[ "function checkForBlocking(p1Action, p2Action) {\n\t// Since the player with the most stamina will set the current actionCount we\n\t// need to see which ones has less or if they're equal. If one has less stamina then\n\t// we'll set up which block they chose. (i.e. punch-blocking, low-lick-blocking, high-kick-blocking)\n\tif(player1.liveStamina < actionCount) {\n\t\tsetBlocks(\"player1\", p1Action, p2Action);\n\t}\n\telse if(player2.liveStamina < actionCount) {\n\t\tsetBlocks(\"player2\", p1Action, p2Action);\n\t}\n\telse {\n\t\tcalculateAttack(p1Action, p2Action);\n\t}\n}", "function showImpactAssessmentWarningDialogue() {\n showDialog({\n title: 'WARNING: Inconsistent data',\n text: 'Elements on this page need correcting: \\nRows of risk weights should NOT EXCEED 100 for each area\\nProblem groups highlighted in red'.split('\\n').join('<br>'),\n negative: {\n title: 'Continue'\n }\n });\n}", "function notify_anomaly_type_wrong() {\n if (DEBUG) {\n console.log(\"FUNCTION : notify_anomaly_type_wrong\");\n }\n $.notify({\n title: \"<strong>anomaly_type</strong>\",\n message: 'wrong',\n }, {\n type: \"danger\",\n placement: {\n from: \"bottom\",\n align: \"center\"\n }\n });\n}", "function showRiskAssessmentWarningDialogue() {\n showDialog({\n title: 'WARNING: Inconsistent data',\n text: 'Elements on this page need correcting: \\nThe objective weights for each category must TOTAL 100 \\nProblem groups highlighted in red.'.split('\\n').join('<br>'),\n negative: {\n title: 'Continue'\n }\n });\n}", "function notify_risk_type_wrong() {\n if (DEBUG) {\n console.log(\"FUNCTION : notify_risk_type_wrong\");\n }\n $.notify({\n title: \"<strong>risk_type</strong>\",\n message: 'wrong',\n }, {\n type: \"danger\",\n placement: {\n from: \"bottom\",\n align: \"center\"\n }\n });\n}", "function showRiskCharacteristicsWarningDialogue() {\n showDialog({\n title: 'WARNING: Inconsistent data',\n text: 'Elements on this page need correcting: \\nColumns of risk weights must TOTAL 100\\nProblem groups highlighted in red'.split('\\n').join('<br>'),\n negative: {\n title: 'Continue'\n }\n });\n}", "isStrongerThan(hand) {\n // ˅\n return this.judgeGame(hand) === 1;\n // ˄\n }", "function showAlert(type, message, callback) {\n // Set alert colors\n setAlertStyle(type);\n // Determine type of alert to show\n var hitboxElement;\n if ($('#welcome-blue-hitbox').length) {\n // Check to see if we are on the welcome page\n hitboxElement = $('#welcome-blue-hitbox');\n } else {\n hitboxElement = $('#blue-hitbox-add-pane');\n }\n if (isElementInViewport(hitboxElement)) {\n // Hitbox is in view, show alert there\n return showHitboxAlert(hitboxElement, message, callback);\n } else {\n // Hitbox is not in view, show a fixed alert\n return showFixedAlert(hitboxElement, message, callback);\n }\n}", "function assessSituation(dangerLevel, saveTheDay, badExcuse){\n if (dangerLevel > 50){\n console.log(badExcuse);\n } else if (dangerLevel >= 10){\n console.log(saveTheDay);\n } else {\n console.log(\"Meh. Hard pass.\");\n }\n}", "function askMixed() {\n var mixed = prompt(questionsArr[2]).toLowerCase();\n if (mixed === 'no' || mixed === 'n') {\n userPoints += 1;\n alertPrefixString = 'Correct! ';\n console.log('The user answered question 3 correctly');\n } else {\n alertPrefixString = 'Sorry! ';\n console.log('The user answered question 3 incorrectly');\n }\n var mixedAlert = alert(alertPrefixString + responsesArr[2]);\n askBlack();\n}", "function checkBudget(product, budget, message){\n if (product.price <= budget) {\n return message(product,true)\n } else {\n return message(product,false)\n }\n}", "function errorTime(){\n\tvar timet1 = document.getElementById('TRV_t1_id').value\n var timet2 = document.getElementById('TRV_t2_id').value\n\tvar timet3 = document.getElementById('TRV_t3_id').value\n\ttimet1 = parseFloat(timet1)\n\ttimet2 = parseFloat(timet2)\n\tif (timet1 > timet2){\n\t\treturn true\n\t}\n\tif (timet3!=0 && (timet1!=0 || timet2 != 0)){\n\t\treturn true\n\t} \n\telse {\n\t\treturn false\n\t}\n}", "function myWarning( _msg )\n{\n\tif( _msg.length != 0 )\n\t{\n\t\t$('#alert-warnings').html('<div style=\"margin-top: 6px; margin-bottom: 0px;\" class=\"alert\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\">&times;</button><strong>Warning!</strong> ' + _msg + '</div>' )\n\t\t$('#alert-warnings').css('display','block')\n\t\t$('#divider-warnings').css('display','block')\n\t}\n\telse\n\t{\n\t\t$('#alert-warnings').css('display','none')\n\t\t$('#divider-warnings').css('display','none')\n\t}\n}", "function temp(temp1, temp2){\n\tif((temp1 < 0 && temp2 > 100) || (temp1 > 100 && temp2 < 0)){\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}", "function compareByScore(a, b) {\n \"use strict\";\n if ((a.seize && b.seize) || (!a.seize && !b.seize)) {\n i = b.totalScore - a.totalScore;\n return i;\n } else if (a.seize && !b.seize) {\n return -1;\n } else {\n return 1;\n }\n}", "function showResultsWarningDialogue() {\n showDialog({\n title: 'WARNING: Inconsistent data',\n text: 'Elements on this page need correcting: \\nThe aggregated project weights must TOTAL 100 \\nProblem groups highlighted in red.'.split('\\n').join('<br>'),\n negative: {\n title: 'Continue'\n }\n });\n}", "function areTrue(a, b) {\n\treturn a && b ? 'both' : !a && !b ? 'neither' : a ? 'first' : 'second';\n}", "function alert(guess) {\n\n if (guess < 0 || guess > 9) {\n\n console.log(`ERROR: ${guess} is out of range 0 - 9.`);\n }\n\n}", "function isAdmissibleOverpayment(prices, notes, x) {\n \n const percentDiff = mapDiff(notes);\n \n const priceDiff = prices.map( (price, i) => {\n return (price - (price / percentDiff[i] ));\n })\n \n return (Math.round(priceDiff.reduce( (a, c) => a + c , 0) * 10000) / 10000) <= x ;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
by far, we have got a track's all measures, need to process,normalize
function normalizeMeasures(part) { const measuresLengths = part.measures.map(a => a.beat.length); console.log("12121212121212122", measuresLengths); const lcmOfBeatLength = Util.lcm(...measuresLengths); // 1.转换成对0 2.把track内所有小节beat统一长度 // 不能用foreach,foreach会直接bypass掉empty的(稀疏数组遍历) // part.measures.forEach((measure, measureIndex) => {}); for ( let measureIndex = 0; measureIndex <= part.measures.length - 1; measureIndex += 1 ) { // console.log("measure::::::::::", part.measures[measureIndex]); if (!part.measures[measureIndex]) { //建一个空小节 //potential bug here part.measures[measureIndex] = { measure: measureIndex + 1, sequence: "", beat: Util.createUnderScores(lcmOfBeatLength), matchZero: true }; } else { // 对位处理成对0 if (!part.measures[measureIndex].matchZero) { // 对位转成对0,抽出对应的音//potential bug here, super mario....seemingly solved // const sequenceArray = JSON.parse( // `[${part.measures[measureIndex].sequence}]`.replace( // /([ABCDEFG]#*b*[1-9])/g, // '"$1"' // ) // ); let newSeqArray = part.measures[measureIndex].beat .split("") .map((beatDigit, index) => { if (beatDigit.match(/\d/g)) { return part.measures[measureIndex].sequence[index]; } else { return ""; } }); newSeqArray = newSeqArray.filter(seq => !!seq); // 排掉空的 console.log("bbbbbbbbbbb", newSeqArray); // TO FIX HERE!!! // let s = JSON.stringify(newSeqArray.filter(note => note != "")).replace( // /"/g, // "" // ); // s = s.substring(1, s.length - 1); // 去掉数组的前后方括号 // part.measures[measureIndex].sequence = s; part.measures[measureIndex].sequence = newSeqArray; part.measures[measureIndex].matchZero = true; } // console.log("jjjjjjjjjjjjjj", part.measures[measureIndex].sequence); //对0的,beat延展就行了,原来000的可能变成0--0--0-- (根据最小公倍数) if (part.measures[measureIndex].beat.length < lcmOfBeatLength) { const ratio = lcmOfBeatLength / part.measures[measureIndex].beat.length; // console.log("[][][]"); // console.log(lcmOfBeatLength); // console.log(part.measures[measureIndex].beat.length); const append = Util.createScores(ratio - 1); part.measures[measureIndex].beat = part.measures[measureIndex].beat .split("") .join(append); part.measures[measureIndex].beat += append; } } } console.log("=== measure after normalization==="); console.log(part.measures); //把所有measure合成一大段 应了老话「不要看小节线」 part.tonepart = part.measures.reduce((a, b) => { // console.log("?", a.sequence); return { // potential bug: if a/b is empty string, no comma here, seemingly solved // sequence: `${a.sequence}${a.sequence && b.sequence ? "," : ""}${ // b.sequence // }`, sequence: a.sequence.concat(b.sequence), beat: `${a.beat}${b.beat}` }; }); console.log("=== final part in this part ==="); console.log(part.tonepart); }
[ "function Waveform2Score(wave_start, wave_end, measure_start, measure_end) {\n var wavesegment_options = {\n container: '#waveform',\n waveColor: '#dddddd',\n progressColor: '#3498db',\n loaderColor: 'purple',\n cursorColor: '#e67e22',\n cursorWidth: 1,\n selectionColor: '#d0e9c6',\n backend: 'WebAudio',\n normalize: true,\n loopSelection: false,\n renderer: 'Canvas',\n partialRender: true,\n waveSegmentRenderer: 'Canvas',\n waveSegmentHeight: 50,\n height: 100,\n barWidth: 2,\n plotTimeEnd: wavesurfer.backend.getDuration(),\n wavesurfer: wavesurfer,\n ELAN: elan,\n wavesSegmentsArray,\n scrollParent: false\n };\n\n var measure_duration = (wave_end - wave_start) / (measure_end - measure_start);\n\n for (var i = measure_start; i < measure_end; i++) {\n var msr = createMeasureDIV(i);\n var rect = msr.getBoundingClientRect();\n\n var waveSegmentPos = {\n left: rect.left + \"px\",\n top: rect.top + \"px\",\n width: rect.width,\n container: msr.getAttribute('id')\n }\n\n\n wavesSegmentsArray.push(waveSegmentPos);\n\n var repris = tixlb[i][2];\n var bpm = (60 / measure_duration) * tixbts[i - 1];\n console.log(\"tixbts:\" + tixbts[i - 1]);\n elan.addAnnotation(ANNO_ID + i, wave_start + (i - measure_start) * measure_duration,\n wave_start + (i - measure_start + 1) * measure_duration,\n \"Bar \" + i + \" Rep \" + repris,\n \"BPM: \" + bpm);\n\n\n }\n elanWaveSegment.init(wavesegment_options);\n highlightSelectedDIVs();\n\n}", "newMeasure() {\r\n let measures = this.score.measures;\r\n if(measures[measures.length-1].notes.length > 1) {\r\n measures[measures.length-1].notes.pop();\r\n measures.push(\r\n {\r\n 'attributes': {\r\n repeat: {\r\n left: false,\r\n right: false\r\n }\r\n },\r\n 'notes':[\r\n {'type' : 'input'}\r\n ]\r\n });\r\n }\r\n }", "function calculate() \n{\n\tif(timecount < 10000) { // 10 secs limit\n\t\t//calculate note persistence as a function of time\n\t\tvar notepersistence = persistence_increase(timecount);\n\t\t\n\t\t//accumulate weights in each Harmonic Center (HC)\n\t\tfor(i = 0; i < resolution; i++) {\n\t\t\tvar next_index = Math.abs((i-resolution) % resolution);\n\t\t\tvar noteweight = scale(notepersistence, 0., 10000., 0., weights[next_index]);\n\t\t\t\n\t\t\thcindex_mod = (hcindex + i) % resolution;\n\t\t\thcw[hcindex_mod][next_index] += noteweight;\n\t\t}\n\t}\n\telse {\n\t\tlimit = true;\n\t}\t\n}", "calcMvalues() {\n var _this = this;\n var data = this.data;\n // Loop through all CATEGORIES\n $.each(data.categories, function(index, category) {\n if (_this.debug) console.log(\"\\nCALC M - Category: \" + category.name + \" >>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n\n // Loop through each CRITERIA of each CATEGORY - run calculations and update data model\n $.each(category.criteria, function(index, criteria) {\n // Clear MNI_results\n var MNI_result = [];\n // Temp array to store converted CRITERIA WEIGHT\n var converted_alternative_weights = [];\n if (_this.debug) console.log(\"Crit: \" + criteria.name + \" >>>>>>>>>>>>>>>>>>>>>>>>>>\");\n\n // For each ALTERNATIVE run calculations and update data model\n $.each(data.alternatives, function(index, alternative) {\n // CALCULATE Mni for each CRITERIA/ALTERNATIVE //////////////////\n var convert_alternative_weight = _this.roundTo2(criteria.alternativeWeights[index] * 0.01);\n // Round to 2 decimal places to remove JS floating point variations\n convert_alternative_weight = _this.roundTo2(convert_alternative_weight);\n // Temp store converted weight for later calculations\n converted_alternative_weights.push(convert_alternative_weight);\n // CRITERIA WEIGHT * ALTERNATIVE WEIGHT (convert from percentages)\n var calc = _this.roundTo2((criteria.weight * 0.01) * convert_alternative_weight);\n // Add result to temp array, rounded to 3 decimal places\n MNI_result.push(calc);\n });\n\n // update data model\n criteria.Mni = MNI_result; // records Mni results\n\n // CALCULATE M for each CRITERIA ////////////////////////////////////\n // 1-(sum of MNI_results);\n var M_result = _this.roundTo2(1 - (MNI_result.reduce(_this.getSum)));\n // update data model, rounded to 3 decimal places\n criteria.M = M_result;\n\n // CALCULATE Ml for each CRITERIA ////////////////////////////////////\n // 1-(CRITERIA WEIGHT (convert from percentage));\n criteria.Ml = 1 - _this.roundTo2((criteria.weight * 0.01));\n\n // CALCULATE Mdash for each CRITERIA ////////////////////////////////////\n // CRITERIA WEIGHT * (1-(sum(ALTERNATIVE WEIGHTS)))\n var Mdash_result = _this.roundTo2((criteria.weight * 0.01)) * _this.roundTo2((1 - (converted_alternative_weights.reduce(_this.getSum))));\n criteria.Mdash = Mdash_result;\n\n if (_this.debug) console.log(\">> MNI: \" + criteria.Mni);\n if (_this.debug) console.log(\">> M: \" + criteria.M);\n if (_this.debug) console.log(\">> Ml: \" + criteria.Ml);\n if (_this.debug) console.log(\">> Mdash: \" + criteria.Mdash);\n });\n });\n }", "partitionAnalysis() {\n this.setWaypointFields();\n this.partSizes();\n this.calculatePartBdryStats();\n }", "formatMotionData(obj){\n var orientationX = {label:'orientationX',values:[]},\n orientationY = {label:'orientationY',values:[]},\n orientationZ = {label:'orientationZ',values:[]},\n accelerationX = {label:'accelerationX',values:[]},\n accelerationY = {label:'accelerationY',values:[]},\n accelerationZ = {label:'accelerationZ',values:[]},\n speed = {label:'speed',values:[]},\n distance = {label:'distance',values:[]}, earliestTime, skipsTime, latestTime;\n\n var totals = {\n s:0, d:0\n };\n var curVals = {};\n try{\n var newObj = obj[0];\n if(newObj){\n var previousTime;\n var avg = 0;\n for(let val in newObj){\n if(!isNaN(val)){\n var curVal = newObj[val];\n if(curVal){\n curVals = curVal;\n curVal.hasOwnProperty('speed') && speed.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['speed']}) && !isNaN(curVal['speed']) && (totals.s += curVal['speed']);\n curVal.hasOwnProperty('ox') && orientationX.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['ox']});\n curVal.hasOwnProperty('oy') && orientationY.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['oy']});\n curVal.hasOwnProperty('oz') && orientationZ.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['oz']});\n curVal.hasOwnProperty('ax') && accelerationX.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['ax']});\n curVal.hasOwnProperty('ay') && accelerationY.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['ay']});\n curVal.hasOwnProperty('az') && accelerationZ.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['az']});\n curVal.hasOwnProperty('distance') && distance.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['distance']}) && !isNaN(curVal['distance']) && (totals.d += curVal['distance']);\n if(parseInt(val,10) < earliestTime || !earliestTime){\n earliestTime = parseInt(val,10);\n }\n if(parseInt(val,10) > latestTime || !latestTime){\n latestTime = parseInt(val,10);\n }\n if(parseInt(val,10) - previousTime > 10000){\n skipsTime = true;\n }\n previousTime = parseInt(val,10);\n }\n }\n }\n }\n }\n catch(e){\n console.error(e);\n }\n var data = {\n skipsTime:skipsTime,\n acceleration:[accelerationX,accelerationY,accelerationZ],\n speed:[speed],\n distance:[distance],\n orientation:[orientationX,orientationY,orientationZ],\n currentValues:curVals\n };\n data['acceleration'].earliestTime = earliestTime;\n data['acceleration'].latestTime = latestTime;\n data['acceleration'].skipsTime = skipsTime;\n data['speed'].earliestTime = earliestTime;\n data['speed'].latestTime = latestTime;\n data['speed'].skipsTime = skipsTime;\n data['speed'].avg = totals.s ? totals.s / speed.values.length : 0;\n data['distance'].earliestTime = earliestTime;\n data['distance'].latestTime = latestTime;\n data['distance'].skipsTime = skipsTime;\n data['distance'].avg = totals.d ? totals.d / speed.values.length : 0;\n data['orientation'].earliestTime = earliestTime;\n data['orientation'].latestTime = latestTime;\n data['orientation'].skipsTime = skipsTime;\n return data;\n }", "function vxMeasure (name, pt1, pt2, nrml1, nrml2) {\n \n // Mesh Name\n this.Name = name;\n \n // The Owning Model\n this.Model = null;\n \n var col = 0.75;\n this.meshcolor = new vxColour(col, col, col, 1);\n \n this.colour = [0, 162/255, 1, 1];\n \n // Place holders to determine if the Hover index is with in this\n // mesh or not.\n this.IndexStart = 0;\n this.IndexEnd = 0;\n\n //Vertice Array\n this.mesh_vertices = [];\n this.edgevertices = [];\n \n //Normal Array\n this.vert_noramls = [];\n this.edge_noramls = [];\n\n // texture uvs for consistency\n this.vert_uvcoords = [];\n this.edge_uvcoords = [];\n \n //Colour Array\n this.vert_colours = [];\n this.wire_colours = [];\n this.edge_colours = [];\n \n //Selection Colour Array\n this.vert_selcolours = [];\n\n //Indices\n this.Indices = [];\n this.EdgeIndices = [];\n \n this.meshBuffers = {\n verticies: null,\n normals: null,\n uvCoords: null,\n colours: null,\n selectionColours: null,\n wireframeColours: null,\n indices: null,\n }\n \n this.edgeBuffers = {\n verticies: null,\n normals: null,\n uvCoords: null,\n colours: null,\n selectionColours: null,\n wireframeColours: null,\n indices: null,\n }\n\n this.Texture = null;\n\n //What is the model type\n this.meshType = MeshType.Lines;\n \n //Should it be Drawn\n this.Enabled = true;\n \n // The Max Point of this Mesh\n this.MaxPoint = new vxVertex3D(0,0,0);\n \n this.Center = [0,0,0];\n \n this.IndexStart = numOfFaces;\n \n this.Point1 = pt1;\n this.Point2 = pt2;\n\n // Get the average vector of the face and then normalise it.\n this.Direction = new vxVertex3D(0,0,0);\n\n // setup the cross product\n this.CrossProd = [0,0,0];\n\n this.Delta = [0,0,0];\n this.Delta[0] = this.Point2[0] - this.Point1[0];\n this.Delta[1] = this.Point2[1] - this.Point1[1];\n this.Delta[2] = this.Point2[2] - this.Point1[2];\n\n this.NormalAvg = [0,0,0];\n\n\n vec3.cross(this.CrossProd, nrml1, nrml2);\n vec3.avg(this.NormalAvg, nrml1, nrml2);\n\n\n // If two vectors are parrellal, then we need to shift the normal direction slightly and re try the cross prod\n if(this.CrossProd[0]==0 && this.CrossProd[1]==0 && this.CrossProd[1]==0) {\n \n nrml2[0] = 1;\n nrml2[1] = 0;\n nrml2[2] = 0;\n\n vec3.cross(this.CrossProd, nrml1, nrml2);\n vec3.avg(this.NormalAvg, nrml1, nrml2);\n\n if(this.CrossProd[0]==0 && this.CrossProd[1]==0 && this.CrossProd[1]==0) {\n \n nrml2[0] = 0;\n nrml2[1] = 0;\n nrml2[2] = 1;\n\n vec3.cross(this.CrossProd, nrml1, nrml2);\n vec3.avg(this.NormalAvg, nrml1, nrml2);\n }\n }\n\n // Now we have a vector which is 90 degrees to both normals, which means it's also\n // tangent to both faces. With this we can then calculate a new cross product between\n // the tanget vector, and the vector between the two points.\n this.FinalCrossProd = [0,0,0];\n\n vec3.cross(this.FinalCrossProd, this.CrossProd, this.Delta);\n\n // Now check the angle between the Final Cross prod and the average normal this is\n // to prevent the leader lines going into the mesh. \n var rad = vec3.angle(this.FinalCrossProd, this.NormalAvg);\n var angle = rad * 180/3.14159;\n var dirFactor = 1;\n if(angle > 90)\n dirFactor = -1;\n\n // First try setting the direction as the average of the two faces.\n this.Direction.X = this.FinalCrossProd[0] * dirFactor;\n this.Direction.Y = this.FinalCrossProd[1] * dirFactor;\n this.Direction.Z = this.FinalCrossProd[2] * dirFactor;\n\n this.Direction.Normalise();\n\n\n // now get the magnitude of the difference\n this.DeltaX = this.Point2[0] - this.Point1[0];\n this.DeltaY = this.Point2[1] - this.Point1[1];\n this.DeltaZ = this.Point2[2] - this.Point1[2];\n \n this.Length = Math.sqrt(this.DeltaX * this.DeltaX + this.DeltaY * this.DeltaY + this.DeltaZ * this.DeltaZ);\n \n // The height of the vertical lines\n this.vertLineHeight = this.Length;\n \n // height of the distance marker line\n this.leaderHeight = this.Length * 0.75;\n\n \n //log(\"Measurement\");\n //log(\"=================================\");\n //log(\"Point1 = \" + this.Point1);\n //log(\"Point2 = \" + this.Point2);\n //log(\"---------------------------------\");\n //log(\"Direction = \" + this.Direction.Z);\n //log(\"Length = \" + this.Length);\n //log(\"=================================\");\n \n this.leaderPadding = this.Length * 0.12525;\n\n// console.log(this.Direction);\n this.Direction.X = this.leaderHeight * this.Direction.X;\n this.Direction.Y = this.leaderHeight * this.Direction.Y;\n this.Direction.Z = this.leaderHeight * this.Direction.Z;\n \n // Top Distance Line\n this.AddVertices(-this.Point1[0] + this.Direction.X, -this.Point1[1] + this.Direction.Y, -this.Point1[2] + this.Direction.Z);\n this.AddVertices(-this.Point2[0] + this.Direction.X, -this.Point2[1] + this.Direction.Y, -this.Point2[2] + this.Direction.Z);\n \n\n this.Direction.X += this.leaderPadding * this.Direction.X;\n this.Direction.Y += this.leaderPadding * this.Direction.Y;\n this.Direction.Z += this.leaderPadding * this.Direction.Z;\n\n // First Leader Line\n this.AddVertices(-this.Point1[0], -this.Point1[1], -this.Point1[2]);\n this.AddVertices(-this.Point1[0] + this.Direction.X, -this.Point1[1] + this.Direction.Y, -this.Point1[2] + this.Direction.Z);\n \n // Second Leader Line\n this.AddVertices(-this.Point2[0], -this.Point2[1], -this.Point2[2]);\n this.AddVertices(-this.Point2[0] + this.Direction.X, -this.Point2[1] + this.Direction.Y, -this.Point2[2] + this.Direction.Z);\n \n \n this.InitialiseBuffers();\n //distanceMesh.meshType = MeshType.Lines;\n \n //this.Center = this.Point1[0];\n\n var lengthShort = this.Length.toString().substr(0, this.Length.toString().indexOf(\".\")+5);\n \n AddTreeNode(\"node_\"+name, name, measureNodeId, \"measure\");\n AddTreeNode(\"node_\"+name+\"_dist\", 'Distance: '+ lengthShort, \"node_\"+name, \"bullet_vector\");\n AddTreeNode(\"node_\"+name+\"_length\", 'Length: '+ this.Length, \"node_\"+name+\"_dist\", \"hash\");\n AddTreeNode(\"node_\"+name+\"_deltax\", 'Delta X: '+ this.DeltaX, \"node_\"+name+\"_dist\", \"bullet_red\");\n AddTreeNode(\"node_\"+name+\"_deltay\", 'Delta Y: '+ this.DeltaY, \"node_\"+name+\"_dist\", \"bullet_green\");\n AddTreeNode(\"node_\"+name+\"_deltaz\", 'Delta Z: '+ this.DeltaZ, \"node_\"+name+\"_dist\", \"bullet_blue\");\n \n this.TextPos = [0,0,0,0];\n this.TextCenter = [(-this.Point1[0] - this.Point2[0])/2 + this.Direction.X, (-this.Point1[1] - this.Point2[1])/2 + this.Direction.Y, (-this.Point1[2] - this.Point2[2])/2+ this.Direction.Z];\n \n var maindiv = document.getElementById(\"div_canvas\");\n \n this.text = document.createElement(\"a\");\n this.text.style.position = \"absolute\";\n this.text.style.top = \"200px\";\n this.text.style.left = \"300px\";\n this.text.innerHTML = this.Name +\" = \"+ lengthShort;\n //inp1.setAttribute(\"id\", id); // added line\n this.text.setAttribute(\"class\", \"measure\"); // added line\n \n maindiv.appendChild( this.text);\n}", "function preProcessData(data) {\n\t\t\t// set defaults for values that may be missing from older streams\n\t\t\tsetIfMissing(data, \"rollingCountBadRequests\", 0);\n\t\t\t// assert all the values we need\n\t\t\tvalidateData(data);\n\t\t\t// escape string used in jQuery & d3 selectors\n\t\t\tdata.escapedName = data.name.replace(/([ !\"#$%&'()*+,./:;<=>?@[\\]^`{|}~])/g,'\\\\$1') + '_' + data.index;\n\t\t\t// do math\n\t\t\tconvertAllAvg(data);\n\t\t\tcalcRatePerSecond(data);\n\t\t}", "function doPathMeasures(fromNet , toNet){\n var fromNetID = getNetworkID(fromNet);\n var toNetID = getNetworkID(toNet);\n if (!fromNetID || !toNetID)\n return;\n var probesId = hasProbeType(fromNetID , REACHABILITY_CAPABILITY);\n // Are there any probes in the from net?\n if (probesId.length == 0){\n cli.debug(\"No available probes to do measure from \\'\"+getNetworkDescription(fromNetID)+\"\\' to \\'\"+getNetworkDescription(toNetID)+\"\\'\");\n return;\n }\n // Randomly select a probe from available capabilities\n //var probe = __availableProbes[getRandomInt(0,(probesId.length -1))];\n var probe = __availableProbes[probesId[0]];\n try{\n var spec = new mplane.Specification(probe);\n }catch(e){\n cli.error(\"doPathMeasures: Error creating the specification\");\n return;\n }\n\n // Do we have a path?\n if (!SPTree[fromNet][toNet]){\n showTitle(\"No PATH available \"+fromNet +\"(\" + fromNetID + \") -> \"+toNet+\"(\"+toNetID+\")\");\n }else{\n cli.info(\"Considering a new measure: \"+fromNet + \"->\" + toNet);\n // Array of IPs to be used ad target for our measures\n var targetIps = ipPath(fromNet , toNet);\n targetIps.forEach(function(curIP , index) {\n // If we can register the measure, proceed\n if (registerMeasure(fromNet , toNet) && curIP) {\n var destParam = probe.getParameter(\"destination.ip4\");\n // Check if the destination is accepted by the probe\n if ((destParam.isValid(curIP) && destParam.met_by(curIP, undefined))) {\n spec.set_when(\"now + 1s\");\n try {\n spec.setParameterValue(\"destination.ip4\", curIP);\n spec.setParameterValue(\"source.ip4\", probe.ipAddr);\n spec.set_metadata_value(\"Destination_NET\", toNet);\n // Very bad... for now it works\n if (probe.has_parameter(\"number\"))\n spec.setParameterValue('number', \"5\");\n // We changed the params, so we should update the default token, or we will have a lot of specification with the same token!!!\n spec.update_token();\n } catch (e) {\n cli.error(\"Error in parameter set\");\n cli.error(e);\n }\n supervisor.registerSpecification(\n spec\n , probe.DN\n , {\n host: cli.options.supervisorHost,\n port: cli.options.supervisorPort,\n keyFile: cli.options.key,\n certFile: cli.options.cert,\n caFile: cli.options.ca\n },\n function (err, receipt) {\n if (err)\n console.log(err);\n else {\n cli.info(\" Measure registered (\" + curIP+\")@\"+probe.DN);\n // Register the receipt\n var rec = mplane.from_dict(JSON.parse(receipt));\n rec._eventTime = new Date(); // Informational\n\n // The RI does not set the label in the receipt\n // Since we have it from the spec, simply set it in the receipt\n rec.set_label(spec.get_label());\n if (!(rec instanceof mplane.Receipt)) {\n cli.error(\"The returned message is not a valid Receipt\");\n } else {\n // We keep local registry of all spec and relative receipts\n if (rec) {\n rec._specification = spec;\n rec.fromNet = fromNet;\n rec.toNet = toNet;\n rec.destonationIP = curIP;\n rec.sourceIP = probe.ipAddr;\n registerReceipt(fromNet, toNet, rec);\n }\n }\n }\n });\n } else {\n cli.info(\"... \" + curIP + \" is not a valid value for this capability\");\n }\n }else{\n cli.debug(\" No slots available\");\n }\n\n });\n }\n}", "function measureChange() {\n measure = document.getElementById(measureName + \"-select\").value;\n updateColorAxis();\n chart.series[0].setData(get_data());\n }", "calcAggregatedMvalues() {\n var _this = this;\n var data = this.data;\n\n if (_this.debug) console.log(\"\\n\\n<<<<<<<<< RESULT PAGE CALCULATIONS >>>>>>>>>>>>>>>>>\");\n // Loop through all CATEGORIES\n $.each(data.categories, function(index, category) {\n if (_this.debug) console.log(\"\\nCALC Aggregated M values - Category: \" + category.name + \" >>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n\n var aggMni_results = []; // capture agregated Mni values for each CATEGORY (one per each solution)\n\n // Loop over each belief value for Mni\n for (var i = 0; i < category.Beliefs.length; i++) {\n aggMni_results.push(category.Beliefs[i] * (category.weight / 100));\n }\n category.Mni = aggMni_results;\n\n // CALCULATE M for each CATEGORY ////////////////////////////////////\n // 1-(sum Mni aggMni_results)\n var M_result = 1 - (aggMni_results.reduce(_this.getSum));\n // update data model, rounded to 3 decimal places\n category.M = M_result;\n\n // CALCULATE Ml for each CATEGORY ////////////////////////////////////\n // 1-(category weight (convert from percentage)\n category.Ml = 1 - (category.weight * 0.01);\n\n // CALCULATE Mdash for each CATEGORY ////////////////////////////////////\n // category weight * (1-(sum(alternative beliefs)))\n var Mdash_result = (category.weight * 0.01) * (1 - (category.Beliefs.reduce(_this.getSum)));\n category.Mdash = Mdash_result;\n\n if (_this.debug) console.log(\"MNI: \" + category.Mni);\n if (_this.debug) console.log(\"M: \" + category.M);\n if (_this.debug) console.log(\"Ml: \" + category.Ml);\n if (_this.debug) console.log(\"Mdash: \" + category.Mdash);\n });\n }", "function analyze() {\n raf = requestAnimationFrame(analyze);\n var stream = audioAnalyzer.getFrequencyAnalysis();\n\n if(false === stream) {\n onEnd();\n return;\n }\n\n var a = utils.average(stream),\n id;\n // Glitch on clap\n if (a > 100.5 && a < 102.5) {\n if(Date.now() - lastGlitch < 500) {\n // Don't replay glitch before 0.5s\n return;\n }\n // Play glitch scene\n SM.play(0);\n lastSwitch = lastGlitch = Date.now();\n\n return;\n }\n // Change scene on specific frequency\n if(a > 78 && a < 88) {\n if(Date.now() - lastSwitch < 300) {\n // Don't change scene before 0.3s\n return;\n }\n\n playRandomScene();\n if (false === rendering) {\n SM.render();\n TweenMax.set(render, {autoAlpha: 1, display: 'block'});\n rendering = true;\n }\n lastSwitch = Date.now();\n }\n}", "getMetricsData() {\n\n let innerMap = new Map();\n\n // Get interactions for each agent in current time\n for (let agent of this.agents) {\n this.getInteractions(innerMap, agent);\n }\n\n //save interactions for the current tick time.\n this.metricsMap.set(world.getTicks(), innerMap);\n\n for (let agent of this.agents) {\n this.recordAgentViscosityData(agent);\n }\n\n let vscsty = this.recordGlobalViscosityData();\n\n document.getElementById(\"viscosityInWorld\").innerHTML = vscsty.toFixed(2);\n }", "parse() {\n\t\t// console.log('Started parsing');\n\t\tthis.parseHeader();\n\t\tif (this.error !== null) {\n\t\t\tif (this.error.code <= 2 && this.error.code !== 0) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tthis.trks = new Array(this.ntrks);\n\t\tlet t0 = (new Date()).getTime();\n\t\tlet i;\n\t\tfor (i = 0; i < this.ntrks; i++) {\n\t\t\tthis.trks[i] = new MIDItrack();\n\t\t}\n\t\tfor (tpos = 0; tpos < this.ntrks; tpos++) {\n\t\t\tisNewTrack = true;\n\t\t\tthis.trks[tpos].usedInstruments.push();\n\t\t\tthis.parseTrack();\n\t\t\t// console.log(this.trks[tpos].events);\n\t\t}\n\t\tlet lowestQuantizeError = Infinity;\n\t\tlet bestBPB = 0;\n\t\tfor (i = 0; i < 16; i++) {\n\t\t\tlet total = 0;\n\t\t\tfor (let j = 0; j < this.trks.length; j++) {\n\t\t\t\ttotal += this.trks[j].quantizeErrors[i];\n\t\t\t}\n\t\t\t// console.log('BPB: ' + (i+1) + ', error: ' + total);\n\t\t\tif (total < lowestQuantizeError && i < 8) {\n\t\t\t\tlowestQuantizeError = total;\n\t\t\t\tbestBPB = i + 1;\n\t\t\t}\n\t\t}\n\t\tthis.blocksPerBeat = bestBPB;\n\t\t// console.log(this);\n\t\t// console.log(this.noteCount+' notes');\n\t\t// console.log('MIDI data loaded in '+((new Date).getTime() - t0)+' ms');\n\t}", "function measureChange() {\n measure = document.getElementById(measureName + \"-select\").value;\n updateData();\n }", "normalize(){\n for (var column = 0; column < 4; column++){\n for(var row = 0; row < 4; row++){\n this.matArray[column][row]\n }\n }\n }", "resultsCalc(data) {\n if (this.debug) console.log(\"\\nCALCULATE RESULTS >>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n // DATA is either PROBLEM object for DECISION MAKING\n this.data = data;\n // Calculate M values for each CRITERION (Mni and M and Ml and Mdash) (row 17 + 26 + 35 + 44)\n this.calcMvalues();\n // Calculate K value for CATEGORY (row 53)\n this.calcK();\n // Calculate M values for each ALTERNATIVE in Category (row 56)\n this.calcMalternatives();\n // Calculate M dash H value for CATEGORY (row 63)\n this.calcMdashH();\n // Calculate Ml H value for CATEGORY (row 66)\n this.calcMlH();\n // Calculate array of Beliefs relating to each ALTERNATIVE (row 71)\n this.calcBeliefs();\n // Calculate level of ignorance associated with ALTERNATIVES of this CATEGORY (row 77)\n this.calcIgnorance();\n\n // RESULTS PAGE calculations\n // Calculate array of M n,i relating to each category (summary sheet row 41 + 52 + 63 + 74)\n this.calcAggregatedMvalues();\n // Calculate aggregated K value for PROJECT (summary sheet row 85)\n this.calcAggregatedK();\n // Calculate aggregated M values for each ALTERNATIVE in PROJECT (summary sheet row 88)\n this.calcAggregatedMalternatives();\n // Calculate aggregated M dash H value for PROJECT (summary sheet row 95)\n this.calcAggregatedMdashH();\n // Calculate aggregated Ml H value for PROJECT (summary sheet row 98)\n this.calcAggregatedMlH();\n // Calculate array of aggregated Beliefs relating to each ALTERNATIVE (summary sheet row 103)\n this.calcAggregatedBeliefs();\n // Calculate aggregated level of ignorance associated with ALTERNATIVES of this PROJECT (summary sheet row 109)\n this.calcAggregatedIgnorance();\n }", "setMeasureActive() {\n this.measureActive = true;\n this.profile.measure.clearMeasure();\n this.profile.measure.setMeasureActive();\n }", "function calculate(){\n var productMatrix = matrixMultiply();\n var reflectance = [];\n var no = 1.0;\n var ns = parseFloat($('input#substrate').val());\n \n //for each wavelength find matrix values a-d, then calculate x,y,u,v based\n //on above formula. \n for (var w = 0; w < productMatrix.length; w++){\n var value = productMatrix[w].valueOf();\n var a = value[0][0];\n var b = value[0][1];\n var c = value[1][0];\n var d = value[1][1];\n \n var x = math.multiply(no,a);\n var y = math.multiply(math.multiply(no,ns),b);\n var u = math.multiply(ns,d);\n var v = c;\n \n //calculate reflectance\n //using the math.js api for calculations.\n var num = math.chain(math.round(math.pow(math.subtract(x,u),2),8))\n .subtract(math.round(math.pow(math.subtract(y,v),2),8))\n .done();\n var den = math.chain(math.round(math.pow(math.add(x,u),2),8))\n .subtract(math.round(math.pow(math.add(y,v),2),8))\n .done();\n var R = parseFloat(math.round(math.divide(num,den),8));\n //Look at Y axis selection and formulate \n if ($('select#y-axis').val()===\"R\"){\n reflectance.push(R*100); \n }\n else if ($('select#y-axis').val()===\"T\"){\n reflectance.push((1-R)*100);\n }\n else if ($('select#y-axis').val()===\"OD\"){\n reflectance.push(-math.log10(1-R));\n }\n \n }\n \n return reflectance; \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
updates options for specific profiles
function updateProfileOptions(currentProfile) { // show profile specific route options var i, el; for (var profile in list.showElements) { if (currentProfile == profile) { for (i = 0; i < list.showElements[profile].show.length; i++) { el = $(list.showElements[profile].show[i]); el.show(); } for (i = 0; i < list.showElements[profile].hide.length; i++) { el = $(list.showElements[profile].hide[i]); el.hide(); } } } }
[ "function updateDriver() {\n profileFactory.updateProfile(vm.profile).then(\n function() {}\n );\n }", "function addOption() {\n var province = profile.province;\n var country = profile.country;\n province.options[province.options.length] = SelectProvince;\n country.options[country.options.length] = SelectCountry;\n}", "function selectProfile(cb) {\n if (program.profile) {\n program.profile = _.find(program.globalConfig.profiles, {\n name: program.profile\n });\n }\n\n // Next check if there is an environment variable with the name of a valid profile.\n var envVarProfile = process.env.FF_PROFILE;\n if (_.isEmpty(envVarProfile) === false) {\n program.profile = _.find(program.globalConfig.profiles, {name: envVarProfile});\n if (!program.profile) {\n cb(new Error('Environment variable FF_PROFILE refers to to an invalid 4front profile.'));\n }\n }\n\n // If no selectedProfile, try finding the default one.\n if (!program.profile) {\n program.profile = _.find(program.globalConfig.profiles, {\n default: true\n }) || program.globalConfig.profiles[0];\n }\n\n var endpointUrl = parseUrl(program.profile.endpoint);\n program.virtualHost = endpointUrl.host;\n\n debug('using profile: %o', _.pick(program.profile, 'name', 'url'));\n\n cb();\n }", "function updateOptions(option_elems, option_json_arr) {\n if (!option_elems || option_elems.length == 0) {\n console.warn(\"No option elements passed!\");\n return;\n }\n if (!option_json_arr || option_json_arr.length == 0) {\n console.warn(\"No option objects passed!\");\n return;\n }\n $.each(option_elems, function (i, option) {\n $(option).empty();\n $.each(option_json_arr, function (j, o) {\n if (o.selected) {\n $(option).append($(\"<option>\").text(o.label).attr('value', o.value).attr('selected', 'selected'));\n } else {\n $(option).append($(\"<option>\").text(o.label).attr('value', o.value));\n }\n })\n })\n }", "function updateOptionList (listName, updateFunc) {\n var newOptions;\n\n if (!directory.hasOwnProperty(listName)) {\n $log.error('No known option list with name: ', listName);\n return;\n }\n\n newOptions = updateFunc(angular.copy(directory[listName].options));\n\n if (newOptions) {\n directory[listName].options = newOptions;\n\n // delete lookup property, assuming it is no longer valid\n if (!directory[listName].hasOwnProperty('lookup')) {\n delete directory[listName].lookup;\n }\n }\n }", "static displayProfiles() {\r\n const profiles = Store.getProfiles();\r\n profiles.forEach((profile) => {\r\n\r\n // If the profile doesn't exist add it to the list\r\n if (!Store.profileExists(profile)) {\r\n Profile.addProfileToList(profile);\r\n }\r\n // Otherwise, if the object has been changed, \r\n //remove the previous element from the list and add updated\r\n else if (changed) {\r\n const list = document.querySelector('#profileList');\r\n list.removeChild(list.lastChild);\r\n Profile.addProfileToList(profile);\r\n }\r\n });\r\n }", "_update() {\n var i, pr, inn=0, mer=0, ban=0, bui=0;\n\n for (i in this.profiles) {\n pr = this.profiles[i];\n bui += pr.builder;\n mer += pr.merchant;\n inn += pr.innovator;\n ban += pr.banker;\n }\n \n /* update the average */\n if (this.profiles.length > 0) {\n this.builder = bui / this.profiles.length;\n this.merchant = mer / this.profiles.length;\n this.innovator = inn / this.profiles.length;\n this.banker = ban / this.profiles.length;\n }\n else {\n this.builder = 0;\n this.merchant = 0\n this.innovator = 0;\n this.banker = 0;\n }\n }", "static update(storageProfileId, storageProfile){\n\t\tlet kparams = {};\n\t\tkparams.storageProfileId = storageProfileId;\n\t\tkparams.storageProfile = storageProfile;\n\t\treturn new kaltura.RequestBuilder('storageprofile', 'update', kparams);\n\t}", "function updateLevelDropdown() {\n if (beginnerFlag === true && intermediateFlag === true && advancedFlag === true) {\n levelDropdown.selectpicker('val', 'allLevels');\n } else if (beginnerFlag === true) {\n levelDropdown.selectpicker('val', 'beginner');\n } else if (intermediateFlag === true) {\n levelDropdown.selectpicker('val', 'intermediate');\n } else if (advancedFlag === true) {\n levelDropdown.selectpicker('val', 'advanced');\n }\n noSeminarsParagraph();\n }", "function updateUserPreferences(argv) {\n if (_.lowerCase(argv.enabled) !== 'true' && _.lowerCase(argv.enabled) !== 'false') {\n console.log('Enabled must be set to True or False');\n return;\n }\n\n if (_.lowerCase(argv.enabled) === 'true') {\n enabled = 'Y';\n } else {\n enabled = 'N';\n }\n\n if (argv.userId) {\n userToUpdate = argv.userId;\n }\n categoryCode = argv.category;\n\n if (!argv.host) {\n configHelper.getOracleConfig(argv.config, argv.connectionObject, function(err, config) {\n if (err) {\n console.log(err);\n return;\n }\n oracleConfig = config;\n updatePreferencesOracleProcedure(function(error, result) {\n if (error) {\n console.log(error);\n return;\n }\n console.log('Preferences updated: ' + result);\n return;\n });\n });\n } else {\n oracleConfig.user = argv.user;\n oracleConfig.password = argv.password;\n oracleConfig.connectString = argv.host + ':' + argv.port + '/' + argv.service;\n updatePreferencesOracleProcedure(function(error, result) {\n if (error) {\n console.log(error);\n return;\n }\n console.log('Preferences updated: ' + result);\n return;\n });\n }\n}", "function setupProfileSwitcher(isPreview, profile) {\n var elements = document.getElementsByClassName(\"profile-switch\");\n\n for (var i=0; i<elements.length; i++) {\n var element = elements[i];\n\n // If we have a profile, we can show the live/preview buttons\n if (profile) {\n element.parentElement.style.display = \"inline\";\n\n if (element.getAttribute(\"data-profile\") === \"_preview\" && isPreview) {\n // Current profile is preview, disable the preview button\n element.disabled = true;\n } else if (element.getAttribute(\"data-profile\") === \"\" && !isPreview) {\n // Current profile is live, disable the live button\n element.disabled = true;\n }\n\n // Click handler to switch profile\n element.addEventListener(\"click\", function(evt) {\n switchProfile(profile + evt.target.getAttribute(\"data-profile\"))\n });\n\n } else {\n element.parentElement.style.display = \"none\";\n }\n }\n\n var element = document.getElementById(\"profile-reset\")\n element.addEventListener(\"click\", function(evt) {\n switchProfile(\"_default\");\n });\n\n // If we are already viewing the default profile, hide the button\n if (profile && profile === \"_default\" || profile === \"_default_preview\") {\n element.parentElement.style.display = \"none\";\n }\n}", "function updateSelect() {\n for (var i=0;i<g_points.length;i++){\n figures.options[i+1] = new Option('Surface' +i, i);\n }\n}", "function assignAdvancedSettings(tabs, callback) {\n\tfor(var y=0;y<tabs.length;y++){\n\t\tfor(var i=0;i<advSettings.length;i++){\n\t\t\tif(advSettings[i].url == tabs[y].url) {\n\t\t\t\ttabs[y].reload = advSettings[i].reload;\n\t\t\t\ttabs[y].seconds = advSettings[i].seconds;\n\t\t\t}\n\t\t}\t\n\t}\n\tcallback(tabs);\n}", "static update(id, accessControlProfile){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.accessControlProfile = accessControlProfile;\n\t\treturn new kaltura.RequestBuilder('accesscontrolprofile', 'update', kparams);\n\t}", "function updateLookingfor() {\n\tconst profile = document.getElementById(\"profile\");\n\tremove(profile);\n}", "static update(id, reachProfile){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.reachProfile = reachProfile;\n\t\treturn new kaltura.RequestBuilder('reach_reachprofile', 'update', kparams);\n\t}", "function tagProfileUpdate(event){\n\t\t\tif($('#about').length > 0) if($('#about').val().length >=1) sho.dom.trigger('user:profile:about');\n\t\t\tif($('#location').length > 0) if($('#location').val().length > 2) sho.dom.trigger('user:profile:location');\n\t\t\tif($('#avatarId').length > 0) if($('#avatarId').val() != \"\" || $F($$('input[name^=\"customAvatar\"]')[0]).length > 0) sho.dom.trigger('user:profile:avatar');\t\t\n\t\t}", "function updateFontOptions() {\n styleSelectFont.innerHTML = \"\";\n for (let i = 0; i < fonts.length; i++) {\n const opt = document.createElement(\"option\");\n opt.value = i;\n const font = fonts[i].split(\":\")[0].replace(/\\+/g, \" \");\n opt.style.fontFamily = opt.innerHTML = font;\n styleSelectFont.add(opt);\n }\n}", "static update(id, distributionProfile){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.distributionProfile = distributionProfile;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_distributionprofile', 'update', kparams);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draws a trapezoid connecting a genomic range on one chromosome to a genomic range on another chromosome; a syntenic region.
drawSynteny(syntenicRegions) { var t0 = new Date().getTime(); var r1, r2, syntenies, i, color, opacity, regionID, regions, syntenicRegion, ideo = this; syntenies = d3.select(ideo.selector) .insert('g', ':first-child') .attr('class', 'synteny'); for (i = 0; i < syntenicRegions.length; i++) { regions = syntenicRegions[i]; r1 = regions.r1; r2 = regions.r2; color = '#CFC'; if ('color' in regions) { color = regions.color; } opacity = 1; if ('opacity' in regions) { opacity = regions.opacity; } r1.startPx = this.convertBpToPx(r1.chr, r1.start); r1.stopPx = this.convertBpToPx(r1.chr, r1.stop); r2.startPx = this.convertBpToPx(r2.chr, r2.start); r2.stopPx = this.convertBpToPx(r2.chr, r2.stop); regionID = ( r1.chr.id + '_' + r1.start + '_' + r1.stop + '_' + '__' + r2.chr.id + '_' + r2.start + '_' + r2.stop ); syntenicRegion = syntenies.append('g') .attr('class', 'syntenicRegion') .attr('id', regionID) .on('click', function() { var activeRegion = this; var others = d3.selectAll(ideo.selector + ' .syntenicRegion') .filter(function() { return (this !== activeRegion); }); others.classed('hidden', !others.classed('hidden')); }) .on('mouseover', function() { var activeRegion = this; d3.selectAll(ideo.selector + ' .syntenicRegion') .filter(function() { return (this !== activeRegion); }) .classed('ghost', true); }) .on('mouseout', function() { d3.selectAll(ideo.selector + ' .syntenicRegion') .classed('ghost', false); }); var chrWidth = ideo.config.chrWidth; var x1 = this._layout.getChromosomeSetYTranslate(0); var x2 = this._layout.getChromosomeSetYTranslate(1) - chrWidth; syntenicRegion.append('polygon') .attr('points', x1 + ', ' + r1.startPx + ' ' + x1 + ', ' + r1.stopPx + ' ' + x2 + ', ' + r2.stopPx + ' ' + x2 + ', ' + r2.startPx ) .attr('style', 'fill: ' + color + '; fill-opacity: ' + opacity); syntenicRegion.append('line') .attr('class', 'syntenyBorder') .attr('x1', x1) .attr('x2', x2) .attr('y1', r1.startPx) .attr('y2', r2.startPx); syntenicRegion.append('line') .attr('class', 'syntenyBorder') .attr('x1', x1) .attr('x2', x2) .attr('y1', r1.stopPx) .attr('y2', r2.stopPx); } var t1 = new Date().getTime(); if (ideo.debug) { console.log('Time in drawSyntenicRegions: ' + (t1 - t0) + ' ms'); } }
[ "function makeCurlyBrace(x1,y1,x2,y2,w,q)\n\t\t{\n\t\t\t//Calculate unit vector\n\t\t\tvar dx = x1-x2;\n\t\t\tvar dy = y1-y2;\n\t\t\tvar len = Math.sqrt(dx*dx + dy*dy);\n\t\t\tdx = dx / len;\n\t\t\tdy = dy / len;\n\n\t\t\t//Calculate Control Points of path,\n\t\t\tvar qx1 = x1 + q*w*dy;\n\t\t\tvar qy1 = y1 - q*w*dx;\n\t\t\tvar qx2 = (x1 - .25*len*dx) + (1-q)*w*dy;\n\t\t\tvar qy2 = (y1 - .25*len*dy) - (1-q)*w*dx;\n\t\t\tvar tx1 = (x1 - .5*len*dx) + w*dy;\n\t\t\tvar ty1 = (y1 - .5*len*dy) - w*dx;\n\t\t\tvar qx3 = x2 + q*w*dy;\n\t\t\tvar qy3 = y2 - q*w*dx;\n\t\t\tvar qx4 = (x1 - .75*len*dx) + (1-q)*w*dy;\n\t\t\tvar qy4 = (y1 - .75*len*dy) - (1-q)*w*dx;\n\n \treturn ( \"M \" + x1 + \" \" + y1 +\n \t\t\" Q \" + qx1 + \" \" + qy1 + \" \" + qx2 + \" \" + qy2 +\n \t\t\" T \" + tx1 + \" \" + ty1 +\n \t\t\" M \" + x2 + \" \" + y2 +\n \t\t\" Q \" + qx3 + \" \" + qy3 + \" \" + qx4 + \" \" + qy4 +\n \t\t\" T \" + tx1 + \" \" + ty1 );\n\t\t}", "function _drawRegions(paper, mutationDiagram, id, x, l, w, c)\n{\n // loop variables\n var i = 0;\n var size = 0;\n\n // regions (as rectangles on the sequence rectangle)\n for (i = 0, size = mutationDiagram.regions.length; i < size; i++)\n {\n var regionX = x + scaleHoriz(mutationDiagram.regions[i].start, w, l);\n var regionY = c - 10;\n var regionW = scaleHoriz(mutationDiagram.regions[i].end - mutationDiagram.regions[i].start, w, l);\n var regionH = 20;\n var regionFillColor = mutationDiagram.regions[i].colour;\n var regionStrokeColor = darken(regionFillColor);\n var regionLabel = mutationDiagram.regions[i].text;\n var regionMetadata = mutationDiagram.regions[i].metadata;\n var regionTitle = regionMetadata.identifier + \" \" +\n regionMetadata.type.toLowerCase() + \", \" +\n regionMetadata.description +\n \" (\" + mutationDiagram.regions[i].start + \" - \" +\n mutationDiagram.regions[i].end + \")\";\n\n // region rectangle\n var regionRect = paper.rect(regionX, regionY, regionW, regionH)\n .attr({\"fill\": regionFillColor, \"stroke-width\": 1, \"stroke\": regionStrokeColor});\n\n addRegionMouseOver(regionRect.node, regionTitle, id);\n\n // region label (only if it fits)\n if (regionLabel != null)\n {\n if ((regionLabel.length * 10) < regionW)\n {\n currentText = paper.text(regionX + (regionW / 2), regionY + regionH - 10, regionLabel)\n .attr({\"text-anchor\": \"center\", \"font-size\": \"12px\", \"font-family\": \"sans-serif\", \"fill\": \"white\"});\n\n addRegionMouseOver(currentText.node, regionTitle, id);\n }\n else\n {\n var truncatedLabel = regionLabel.substring(0,3) + \"..\";\n\n if (truncatedLabel.length * 6 < regionW)\n {\n currentText = paper.text(regionX + (regionW / 2), regionY + regionH - 10, truncatedLabel)\n .attr({\"text-anchor\": \"center\", \"font-size\": \"12px\", \"font-family\": \"sans-serif\", \"fill\": \"white\"});\n\n addRegionMouseOver(currentText.node, regionTitle, id);\n }\n }\n }\n }\n}", "crossover(other) {\n // random midpoint\n var mid = floor(random(1, this.len - 1));\n // seperate halves of both genes\n var half1 = this.genes.substr(0, mid);\n var half2 = other.genes.substr(mid, this.len - 1);\n // creates a new DNA and injects it with both halves\n let n = new DNA(this.mRate, this.len);\n n.inject(half1, half2);\n return n;\n }", "function connect(ctx,a,b,off1,off2) {\n var bu = b.getBounds(\"arrowUpper\");\n var bl = a.getBounds(\"arrowLower\");\n\n // a visual may not define arrow bounds (meaning an arrow shouldn't be drawn)\n // if it returns nothing for the arrow bounds\n if (bu == null || bl == null)\n return;\n\n if (!Array.isArray(bu))\n bu = [bu];\n if (!Array.isArray(bl))\n bl = [bl];\n\n for (var i = 0;i < bu.length;++i) {\n for (var j = 0;j < bl.length;++j) {\n var hx, hy, tx, ty;\n if (Array.isArray(bu[i])) {\n hx = bu[i][0];\n hy = bu[i][1];\n }\n else {\n hx = 0;\n hy = bu[i];\n }\n if (Array.isArray(bl[j])) {\n tx = bl[j][0];\n ty = bl[j][1];\n }\n else {\n tx = 0;\n ty = bl[j];\n }\n\n // perform the same transformations that draw() does but with a different\n // translation for the head and tail (this does not include the padding\n // transformations)\n hx *= ONE_THIRD; tx *= ONE_THIRD;\n hy *= ONE_THIRD; hy += off2;\n ty *= ONE_THIRD; ty += off1;\n\n ctx.drawArrow([tx,ty],[hx,hy]);\n }\n }\n }", "function TranscriptTrack(gsvg, data, trackClass, density) {\n var that = Track(gsvg, data, trackClass, \"Selected Gene Transcripts\");\n\n that.createToolTip = function (d) {\n var tooltip = \"\";\n var strand = \".\";\n if (d.getAttribute(\"strand\") == 1) {\n strand = \"+\";\n } else if (d.getAttribute(\"strand\") == -1) {\n strand = \"-\";\n }\n var id = d.getAttribute(\"ID\");\n tooltip = \"ID: \" + id + \"<BR>Location: chr\" + d.getAttribute(\"chromosome\") + \":\" + numberWithCommas(d.getAttribute(\"start\")) + \"-\" + numberWithCommas(d.getAttribute(\"stop\")) + \"<BR>Strand: \" + strand;\n if (new String(d.getAttribute(\"ID\")).indexOf(\"ENS\") == -1) {\n var annot = getFirstChildByName(getFirstChildByName(d, \"annotationList\"), \"annotation\");\n if (annot != null) {\n tooltip += \"<BR>Matching: \" + annot.getAttribute(\"reason\");\n }\n }\n return tooltip;\n };\n\n that.color = function (d) {\n var color = d3.rgb(\"#000000\");\n if (that.gsvg.txType == \"protein\") {\n if ((new String(d.getAttribute(\"ID\"))).indexOf(\"ENS\") > -1) {\n color = d3.rgb(\"#DFC184\");\n } else {\n color = d3.rgb(\"#7EB5D6\");\n }\n } else if (that.gsvg.txType == \"long\") {\n if ((new String(d.getAttribute(\"ID\"))).indexOf(\"ENS\") > -1) {\n color = d3.rgb(\"#B58AA5\");\n } else {\n color = d3.rgb(\"#CECFCE\");\n }\n } else if (that.gsvg.txType == \"small\") {\n if ((new String(d.getAttribute(\"ID\"))).indexOf(\"ENS\") > -1) {\n color = d3.rgb(\"#FFCC00\");\n } else {\n color = d3.rgb(\"#99CC99\");\n }\n } else if (that.gsvg.txType == \"liverTotal\") {\n color = d3.rgb(\"#bbbedd\");\n } else if (that.gsvg.txType == \"heartTotal\") {\n color = d3.rgb(\"#DC7252\");\n } else if (that.gsvg.txType == \"mergedTotal\") {\n color = d3.rgb(\"#9F4F92\");\n }\n return color;\n };\n\n that.drawTrx = function (d, i) {\n var cdsStart = parseInt(d.getAttribute(\"start\"), 10);\n var cdsStop = parseInt(d.getAttribute(\"stop\"), 10);\n if (typeof d.getAttribute(\"cdsStart\") !== 'undefined' && typeof d.getAttribute(\"cdsStop\") !== 'undefined') {\n cdsStart = parseInt(d.getAttribute(\"cdsStart\"), 10);\n cdsStop = parseInt(d.getAttribute(\"cdsStop\"), 10);\n }\n\n var txG = d3.select(\"#Level\" + that.gsvg.levelNumber + that.trackClass + \" #tx\" + d.getAttribute(\"ID\"));\n exList = getAllChildrenByName(getFirstChildByName(d, \"exonList\"), \"exon\");\n for (var m = 0; m < exList.length; m++) {\n var exStrt = parseInt(exList[m].getAttribute(\"start\"), 10);\n var exStp = parseInt(exList[m].getAttribute(\"stop\"), 10);\n if ((exStrt < cdsStart && cdsStart < exStp) || (exStp > cdsStop && cdsStop > exStrt)) {//need to draw two rect one for CDS and one non CDS\n var xPos1 = 0;\n var xWidth1 = 0;\n var xPos2 = 0;\n var xWidth2 = 0;\n if (exStrt < cdsStart) {\n xPos1 = that.xScale(exList[m].getAttribute(\"start\"));\n xWidth1 = that.xScale(cdsStart) - that.xScale(exList[m].getAttribute(\"start\"));\n xPos2 = that.xScale(cdsStart);\n xWidth2 = that.xScale(exList[m].getAttribute(\"stop\")) - that.xScale(cdsStart);\n } else if (exStp > cdsStop) {\n xPos2 = that.xScale(exList[m].getAttribute(\"start\"));\n xWidth2 = that.xScale(cdsStop) - that.xScale(exList[m].getAttribute(\"start\"));\n xPos1 = that.xScale(cdsStop);\n xWidth1 = that.xScale(exList[m].getAttribute(\"stop\")) - that.xScale(cdsStop);\n }\n txG.append(\"rect\")//non CDS\n .attr(\"x\", xPos1)\n .attr(\"y\", 2.5)\n .attr(\"height\", 5)\n .attr(\"width\", xWidth1)\n .attr(\"title\", function (d) {\n return exList[m].getAttribute(\"ID\");\n })\n .attr(\"id\", function (d) {\n return \"ExNC\" + exList[m].getAttribute(\"ID\");\n })\n .style(\"fill\", that.color)\n .style(\"cursor\", \"pointer\");\n txG.append(\"rect\")//CDS\n .attr(\"x\", xPos2)\n .attr(\"height\", 10)\n .attr(\"width\", xWidth2)\n .attr(\"title\", function (d) {\n return exList[m].getAttribute(\"ID\");\n })\n .attr(\"id\", function (d) {\n return \"Ex\" + exList[m].getAttribute(\"ID\");\n })\n .style(\"fill\", that.color)\n .style(\"cursor\", \"pointer\");\n\n } else {\n var height = 10;\n var y = 0;\n if ((exStrt < cdsStart && exStp < cdsStart) || (exStp > cdsStop && exStrt > cdsStop)) {\n height = 5;\n y = 2.5;\n }\n txG.append(\"rect\")\n .attr(\"x\", function (d) {\n return that.xScale(exList[m].getAttribute(\"start\"));\n })\n .attr(\"y\", y)\n //.attr(\"rx\",1)\n //.attr(\"ry\",1)\n .attr(\"height\", height)\n .attr(\"width\", function (d) {\n return that.xScale(exList[m].getAttribute(\"stop\")) - that.xScale(exList[m].getAttribute(\"start\"));\n })\n .attr(\"title\", function (d) {\n return exList[m].getAttribute(\"ID\");\n })\n .attr(\"id\", function (d) {\n return \"Ex\" + exList[m].getAttribute(\"ID\");\n })\n .style(\"fill\", that.color)\n .style(\"cursor\", \"pointer\");\n }\n /*txG.append(\"rect\")\n\t\t\t.attr(\"x\",function(d){ return that.xScale(exList[m].getAttribute(\"start\")); })\n\t\t\t.attr(\"rx\",1)\n\t\t\t.attr(\"ry\",1)\n\t \t.attr(\"height\",10)\n\t\t\t.attr(\"width\",function(d){ return that.xScale(exList[m].getAttribute(\"stop\")) - that.xScale(exList[m].getAttribute(\"start\")); })\n\t\t\t.attr(\"title\",function(d){ return exList[m].getAttribute(\"ID\");})\n\t\t\t.attr(\"id\",function(d){return \"Ex\"+exList[m].getAttribute(\"ID\");})\n\t\t\t.style(\"fill\",that.color)\n\t\t\t.style(\"cursor\", \"pointer\");*/\n if (m > 0) {\n txG.append(\"line\")\n .attr(\"x1\", function (d) {\n return that.xScale(exList[m - 1].getAttribute(\"stop\"));\n })\n .attr(\"x2\", function (d) {\n return that.xScale(exList[m].getAttribute(\"start\"));\n })\n .attr(\"y1\", 5)\n .attr(\"y2\", 5)\n .attr(\"id\", function (d) {\n return \"Int\" + exList[m - 1].getAttribute(\"ID\") + \"_\" + exList[m].getAttribute(\"ID\");\n })\n .attr(\"stroke\", that.color)\n .attr(\"stroke-width\", \"2\");\n var strChar = \">\";\n if (d.getAttribute(\"strand\") == \"-1\") {\n strChar = \"<\";\n }\n var fullChar = strChar;\n var intStart = that.xScale(exList[m - 1].getAttribute(\"stop\"));\n var intStop = that.xScale(exList[m].getAttribute(\"start\"));\n var rectW = intStop - intStart;\n var alt = 0;\n var charW = 7.0;\n if (rectW < charW) {\n fullChar = \"\";\n } else {\n rectW = rectW - charW;\n while (rectW > (charW + 1)) {\n if (alt == 0) {\n fullChar = fullChar + \" \";\n alt = 1;\n } else {\n fullChar = fullChar + strChar;\n alt = 0;\n }\n rectW = rectW - charW;\n }\n }\n txG.append(\"svg:text\").attr(\"id\", function (d) {\n return \"IntTxt\" + exList[m - 1].getAttribute(\"ID\") + \"_\" + exList[m].getAttribute(\"ID\");\n }).attr(\"dx\", intStart + 1)\n .attr(\"dy\", \"11\")\n .style(\"pointer-events\", \"none\")\n .style(\"opacity\", \"0.5\")\n .style(\"fill\", that.color)\n .style(\"font-size\", \"16px\")\n .text(fullChar);\n\n }\n }\n\n };\n\n that.redraw = function () {\n\n var txG = d3.select(\"#Level\" + that.gsvg.levelNumber + that.trackClass).selectAll(\"g.trx\" + that.gsvg.levelNumber);\n //var txG=that.svg.selectAll(\"g.trx\"+that.gsvg.levelNumber);\n\n txG//.attr(\"transform\",function(d,i){ return \"translate(\"+txXScale(d.getAttribute(\"start\"))+\",\"+i*15+\")\";})\n .each(function (d, i) {\n var cdsStart = parseInt(d.getAttribute(\"start\"), 10);\n var cdsStop = parseInt(d.getAttribute(\"stop\"), 10);\n if (typeof d.getAttribute(\"cdsStart\") !== 'undefined' && typeof d.getAttribute(\"cdsStop\") !== 'undefined') {\n cdsStart = parseInt(d.getAttribute(\"cdsStart\"), 10);\n cdsStop = parseInt(d.getAttribute(\"cdsStop\"), 10);\n }\n exList = getAllChildrenByName(getFirstChildByName(d, \"exonList\"), \"exon\");\n var pref = \"tx\";\n for (var m = 0; m < exList.length; m++) {\n var exStrt = parseInt(exList[m].getAttribute(\"start\"), 10);\n var exStp = parseInt(exList[m].getAttribute(\"stop\"), 10);\n if ((exStrt < cdsStart && cdsStart < exStp) || (exStp > cdsStop && cdsStop > exStrt)) {\n var ncStrt = exStrt;\n var ncStp = cdsStart;\n if (exStp > cdsStop) {\n ncStrt = cdsStop;\n ncStp = exStp;\n exStrt = exStrt;\n exStp = cdsStop;\n } else {\n exStrt = cdsStart;\n exStp = exStp;\n }\n d3.select(\"#Level\" + that.gsvg.levelNumber + that.trackClass + \" g#\" + pref + d.getAttribute(\"ID\") + \" rect#ExNC\" + exList[m].getAttribute(\"ID\"))\n .attr(\"x\", function (d) {\n return that.xScale(ncStrt);\n })\n .attr(\"width\", function (d) {\n return that.xScale(ncStp) - that.xScale(ncStrt);\n });\n }\n d3.select(\"#Level\" + that.gsvg.levelNumber + that.trackClass + \" g#\" + pref + d.getAttribute(\"ID\") + \" rect#Ex\" + exList[m].getAttribute(\"ID\"))\n .attr(\"x\", function (d) {\n return that.xScale(exStrt);\n })\n .attr(\"width\", function (d) {\n return that.xScale(exStp) - that.xScale(exStrt);\n });\n if (m > 0) {\n var strChar = \">\";\n if (d.getAttribute(\"strand\") == \"-1\") {\n strChar = \"<\";\n }\n var fullChar = strChar;\n var intStart = that.xScale(exList[m - 1].getAttribute(\"stop\"));\n var intStop = that.xScale(exList[m].getAttribute(\"start\"));\n var rectW = intStop - intStart;\n var alt = 0;\n var charW = 7.0;\n if (rectW < charW) {\n fullChar = \"\";\n } else {\n rectW = rectW - charW;\n while (rectW > (charW + 1)) {\n if (alt == 0) {\n fullChar = fullChar + \" \";\n alt = 1;\n } else {\n fullChar = fullChar + strChar;\n alt = 0;\n }\n rectW = rectW - charW;\n }\n }\n d3.select(\"#Level\" + that.gsvg.levelNumber + that.trackClass + \" g#tx\" + d.getAttribute(\"ID\") + \" line#Int\" + exList[m - 1].getAttribute(\"ID\") + \"_\" + exList[m].getAttribute(\"ID\"))\n .attr(\"x1\", intStart)\n .attr(\"x2\", intStop);\n\n d3.select(\"#Level\" + that.gsvg.levelNumber + that.trackClass + \" g#tx\" + d.getAttribute(\"ID\") + \" #IntTxt\" + exList[m - 1].getAttribute(\"ID\") + \"_\" + exList[m].getAttribute(\"ID\"))\n .attr(\"dx\", intStart + 1).text(fullChar);\n }\n }\n });\n that.redrawSelectedArea();\n };\n\n that.update = function () {\n var txList = getAllChildrenByName(getFirstChildByName(that.gsvg.selectedData, \"TranscriptList\"), \"Transcript\");\n var min = parseInt(that.gsvg.selectedData.getAttribute(\"start\"), 10);\n var max = parseInt(that.gsvg.selectedData.getAttribute(\"stop\"), 10);\n if (typeof that.gsvg.selectedData.getAttribute(\"extStart\") !== 'undefined' && typeof that.gsvg.selectedData.getAttribute(\"extStop\") !== 'undefined') {\n min = parseInt(that.gsvg.selectedData.getAttribute(\"extStart\"), 10);\n max = parseInt(that.gsvg.selectedData.getAttribute(\"extStop\"), 10);\n }\n that.txMin = min;\n that.txMax = max;\n that.svg.attr(\"height\", (1 + txList.length) * 15);\n d3.select(\"#Level\" + that.gsvg.levelNumber + that.trackClass).selectAll(\".trx\" + that.gsvg.levelNumber).remove();\n var tx = d3.select(\"#Level\" + that.gsvg.levelNumber + that.trackClass).selectAll(\".trx\" + that.gsvg.levelNumber)\n .data(txList, key)\n .attr(\"transform\", function (d, i) {\n return \"translate(\" + that.xScale(d.getAttribute(\"start\")) + \",\" + that.calcY(d, i) + \")\";\n });\n\n tx.enter().append(\"g\")\n .attr(\"class\", \"trx\" + that.gsvg.levelNumber)\n //.attr(\"transform\",function(d,i){ return \"translate(\"+txXScale(d.getAttribute(\"start\"))+\",\"+i*15+\")\";})\n .attr(\"transform\", function (d, i) {\n return \"translate(0,\" + that.calcY(d, i) + \")\";\n })\n .attr(\"id\", function (d) {\n return d.getAttribute(\"ID\");\n })\n //.attr(\"pointer-events\", \"all\")\n .style(\"cursor\", \"pointer\")\n .on(\"mouseover\", function (d) {\n if (that.gsvg.isToolTip == 0) {\n d3.select(this).selectAll(\"line\").style(\"stroke\", \"green\");\n d3.select(this).selectAll(\"rect\").style(\"fill\", \"green\");\n d3.select(this).selectAll(\"text\").style(\"opacity\", \"0.3\").style(\"fill\", \"green\");\n tt.transition()\n .duration(200)\n .style(\"opacity\", 1);\n tt.html(that.createToolTip(d))\n .style(\"left\", function () {\n return that.positionTTLeft(d3.event.pageX);\n })\n .style(\"top\", function () {\n return that.positionTTTop(d3.event.pageY);\n });\n }\n })\n .on(\"mouseout\", function (d) {\n d3.select(this).selectAll(\"line\").style(\"stroke\", that.color);\n d3.select(this).selectAll(\"rect\").style(\"fill\", that.color);\n d3.select(this).selectAll(\"text\").style(\"opacity\", \"0.6\").style(\"fill\", that.color);\n tt.transition()\n .delay(500)\n .duration(200)\n .style(\"opacity\", 0);\n })\n .each(that.drawTrx);\n\n\n tx.exit().remove();\n that.svg.selectAll(\".legend\").remove();\n var legend = [];\n if (that.gsvg.txType == \"protein\") {\n legend = [{color: \"#DFC184\", label: \"Ensembl\"}, {color: \"#7EB5D6\", label: \"RNA-Seq\"}];\n } else if (that.gsvg.txType == \"long\") {\n legend = [{color: \"#B58AA5\", label: \"Ensembl\"}, {color: \"#CECFCE\", label: \"RNA-Seq\"}];\n } else if (that.gsvg.txType == \"small\") {\n legend = [{color: \"#FFCC00\", label: \"Ensembl\"}, {color: \"#99CC99\", label: \"RNA-Seq\"}];\n } else if (that.gsvg.txType == \"liverTotal\") {\n legend = [{color: \"#bbbedd\", label: \"Liver RNA-Seq\"}];\n } else if (that.gsvg.txType == \"mergedTotal\") {\n legend = [{color: \"#9F4F92\", label: \"Merged RNA-Seq\"}];\n }\n\n that.drawLegend(legend);\n };\n\n that.calcY = function (d, i) {\n return (i + 1) * 15;\n }\n\n that.redrawLegend = function () {\n };\n if (typeof that.gsvg.selectedData.getAttribute(\"extStart\") !== 'undefined') {\n that.txMin = parseInt(that.gsvg.selectedData.getAttribute(\"extStart\"), 10);\n that.txMax = parseInt(that.gsvg.selectedData.getAttribute(\"extStop\"), 10);\n } else {\n that.txMin = parseInt(that.gsvg.selectedData.getAttribute(\"start\"), 10);\n that.txMax = parseInt(that.gsvg.selectedData.getAttribute(\"stop\"), 10);\n }\n d3.select(\"#Level\" + that.gsvg.levelNumber + that.trackClass).attr(\"height\", (1 + data.length) * 15);\n d3.select(\"#Level\" + that.gsvg.levelNumber + that.trackClass).selectAll(\".trx\" + that.gsvg.levelNumber).remove();\n var tx = d3.select(\"#Level\" + that.gsvg.levelNumber + that.trackClass).selectAll(\".trx\" + that.gsvg.levelNumber)\n .data(data, key)\n .attr(\"transform\", function (d, i) {\n return \"translate(\" + that.xScale(d.getAttribute(\"start\")) + \",\" + that.calcY(d, i) + \")\";\n });\n\n tx.enter().append(\"g\")\n .attr(\"class\", \"trx\" + that.gsvg.levelNumber)\n //.attr(\"transform\",function(d,i){ return \"translate(\"+txXScale(d.getAttribute(\"start\"))+\",\"+i*15+\")\";})\n .attr(\"transform\", function (d, i) {\n return \"translate(0,\" + that.calcY(d, i) + \")\";\n })\n .attr(\"id\", function (d) {\n return \"tx\" + d.getAttribute(\"ID\");\n })\n //.attr(\"pointer-events\", \"all\")\n .style(\"cursor\", \"pointer\")\n .on(\"mouseover\", function (d) {\n if (that.gsvg.isToolTip == 0) {\n d3.select(this).selectAll(\"line\").style(\"stroke\", \"green\");\n d3.select(this).selectAll(\"rect\").style(\"fill\", \"green\");\n d3.select(this).selectAll(\"text\").style(\"opacity\", \"0.3\").style(\"fill\", \"green\");\n tt.transition()\n .duration(200)\n .style(\"opacity\", 1);\n tt.html(that.createToolTip(d))\n .style(\"left\", function () {\n return that.positionTTLeft(d3.event.pageX);\n })\n .style(\"top\", function () {\n return that.positionTTTop(d3.event.pageY);\n });\n }\n })\n .on(\"mouseout\", function (d) {\n d3.select(this).selectAll(\"line\").style(\"stroke\", that.color);\n d3.select(this).selectAll(\"rect\").style(\"fill\", that.color);\n d3.select(this).selectAll(\"text\").style(\"opacity\", \"0.6\").style(\"fill\", that.color);\n tt.transition()\n .delay(500)\n .duration(200)\n .style(\"opacity\", 0);\n })\n .each(that.drawTrx);\n\n\n tx.exit().remove();\n that.redrawLegend();\n that.scaleSVG.transition()\n .duration(300)\n .style(\"opacity\", 1);\n that.svg.transition()\n .duration(300)\n .style(\"opacity\", 1);\n that.redraw();\n return that;\n}", "newStrand(p0, p1, over=true, marker=undefined, p0_over=true, p1_over=true){ //third arg is if this strand should go over existing ones by default\n\t\tlet new_strand = new Strand(p0,p1,p0_over,p1_over, marker);\n\t\t\n\t\t//intersection checking\n\t\tfor(let s=0; s<this.strands.length; s++){\n\t\t\tlet other_strand = this.strands[s];\n\t\t\t\n\t\t\t//if the strand is connected to either of the new strand's points, don't check for intersection - there won't be a meaningful one\n\t\t\tif(p0.strands.indexOf(other_strand) !== -1 || p1.strands.indexOf(other_strand) !== -1){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tlet intersection = intersect(new_strand, other_strand);\n\t\t\tif(intersection){\n\t\t\t\t\n\t\t\t\t//remove the other strand so it can be replaced\n\t\t\t\tthis.removeStrand(other_strand);\n\t\t\t\t//disconnect the new strand we just made. Don't need to fully remove it b/c wasn't yet pushed to this.strands\n\t\t\t\tnew_strand.disconnect();\n\t\t\t\t\n\t\t\t\t//add the intersection point to points\n\t\t\t\tthis.points.push(intersection);\n\t\t\t\t\n\t\t\t\t//split this strand and the other strand in two\t\t\t\t\n\t\t\t\t//this strand\n\t\t\t\tthis.newStrand(p0, intersection, over, marker, p0_over, over); //preserve over/under at non-intersection points, set it at intersection points based on \"over\" arg\n\t\t\t\tthis.newStrand(intersection, p1, over, marker, over, p1_over);\n\t\t\t\t//other strand\n\t\t\t\tthis.newStrand(other_strand.p0, intersection, true, other_strand.marker, other_strand.p0_over, !over); //args follow same logic as for new strand, except we assume over is true (shouldn't matter really since no cascading intersections for this one)\n\t\t\t\tthis.newStrand(intersection, other_strand.p1, true, other_strand.marker, !over, other_strand.p1_over);\n\t\t\t\t\n\t\t\t\treturn; //other intersections will be taken care of by the recursive calls for new strands\n\t\t\t}\n\t\t}\n\t\t\n\t\t//if no intersections, push this strand\n\t\tthis.strands.push(new_strand);\n\t\tnew_strand.state = this;\n\t}", "getCurve( startX, startY, endX, endY ) {\n let middleX = startX + (endX - startX) / 2;\n return `M ${startX} ${startY} C ${middleX},${startY} ${middleX},${endY} ${endX},${endY}`;\n }", "function createRangeDescription() {\n if((!dual || single) && incrementTop === 1) {\n return `(range: ${topStart} to ${topEnd})`;\n } else if((!dual || single) && incrementTop !== 1) {\n return `(range: ${topStart} to ${topEnd}(step ${incrementTop}))`;\n } else if((topStart === bottomStart && topEnd === bottomEnd)) {\n return `(range: ${topStart} to ${topEnd}(top step ${incrementTop}, bottom step ${incrementBottom}))`;\n } else if(incrementTop === incrementBottom && (incrementTop !== 1 || incrementBottom !== 1)) {\n return `(ranges: ${topStart} to ${topEnd}(top) ${bottomStart} to ${bottomEnd}(bottom) (step ${incrementTop}))`;\n } else if(incrementTop === incrementBottom){\n return `(ranges: ${topStart} to ${topEnd}(top) ${bottomStart} to ${bottomEnd}(bottom))`;\n } else {\n return `(ranges: ${topStart} to ${topEnd}(top) (step ${incrementTop}) ${bottomStart} to ${bottomEnd}(bottom) (step ${incrementBottom}))`;\n }\n }", "arrowhead(x0, y0, x1, y1) {\n const dx = x0 - x1;\n const dy = y0 - y1;\n\n let alpha = Math.atan(dy / dx);\n if (dy === 0) {\n alpha = dx < 0 ? -Math.PI : 0;\n }\n\n const alpha3 = alpha + 0.5;\n const alpha4 = alpha - 0.5;\n\n const l3 = 20;\n const x3 = x1 + l3 * Math.cos(alpha3);\n const y3 = y1 + l3 * Math.sin(alpha3);\n\n this.ctx.beginPath();\n this.moveTo(x3, y3);\n this.lineTo(x1, y1);\n this.ctx.stroke();\n\n const l4 = 20;\n const x4 = x1 + l4 * Math.cos(alpha4);\n const y4 = y1 + l4 * Math.sin(alpha4);\n\n this.ctx.beginPath();\n this.moveTo(x4, y4);\n this.lineTo(x1, y1);\n this.stroke();\n }", "function draw_arrow(begin, end, alpha){\n //begin = createVector(begin[0], begin[1]);\n //end = createVector(end[0], end[1]);\n if (alpha < 0) {\n stroke(255, 0, 0, -alpha);\n fill(255, 0, 0, -alpha);\n } else {\n stroke(0, 0, 255, alpha);\n fill(0, 0, 255, alpha);\n }\n line(begin.x, begin.y, end.x, end.y);\n let v = p5.Vector.sub(end, begin);\n v.mult(3 / v.mag());\n let a1 = p5.Vector.add(end, v);\n v.rotate(2 * PI / 3);\n let a2 = p5.Vector.add(end, v);\n v.rotate(2 * PI / 3);\n let a3 = p5.Vector.add(end, v);\n triangle(a1.x, a1.y, a2.x, a2.y, a3.x, a3.y);\n}", "function quad(x1, y1, x2, y2, x3, y3, x4, y4)\n{\n $context.beginPath();\n $context.moveTo(x1,y1);\n $context.lineTo(x2,y2);\n $context.lineTo(x3,y3);\n $context.lineTo(x4,y4);\n $context.closePath();\n draw_fill();\n draw_stroke();\n}", "static get_outers_and_intersect_latLngs(way1, way2) {\n function latLng_eq(p1, p2) {\n return (p1[0] == p2[0]) && (p1[1] == p2[1])\n }\n\n function is_closed(way) {\n return latLng_eq(way[0], way[way.length - 1]);\n }\n\n if (!(is_closed(way1) && is_closed(way2))) {\n throw new GeometryError(\"not closed polygons\");\n }\n way1 = way1.slice(1);\n way2 = way2.slice(1);\n if (way1.length < way2.length) {\n let w = way1;\n way1 = way2;\n way2 = w;\n }\n const length1 = way1.length;\n const length2 = way2.length\n\n // rotate way1 so that it starts with a point not common with way2:\n let i1 = way1.findIndex(p1 => way2.findIndex(p2 => latLng_eq(p1, p2)) < 0);\n if (i1 == -1) {\n throw new GeometryError(\"no distincts points\");\n }\n way1 = way1.slice(i1, length1).concat(way1.slice(0, i1));\n\n // get the intersection points (the points common to the two ways)\n const intersect = way1.filter(p1 => way2.findIndex(p2 => latLng_eq(p1, p2)) >= 0);\n\n // rotate way1 so that it starts with the first intersecting point:\n i1 = way1.findIndex(p1 => latLng_eq(p1, intersect[0]));\n if (i1 == -1) {\n throw new GeometryError(\"no common points\");\n }\n way1 = way1.slice(i1, length1).concat(way1.slice(0, i1));\n\n // get the outer part of way1\n const outer1 = way1.filter(p1 => intersect.findIndex(p2 => latLng_eq(p1, p2)) < 0);\n\n\n // rotate and reverse way2 so that it starts with the first intersecting point:\n let i2 = way2.findIndex(p2 => latLng_eq(intersect[0], p2));\n if (latLng_eq(way2[(i2 + 1) % length2], intersect[1])) {\n way2.reverse();\n i2 = length2 - 1 - i2;\n }\n way2 = way2.slice(i2, length2).concat(way2.slice(0, i2));\n\n // get the outer part of way2\n const outer2 = way2.filter(p2 => intersect.findIndex(p1 => latLng_eq(p1, p2)) < 0)\n\n // join outer1 and outer2 \n //const joined = [intersect[intersect.length-1]].concat(outer1).concat([intersect[0]]).concat(outer2).concat([intersect[intersect.length-1]]);\n\n const full_outer1 = intersect.slice(-1).concat(outer1).concat(intersect.slice(0, 1));\n const full_outer2 = intersect.slice(0, 1).concat(outer2).concat(intersect.slice(-1));\n\n return [full_outer1, full_outer2, intersect];\n }", "drawNote() {\n push();\n colorMode(HSB, 360, 100, 100);\n stroke(this.color, 100, 100, 100);\n fill(this.color, 100, 100, 100);\n let v = this;\n let v2 = createVector(v.x + 5, v.y - 15);\n circle(v.x, v.y, 7);\n strokeWeight(3);\n line(v.x + 3, v.y, v2.x, v2.y);\n quad(v2.x, v2.y, v2.x + 5, v2.y + 2, v2.x + 6, v2.y, v2.x, v2.y - 2);\n pop();\n }", "initDrawChromosomes(bandsArray) {\n var ideo = this,\n taxids = ideo.config.taxids,\n ploidy = ideo.config.ploidy,\n taxid,\n chrIndex = 0,\n chrSetNumber = 0,\n bands,\n i, j, chrs, chromosome, chrModel,\n defs, transform;\n\n defs = d3.select(ideo.selector + ' defs');\n\n for (i = 0; i < taxids.length; i++) {\n taxid = taxids[i];\n chrs = ideo.config.chromosomes[taxid];\n\n ideo.chromosomes[taxid] = {};\n\n ideo.setSexChromosomes(chrs);\n\n for (j = 0; j < chrs.length; j++) {\n chromosome = chrs[j];\n bands = bandsArray[chrIndex];\n chrIndex += 1;\n\n chrModel = ideo.getChromosomeModel(bands, chromosome, taxid, chrIndex);\n\n ideo.chromosomes[taxid][chromosome] = chrModel;\n ideo.chromosomesArray.push(chrModel);\n\n if (\n 'sex' in ideo.config &&\n (\n ploidy === 2 && ideo.sexChromosomes.index + 2 === chrIndex ||\n ideo.config.sex === 'female' && chrModel.name === 'Y'\n )\n ) {\n continue;\n }\n\n transform = ideo._layout.getChromosomeSetTranslate(chrSetNumber);\n chrSetNumber += 1;\n\n // Append chromosome set container\n var container = d3.select(ideo.selector)\n .append('g')\n .attr('class', 'chromosome-set-container')\n .attr('data-set-number', j)\n .attr('transform', transform)\n .attr('id', chrModel.id + '-chromosome-set');\n\n if (\n 'sex' in ideo.config &&\n ploidy === 2 &&\n ideo.sexChromosomes.index + 1 === chrIndex\n ) {\n ideo.drawSexChromosomes(bandsArray, taxid, container, defs, j, chrs);\n continue;\n }\n\n var shape;\n var numChrsInSet = 1;\n if (ploidy > 1) {\n numChrsInSet = this._ploidy.getChromosomesNumber(j);\n }\n for (var k = 0; k < numChrsInSet; k++) {\n shape = ideo.drawChromosome(chrModel, chrIndex - 1, container, k);\n }\n\n defs.append('clipPath')\n .attr('id', chrModel.id + '-chromosome-set-clippath')\n .selectAll('path')\n .data(shape)\n .enter()\n .append('path')\n .attr('d', function(d) {\n return d.path;\n }).attr('class', function(d) {\n return d.class;\n });\n }\n\n if (ideo.config.showBandLabels === true) {\n ideo.drawBandLabels(ideo.chromosomes);\n }\n }\n }", "function drawArc(texte, e1, e2, a, k, num_arc, coordonnees, first, p) {\n\n var x = 140 + (a - 1) * 180,\n y = 55 + (4 - e1) * 50 - (e2 - e1) * 25,\n h = 2 + (e2 - e1) * 50,\n 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 } else {\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\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 } 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\n document.getElementById(\"sketch-auto\").appendChild(arc_div);\n arc_div.onmousedown = function(evt) {\n traine = true;\n xi = num_arc;\n xj = 0;\n yi = num_arc;\n yj = 1;\n }\n\n }\n\n if (selectedGenes[a-1]){\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 p.line(x, y - h / 2, x + 8, y - h / 2 - 8);\n p.line(x, y - h / 2, x + 8, y - h / 2 + 8);\n p.noFill();\n p.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 = p.bezierPoint(x1, coordonnees[num_arc][0], coordonnees[num_arc][0], x4, 1 / 2);\n yy = p.bezierPoint(y1, coordonnees[num_arc][1] + (e1 - e2 - 1) * 25 + 20, coordonnees[num_arc][1] - (e1 - e2 - 1) * 25 - 20, y4, 1 / 2);\n p.fill(0, 0, 255);\n p.textSize(15);\n p.text(texte, xx, yy + 10);\n p.textSize(10);\n } else {\n x1 = x4 = x - 18;\n y1 = y + 24 + (e2 - e1 - 1) * 25;\n y4 = y - 26 - (e2 - e1 - 1) * 25;\n p.line(x - 26, y - h / 2 - 9, x - 19, y - h / 2 - 1);\n p.line(x - 26, y - h / 2 + 7, x - 19, y - h / 2 - 1);\n p.noFill();\n p.bezier(x1, y1, coordonnees[num_arc][0] - 18, coordonnees[num_arc][1] + (e2 - e1 - 1) * 25 + 20, coordonnees[num_arc][0] - 18, coordonnees[num_arc][1] - (e2 - e1 - 1) * 25 - 20, x4, y4);\n xx = p.bezierPoint(x1, coordonnees[num_arc][0] - 18, coordonnees[num_arc][0] - 18, x4, 1 / 2);\n yy = p.bezierPoint(y1, coordonnees[num_arc][1] + (e2 - e1 - 1) * 25 + 20, coordonnees[num_arc][1] - (e2 - e1 - 1) * 25 - 20, y4, 1 / 2);\n p.fill(0, 0, 255);\n p.textSize(15);\n p.text(texte, xx, yy - 10);\n p.textSize(10);\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 p.line(x, y - h / 2, x + 7, y - h / 2 - 8);\n p.line(x, y - h / 2, x + 7, y - h / 2 + 8);\n p.noFill();\n p.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 = p.bezierPoint(x1, coordonnees[num_arc][0], coordonnees[num_arc][0], x4, 1 / 2);\n yy = p.bezierPoint(y1, coordonnees[num_arc][1] + (e2 - e1 - 1) * 25 + 20, coordonnees[num_arc][1] - (e2 - e1 - 1) * 25 - 20, y4, 1 / 2);\n p.fill(0, 0, 255);\n p.textSize(15);\n p.text(texte, xx + 10, yy);\n p.textSize(10);\n\n\n } else {\n x1 = x4 = x - 18;\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 p.line(x - 26, y - h / 2 - 9, x - 19, y - h / 2 - 1);\n p.line(x - 26, y - h / 2 + 7, x - 19, y - h / 2 - 1);\n p.noFill();\n p.bezier(x1, y1, coordonnees[num_arc][0] - 18, coordonnees[num_arc][1] + (e1 - e2 - 1) * 25 + 20, coordonnees[num_arc][0] - 18, coordonnees[num_arc][1] - (e1 - e2 - 1) * 25 - 20, x4, y4);\n xx = p.bezierPoint(x1, coordonnees[num_arc][0] - 18, coordonnees[num_arc][0] - 18, x4, 1 / 2);\n yy = p.bezierPoint(y1, coordonnees[num_arc][1] + (e1 - e2 - 1) * 25 + 20, coordonnees[num_arc][1] - (e1 - e2 - 1) * 25 - 20, y4, 1 / 2);\n p.fill(0, 0, 255);\n p.textSize(15);\n p.text(texte, xx - 10, yy);\n p.textSize(10);\n\n }\n }\n var margeY = document.getElementById(\"sketch-auto\").offsetTop;\n var margeX = document.getElementById(\"sketch-auto\").offsetLeft;\n divs[num_arc].style.top = margeY + yy - 7.5 + \"px\" ;\n divs[num_arc].style.left = margeX + xx - 7.5 + \"px\";\n p.fill(255);\n p.ellipse(xx, yy, 5, 5);\n\n function move(evt) {\n if (traine) {\n p.clear();\n coordonnees[xi][xj] = p.mouseX + 15;\n coordonnees[yi][yj] = p.mouseY;\n }\n }\n\n function stopTraine() {\n traine = false;\n }\n\n\n document.getElementById(\"sketch-auto\").onmousemove = move;\n document.getElementById(\"sketch-auto\").onmouseup = stopTraine;\n\n }\n\n}", "function drawArrow(x1, y1, x2, y2) {\n\tvar scale = 3*Math.sqrt(c.lineWidth);\n\n\tvar deltaX = x2-x1;\n\tvar deltaY = y2-y1;\n\tvar oldLen = Math.sqrt(deltaX*deltaX+deltaY*deltaY);\n\tvar angle = 0.523598776;\n\tdeltaX *= scale/oldLen*3;\n\tdeltaY *= scale/oldLen*3;\n\n\t// draw head\n\tc.beginPath();\n\tc.moveTo(x2,y2);\n\tc.lineTo(x2-Math.sin(angle)*deltaY-Math.cos(angle)*deltaX,y2+\n\t\tMath.sin(angle)*deltaX-Math.cos(angle)*deltaY);\n\tc.lineTo(x2+Math.sin(angle)*deltaY-Math.cos(angle)*deltaX,y2-\n\t\tMath.sin(angle)*deltaX-Math.cos(angle)*deltaY);\n\tc.fill();\n\n\t// draw line\n\tc.beginPath();\n\tc.moveTo(x1,y1);\n\tc.lineTo(x2 - Math.cos(angle)*deltaX,y2 - Math.cos(angle)*deltaY);\n\tc.stroke();\n}", "function drawCornerCurve (xFrom, yFrom, xTo, yTo, bendDown, attr, doubleCurve, shiftx1, shifty1, shiftx2, shifty2 ) {\n var xDistance = xTo - xFrom;\n var yDistance = yFrom - yTo;\n\n var dist1x = xDistance/2;\n var dist2x = xDistance/10;\n var dist1y = yDistance/2;\n var dist2y = yDistance/10;\n\n var curve;\n\n if (bendDown) {\n var raphaelPath = 'M ' + (xFrom) + ' ' + (yFrom) +\n ' C ' + (xFrom + dist1x) + ' ' + (yFrom + dist2y) +\n ' ' + (xTo + dist2x) + ' ' + (yTo + dist1y) +\n ' ' + (xTo) + ' ' + (yTo);\n curve = editor.getPaper().path(raphaelPath).attr(attr).toBack();\n } else {\n var raphaelPath = 'M ' + (xFrom) + ' ' + (yFrom) +\n ' C ' + (xFrom - dist2x) + ' ' + (yFrom - dist1y) +\n ' ' + (xTo - dist1x) + ' ' + (yTo - dist2y) +\n ' ' + (xTo) + ' ' + (yTo);\n curve = editor.getPaper().path(raphaelPath).attr(attr).toBack();\n }\n\n if (doubleCurve) {\n var curve2 = curve.clone().toBack();\n curve .transform('t ' + shiftx1 + ',' + shifty1 + '...');\n curve2.transform('t ' + shiftx2 + ',' + shifty2 + '...');\n }\n}", "function createPitch() {\n ctx.beginPath();\n ctx.moveTo(boardWidth/2,0);\n ctx.lineTo(boardWidth/2,boardHeight);\n ctx.closePath();\n ctx.lineWidth = 8;\n ctx.strokeStyle = \"white\";\n ctx.stroke();\n\n ctx.beginPath();\n ctx.arc(boardWidth/2,boardHeight/2,2*step,0,Math.PI*2,true);\n ctx.stroke();\n \n function goalArea(x0,x1){\n ctx.beginPath();\n ctx.moveTo(x0,boardHeight/2-2*step);\n ctx.lineTo(x1,boardHeight/2-2*step);\n ctx.lineTo(x1,boardHeight/2+2*step);\n ctx.lineTo(x0,boardHeight/2+2*step);\n ctx.stroke();\n }\n\n goalArea(0,2*step)\n goalArea(boardWidth,boardWidth-2*step)\n\n function goalLine(x0,color){\n ctx.beginPath();\n ctx.moveTo(x0,boardHeight/2);\n ctx.lineTo(x0,boardHeight/2-step);\n ctx.lineTo(x0,boardHeight/2+step);\n ctx.strokeStyle = color;\n ctx.stroke();\n }\n\n goalLine(0,\"green\");\n goalLine(boardWidth,\"red\");\n\n function corners(x0,y0,direction){\n ctx.beginPath();\n ctx.arc(x0,y0,step/2,0,Math.PI*0.5,direction);\n ctx.strokeStyle = \"white\";\n ctx.stroke();\n }\n \n corners(0,0,false)\n corners(boardWidth,0,true)\n corners(0,boardHeight,true)\n corners(boardWidth,boardHeight,true)\n\n function semicircle(x0,direction){\n ctx.beginPath();\n ctx.arc(x0,boardHeight/2,step,Math.PI*0.5,Math.PI*1.5,direction);\n ctx.stroke();\n }\n \n semicircle(2*step,true)\n semicircle(boardWidth-2*step,false)\n }", "drawChromosomeLabels() {\n var ideo = this;\n\n var chromosomeLabelClass = ideo._layout.getChromosomeLabelClass();\n\n var chrSetLabelXPosition = ideo._layout.getChromosomeSetLabelXPosition();\n var chrSetLabelTranslate = ideo._layout.getChromosomeSetLabelTranslate();\n\n // Append chromosomes set's labels\n d3.selectAll(ideo.selector + ' .chromosome-set-container')\n .append('text')\n .data(ideo.chromosomesArray)\n .attr('class', 'chromosome-set-label ' + chromosomeLabelClass)\n .attr('transform', chrSetLabelTranslate)\n .attr('x', chrSetLabelXPosition)\n .attr('y', function(d, i) {\n return ideo._layout.getChromosomeSetLabelYPosition(i);\n })\n .attr('text-anchor', ideo._layout.getChromosomeSetLabelAnchor())\n .each(function(d, i) {\n // Get label lines\n var lines;\n if (d.name.indexOf(' ') === -1) {\n lines = [d.name];\n } else {\n lines = d.name.match(/^(.*)\\s+([^\\s]+)$/).slice(1).reverse();\n }\n\n if (\n 'sex' in ideo.config &&\n ideo.config.ploidy === 2 &&\n i === ideo.sexChromosomes.index\n ) {\n if (ideo.config.sex === 'male') {\n lines = ['XY'];\n } else {\n lines = ['XX'];\n }\n }\n\n // Render label lines\n d3.select(this).selectAll('tspan')\n .data(lines)\n .enter()\n .append('tspan')\n .attr('dy', function(d, i) {\n return i * -1.2 + 'em';\n })\n .attr('x', ideo._layout.getChromosomeSetLabelXPosition())\n .attr('class', function(a, i) {\n var fullLabels = ideo.config.fullChromosomeLabels;\n return i === 1 && fullLabels ? 'italic' : null;\n }).text(String);\n });\n\n var setLabelTranslate = ideo._layout.getChromosomeSetLabelTranslate();\n\n // Append chromosomes labels\n d3.selectAll(ideo.selector + ' .chromosome-set-container')\n .each(function(a, chrSetNumber) {\n d3.select(this).selectAll('.chromosome')\n .append('text')\n .attr('class', 'chrLabel')\n .attr('transform', setLabelTranslate)\n .attr('x', function(d, i) {\n return ideo._layout.getChromosomeLabelXPosition(i);\n }).attr('y', function(d, i) {\n return ideo._layout.getChromosomeLabelYPosition(i);\n }).text(function(d, chrNumber) {\n return ideo._ploidy.getAncestor(chrSetNumber, chrNumber);\n }).attr('text-anchor', 'middle');\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Refresh this Model instance's internal data by refetching from the database
async refresh() { // Ensure model is registered before fetching model data assert.instanceOf(this.constructor.__db, DbApi, 'Model must be registered.'); // Ensure this Model instance is stored in database assert.isNotNull(this.__id, 'Model must be stored in database to refresh.'); // Replace this Model instance's internal data with fetched data from the database this.__data = await this.constructor.__db.findDataById(this.constructor, this.__id); // Reset internally stored updates this.__updates = new Set(); }
[ "_update() {\n if (this.hydrateOnUpdate()) {\n return super._update().then((model) => {\n Object.assign(this, model);\n return this;\n });\n }\n\n return super._update();\n }", "function redata(params, onUpdate) {\n // console.log('redata()', params);\n // If should not reload the data.\n if (!shouldReload(params)) {\n console.log('will not reload');\n // Inform any subscriber.\n onUpdate && onUpdate(ctx.lastData);\n\n // Resolve with last data.\n return Promise.resolve(ctx.lastData);\n }\n console.log('will reload');\n // Data not valid, will load new data and subscribe to its updates.\n // Reset lastData, since it is no longer valid.\n ctx.lastData = _extends({}, defaultInitialData);\n // debugger;\n // Update any subscriber about new data.\n onUpdate && onUpdate(ctx.lastData);\n\n // Store promise reference in order to check which is the last one if multiple resolve.\n ctx.promise = load(ctx, loader, params, onUpdate);\n // console.log('storing ctx promise', ctx.promise);\n ctx.promise.loader = loader;\n return ctx.promise;\n }", "function updateAndRebuildFeed()\n {\n $loading.show();\n FeedAPI.get().done((results) => {\n cache = results;\n\n buildFeed(currentFeed);\n $loading.delay(200).hide(0);\n }).fail(() => {\n options();\n });\n }", "refreshDateFromNow() {\n this.update({ dateFromNow: this._computeDateFromNow() });\n }", "@api \n async refresh() { \n \n this.isLoading = true;\n this.notifyLoading(true); \n refreshApex(this.boats);\n this.isLoading = false;\n this.notifyLoading(false); \n \n }", "async refresh() {\n this.locations = await this.getLocations();\n this.weatherModels = [];\n\n if (this.locations.length > 0) {\n document.getElementById('no-locations').style.display = 'none';\n }\n\n _util.default.displayLoading(true);\n\n if (this.locations.length) {\n _util.default.clearDivContents('weather');\n\n for (let i = 0; i < this.locations.length; i++) {\n if (this.locations[i]) {\n let model = new WeatherModel(this.locations[i].lat, this.locations[i].lng, i, this.locations[i].full_name);\n await model.init();\n new WeatherView(model).render();\n this.weatherModels.push(model);\n }\n }\n\n this.updateLastUpdated();\n }\n\n _util.default.displayLoading(false);\n }", "_refresh(){\n this._refreshSize();\n this._refreshPosition();\n }", "function refreshProductList() {\n loadProducts()\n .then(function (results) {\n vm.products = results;\n });\n }", "function refresh() {\n $scope.award = {};\n $scope.awardLocation = {};\n\n getAwardList(personReferenceKey);\n\n\n\n\n }", "_checkIfDirty(){\n if (this._isDirty === true){\n this._isDirty = false;\n this._refresh();\n }\n }", "reload() {\n new TotoMLRegistryAPI().getModel(this.state.modelName).then((data) => {this.setState({model: data})});\n new TotoMLRegistryAPI().getRetrainedModel(this.state.modelName).then((data) => {this.setState({retrainedModel: data})});\n }", "clearCache() {\n // Reset current models.\n this.models = [];\n this._model_map = {};\n }", "reload(newData) {\n this.mapData = newData;\n console.log('New Dataset: ', this.mapData);\n console.log('Reloading the map using a new dataset');\n this.render();\n }", "function refreshWorksheetData(){\n const worksheet = props.selectedSheet;\n worksheet.getDataSourcesAsync().then(sources => {\n for (var src in sources){\n sources[src].refreshAsync().then(function () {\n console.log(sources[src].name + ': Refreshed Successfully');\n });\n }\n })\n }", "function sync() {\n\t\tvar this$1 = this;\n\n\t\teach(this.store.history, function (record) {\n\t\t\treveal.call(this$1, record.target, record.options, true);\n\t\t});\n\n\t\tinitialize.call(this);\n\t}", "function refreshDisplay() {\r\n updateSummaryMessage('Loading Data from Azure');\r\n\r\n if (useOfflineSync) {\r\n syncLocalTable().then(displayItems);\r\n } else {\r\n displayItems();\r\n } \r\n }", "_populateModels() {\n if (!this.populated) {\n for (const modelName in this.data) {\n const model = this.data[modelName];\n const fieldNames = Object.keys(model.fields).filter(f => f !== 'id');\n const size = modelName === this.mainModel ?\n SampleServer.MAIN_RECORDSET_SIZE :\n SampleServer.SUB_RECORDSET_SIZE;\n for (let id = 1; id <= size; id++) {\n const record = { id };\n for (const fieldName of fieldNames) {\n record[fieldName] = this._generateFieldValue(modelName, fieldName, id);\n }\n model.records.push(record);\n }\n }\n this.populated = true;\n }\n }", "sync() {\n each(this.models, method(\"sync\"));\n }", "function refreshRss() {\n\trss.loadRssFeed({\n\t\tsuccess: function(data) {\n\t\t\tvar rows = [];\n\t\t\t_.each(data, function(item) {\n\t\t\t\trows.push(Alloy.createController('row', {\n\t\t\t\t\tarticleUrl: item.link,\n\t\t\t\t\timage: item.image,\n\t\t\t\t\ttitle: item.title,\n\t\t\t\t\tdate: item.pubDate\n\t\t\t\t}).getView());\n\t\t\t});\n\t\t\t$.fb_table_albums.setData(rows);\n\t\t}\n\t});\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inject a function that returns a number.
function inject (taskKey) { var taskName = task[taskKey] var num = parseFloat(taskName) if (!isNaN(num)) { funcs[taskName] = function () { return num } } }
[ "visitNumeric_function_wrapper(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function numberFact (num, fn) {\n return fn(num);\n}", "visitNumeric_function(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function add5() {\n return function (x) {\n return add(x, 5);\n };\n}", "function addsNum(n) {\n\treturn (m) => m + n;\n}", "function four(){\n return 4;\n}", "function getRandomNumber(param){\n return Math.floor(Math.random() * param)\n}", "function generateNum() {\n\n /*TODO 2: implement the body of the function here to return a random number between 0 and 1*/\n\n}", "add(num1 = 0, num2 = 0, callback) {\n return callback(null, num1 + num2);\n }", "function apply_primitive_function(fun,args) {\n return apply_in_underlying_javascript(\n primitive_implementation(fun),\n args); \n}", "function getAge() {\n return 41;\n}", "function createFareMultiplier(multiplier) {\n return function(fare) {\n return fare*multiplier;\n };\n}", "function four() {\n return 4;\n}", "enterFunctionValueParameter(ctx) {\n\t}", "function myFunction() {\n const hash = {};\n return sum =(...args) => {\n if (args.length < 1) {\n return 0;\n }\n if (args.length === 1) {\n return args[0];\n }\n const stringifiedVal = args.toString();\n if (hash[stringifiedVal]) {\n return hash[stringifiedVal];\n }\n let result = 0;\n for (let i =0; i < args.length; i++) {\n result += args[i];\n }\n hash[stringifiedVal] = result;\n return result\n }\n}", "function product(a) {\n return function (b) {\n return a * b;\n };\n}", "NumericLiteral() {\n const token = this._eat(\"NUMBER\");\n return factory.NumericLiteral(Number(token.value));\n }", "function numberFactory (name, value) {\n const dependencies = ['config', 'BigNumber']\n\n return factory(name, dependencies, ({ config, BigNumber }) => {\n return config.number === 'BigNumber'\n ? new BigNumber(value)\n : value\n })\n}", "function makeCalculator() {\n var sum = 0;\n return {\n add: function(x) {\n sum += x;\n },\n subtract: function(x) {\n sum -= x;\n },\n times: function(x) {\n sum *= x;\n },\n getNumber: function() {\n return sum;\n }\n };\n\n}", "function getFunctionValue(func, point) {\n return func[0] * point.x + func[1] * point.y + func[2] * point.x * point.y + func[3];\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Precomputed BRDF, for using with PBR shaders
static PrecomputedBRDFLookupTexture(context) { return Texture.FromBase64Image(context,bg.base._brdfLUTData); }
[ "function coeff_biquad_lowpass12db(freq, gain) {\n var w = 2.0 * Math.PI * freq / samplerate;\n var s = Math.sin(w);\n var c = Math.cos(w);\n var q = gain;\n var alpha = s / (2.0 * q);\n var scale = 1.0 / (1.0 + alpha);\n\n var a1 = 2.0 * c * scale;\n var a2 = (alpha - 1.0) * scale;\n var b1 = (1.0 - c) * scale;\n var b0 = 0.5 * b1;\n var b2 = b0;\n\n return [0, 0, 0, 0, b0, b1, b2, a1, a2];\n}", "function PHSK_BFeld( draht, BPoint) {\n\tif ( GMTR_MagnitudeSquared( GMTR_CrossProduct( GMTR_VectorDifference(draht.a ,draht.b ),GMTR_VectorDifference(draht.a ,BPoint ) )) < 10E-10)\n\t\treturn new Vec3 (0.0, 0.0, 0.0);\n\n\n\tlet A = draht.a;\n\tlet B = draht.b;\n\tlet P = BPoint;\n\t\n\tlet xd = -(GMTR_DotProduct(A,A) - GMTR_DotProduct(A,B) + GMTR_DotProduct(P , GMTR_VectorDifference(A,B))) / (GMTR_Distance(A,B));\n\tlet x = xd / (GMTR_Distance(A,B));\n\tlet yd = xd + GMTR_Distance(A,B);\n\t\n\tlet F1 = (yd / GMTR_Distance(P,B)) - (xd / GMTR_Distance(P,A));\n\tlet F2 = 1 / (GMTR_Distance(P,GMTR_VectorAddition(A,GMTR_ScalarMultiplication( GMTR_VectorDifference(B,A), x))));\n\tlet F3 = GMTR_CrossProductNormal( GMTR_VectorDifference(A,B),GMTR_VectorDifference(A,P) );\n\n\treturn GMTR_ScalarMultiplication(F3,F1*F2);\n}", "function preproc()\n{\n // nodal coordinates as passed to opengl\n let coords = []\n // 3 corner nodes of a face to compute the face normal in the shader\n let As = []\n let Bs = []\n let Cs = []\n // triangles as passed to open gl\n let trias = []\n // displacement vector per vertex to displace said vertex\n let disps = []\n // global min/max to normalize result amplitudes\n let min = 0.0\n let max = 0.0\n // texture coordinates to properly map results per face\n let texcoords = []\n // all four corner nodes to compute the texture mapping\n let corners = []\n\n // for each quad\n for(let i = 0; i < quads.length; ++i) {\n let quad = quads[i]\n // triangulate\n trias.push(4 * i + 0, 4 * i + 1, 4 * i + 2, 4 * i + 0, 4 * i + 2, 4 * i + 3)\n // set texture coordinates\n texcoords.push(\n 0.0, 0.0,\n 0.0, 1.0,\n 1.0, 1.0,\n 1.0, 0.0\n )\n // push coordinates\n coords.push(\n nodes[3 * quad[0] + 0],\n nodes[3 * quad[0] + 1],\n nodes[3 * quad[0] + 2],\n nodes[3 * quad[1] + 0],\n nodes[3 * quad[1] + 1],\n nodes[3 * quad[1] + 2],\n nodes[3 * quad[2] + 0],\n nodes[3 * quad[2] + 1],\n nodes[3 * quad[2] + 2],\n nodes[3 * quad[3] + 0],\n nodes[3 * quad[3] + 1],\n nodes[3 * quad[3] + 2])\n // push A,B and C corner nodes to compute the face normal\n As.push(\n nodes[3 * quad[0] + 0] + results[3 * quad[0] + 0],\n nodes[3 * quad[0] + 1] + results[3 * quad[0] + 1],\n nodes[3 * quad[0] + 2] + results[3 * quad[0] + 2],\n nodes[3 * quad[0] + 0] + results[3 * quad[0] + 0],\n nodes[3 * quad[0] + 1] + results[3 * quad[0] + 1],\n nodes[3 * quad[0] + 2] + results[3 * quad[0] + 2],\n nodes[3 * quad[0] + 0] + results[3 * quad[0] + 0],\n nodes[3 * quad[0] + 1] + results[3 * quad[0] + 1],\n nodes[3 * quad[0] + 2] + results[3 * quad[0] + 2],\n nodes[3 * quad[0] + 0] + results[3 * quad[0] + 0],\n nodes[3 * quad[0] + 1] + results[3 * quad[0] + 1],\n nodes[3 * quad[0] + 2] + results[3 * quad[0] + 2])\n Bs.push(\n nodes[3 * quad[1] + 0] + results[3 * quad[1] + 0],\n nodes[3 * quad[1] + 1] + results[3 * quad[1] + 1],\n nodes[3 * quad[1] + 2] + results[3 * quad[1] + 2],\n nodes[3 * quad[1] + 0] + results[3 * quad[1] + 0],\n nodes[3 * quad[1] + 1] + results[3 * quad[1] + 1],\n nodes[3 * quad[1] + 2] + results[3 * quad[1] + 2],\n nodes[3 * quad[1] + 0] + results[3 * quad[1] + 0],\n nodes[3 * quad[1] + 1] + results[3 * quad[1] + 1],\n nodes[3 * quad[1] + 2] + results[3 * quad[1] + 2],\n nodes[3 * quad[1] + 0] + results[3 * quad[1] + 0],\n nodes[3 * quad[1] + 1] + results[3 * quad[1] + 1],\n nodes[3 * quad[1] + 2] + results[3 * quad[1] + 2])\n Cs.push(\n nodes[3 * quad[2] + 0] + results[3 * quad[2] + 0],\n nodes[3 * quad[2] + 1] + results[3 * quad[2] + 1],\n nodes[3 * quad[2] + 2] + results[3 * quad[2] + 2],\n nodes[3 * quad[2] + 0] + results[3 * quad[2] + 0],\n nodes[3 * quad[2] + 1] + results[3 * quad[2] + 1],\n nodes[3 * quad[2] + 2] + results[3 * quad[2] + 2],\n nodes[3 * quad[2] + 0] + results[3 * quad[2] + 0],\n nodes[3 * quad[2] + 1] + results[3 * quad[2] + 1],\n nodes[3 * quad[2] + 2] + results[3 * quad[2] + 2],\n nodes[3 * quad[2] + 0] + results[3 * quad[2] + 0],\n nodes[3 * quad[2] + 1] + results[3 * quad[2] + 1],\n nodes[3 * quad[2] + 2] + results[3 * quad[2] + 2])\n // push displacements\n disps.push(\n results[3 * quad[0] + 0],\n results[3 * quad[0] + 1],\n results[3 * quad[0] + 2],\n results[3 * quad[1] + 0],\n results[3 * quad[1] + 1],\n results[3 * quad[1] + 2],\n results[3 * quad[2] + 0],\n results[3 * quad[2] + 1],\n results[3 * quad[2] + 2],\n results[3 * quad[3] + 0],\n results[3 * quad[3] + 1],\n results[3 * quad[3] + 2])\n let sqr = x => x*x;\n min = globalMin\n max = globalMax\n let result = state.component\n if(result == 3) {\n let sqr = (x) => x*x;\n corners.push(\n Math.sqrt(sqr(results[3 * quad[0] + 0]) + sqr(results[3 * quad[0] + 1]) + sqr(results[3 * quad[0] + 2])),\n Math.sqrt(sqr(results[3 * quad[1] + 0]) + sqr(results[3 * quad[1] + 1]) + sqr(results[3 * quad[1] + 2])),\n Math.sqrt(sqr(results[3 * quad[2] + 0]) + sqr(results[3 * quad[2] + 1]) + sqr(results[3 * quad[2] + 2])),\n Math.sqrt(sqr(results[3 * quad[3] + 0]) + sqr(results[3 * quad[3] + 1]) + sqr(results[3 * quad[3] + 2])),\n Math.sqrt(sqr(results[3 * quad[0] + 0]) + sqr(results[3 * quad[0] + 1]) + sqr(results[3 * quad[0] + 2])),\n Math.sqrt(sqr(results[3 * quad[1] + 0]) + sqr(results[3 * quad[1] + 1]) + sqr(results[3 * quad[1] + 2])),\n Math.sqrt(sqr(results[3 * quad[2] + 0]) + sqr(results[3 * quad[2] + 1]) + sqr(results[3 * quad[2] + 2])),\n Math.sqrt(sqr(results[3 * quad[3] + 0]) + sqr(results[3 * quad[3] + 1]) + sqr(results[3 * quad[3] + 2])),\n Math.sqrt(sqr(results[3 * quad[0] + 0]) + sqr(results[3 * quad[0] + 1]) + sqr(results[3 * quad[0] + 2])),\n Math.sqrt(sqr(results[3 * quad[1] + 0]) + sqr(results[3 * quad[1] + 1]) + sqr(results[3 * quad[1] + 2])),\n Math.sqrt(sqr(results[3 * quad[2] + 0]) + sqr(results[3 * quad[2] + 1]) + sqr(results[3 * quad[2] + 2])),\n Math.sqrt(sqr(results[3 * quad[3] + 0]) + sqr(results[3 * quad[3] + 1]) + sqr(results[3 * quad[3] + 2])),\n Math.sqrt(sqr(results[3 * quad[0] + 0]) + sqr(results[3 * quad[0] + 1]) + sqr(results[3 * quad[0] + 2])),\n Math.sqrt(sqr(results[3 * quad[1] + 0]) + sqr(results[3 * quad[1] + 1]) + sqr(results[3 * quad[1] + 2])),\n Math.sqrt(sqr(results[3 * quad[2] + 0]) + sqr(results[3 * quad[2] + 1]) + sqr(results[3 * quad[2] + 2])),\n Math.sqrt(sqr(results[3 * quad[3] + 0]) + sqr(results[3 * quad[3] + 1]) + sqr(results[3 * quad[3] + 2])))\n } else {\n corners.push(\n results[3 * quad[0] + result],\n results[3 * quad[1] + result],\n results[3 * quad[2] + result],\n results[3 * quad[3] + result],\n results[3 * quad[0] + result],\n results[3 * quad[1] + result],\n results[3 * quad[2] + result],\n results[3 * quad[3] + result],\n results[3 * quad[0] + result],\n results[3 * quad[1] + result],\n results[3 * quad[2] + result],\n results[3 * quad[3] + result],\n results[3 * quad[0] + result],\n results[3 * quad[1] + result],\n results[3 * quad[2] + result],\n results[3 * quad[3] + result])\n }\n // pick the appropriate min/max per the selected component\n max = max[result]\n min = min[result]\n }\n\n document.getElementById('progress').innerHTML = ''\n return {\n coords: coords,\n trias: trias,\n disps: disps,\n As: As,\n Bs: Bs,\n Cs, Cs,\n min: min,\n max: max,\n texcoords: texcoords,\n corners: corners\n }\n}", "function DepthOfFieldMergePostProcess(name,originalFromInput,circleOfConfusion,blurSteps,options,camera,samplingMode,engine,reusable,textureType,blockCompilation){if(textureType===void 0){textureType=BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;}if(blockCompilation===void 0){blockCompilation=false;}var _this=_super.call(this,name,\"depthOfFieldMerge\",[],[\"circleOfConfusionSampler\",\"blurStep0\",\"blurStep1\",\"blurStep2\"],options,camera,samplingMode,engine,reusable,null,textureType,undefined,null,true)||this;_this.blurSteps=blurSteps;_this.onApplyObservable.add(function(effect){effect.setTextureFromPostProcess(\"textureSampler\",originalFromInput);effect.setTextureFromPostProcessOutput(\"circleOfConfusionSampler\",circleOfConfusion);blurSteps.forEach(function(step,index){effect.setTextureFromPostProcessOutput(\"blurStep\"+(blurSteps.length-index-1),step);});});if(!blockCompilation){_this.updateEffect();}return _this;}", "function ChromaticAberrationPostProcess(name,screenWidth,screenHeight,options,camera,samplingMode,engine,reusable,textureType,blockCompilation){if(textureType===void 0){textureType=BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;}if(blockCompilation===void 0){blockCompilation=false;}var _this=_super.call(this,name,\"chromaticAberration\",[\"chromatic_aberration\",\"screen_width\",\"screen_height\",\"direction\",\"radialIntensity\",\"centerPosition\"],[],options,camera,samplingMode,engine,reusable,null,textureType,undefined,null,blockCompilation)||this;/**\n * The amount of seperation of rgb channels (default: 30)\n */_this.aberrationAmount=30;/**\n * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)\n */_this.radialIntensity=0;/**\n * The normilized direction in which the rgb channels should be seperated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707))\n */_this.direction=new BABYLON.Vector2(0.707,0.707);/**\n * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corder] (default: Vector2(0.5 ,0.5))\n */_this.centerPosition=new BABYLON.Vector2(0.5,0.5);_this.onApplyObservable.add(function(effect){effect.setFloat('chromatic_aberration',_this.aberrationAmount);effect.setFloat('screen_width',screenWidth);effect.setFloat('screen_height',screenHeight);effect.setFloat('radialIntensity',_this.radialIntensity);effect.setFloat2('direction',_this.direction.x,_this.direction.y);effect.setFloat2('centerPosition',_this.centerPosition.x,_this.centerPosition.y);});return _this;}", "SolveBend_PBD_Triangle() {\n const stiffness = this.m_tuning.bendStiffness;\n for (let i = 0; i < this.m_bendCount; ++i) {\n const c = this.m_bendConstraints[i];\n const b0 = this.m_ps[c.i1].Clone();\n const v = this.m_ps[c.i2].Clone();\n const b1 = this.m_ps[c.i3].Clone();\n const wb0 = c.invMass1;\n const wv = c.invMass2;\n const wb1 = c.invMass3;\n const W = wb0 + wb1 + 2.0 * wv;\n const invW = stiffness / W;\n const d = new b2_math_js_1.b2Vec2();\n d.x = v.x - (1.0 / 3.0) * (b0.x + v.x + b1.x);\n d.y = v.y - (1.0 / 3.0) * (b0.y + v.y + b1.y);\n const db0 = new b2_math_js_1.b2Vec2();\n db0.x = 2.0 * wb0 * invW * d.x;\n db0.y = 2.0 * wb0 * invW * d.y;\n const dv = new b2_math_js_1.b2Vec2();\n dv.x = -4.0 * wv * invW * d.x;\n dv.y = -4.0 * wv * invW * d.y;\n const db1 = new b2_math_js_1.b2Vec2();\n db1.x = 2.0 * wb1 * invW * d.x;\n db1.y = 2.0 * wb1 * invW * d.y;\n b0.SelfAdd(db0);\n v.SelfAdd(dv);\n b1.SelfAdd(db1);\n this.m_ps[c.i1].Copy(b0);\n this.m_ps[c.i2].Copy(v);\n this.m_ps[c.i3].Copy(b1);\n }\n }", "_setupFramebuffers(opts) {\n const {\n textures,\n framebuffers,\n maxMinFramebuffers,\n minFramebuffers,\n maxFramebuffers,\n meanTextures,\n equations\n } = this.state;\n const {\n weights\n } = opts;\n const {\n numCol,\n numRow\n } = opts;\n const framebufferSize = {\n width: numCol,\n height: numRow\n };\n\n for (const id in weights) {\n const {\n needMin,\n needMax,\n combineMaxMin,\n operation\n } = weights[id];\n textures[id] = weights[id].aggregationTexture || textures[id] || Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFloatTexture\"])(this.gl, {\n id: `${id}-texture`,\n width: numCol,\n height: numRow\n });\n textures[id].resize(framebufferSize);\n let texture = textures[id];\n\n if (operation === _aggregation_operation_utils__WEBPACK_IMPORTED_MODULE_5__[\"AGGREGATION_OPERATION\"].MEAN) {\n // For MEAN, we first aggregatet into a temp texture\n meanTextures[id] = meanTextures[id] || Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFloatTexture\"])(this.gl, {\n id: `${id}-mean-texture`,\n width: numCol,\n height: numRow\n });\n meanTextures[id].resize(framebufferSize);\n texture = meanTextures[id];\n }\n\n if (framebuffers[id]) {\n framebuffers[id].attach({\n [_luma_gl_constants__WEBPACK_IMPORTED_MODULE_0__[\"default\"].COLOR_ATTACHMENT0]: texture\n });\n } else {\n framebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-fb`,\n width: numCol,\n height: numRow,\n texture\n });\n }\n\n framebuffers[id].resize(framebufferSize);\n equations[id] = _gpu_grid_aggregator_constants__WEBPACK_IMPORTED_MODULE_4__[\"EQUATION_MAP\"][operation] || _gpu_grid_aggregator_constants__WEBPACK_IMPORTED_MODULE_4__[\"EQUATION_MAP\"].SUM; // For min/max framebuffers will use default size 1X1\n\n if (needMin || needMax) {\n if (needMin && needMax && combineMaxMin) {\n if (!maxMinFramebuffers[id]) {\n texture = weights[id].maxMinTexture || this._getMinMaxTexture(`${id}-maxMinTexture`);\n maxMinFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-maxMinFb`,\n texture\n });\n }\n } else {\n if (needMin) {\n if (!minFramebuffers[id]) {\n texture = weights[id].minTexture || this._getMinMaxTexture(`${id}-minTexture`);\n minFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-minFb`,\n texture\n });\n }\n }\n\n if (needMax) {\n if (!maxFramebuffers[id]) {\n texture = weights[id].maxTexture || this._getMinMaxTexture(`${id}-maxTexture`);\n maxFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-maxFb`,\n texture\n });\n }\n }\n }\n }\n }\n }", "function piRenderer()\n{\n // private members\n\n var mGL = null;\n var mBindedShader = null;\n var mFloat32Textures;\n var mFloat32Filter;\n var mFloat16Textures;\n var mDrawBuffers;\n var mDepthTextures;\n var mDerivatives;\n var mFloat32Filter;\n var mFloat16Filter;\n var mShaderTextureLOD;\n var mVBO_Quad = null;\n var mPrecision;\n\n // public members\n var me = {};\n\n me.CLEAR = { Color: 1, Zbuffer : 2, Stencil : 4 };\n me.TEXFMT = { C4I8 : 0, C1I8 : 1,C1F16 : 2, C4F16 : 3, Z16 : 4 };\n me.TEXWRP = { CLAMP : 0, REPEAT : 1 };\n me.BUFTYPE = { STATIC : 0, DYNAMIC : 1 };\n me.PRIMTYPE = { POINTS : 0, LINES : 1, LINE_LOOP : 2, LINE_STRIP : 3, TRIANGLES : 4, TRIANGLE_STRIP : 5 };\n me.RENDSTGATE = { WIREFRAME : 0, FRONT_FACE : 1, CULL_FACE : 2, DEPTH_TEST : 3 };\n me.TEXTYPE = { T2D : 0, T3D : 1, CUBEMAP : 2 };\n me.FILTER = { NONE : 0, LINEAR : 1, MIPMAP : 2, NONE_MIPMAP : 3 };\n\n // private functions\n\n var iFormatPI2GL = function( format )\n {\n if (format === me.TEXFMT.C4I8) return { mGLFormat: mGL.RGBA, mGLType: mGL.UNSIGNED_BYTE }\n else if (format === me.TEXFMT.C1I8) return { mGLFormat: mGL.LUMINANCE, mGLType: mGL.UNSIGNED_BYTE }\n else if (format === me.TEXFMT.C1F16) return { mGLFormat: mGL.LUMINANCE, mGLType: mGL.FLOAT }\n else if (format === me.TEXFMT.C4F16) return { mGLFormat: mGL.RGBA, mGLType: mGL.FLOAT }\n else if (format === me.TEXFMT.Z16) return { mGLFormat: mGL.DEPTH_COMPONENT, mGLType: mGL.UNSIGNED_SHORT }\n\n return null;\n }\n\n // public functions\n\n me.Initialize = function( gl )\n {\n mGL = gl;\n mFloat32Textures = mGL.getExtension( 'OES_texture_float' );\n mFloat32Filter = mGL.getExtension( 'OES_texture_float_linear');\n mFloat16Textures = mGL.getExtension( 'OES_texture_half_float' );\n mFloat16Filter = mGL.getExtension( 'OES_texture_half_float_linear' );\n mDerivatives = mGL.getExtension( 'OES_standard_derivatives' );\n mDrawBuffers = mGL.getExtension( 'WEBGL_draw_buffers' );\n mDepthTextures = mGL.getExtension( 'WEBGL_depth_texture' );\n mShaderTextureLOD = mGL.getExtension( 'EXT_shader_texture_lod' );\n\n /*\n var maxTexSize = mGL.getParameter( mGL.MAX_TEXTURE_SIZE );\n var maxCubeSize = mGL.getParameter( mGL.MAX_CUBE_MAP_TEXTURE_SIZE );\n var maxRenderbufferSize = mGL.getParameter( mGL.MAX_RENDERBUFFER_SIZE );\n var extensions = mGL.getSupportedExtensions();\n var textureUnits = mGL.getParameter( mGL.MAX_TEXTURE_IMAGE_UNITS );\n console.log(\"Story Studio Web Renderer:\" +\n \"\\n Float32 Textures: \" + ((this.mFloat32Textures != null) ? \"yes\" : \"no\") +\n \"\\n Float16 Textures: \" + ((this.mFloat16Textures != null) ? \"yes\" : \"no\") +\n \"\\n Multiple Render Targets: \" + ((this.mDrawBuffers != null) ? \"yes\" : \"no\") +\n \"\\n Depth Textures: \" + ((this.mDepthTextures != null) ? \"yes\" : \"no\") +\n \"\\n Shader Texture LOD: \" + ((this.mShaderTextureLOD != null) ? \"yes\" : \"no\") +\n \"\\n Texture Units: \" + textureUnits +\n \"\\n Max Texture Size: \" + maxTexSize +\n \"\\n Max Render Buffer Size: \" + maxRenderbufferSize +\n \"\\n Max Cubemap Size: \" + maxCubeSize);\n\n //console.log(\"\\n\" + extensions);\n */\n\n if( mDerivatives != null) mGL.hint( mDerivatives.FRAGMENT_SHADER_DERIVATIVE_HINT_OES, mGL.NICEST);\n\n // create a 2D quad Vertex Buffer\n var vertices = new Float32Array( [ -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0] );\n mVBO_Quad = mGL.createBuffer();\n mGL.bindBuffer( mGL.ARRAY_BUFFER, mVBO_Quad );\n mGL.bufferData( mGL.ARRAY_BUFFER, vertices, mGL.STATIC_DRAW );\n mGL.bindBuffer( mGL.ARRAY_BUFFER, null );\n\n\n // determine precision\n\n mPrecision = \"\";\n var h1 = \"#ifdef GL_ES\\nprecision highp float;\\n#endif\\n\";\n var h2 = \"#ifdef GL_ES\\nprecision mediump float;\\n#endif\\n\";\n var h3 = \"#ifdef GL_ES\\nprecision lowp float;\\n#endif\\n\";\n var vstr = \"void main() { gl_Position = vec4(1.0); }\\n\";\n var fstr = \"void main() { gl_FragColor = vec4(1.0); }\\n\";\n var errorStr;\n if( me.CreateShader( vstr, h1 + fstr, errorStr)!=null ) mPrecision=h1;\n else if( me.CreateShader( vstr, h2 + fstr, errorStr)!=null ) mPrecision=h2;\n else if( me.CreateShader( vstr, h3 + fstr, errorStr)!=null ) mPrecision=h3;\n\n return true;\n };\n\n me.GetPrecisionString = function()\n {\n return mPrecision;\n };\n\n me.GetCaps = function ()\n {\n return { mFloat32Textures: mFloat32Textures != null,\n mFloat16Textures: mFloat16Textures != null,\n mDrawBuffers: mDrawBuffers != null,\n mDepthTextures: mDepthTextures != null,\n mDerivatives: mDerivatives != null,\n mShaderTextureLOD: mShaderTextureLOD != null };\n };\n\n me.CheckErrors = function()\n {\n var error = mGL.getError();\n if( error != mGL.NO_ERROR ) { console.log( \"GL Error: \" + error ); }\n };\n\n me.Clear = function( flags, ccolor, cdepth, cstencil )\n {\n var mode = 0;\n if( flags & 1 ) { mode |= mGL.COLOR_BUFFER_BIT; mGL.clearColor( ccolor[0], ccolor[1], ccolor[2], ccolor[3] ); }\n if( flags & 2 ) { mode |= mGL.DEPTH_BUFFER_BIT; mGL.clearDepth( cdepth ); }\n if( flags & 4 ) { mode |= mGL.STENCIL_BUFFER_BIT; mGL.clearStencil( cstencil ); }\n mGL.clear( mode );\n };\n\n\n me.CreateTexture = function ( type, xres, yres, format, filter, wrap, buffer)\n {\n if( mGL===null ) return null;\n\n var id = mGL.createTexture();\n\n var glFoTy = iFormatPI2GL( format );\n var glWrap = mGL.REPEAT; if (wrap === me.TEXWRP.CLAMP) glWrap = mGL.CLAMP_TO_EDGE;\n\n if( type===me.TEXTYPE.T2D )\n {\n mGL.bindTexture( mGL.TEXTURE_2D, id );\n mGL.texImage2D( mGL.TEXTURE_2D, 0, glFoTy.mGLFormat, xres, yres, 0, glFoTy.mGLFormat, glFoTy.mGLType, buffer );\n\n mGL.texParameteri( mGL.TEXTURE_2D, mGL.TEXTURE_WRAP_S, glWrap );\n mGL.texParameteri( mGL.TEXTURE_2D, mGL.TEXTURE_WRAP_T, glWrap );\n\n if (filter === me.FILTER.NONE)\n {\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_MAG_FILTER, mGL.NEAREST);\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_MIN_FILTER, mGL.NEAREST);\n }\n else if (filter === me.FILTER.LINEAR)\n {\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_MAG_FILTER, mGL.LINEAR);\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_MIN_FILTER, mGL.LINEAR);\n }\n else if (filter === me.FILTER.MIPMAP)\n {\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_MAG_FILTER, mGL.LINEAR);\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_MIN_FILTER, mGL.LINEAR_MIPMAP_LINEAR);\n mGL.generateMipmap(mGL.TEXTURE_2D);\n }\n else\n {\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_MAG_FILTER, mGL.NEAREST);\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_MIN_FILTER, mGL.NEAREST_MIPMAP_LINEAR);\n mGL.generateMipmap(mGL.TEXTURE_2D);\n }\n\n mGL.bindTexture( mGL.TEXTURE_2D, null );\n\n }\n else if( type===me.TEXTYPE.T3D )\n {\n return null;\n }\n else \n {\n mGL.bindTexture( mGL.TEXTURE_CUBE_MAP, id );\n mGL.texParameteri( mGL.TEXTURE_CUBE_MAP, mGL.TEXTURE_MAG_FILTER, mGL.LINEAR );\n mGL.texParameteri( mGL.TEXTURE_CUBE_MAP, mGL.TEXTURE_MIN_FILTER, mGL.LINEAR );\n\n mGL.bindTexture( mGL.TEXTURE_CUBE_MAP, null );\n }\n\n return { mObjectID: id, mXres: xres, mYres: yres, mFormat: format, mType: type, mFilter: filter, mWrap: wrap, mVFlip:false };\n };\n\n me.CreateTextureFromImage = function ( type, image, format, filter, wrap, flipY) \n {\n if( mGL===null ) return null;\n\n var id = mGL.createTexture();\n\n var glFoTy = iFormatPI2GL( format );\n\n var glWrap = mGL.REPEAT; if (wrap === me.TEXWRP.CLAMP) glWrap = mGL.CLAMP_TO_EDGE;\n\n if( type===me.TEXTYPE.T2D )\n {\n mGL.bindTexture(mGL.TEXTURE_2D, id);\n\n mGL.pixelStorei(mGL.UNPACK_FLIP_Y_WEBGL, flipY);\n\n mGL.texImage2D(mGL.TEXTURE_2D, 0, glFoTy.mGLFormat, glFoTy.mGLFormat, glFoTy.mGLType, image);\n\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_WRAP_S, glWrap);\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_WRAP_T, glWrap);\n\n if (filter === me.FILTER.NONE)\n {\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_MAG_FILTER, mGL.NEAREST);\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_MIN_FILTER, mGL.NEAREST);\n }\n else if (filter === me.FILTER.LINEAR)\n {\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_MAG_FILTER, mGL.LINEAR);\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_MIN_FILTER, mGL.LINEAR);\n }\n else if( filter === me.FILTER.MIPMAP)\n {\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_MAG_FILTER, mGL.LINEAR);\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_MIN_FILTER, mGL.LINEAR_MIPMAP_LINEAR);\n mGL.generateMipmap(mGL.TEXTURE_2D);\n }\n else\n {\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_MAG_FILTER, mGL.LINEAR);\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_MIN_FILTER, mGL.NEAREST_MIPMAP_LINEAR);\n mGL.generateMipmap(mGL.TEXTURE_2D);\n }\n\n mGL.bindTexture(mGL.TEXTURE_2D, null);\n }\n else if( type===me.TEXTYPE.T3D )\n {\n return null;\n }\n else \n {\n mGL.bindTexture( mGL.TEXTURE_CUBE_MAP, id );\n mGL.pixelStorei(mGL.UNPACK_FLIP_Y_WEBGL, flipY);\n mGL.texParameteri( mGL.TEXTURE_CUBE_MAP, mGL.TEXTURE_MAG_FILTER, mGL.LINEAR );\n mGL.texParameteri( mGL.TEXTURE_CUBE_MAP, mGL.TEXTURE_MIN_FILTER, mGL.LINEAR );\n\n for( var i=0; i<6; i++ )\n {\n mGL.texImage2D( mGL.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFoTy.mGLFormat, glFoTy.mGLFormat, glFoTy.mGLType, image[i] );\n }\n\n mGL.bindTexture( mGL.TEXTURE_CUBE_MAP, null );\n\n }\n return { mObjectID: id, mXres: image.width, mYres: image.height, mFormat: format, mType: type, mFilter: filter, mWrap:wrap, mVFlip:flipY };\n };\n\n me.SetSamplerFilter = function (te, filter) \n {\n if (te.mFilter === filter) return;\n\n var id = te.mObjectID;\n\n if (te.mType === me.TEXTYPE.T2D) \n {\n mGL.bindTexture(mGL.TEXTURE_2D, id);\n\n if (filter === me.FILTER.NONE) \n {\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_MAG_FILTER, mGL.NEAREST);\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_MIN_FILTER, mGL.NEAREST);\n }\n else if (filter === me.FILTER.LINEAR) \n {\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_MAG_FILTER, mGL.LINEAR);\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_MIN_FILTER, mGL.LINEAR);\n }\n else if (filter === me.FILTER.MIPMAP) \n {\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_MAG_FILTER, mGL.LINEAR);\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_MIN_FILTER, mGL.LINEAR_MIPMAP_LINEAR);\n mGL.generateMipmap(mGL.TEXTURE_2D)\n }\n else {\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_MAG_FILTER, mGL.NEAREST);\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_MIN_FILTER, mGL.NEAREST_MIPMAP_LINEAR);\n mGL.generateMipmap(mGL.TEXTURE_2D)\n }\n\n mGL.bindTexture(mGL.TEXTURE_2D, null);\n\n }\n\n te.mFilter = filter;\n };\n\n me.SetSamplerWrap = function (te, wrap)\n {\n if (te.mWrap === wrap) return;\n\n var glWrap = mGL.REPEAT; if (wrap === me.TEXWRP.CLAMP) glWrap = mGL.CLAMP_TO_EDGE;\n\n var id = te.mObjectID;\n\n if (te.mType === me.TEXTYPE.T2D)\n {\n mGL.bindTexture(mGL.TEXTURE_2D, id);\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_WRAP_S, glWrap);\n mGL.texParameteri(mGL.TEXTURE_2D, mGL.TEXTURE_WRAP_T, glWrap);\n mGL.bindTexture(mGL.TEXTURE_2D, null);\n\n }\n\n te.mWrap = wrap;\n };\n\n me.SetSamplerVFlip = function (te, vflip, image)\n {\n if (te.mVFlip === vflip) return;\n\n var id = te.mObjectID;\n\n if (te.mType === me.TEXTYPE.T2D)\n {\n if( image != null)\n {\n mGL.activeTexture( mGL.TEXTURE0 );\n mGL.bindTexture(mGL.TEXTURE_2D, id);\n mGL.pixelStorei(mGL.UNPACK_FLIP_Y_WEBGL, vflip);\n var glFoTy = iFormatPI2GL( te.mFormat );\n mGL.texImage2D(mGL.TEXTURE_2D, 0, glFoTy.mGLFormat, glFoTy.mGLFormat, glFoTy.mGLType, image);\n mGL.bindTexture(mGL.TEXTURE_2D, null);\n }\n }\n else if (te.mType === me.TEXTYPE.CUBEMAP)\n {\n if( image != null)\n {\n var glFoTy = iFormatPI2GL( te.mFormat );\n\n mGL.activeTexture( mGL.TEXTURE0 );\n mGL.bindTexture( mGL.TEXTURE_CUBE_MAP, id );\n mGL.pixelStorei( mGL.UNPACK_FLIP_Y_WEBGL, vflip);\n mGL.texImage2D( mGL.TEXTURE_CUBE_MAP_POSITIVE_X, 0, glFoTy.mGLFormat, glFoTy.mGLFormat, glFoTy.mGLType, image[0] );\n mGL.texImage2D( mGL.TEXTURE_CUBE_MAP_NEGATIVE_X, 0, glFoTy.mGLFormat, glFoTy.mGLFormat, glFoTy.mGLType, image[1] );\n mGL.texImage2D( mGL.TEXTURE_CUBE_MAP_POSITIVE_Y, 0, glFoTy.mGLFormat, glFoTy.mGLFormat, glFoTy.mGLType, (vflip ? image[3] : image[2]) );\n mGL.texImage2D( mGL.TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, glFoTy.mGLFormat, glFoTy.mGLFormat, glFoTy.mGLType, (vflip ? image[2] : image[3]) );\n mGL.texImage2D( mGL.TEXTURE_CUBE_MAP_POSITIVE_Z, 0, glFoTy.mGLFormat, glFoTy.mGLFormat, glFoTy.mGLType, image[4] );\n mGL.texImage2D( mGL.TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, glFoTy.mGLFormat, glFoTy.mGLFormat, glFoTy.mGLType, image[5] );\n mGL.bindTexture( mGL.TEXTURE_CUBE_MAP, null );\n }\n \n }\n\n te.mVFlip = vflip;\n };\n\n me.CreateMipmaps = function (te)\n {\n if( te.mType===me.TEXTYPE.T2D )\n {\n mGL.activeTexture(mGL.TEXTURE0);\n mGL.bindTexture(mGL.TEXTURE_2D, te.mObjectID);\n mGL.generateMipmap(mGL.TEXTURE_2D);\n mGL.bindTexture(mGL.TEXTURE_2D, null);\n }\n };\n\n me.UpdateTexture = function( tex, x0, y0, xres, yres, buffer )\n {\n var glFoTy = iFormatPI2GL( tex.mFormat );\n if( tex.mType===me.TEXTYPE.T2D )\n {\n mGL.activeTexture( mGL.TEXTURE0);\n mGL.bindTexture( mGL.TEXTURE_2D, tex.mObjectID );\n mGL.pixelStorei(mGL.UNPACK_FLIP_Y_WEBGL, tex.mVFlip );\n mGL.texSubImage2D( mGL.TEXTURE_2D, 0, x0, y0, xres, yres, glFoTy.mGLFormat, glFoTy.mGLType, buffer );\n mGL.bindTexture( mGL.TEXTURE_2D, null );\n }\n };\n\n me.UpdateTextureFromImage = function( tex, image )\n {\n var glFoTy = iFormatPI2GL( tex.mFormat );\n if( tex.mType===me.TEXTYPE.T2D )\n {\n mGL.activeTexture( mGL.TEXTURE0 );\n mGL.bindTexture( mGL.TEXTURE_2D, tex.mObjectID );\n mGL.pixelStorei(mGL.UNPACK_FLIP_Y_WEBGL, tex.mVFlip );\n mGL.texImage2D( mGL.TEXTURE_2D, 0, glFoTy.mGLFormat, glFoTy.mGLFormat, glFoTy.mGLType, image );\n mGL.bindTexture( mGL.TEXTURE_2D, null );\n }\n };\n\n me.DestroyTexture = function( te )\n {\n mGL.deleteTexture( te.mObjectID );\n };\n\n me.AttachTextures = function (num, t0, t1, t2, t3) \n {\n if (num > 0 && t0 != null) \n {\n mGL.activeTexture(mGL.TEXTURE0);\n if (t0.mType === me.TEXTYPE.T2D) mGL.bindTexture(mGL.TEXTURE_2D, t0.mObjectID);\n else if (t0.mType === me.TEXTYPE.CUBEMAP) mGL.bindTexture(mGL.TEXTURE_CUBE_MAP, t0.mObjectID);\n }\n\n if (num > 1 && t1 != null) \n {\n mGL.activeTexture(mGL.TEXTURE1);\n if (t1.mType === me.TEXTYPE.T2D) mGL.bindTexture(mGL.TEXTURE_2D, t1.mObjectID);\n else if (t1.mType === me.TEXTYPE.CUBEMAP) mGL.bindTexture(mGL.TEXTURE_CUBE_MAP, t1.mObjectID);\n }\n\n if (num > 2 && t2 != null) \n {\n mGL.activeTexture(mGL.TEXTURE2);\n if (t2.mType === me.TEXTYPE.T2D) mGL.bindTexture(mGL.TEXTURE_2D, t2.mObjectID);\n else if (t2.mType === me.TEXTYPE.CUBEMAP) mGL.bindTexture(mGL.TEXTURE_CUBE_MAP, t2.mObjectID);\n }\n\n if (num > 3 && t3 != null) \n {\n mGL.activeTexture(mGL.TEXTURE3);\n if (t3.mType === me.TEXTYPE.T2D) mGL.bindTexture(mGL.TEXTURE_2D, t3.mObjectID);\n else if (t3.mType === me.TEXTYPE.CUBEMAP) mGL.bindTexture(mGL.TEXTURE_CUBE_MAP, t3.mObjectID);\n }\n };\n\n me.DettachTextures = function()\n {\n mGL.activeTexture(mGL.TEXTURE0);\n mGL.bindTexture(mGL.TEXTURE_2D, null);\n mGL.bindTexture(mGL.TEXTURE_CUBE_MAP, null);\n\n mGL.activeTexture(mGL.TEXTURE1);\n mGL.bindTexture(mGL.TEXTURE_2D, null);\n mGL.bindTexture(mGL.TEXTURE_CUBE_MAP, null);\n\n mGL.activeTexture(mGL.TEXTURE2);\n mGL.bindTexture(mGL.TEXTURE_2D, null);\n mGL.bindTexture(mGL.TEXTURE_CUBE_MAP, null);\n\n mGL.activeTexture(mGL.TEXTURE3);\n mGL.bindTexture(mGL.TEXTURE_2D, null);\n mGL.bindTexture(mGL.TEXTURE_CUBE_MAP, null);\n };\n\n me.CreateRenderTarget = function ( color0, color1, color2, color3, depth, wantZbuffer )\n {\n var id = mGL.createFramebuffer();\n mGL.bindFramebuffer(mGL.FRAMEBUFFER, id);\n\n if (depth === null)\n {\n if( wantZbuffer===true )\n {\n var zb = mGL.createRenderbuffer();\n mGL.bindRenderbuffer(mGL.RENDERBUFFER, zb);\n mGL.renderbufferStorage(mGL.RENDERBUFFER, mGL.DEPTH_COMPONENT16, color0.mXres, color0.mYres);\n\n mGL.framebufferRenderbuffer(mGL.FRAMEBUFFER, mGL.DEPTH_ATTACHMENT, mGL.RENDERBUFFER, zb);\n }\n }\n else\n {\n mGL.framebufferTexture2D(mGL.FRAMEBUFFER, mGL.DEPTH_ATTACHMENT, mGL.TEXTURE_2D, depth.mObjectID, 0);\n }\n\n if( color0 !=null ) mGL.framebufferTexture2D(mGL.FRAMEBUFFER, mGL.COLOR_ATTACHMENT0, mGL.TEXTURE_2D, color0.mObjectID, 0);\n\n if (mGL.checkFramebufferStatus(mGL.FRAMEBUFFER) != mGL.FRAMEBUFFER_COMPLETE)\n return null;\n\n mGL.bindRenderbuffer(mGL.RENDERBUFFER, null);\n mGL.bindFramebuffer(mGL.FRAMEBUFFER, null);\n\n return { mObjectID: id };\n };\n\n me.DestroyRenderTarget = function ( tex )\n {\n mGL.deleteFramebuffer(tex.mObjectID);\n };\n\n me.SetRenderTarget = function (tex)\n {\n if( tex===null )\n mGL.bindFramebuffer(mGL.FRAMEBUFFER, null);\n else\n mGL.bindFramebuffer(mGL.FRAMEBUFFER, tex.mObjectID);\n };\n\n me.SetViewport = function( vp )\n {\n mGL.viewport( vp[0], vp[1], vp[2], vp[3] );\n };\n\n me.SetWriteMask = function( c0, c1, c2, c3, z )\n {\n mGL.depthMask(z);\n mGL.colorMask(c0,c0,c0,c0);\n };\n\n me.SetState = function( stateName, stateValue )\n {\n if (stateName === me.RENDSTGATE.WIREFRAME)\n\t {\n\t\t if( stateValue ) mGL.polygonMode( mGL.FRONT_AND_BACK, mGL.LINE );\n\t\t else mGL.polygonMode( mGL.FRONT_AND_BACK, mGL.FILL );\n\t }\n else if (stateName === me.RENDSTGATE.FRONT_FACE)\n {\n if( stateValue ) mGL.cullFace( mGL.BACK );\n else mGL.cullFace( mGL.FRONT );\n }\n else if (stateName === me.RENDSTGATE.CULL_FACE)\n\t {\n\t\t if( stateValue ) mGL.enable( mGL.CULL_FACE );\n\t\t else mGL.disable( mGL.CULL_FACE );\n\t }\n else if (stateName === me.RENDSTGATE.DEPTH_TEST)\n\t {\n\t\t if( stateValue ) mGL.enable( mGL.DEPTH_TEST );\n\t\t else mGL.disable( mGL.DEPTH_TEST );\n\t }\n };\n\n me.CreateShader = function (vsSource, fsSource) \n {\n if( mGL===null ) return { mProgram: null, mResult: false, mInfo: \"No WebGL\" };\n\n var te = { mProgram: null, mResult: true, mInfo: \"Shader compiled successfully\" };\n\n var vs = mGL.createShader( mGL.VERTEX_SHADER );\n var fs = mGL.createShader( mGL.FRAGMENT_SHADER );\n\n mGL.shaderSource(vs, vsSource);\n mGL.shaderSource(fs, fsSource);\n\n mGL.compileShader(vs);\n mGL.compileShader(fs);\n \n //-------------\n\n if (!mGL.getShaderParameter(vs, mGL.COMPILE_STATUS)) \n {\n var infoLog = mGL.getShaderInfoLog(vs);\n te.mInfo = infoLog;\n te.mResult = false;\n return te;\n }\n\n if (!mGL.getShaderParameter(fs, mGL.COMPILE_STATUS)) {\n var infoLog = mGL.getShaderInfoLog(fs);\n te.mInfo = infoLog;\n te.mResult = false;\n return te;\n }\n //-------------\n\n te.mProgram = mGL.createProgram();\n\n mGL.attachShader(te.mProgram, vs);\n mGL.attachShader(te.mProgram, fs);\n\n mGL.linkProgram(te.mProgram);\n\n if (!mGL.getProgramParameter(te.mProgram, mGL.LINK_STATUS)) \n {\n var infoLog = mGL.getProgramInfoLog(te.mProgram);\n mGL.deleteProgram(te.mProgram);\n te.mInfo = infoLog;\n te.mResult = false;\n return te;\n }\n return te;\n };\n\n me.AttachShader = function( shader )\n {\n if( shader===null )\n {\n mBindedShader = null;\n mGL.useProgram( null );\n }\n else\n {\n mBindedShader = shader;\n mGL.useProgram(shader.mProgram);\n }\n };\n\n me.DetachShader = function ()\n {\n mGL.useProgram(null);\n };\n\n me.DestroyShader = function( tex )\n {\n mGL.deleteProgram(tex.mProgram);\n };\n\n me.GetAttribLocation = function (shader, name)\n {\n return mGL.getAttribLocation(shader.mProgram, name);\n };\n\n me.SetShaderConstantLocation = function (shader, name)\n {\n return mGL.getUniformLocation(shader.mProgram, name);\n };\n\n me.SetShaderConstantMat4F = function( uname, params, istranspose )\n {\n var program = mBindedShader;\n\n var pos = mGL.getUniformLocation( program.mProgram, uname );\n if( pos===null )\n return false;\n\n if( istranspose===false )\n {\n var tmp = new Float32Array( [ params[0], params[4], params[ 8], params[12],\n params[1], params[5], params[ 9], params[13],\n params[2], params[6], params[10], params[14],\n params[3], params[7], params[11], params[15] ] );\n\t mGL.uniformMatrix4fv(pos,false,tmp);\n }\n else\n mGL.uniformMatrix4fv(pos,false,new Float32Array(params) );\n return true;\n };\n\n me.SetShaderConstant1F_Pos = function(pos, x)\n {\n mGL.uniform1f(pos, x);\n return true;\n };\n\n me.SetShaderConstant1F = function( uname, x )\n {\n var pos = mGL.getUniformLocation(mBindedShader.mProgram, uname);\n if (pos === null)\n return false;\n mGL.uniform1f(pos, x);\n return true;\n };\n\n me.SetShaderConstant1I = function(uname, x)\n {\n var pos = mGL.getUniformLocation(mBindedShader.mProgram, uname);\n if (pos === null)\n return false;\n mGL.uniform1i(pos, x);\n return true;\n };\n\n me.SetShaderConstant2F = function(uname, x)\n {\n var pos = mGL.getUniformLocation(mBindedShader.mProgram, uname);\n if (pos === null)\n return false;\n mGL.uniform2fv(pos, x);\n return true;\n };\n\n me.SetShaderConstant3F = function(uname, x, y, z)\n {\n var pos = mGL.getUniformLocation(mBindedShader.mProgram, uname);\n if (pos === null)\n return false;\n mGL.uniform3f(pos, x, y, z);\n return true;\n };\n\n me.SetShaderConstant1FV = function(uname, x)\n {\n var pos = mGL.getUniformLocation(mBindedShader.mProgram, uname);\n if (pos === null)\n return false;\n mGL.uniform1fv(pos, new Float32Array(x));\n return true;\n };\n\n me.SetShaderConstant3FV = function(uname, x) \n {\n var pos = mGL.getUniformLocation(mBindedShader.mProgram, uname);\n if (pos === null) return false;\n mGL.uniform3fv(pos, new Float32Array(x) );\n return true;\n };\n\n me.SetShaderConstant4FV = function(uname, x) \n {\n var pos = mGL.getUniformLocation(mBindedShader.mProgram, uname);\n if (pos === null) return false;\n mGL.uniform4fv(pos, new Float32Array(x) );\n return true;\n };\n\n me.SetShaderTextureUnit = function( uname, unit )\n {\n var program = mBindedShader;\n var pos = mGL.getUniformLocation(program.mProgram, uname);\n if (pos === null) return false;\n mGL.uniform1i(pos, unit);\n return true;\n };\n\n me.CreateVertexArray = function( data, mode )\n {\n var id = mGL.createBuffer();\n mGL.bindBuffer(mGL.ARRAY_BUFFER, id);\n if (mode === me.BUFTYPE.STATIC)\n mGL.bufferData(mGL.ARRAY_BUFFER, data, mGL.STATIC_DRAW);\n else\n mGL.bufferData(mGL.ARRAY_BUFFER, data, mGL.DYNAMIC_DRAW);\n return { mObject: id };\n };\n\n me.CreateIndexArray = function( data, mode )\n {\n var id = mGL.createBuffer();\n mGL.bindBuffer(mGL.ELEMENT_ARRAY_BUFFER, id );\n if (mode === me.BUFTYPE.STATIC)\n mGL.bufferData(mGL.ELEMENT_ARRAY_BUFFER, data, mGL.STATIC_DRAW);\n else\n mGL.bufferData(mGL.ELEMENT_ARRAY_BUFFER, data, mGL.DYNAMIC_DRAW);\n return { mObject: id };\n };\n\n me.DestroyArray = function( tex )\n {\n mGL.destroyBuffer(tex.mObject);\n };\n\n me.AttachVertexArray = function( tex, attribs, pos )\n {\n var shader = mBindedShader;\n\n mGL.bindBuffer( mGL.ARRAY_BUFFER, tex.mObject);\n\n var num = attribs.mChannels.length;\n var stride = attribs.mStride;\n\n var offset = 0;\n for (var i = 0; i < num; i++)\n {\n var id = pos[i];\n mGL.enableVertexAttribArray(id);\n mGL.vertexAttribPointer(id, attribs.mChannels[i], mGL.FLOAT, false, stride, offset);\n offset += attribs.mChannels[i] * 4;\n }\n };\n\n me.AttachIndexArray = function( tex )\n {\n mGL.bindBuffer(mGL.ELEMENT_ARRAY_BUFFER, tex.mObject);\n };\n\n me.DetachVertexArray = function (tex, attribs)\n {\n var num = attribs.mChannels.length;\n for (var i = 0; i < num; i++)\n mGL.disableVertexAttribArray(i);\n mGL.bindBuffer(mGL.ARRAY_BUFFER, null);\n };\n\n me.DetachIndexArray = function( tex )\n {\n mGL.bindBuffer(mGL.ELEMENT_ARRAY_BUFFER, null);\n };\n\n me.DrawPrimitive = function( typeOfPrimitive, num, useIndexArray )\n {\n var glType = mGL.POINTS;\n if( typeOfPrimitive===me.PRIMTYPE.POINTS ) glType = mGL.POINTS;\n if( typeOfPrimitive===me.PRIMTYPE.LINES ) glType = mGL.LINES;\n if( typeOfPrimitive===me.PRIMTYPE.LINE_LOOP ) glType = mGL.LINE_LOOP;\n if( typeOfPrimitive===me.PRIMTYPE.LINE_STRIP ) glType = mGL.LINE_STRIP;\n if( typeOfPrimitive===me.PRIMTYPE.TRIANGLES ) glType = mGL.TRIANGLES;\n if( typeOfPrimitive===me.PRIMTYPE.TRIANGLE_STRIP ) glType = mGL.TRIANGLE_STRIP;\n\n \t if( useIndexArray )\n\t\t mGL.drawElements( glType, num, mGL.UNSIGNED_SHORT, 0 );\n\t else\n\t\t mGL.drawArrays( glType, 0, num );\n };\n\n me.DrawUnitQuad_XY = function( vpos )\n {\n mGL.bindBuffer( mGL.ARRAY_BUFFER, mVBO_Quad );\n mGL.vertexAttribPointer( vpos, 2, mGL.FLOAT, false, 0, 0 );\n mGL.enableVertexAttribArray( vpos );\n mGL.drawArrays( mGL.TRIANGLES, 0, 6 );\n mGL.disableVertexAttribArray( vpos );\n mGL.bindBuffer( mGL.ARRAY_BUFFER, null );\n };\n\n me.SetBlend = function( enabled )\n {\n if( enabled )\n {\n mGL.enable( mGL.BLEND );\n mGL.blendEquationSeparate( mGL.FUNC_ADD, mGL.FUNC_ADD );\n mGL.blendFuncSeparate( mGL.SRC_ALPHA, mGL.ONE_MINUS_SRC_ALPHA, mGL.ONE, mGL.ONE_MINUS_SRC_ALPHA );\n }\n else\n {\n mGL.disable( mGL.BLEND );\n }\n };\n\n me.GetPixelData = function( data, xres, yres )\n {\n mGL.readPixels(0, 0, xres, yres, mGL.RGBA, mGL.UNSIGNED_BYTE, data);\n };\n\n return me;\n}", "_setupFramebuffers(opts) {\n const {\n textures,\n framebuffers,\n maxMinFramebuffers,\n minFramebuffers,\n maxFramebuffers,\n meanTextures,\n equations\n } = this.state;\n const {weights} = opts;\n const {numCol, numRow} = opts;\n const framebufferSize = {width: numCol, height: numRow};\n for (const id in weights) {\n const {needMin, needMax, combineMaxMin, operation} = weights[id];\n textures[id] =\n weights[id].aggregationTexture ||\n textures[id] ||\n Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFloatTexture\"])(this.gl, {id: `${id}-texture`, width: numCol, height: numRow});\n textures[id].resize(framebufferSize);\n let texture = textures[id];\n if (operation === _aggregation_operation_utils__WEBPACK_IMPORTED_MODULE_3__[\"AGGREGATION_OPERATION\"].MEAN) {\n // For MEAN, we first aggregatet into a temp texture\n meanTextures[id] =\n meanTextures[id] ||\n Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFloatTexture\"])(this.gl, {id: `${id}-mean-texture`, width: numCol, height: numRow});\n meanTextures[id].resize(framebufferSize);\n texture = meanTextures[id];\n }\n if (framebuffers[id]) {\n framebuffers[id].attach({[_luma_gl_constants__WEBPACK_IMPORTED_MODULE_0___default.a.COLOR_ATTACHMENT0]: texture});\n } else {\n framebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-fb`,\n width: numCol,\n height: numRow,\n texture\n });\n }\n framebuffers[id].resize(framebufferSize);\n equations[id] = _gpu_grid_aggregator_constants__WEBPACK_IMPORTED_MODULE_2__[\"EQUATION_MAP\"][operation] || _gpu_grid_aggregator_constants__WEBPACK_IMPORTED_MODULE_2__[\"EQUATION_MAP\"].SUM;\n // For min/max framebuffers will use default size 1X1\n if (needMin || needMax) {\n if (needMin && needMax && combineMaxMin) {\n if (!maxMinFramebuffers[id]) {\n texture = weights[id].maxMinTexture || this._getMinMaxTexture(`${id}-maxMinTexture`);\n maxMinFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFramebuffer\"])(this.gl, {id: `${id}-maxMinFb`, texture});\n }\n } else {\n if (needMin) {\n if (!minFramebuffers[id]) {\n texture = weights[id].minTexture || this._getMinMaxTexture(`${id}-minTexture`);\n minFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-minFb`,\n texture\n });\n }\n }\n if (needMax) {\n if (!maxFramebuffers[id]) {\n texture = weights[id].maxTexture || this._getMinMaxTexture(`${id}-maxTexture`);\n maxFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-maxFb`,\n texture\n });\n }\n }\n }\n }\n }\n }", "blendSide(data, left) {\n let _sideLength = data.data.length\n let _sourceX = left ? 0 : this._imageWidth - BLEND\n let _sourceHeight = this._imageHeight + this._offset\n //let _sourceData = this._ctx.getImageData(0, 0, this._imageWidth, this._imageHeight + this._offset)\n let _sourceData = this._ctx.getImageData(_sourceX, 0, BLEND, _sourceHeight)\n\n let _total = 4 * _sourceHeight * BLEND\n //let _total = 4 * this._imageWidth * BLEND\n let pixels = _total;\n let _weight = 0\n let _wT = BLEND\n /*while (pixels--) {\n _sourceData.data[pixels] = Math.floor(Math.random() * 255) // _currentPixelR + _newPixelR\n //_sourceData.data[_p + 1] = 0 // _currentPixelG + _newPixelG\n //_sourceData.data[_p + 2] = 0 //_currentPixelB + _newPixelB\n //_sourceData.data[_p + 3] = 255 //_currentPixelA + _newPixelA\n }\n this._ctx.putImageData(_sourceData, 0, 0)\n return*/\n\n let i = left ? 0 : _total\n i = 0\n let l = left ? _total : 0\n l = _total\n let _a = left ? 4 : -4\n _a = 4\n for (i; i < l; i += _a) {\n let _weight = 1.\n let _roll = i % _sideLength\n _weight = i % (BLEND * 4) / (BLEND * 4)\n\n if (!left) {\n _weight = 1 - _weight\n //_weight = 0\n }\n\n let _newPixelR = Math.floor(data.data[_roll] * (1 - _weight))\n let _newPixelG = Math.floor(data.data[_roll + 1] * (1 - _weight))\n let _newPixelB = Math.floor(data.data[_roll + 2] * (1 - _weight))\n let _newPixelA = Math.floor(data.data[_roll + 3])\n\n let _currentPixelR = Math.floor(_sourceData.data[i] * _weight)\n let _currentPixelG = Math.floor(_sourceData.data[i + 1] * _weight)\n let _currentPixelB = Math.floor(_sourceData.data[i + 2] * _weight)\n let _currentPixelA = Math.floor(_sourceData.data[i + 3])\n\n _sourceData.data[i] = _newPixelR + _currentPixelR\n _sourceData.data[i + 1] = _newPixelG + _currentPixelG\n _sourceData.data[i + 2] = _newPixelB + _currentPixelB\n _sourceData.data[i + 3] = 255\n }\n /*console.log(_total, _sourceData.data.length);\n for (let i = 0; i < _wT * 4; i += 3) {\n _weight = i / _wT\n for (let j = 0; j < _sourceHeight * 4; j += 4) {\n let _p = i * j\n let _newPixelR = Math.floor(data.data[_p] * (_weight))\n let _newPixelG = Math.floor(data.data[_p + 1] * (_weight))\n let _newPixelB = Math.floor(data.data[_p + 2] * (_weight))\n let _newPixelA = Math.floor(data.data[_p + 3] * (_weight))\n\n let _currentPixelR = Math.floor(_sourceData.data[_p] * (1 - _weight))\n let _currentPixelG = Math.floor(_sourceData.data[_p + 1] * (1 - _weight))\n let _currentPixelB = Math.floor(_sourceData.data[_p + 2] * (1 - _weight))\n let _currentPixelA = Math.floor(_sourceData.data[_p + 3] * (1 - _weight))\n\n\n _sourceData.data[_p] = 255 // _currentPixelR + _newPixelR\n _sourceData.data[_p + 1] = 0 // _currentPixelG + _newPixelG\n _sourceData.data[_p + 2] = 0 //_currentPixelB + _newPixelB\n _sourceData.data[_p + 3] = 255 //_currentPixelA + _newPixelA\n }\n }*/\n this._ctx.putImageData(_sourceData, _sourceX, 0)\n }", "function BlurPostProcess(name,/** The direction in which to blur the image. */direction,kernel,options,camera,samplingMode,engine,reusable,textureType,defines,blockCompilation){if(samplingMode===void 0){samplingMode=BABYLON.Texture.BILINEAR_SAMPLINGMODE;}if(textureType===void 0){textureType=BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;}if(defines===void 0){defines=\"\";}if(blockCompilation===void 0){blockCompilation=false;}var _this=_super.call(this,name,\"kernelBlur\",[\"delta\",\"direction\",\"cameraMinMaxZ\"],[\"circleOfConfusionSampler\"],options,camera,samplingMode,engine,reusable,null,textureType,\"kernelBlur\",{varyingCount:0,depCount:0},true)||this;_this.direction=direction;_this.blockCompilation=blockCompilation;_this._packedFloat=false;_this._staticDefines=\"\";_this._staticDefines=defines;_this.onApplyObservable.add(function(effect){if(_this._outputTexture){effect.setFloat2('delta',1/_this._outputTexture.width*_this.direction.x,1/_this._outputTexture.height*_this.direction.y);}else{effect.setFloat2('delta',1/_this.width*_this.direction.x,1/_this.height*_this.direction.y);}});_this.kernel=kernel;return _this;}", "function DepthOfFieldEffect(scene,depthTexture,blurLevel,pipelineTextureType,blockCompilation){if(blurLevel===void 0){blurLevel=DepthOfFieldEffectBlurLevel.Low;}if(pipelineTextureType===void 0){pipelineTextureType=0;}if(blockCompilation===void 0){blockCompilation=false;}var _this=_super.call(this,scene.getEngine(),\"depth of field\",function(){return _this._effects;},true)||this;/**\n * @hidden Internal post processes in depth of field effect\n */_this._effects=[];// Circle of confusion value for each pixel is used to determine how much to blur that pixel\n_this._circleOfConfusion=new BABYLON.CircleOfConfusionPostProcess(\"circleOfConfusion\",depthTexture,1,null,BABYLON.Texture.BILINEAR_SAMPLINGMODE,scene.getEngine(),false,pipelineTextureType,blockCompilation);// Create a pyramid of blurred images (eg. fullSize 1/4 blur, half size 1/2 blur, quarter size 3/4 blur, eith size 4/4 blur)\n// Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts\n// See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf\n_this._depthOfFieldBlurY=[];_this._depthOfFieldBlurX=[];var blurCount=1;var kernelSize=15;switch(blurLevel){case DepthOfFieldEffectBlurLevel.High:{blurCount=3;kernelSize=51;break;}case DepthOfFieldEffectBlurLevel.Medium:{blurCount=2;kernelSize=31;break;}default:{kernelSize=15;blurCount=1;break;}}var adjustedKernelSize=kernelSize/Math.pow(2,blurCount-1);var ratio=1.0;for(var i=0;i<blurCount;i++){var blurY=new BABYLON.DepthOfFieldBlurPostProcess(\"verticle blur\",scene,new BABYLON.Vector2(0,1.0),adjustedKernelSize,ratio,null,_this._circleOfConfusion,i==0?_this._circleOfConfusion:null,BABYLON.Texture.BILINEAR_SAMPLINGMODE,scene.getEngine(),false,pipelineTextureType,blockCompilation);blurY.autoClear=false;ratio=0.75/Math.pow(2,i);var blurX=new BABYLON.DepthOfFieldBlurPostProcess(\"horizontal blur\",scene,new BABYLON.Vector2(1.0,0),adjustedKernelSize,ratio,null,_this._circleOfConfusion,null,BABYLON.Texture.BILINEAR_SAMPLINGMODE,scene.getEngine(),false,pipelineTextureType,blockCompilation);blurX.autoClear=false;_this._depthOfFieldBlurY.push(blurY);_this._depthOfFieldBlurX.push(blurX);}// Set all post processes on the effect.\n_this._effects=[_this._circleOfConfusion];for(var i=0;i<_this._depthOfFieldBlurX.length;i++){_this._effects.push(_this._depthOfFieldBlurY[i]);_this._effects.push(_this._depthOfFieldBlurX[i]);}// Merge blurred images with original image based on circleOfConfusion\n_this._dofMerge=new BABYLON.DepthOfFieldMergePostProcess(\"dofMerge\",_this._circleOfConfusion,_this._circleOfConfusion,_this._depthOfFieldBlurX,ratio,null,BABYLON.Texture.BILINEAR_SAMPLINGMODE,scene.getEngine(),false,pipelineTextureType,blockCompilation);_this._dofMerge.autoClear=false;_this._effects.push(_this._dofMerge);return _this;}", "function decodeFDCB(z80) {\n z80.incTStateCount(3);\n const offset = z80.readByteInternal(z80.regs.pc);\n z80.regs.memptr = add16(z80.regs.iy, signedByte(offset));\n z80.regs.pc = inc16(z80.regs.pc);\n z80.incTStateCount(3);\n const inst = z80.readByteInternal(z80.regs.pc);\n z80.incTStateCount(2);\n z80.regs.pc = inc16(z80.regs.pc);\n const func = decodeMapFDCB.get(inst);\n if (func === undefined) {\n console.log(\"Unhandled opcode in FDCB: \" + toHex(inst, 2));\n }\n else {\n func(z80);\n }\n}", "function BlackAndWhitePostProcess(name,options,camera,samplingMode,engine,reusable){var _this=_super.call(this,name,\"blackAndWhite\",[\"degree\"],null,options,camera,samplingMode,engine,reusable)||this;/**\n * Linear about to convert he result to black and white (default: 1)\n */_this.degree=1;_this.onApplyObservable.add(function(effect){effect.setFloat(\"degree\",_this.degree);});return _this;}", "function getAnchoBandaMinimoFSK(Fb,des) {\n B=2*(Fb+des)\n return B;\n}", "constructor (gl, fs, ins, outs, dim) {\n this.ins = ins;\n this.outs = outs;\n this.dim = dim;\n if (dim.length == 1) {\n this.w = dim[0];\n this.h = 1;\n }\n if (dim.length == 2) {\n this.w = dim[0];\n this.h = dim[1];\n }\n if (dim.length == 3) {\n this.w = dim[0]*dim[2];\n this.h = dim[1];\n }\n if (dim.length == 4) {\n this.w = dim[0]*dim[2];\n this.h = dim[1]*dim[3];\n }\n const vs = `#version 300 es\n\t\t in vec2 _V;\n\t\t void main () {gl_Position = vec4(_V*2.-1., 0, 1);}`;\n\t\tfs = `#version 300 es\n \t\t#ifdef GL_FRAGMENT_PRECISION_HIGH\n \t\t\tprecision highp float;\n \t\t#else\n \t\t\tprecision mediump float;\n \t\t#endif\n \t\t#define _U gl_FragCoord.xy;\n \t\tlayout(location = 0) out vec4 OUT0\n \t\tlayout(location = 1) out vec4 OUT1\n \t\tlayout(location = 2) out vec4 OUT2\n \t\tlayout(location = 3) out vec4 OUT3\n \t\tuniform sampler2D IN0;\n \t\tuniform sampler2D IN1;\n \t\tuniform sampler2D IN2;\n \t\tuniform sampler2D IN3;\n \t\t#define Main void main ()\n \t\tivec4 _24 (ivec2 u, ivec4 iR4D, ivec2 iR) {\n \t\t u = u%iR;\n \t\t\tint i = u.x+iR.x*u.y;\n \t\t\tivec4 v = ivec4 (\n \t\t\t\ti%iR4D.x,\n \t\t\t\t(i/iR4D.x)%iR4D.y,\n \t\t\t\t(i/(iR4D.x*iR4D.y))%iR4D.z,\n \t\t\t\ti/(iR4D.x*iR4D.y*iR4D.z)\n \t\t\t);\n \t\t\treturn v;\n \t\t}\n \t\tivec2 _42 (ivec4 v, ivec4 iR4D, ivec2 iR) {\n \t\t v = v%iR4D;\n \t\t\tint i = v.w*iR4D.x*iR4D.y*iR4D.z;\n \t\t\ti+=v.z*iR4D.x*iR4D.y;\n \t\t\ti+=v.y*iR4D.x+v.x;\n \t\t\treturn ivec2(i%iR.x,i/iR.x);\n \t\t}\n \t\t#define GET_IN0(x,iR4D,iR) texelFetch(IN0,_42(ivec4(x),iR4D,iR))\n \t\t#define GET_IN1(x,iR4D,iR) texelFetch(IN1,_42(ivec4(x),iR4D,iR))\n \t\t#define GET_IN2(x,iR4D,iR) texelFetch(IN2,_42(ivec4(x),iR4D,iR))\n \t\t#define GET_IN3(x,iR4D,iR) texelFetch(IN3,_42(ivec4(x),iR4D,iR))\n \t\tvec4 vec(float x) {return vec4(x,0,0,0);}\n \t\tvec4 vec(float x, float y) {return vec4(x,y,0,0);}\n \t\tvec4 vec(float x, float y, float z) {return vec4(x,y,z,0);}\n \t\tvec4 vec(float x, float y, float z, float w) {return vec4(x,y,z,w);}\n \t\t\n\t\t`+fs;\n this.program = this.creatProgram(gl, vs, fs);\n this.framebuffer = gl.createFramebuffer();\n gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);\n this.renderbuffer = gl.createRenderbuffer();\n this.ins = new Array(4);\n this.outs = new Array(4);\n for (let i = 0; i < 4; i++) {\n this.ins[i] = new Texture(gl, i, gl.FLOAT);\n \n this.outs[i] = new Texture(gl, 4+i, gl.FLOAT);\n gl.bindRenderbuffer(gl.RENDERBUFFER, this.renderbuffer);\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0+i, gl.TEXTURE_2D, this.outs[i].texture, 0);\n }\n if (!gl.vertexActivated) {\n gl.vertexActivated = true;\n let arr = new Float32Array([0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1]);\n let buffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer);\n gl.bufferData(gl.ARRAY_BUFFER, arr, gl.STATIC_DRAW);\n gl.useProgram(this.program);\n let attrib = gl.getAttribLocation(this.program, 'av');\n gl.enableVertexAttribArray(attrib);\n gl.vertexAttribPointer(attrib, 2, gl.FLOAT, gl.FALSE, 0, 0);\n }\n }", "function get_loadingCellShader() {\n return [\n \"#define PI 3.14159265359\",\n \"precision mediump float;uniform float time;uniform vec2 mouse;uniform vec2 resolution;mat2 rotate2d(float _angle){return mat2(cos(_angle),-sin(_angle), sin(_angle),cos(_angle));}vec3 hsv(float h, float s, float v){return mix(vec3(1.0),clamp((abs(fract( h+vec3(3.0, 2.0, 1.0)/3.0)*6.0-3.0)-1.0), 0.0, 1.0),s)*v;}float shape(vec2 p){return abs(p.x)+abs(p.y)-1.0;}void main( void ){vec2 uv=gl_FragCoord.xy/resolution.xy;vec2 pos=uv*2.0-1.0;pos.x *=resolution.x/resolution.y;pos=pos*cos(0.00005)+vec2(pos.y,-pos.x)*sin(0.00005);pos.x +=1.0;pos.y +=1.0;pos=mod(pos*\" + cellsCntX + \".0, 2.0)-1.0;uv -=vec2(0.5);pos=rotate2d( sin(time)*PI ) * pos;uv +=vec2(0.5);float c=0.05/abs(sin(0.3*shape(3.0*pos)));vec3 col=hsv(fract(0.1*time),1.0,1.0);gl_FragColor=vec4(col*c,1.0);}\"\n ];\n}", "function preload()\r\n{\r\n // Spiderman Mask Filter asset\r\n imgSpidermanMask = loadImage(\"https://i.ibb.co/9HB2sSv/spiderman-mask-1.png\");\r\n\r\n // Dog Face Filter assets\r\n imgDogEarRight = loadImage(\"https://i.ibb.co/bFJf33z/dog-ear-right.png\");\r\n imgDogEarLeft = loadImage(\"https://i.ibb.co/dggwZ1q/dog-ear-left.png\");\r\n imgDogNose = loadImage(\"https://i.ibb.co/PWYGkw1/dog-nose.png\");\r\n}", "function AugmentBroadband ( Inb, Ibb, F, exposBB, exposNB, fwBB, fwNB, outname ) {\n // setup CONSTANTS\n let k1 = exposNB/exposBB;\n let k3 = k1*fwNB/fwBB;\n\n // equations that mix narrowband into the broadband channel\n let BkgnEQ = \"Bkgn=(\"+k1+\"*\"+Ibb.id+\"-\"+Inb.id+\")/(\"+k1+\"-\"+k3+\"); \";\n let LineEQ = \"Line=max(\"+Ibb.id+\"-Bkgn, 0); \";\n let MixEQ = F+\"*Line+Bkgn; \";\n let EQ = BkgnEQ + LineEQ + MixEQ; // order dependent!!!\n\n // implement above equations in PixelMath\n var P = new PixelMath;\n P.expression = EQ;\n P.symbols = \"Inb, Ibb, F, Line, Bkgn, Mix, outname\";\n P.expression1 = \"\";\n P.expression2 = \"\";\n P.useSingleExpression = true;\n P.generateOutput = true;\n P.singleThreaded = false;\n P.optimization = true;\n P.use64BitWorkingImage = true;\n P.rescale = true;\n P.rescaleLower = 0;\n P.rescaleUpper = 1;\n P.truncate = true;\n P.truncateLower = 0;\n P.truncateUpper = 1;\n P.createNewImage = true;\n P.showNewImage = true;\n P.newImageId = outname;\n P.newImageWidth = 0;\n P.newImageHeight = 0;\n P.newImageAlpha = false;\n P.newImageColorSpace = PixelMath.prototype.Gray;\n P.newImageSampleFormat = PixelMath.prototype.SameAsTarget;\n P.executeOn(Ibb);\n\t\tvar view = View.viewById(outname);\n \treturn view;\n}", "function relabel() {\n\tlet d1 = Infinity;\n\tfor (let u = 1; u <= g.n; u++) {\n\t\tif (bloss.state(bloss.outer(u)) == +1) d1 = Math.min(d1, z[u]);\n\t}\n\tif (d1 == Infinity) d1 = 0;\n\n\tlet d2 = Infinity; let d3 = Infinity; let d4 = Infinity;\n\tlet smallOddBloss = 0; // odd blossom with smallest z[b]\n\tfor (let b = bloss.firstOuter(); b; b = bloss.nextOuter(b)) {\n\t\tif (bloss.state(b) == +1) {\n\t\t\tfor (let u = bloss.firstIn(b); u; u = bloss.nextIn(b,u)) {\n\t\t\t\tsteps++;\n\t\t\t\tfor (let e = g.firstAt(u); e; e = g.nextAt(u,e)) {\n\t\t\t\t\tlet v = g.mate(u,e); let V = bloss.outer(v);\n\t\t\t\t\tif (V == b) continue;\n\t\t\t\t\tlet sV = bloss.state(V);\n\t\t\t\t\t\t if (sV == 0) d2 = Math.min(d2, slack(e));\n\t\t\t\t\telse if (sV == 1) d3 = Math.min(d3, slack(e)/2);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (b > g.n && bloss.state(b) == -1) {\n\t\t\tif (z[b]/2 < d4) {\n\t\t\t\td4 = z[b]/2; smallOddBloss = b;\n\t\t\t}\n\t\t\tsteps++;\n\t\t}\n\t}\n\n\tlet delta = Math.min(d1,d2,d3,d4);\n\n\tif (trace) traceString += `relab(${d1} ${d2} ${d3} ${d4})`;\n\t\n\t// adjust the z values for vertices and outer blossoms\n\tfor (let u = 1; u <= g.n; u++) {\n\t\tsteps++;\n\t\tif (bloss.state(bloss.outer(u)) == +1) z[u] -= delta;\n\t\tif (bloss.state(bloss.outer(u)) == -1) z[u] += delta;\n\t}\n\n\tfor (let b = bloss.firstOuter(); b; b = bloss.nextOuter(b)) {\n\t\tsteps++;\n\t\tif (b <= g.n) continue;\n\t\tif (bloss.state(b) == +1) z[b] += 2*delta;\n\t\tif (bloss.state(b) == -1) z[b] -= 2*delta;\n\t}\n\n\tif (delta == d1) {\n\t\tif (trace) traceString += ' and finished\\n';\n\t\treturn true; // we have max weight matching\n\t}\n\n\t// now, add new even edges to q\n\tif (delta == d2 || delta == d3) {\n\t\tfor (let b = bloss.firstOuter(); b; b = bloss.nextOuter(b)) {\n\t\t\tif (bloss.state(b) == +1) add2q(b)\n\t\t\tsteps++;\n\t\t}\n\t}\n\n\tif (delta == d4) {\n\t\t// expand an odd blossom with zero z\n\t\tlet subs = bloss.expandOdd(smallOddBloss); deblossoms++;\n\t\tfor (let b = subs.first(); b; b = subs.next(b)) {\n\t\t\tif (bloss.state(b) == +1) add2q(b);\n\t\t\tsteps++;\n\t\t}\n\t\tif (trace) {\n\t\t\ttraceString += ` ${bloss.x2s(smallOddBloss)}` +\n\t\t\t\t\t\t `[${subs.toString(b => bloss.x2s(b))}]`\n\t\t}\n\t}\n\tif (trace) {\n\t\ttraceString += `\\n ${q.toString(e => g.e2s(e,0,1))}\\n`;\n\t\tlet s = bloss.trees2string(1);\n\t\tif (s.length > 2 && delta == d4) traceString += ` ${s}\\n`;\n\t\ts = bloss.blossoms2string(1);\n\t\tif (s.length > 2 && delta == d4) traceString += ` ${s}\\n`;\n\t}\n\n\treturn false;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Emit from a mesh renderer.
set MeshRenderer(value) {}
[ "get MeshRenderer() {}", "set Mesh(value) {}", "vertexToGeometry () {\n\n let prim = this.prim;\n\n let geo = this.geo; \n\n console.log( 'Mesh::vertexToGeometry()' );\n\n let vertexArr = this.vertexArr;\n\n let numVertices = vertexArr.length;\n\n let indexArr = this.indexArr;\n\n // index array doesn't need to be flattened, just clone it.\n\n let indices = this.indexArr.slice();\n\n // Initialize vertices and texCoords array need to be generated from the Vertex array.\n\n geo.vertices.data = new Array( vertexArr.length * 3 );\n\n geo.texCoords.data = new Array( vertexArr.length * 2 );\n\n let vertices = geo.vertices.data;\n\n let texCoords = geo.texCoords.data;\n\n // Write the flattened coordinate data.\n\n for ( let i = 0; i < numVertices; i++ ) {\n\n let vi = i * 3;\n\n let ti = i * 2;\n\n let vtx = vertexArr[ i ];\n\n if ( vtx ) {\n\n let c = vtx.coords;\n\n let t = vtx.texCoords;\n\n // Recover and flatten coordinate values.\n\n vertices[ vi ] = c.x;\n\n vertices[ vi + 1 ] = c.y;\n\n vertices[ vi + 2 ] = c.z;\n\n // Recover and flatten texture coordinate values.\n\n texCoords[ ti ] = t.u;\n\n texCoords[ ti + 1 ] = t.v;\n\n } else {\n\n console.warn( 'Mesh::vertexToGeometry(): no vertex in vertexArr at pos:' + i );\n\n vertices = vertices.slice( i ); // truncate to keep the vertices valid for debugging\n\n break;\n\n }\n\n }\n\n /* \n * Update our GeometryBuffer object with vertices, indices, and texture coordinates.\n * We do this directly, instead of emitting a NEW_GEOMETRY event since we are using the \n * existing geometry, without changing position, scale, etc.\n */\n\n console.log( 'Mesh::vertexToGeometry(): vertices:' + vertices.length / 3 + ' indices:' + indices.length + ' texCoords:' + texCoords.length / 2 );\n\n geo.setVertices( vertices );\n\n geo.setIndices( indices );\n\n geo.setTexCoords( texCoords );\n\n // Update normals, tangents, and colors to reflect the altered Mesh.\n\n prim.updateNormals();\n\n prim.updateTangents();\n\n prim.updateColors();\n\n //return geo.checkBufferData();\n\n }", "buildMaterials () {\n this._meshes.forEach((mesh) => {\n let material = mesh.material;\n\n let position = new THREE.PositionNode();\n let alpha = new THREE.FloatNode(1.0);\n let color = new THREE.ColorNode(0xEEEEEE);\n\n // Compute transformations\n material._positionVaryingNodes.forEach((varNode) => {\n position = new THREE.OperatorNode(\n position,\n varNode,\n THREE.OperatorNode.ADD\n );\n });\n\n let operator;\n material._transformNodes.forEach((transNode) => {\n position = getOperatornode(\n position,\n transNode.get('node'),\n transNode.get('operator')\n );\n });\n\n // Compute alpha\n material._alphaVaryingNodes.forEach((alphaVarNode) => {\n alpha = new THREE.OperatorNode(\n alpha,\n alphaVarNode,\n THREE.OperatorNode.ADD\n );\n });\n\n material._alphaNodes.forEach((alphaNode) => {\n alpha = getOperatornode(\n alpha,\n alphaNode.get('node'),\n alphaNode.get('operator')\n );\n });\n\n // Compute color\n material._colorVaryingNodes.forEach((colorVarNode) => {\n color = new THREE.OperatorNode(\n color,\n colorVarNode,\n THREE.OperatorNode.ADD\n );\n });\n\n material._colorNodes.forEach((colorNode) => {\n color = getOperatornode(\n color,\n colorNode.get('node'),\n colorNode.get('operator')\n );\n });\n\n // To display surfaces like 2D planes or iso-surfaces whatever\n // the point of view\n mesh.material.side = THREE.DoubleSide;\n\n // Set wireframe status and shading\n if (mesh.type !== 'LineSegments' && mesh.type !== 'Points') {\n mesh.material.wireframe = this._wireframe;\n mesh.material.shading = this._wireframe\n ? THREE.SmoothShading\n : THREE.FlatShading;\n } else {\n mesh.material.wireframe = false;\n // Why ?\n // mesh.material.shading = THREE.SmoothShading;\n }\n\n // Get isoColor node\n mesh.material.transform = position;\n mesh.material.alpha = alpha;\n mesh.material.color = color;\n mesh.material.build();\n });\n }", "async onMeshMessage(payload) {\n // gets the decoded packet\n let {\n username,\n pattern,\n type,\n inner_payload,\n sender\n } = this.decodePacket(payload);\n\n // debug print\n if (DEBUG) {\n console.log({\n username,\n pattern,\n type,\n inner_payload\n });\n }\n\n // login to the serial_computer\n serial_computer.write(type, Buffer.from(username));\n serial_computer.write(0, Buffer.from(String(pattern)));\n // get login success response\n let [success] = await serial_computer_received.shift();\n\n if (DEBUG) {\n console.log(`login ${success?'success':'fail'}`);\n }\n if (success) {\n // if login success, then write message payload\n serial_computer.write(0, Buffer.from(inner_payload));\n // get response\n let [sc_msg_type, msg] = await serial_computer_received.shift();\n // encode response\n let sender_byte = Buffer.from([sender, 1]);\n let msg_bytes = Buffer.from(msg);\n // send over mesh network\n mock_mesh.write(4, Buffer.concat([sender_byte, msg_bytes]));\n } else {\n // if login failed, then respond with failure message\n mock_mesh.write(4, Buffer.from([sender, 0, 0]));\n }\n }", "function setNormals(mesh) {\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.normal);\n\n gl.vertexAttribPointer(shader.faceNormal, 3, gl.FLOAT, false, 0, 0);\n gl.enableVertexAttribArray(shader.faceNormal);\n\n gl.bufferData(gl.ARRAY_BUFFER,\n MV.flatten(mesh.normals),\n gl.STATIC_DRAW);\n}", "function setVertices(mesh) {\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);\n\n gl.vertexAttribPointer(shader.position, 3, gl.FLOAT, false, 0, 0);\n gl.enableVertexAttribArray(shader.position);\n\n gl.bufferData(gl.ARRAY_BUFFER,\n MV.flatten(mesh.vertices),\n gl.STATIC_DRAW);\n}", "_defaultMeshCallback(o, linkName, meshFormat) {\n\n if (meshFormat === 'stl') {\n\n return {\n name: linkName,\n ext: 'stl',\n data: this.STLExporter.parse(o, { binary: true }),\n textures: [],\n material: {\n\n color: o.material ? o.material.color : null,\n opacity: o.material && o.material.transparent ? o.material.opacity : null,\n texture: o.material ? o.material.map : null,\n\n },\n };\n\n } else {\n\n // TODO: dedupe the textures here\n const res = this.ColladaExporter.parse(o, { textureDirectory: 'textures' });\n res.textures.forEach((tex, i) => {\n\n const newname = `${ linkName }-${ i }`;\n const nameregex = new RegExp(`${ tex.name }\\\\.${ tex.ext }`, 'g');\n\n res.data = res.data.replace(nameregex, `${ newname }.${ tex.ext }`);\n tex.name = newname;\n\n });\n\n return {\n name: linkName,\n ext: 'dae',\n data: res.data,\n textures: res.textures,\n };\n\n }\n\n }", "function createText(mesh_data) { \n \n // Duplicate the input mesh\n let mesh = Object.assign({}, mesh_data)\n\n // Convert mesh from 2d to 3d\n mesh.positions = mesh.positions.map((vec2) => {\n // Put the mesh in the XY plane; +Y is up.\n return [vec2[0], -vec2[1], 0]\n })\n \n // Wireframe it for screen-projected-lines\n mesh = wireframe(mesh)\n\n let options = {\n frag: fragRainbow,\n vert: vertWireframe,\n\n attributes: {\n position: mesh.positions,\n nextpos: mesh.nextPositions,\n direction: mesh.directions\n },\n\n elements: mesh.cells,\n\n uniforms: {\n color: [1, 1, 1, 1],\n thickness: 0.07,\n // TODO: we duplicate this matrix code, mostly\n // Use a matrix stack ripped from the documentation.\n // This is how we stick the image into our window as a function of window size.\n proj: ({viewportWidth, viewportHeight}) =>\n mat4.perspective([],\n Math.PI / 2,\n viewportWidth / viewportHeight,\n 0.01,\n 1000),\n // The model is at the center of the scene, which is not the origin. Also\n // move it up, scale it up, and rotate it to face the camera initially and\n // never be mirrored.\n model: () => {\n const t = 0.05 * now()\n \n var modelMat = mat4.rotateY([], mat4.scale([], mat4.translate([], mat4.identity([]), [25, 7, 25]), [4, 4, 4]), Math.PI / 2)\n \n // Work out rotation to use to make the text always face not backward\n if ((t + Math.PI / 2) % (2 * Math.PI) > Math.PI) {\n // We arebetween 1/4 and 3/4 through the spin\n // We need to flip around to face the camera\n modelMat = mat4.rotateY([], modelMat, Math.PI)\n }\n return modelMat\n \n },\n // This is the camera matrix. It's the spinny one from the documentation, modified to spin gooder\n // Also modified to fake text spin so we can always read it\n view: () => {\n const t = 0.05 * now()\n const radius = 25\n const height = 5\n const center = [25, 0, 25]\n return mat4.lookAt([],\n // Here is our eye\n [center[0] + radius * Math.cos(t), center[1] + height, center[2] + radius * Math.sin(t)],\n // Here is where we look\n center,\n // This is up\n [0, 1, 0])\n },\n // We alsop need the aspect ratio for screen-projected-lines\n aspect: ({viewportWidth, viewportHeight}) => {\n return viewportWidth / viewportHeight\n }\n },\n depth: {enable: false}\n }\n \n return regl(options)\n}", "function AbstractMesh(name,scene){if(scene===void 0){scene=null;}var _this=_super.call(this,name,scene,false)||this;_this._facetData=new _FacetDataStorage();/** Gets ot sets the culling strategy to use to find visible meshes */_this.cullingStrategy=AbstractMesh.CULLINGSTRATEGY_STANDARD;// Events\n/**\n * An event triggered when this mesh collides with another one\n */_this.onCollideObservable=new BABYLON.Observable();/**\n * An event triggered when the collision's position changes\n */_this.onCollisionPositionChangeObservable=new BABYLON.Observable();/**\n * An event triggered when material is changed\n */_this.onMaterialChangedObservable=new BABYLON.Observable();// Properties\n/**\n * Gets or sets the orientation for POV movement & rotation\n */_this.definedFacingForward=true;_this._visibility=1.0;/** Gets or sets the alpha index used to sort transparent meshes\n * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index\n */_this.alphaIndex=Number.MAX_VALUE;/**\n * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true\n */_this.isVisible=true;/**\n * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true\n */_this.isPickable=true;/** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */_this.showSubMeshesBoundingBox=false;/** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)\n * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares\n */_this.isBlocker=false;/**\n * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)\n */_this.enablePointerMoveEvents=false;/**\n * Specifies the rendering group id for this mesh (0 by default)\n * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups\n */_this.renderingGroupId=0;_this._receiveShadows=false;/** Defines color to use when rendering outline */_this.outlineColor=BABYLON.Color3.Red();/** Define width to use when rendering outline */_this.outlineWidth=0.02;/** Defines color to use when rendering overlay */_this.overlayColor=BABYLON.Color3.Red();/** Defines alpha to use when rendering overlay */_this.overlayAlpha=0.5;_this._hasVertexAlpha=false;_this._useVertexColors=true;_this._computeBonesUsingShaders=true;_this._numBoneInfluencers=4;_this._applyFog=true;/** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */_this.useOctreeForRenderingSelection=true;/** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */_this.useOctreeForPicking=true;/** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */_this.useOctreeForCollisions=true;_this._layerMask=0x0FFFFFFF;/**\n * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)\n */_this.alwaysSelectAsActiveMesh=false;/**\n * Gets or sets the current action manager\n * @see http://doc.babylonjs.com/how_to/how_to_use_actions\n */_this.actionManager=null;// Collisions\n_this._checkCollisions=false;_this._collisionMask=-1;_this._collisionGroup=-1;/**\n * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))\n * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity\n */_this.ellipsoid=new BABYLON.Vector3(0.5,1,0.5);/**\n * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))\n * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity\n */_this.ellipsoidOffset=new BABYLON.Vector3(0,0,0);_this._oldPositionForCollisions=new BABYLON.Vector3(0,0,0);_this._diffPositionForCollisions=new BABYLON.Vector3(0,0,0);// Edges\n/**\n * Defines edge width used when edgesRenderer is enabled\n * @see https://www.babylonjs-playground.com/#10OJSG#13\n */_this.edgesWidth=1;/**\n * Defines edge color used when edgesRenderer is enabled\n * @see https://www.babylonjs-playground.com/#10OJSG#13\n */_this.edgesColor=new BABYLON.Color4(1,0,0,1);/** @hidden */_this._renderId=0;/** @hidden */_this._intersectionsInProgress=new Array();/** @hidden */_this._unIndexed=false;/** @hidden */_this._lightSources=new Array();/**\n * An event triggered when the mesh is rebuilt.\n */_this.onRebuildObservable=new BABYLON.Observable();_this._onCollisionPositionChange=function(collisionId,newPosition,collidedMesh){if(collidedMesh===void 0){collidedMesh=null;}//TODO move this to the collision coordinator!\nif(_this.getScene().workerCollisions){newPosition.multiplyInPlace(_this._collider._radius);}newPosition.subtractToRef(_this._oldPositionForCollisions,_this._diffPositionForCollisions);if(_this._diffPositionForCollisions.length()>BABYLON.Engine.CollisionsEpsilon){_this.position.addInPlace(_this._diffPositionForCollisions);}if(collidedMesh){_this.onCollideObservable.notifyObservers(collidedMesh);}_this.onCollisionPositionChangeObservable.notifyObservers(_this.position);};_this.getScene().addMesh(_this);_this._resyncLightSources();return _this;}", "drawObject(mesh, drawShaders){\n\t\tvar ctx = this.ctx;\n\t\tctx.clear(ctx.COLOR_BUFFER_BIT | ctx.DEPTH_BUFFER_BIT);\n\t\tvar perspectiveMatrix = GlUtils.makePerspective(89.95, this.realWidth/this.realHeight, 0.1, 100.0);\n\t\tGlUtils.loadIdentity();\n\t\tGlUtils.mvPushMatrix();\n\t\tmesh.translation && GlUtils.mvTranslate(mesh.translation);\n\t\tmesh.scale && GlUtils.mvScale([mesh.scale[0],mesh.scale[1],mesh.scale[2]]);\n\t\tmesh.rotation && GlUtils.mvRotateMultiple(mesh.rotation[0], [1,0,0], mesh.rotation[1], [0,1,0]);\n\t\tctx.useProgram(this.shaderProgram);\n\t\tctx.bindBuffer(ctx.ARRAY_BUFFER, mesh.vertexBuffer);\n\t\tctx.vertexAttribPointer(this.shaderProgram.vertexPositionAttribute, mesh.vertexBuffer.itemSize, ctx.FLOAT, false, 0, 0);\n\t\tctx.bindBuffer(ctx.ARRAY_BUFFER, mesh.normalBuffer);\n\t\tctx.vertexAttribPointer(this.shaderProgram.vertexNormalAttribute, mesh.normalBuffer.itemSize, ctx.FLOAT, false, 0, 0);\n\t\tctx.bindBuffer(ctx.ARRAY_BUFFER, mesh.textureBuffer);\n\t\tctx.vertexAttribPointer(this.shaderProgram.textureCoordAttribute, mesh.textureBuffer.itemSize, ctx.FLOAT, false, 0, 0);\n\t\tctx.activeTexture(ctx.TEXTURE0);\n\t\tctx.bindTexture(ctx.TEXTURE_2D, mesh.texture);\n\t\tctx.uniform1i(this.shaderProgram.samplerUniform, 0);\n\t\tctx.uniform2fv(this.shaderProgram.screenRatio, [1.0, this.frameInfo.screenRatio]);\n\t\tdrawShaders();\n\t\tctx.bindBuffer(ctx.ELEMENT_ARRAY_BUFFER, mesh.indexBuffer);\n\t\tGlUtils.setMatrixUniforms(ctx, this.shaderProgram, perspectiveMatrix);\n\t\tctx.drawElements(ctx.TRIANGLES, mesh.indexBuffer.numItems, ctx.UNSIGNED_SHORT, 0);\n\t\tGlUtils.mvPopMatrix();\n\t}", "function drawTerrainEdges()\n{\n gl.polygonOffset(1,1);\n gl.bindBuffer(gl.ARRAY_BUFFER, tVertexPositionBuffer);\n gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, tVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);\n\n // Bind normal buffer\n gl.bindBuffer(gl.ARRAY_BUFFER, tVertexNormalBuffer);\n gl.vertexAttribPointer(shaderProgram.vertexNormalAttribute, tVertexNormalBuffer.itemSize, gl.FLOAT, false, 0, 0); \n \n //Draw \n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, tIndexEdgeBuffer);\n gl.drawElements(gl.LINES, tIndexEdgeBuffer.numItems, gl.UNSIGNED_SHORT,0); \n}", "get sharedMesh() { return this._sharedMesh; }", "function passTheColor () {\n//\tDebug.Log(\"Got in passTheColor\");\n//\tDebug.Log(inputUnit);\n\t// If inputWireUnit has a value (Mixxit, pengo, and SaraDT_)\n\tif (inputUnit != null) {\n\t\t// Debug.Log(gameObject.name + \"'s input is \" + inputUnit.name);\n\t\t// make that unit's myColor value into this unit's myColor value\n\t\tmyColor = inputUnit.gameObject.GetComponent.<ColorOfLAdjacent>().myColor;\n\t\trenderer.material.color = myColor;\n\t\t// Debug.Log(renderer.material.GetColor(\"_Color\"));\n\t}\n\n\t// If outputWire has a value\n\tif (outputUnit != null) {\n\t\tDebug.Log(gameObject.name + \"'s output is to \" + outputUnit.name);\n\t\t// make that unit run the same method\n\t\toutputUnit.GetComponent.<ColorOfLAdjacent>().passTheColor();\n\t}\n}", "initializeMeshes () {\r\n this.triangleMesh = new Mesh(this.cyanYellowHypnoMaterial, this.triangleGeometry);\r\n this.quadMesh = new Mesh(this.magentaMaterial, this.quadGeometry);\r\n\r\n // texture code\r\n this.texturedQuadMesh = new Mesh(this.texturedMaterial, this.texturedQuadGeometry);\r\n }", "translateMesh (translationVector) {\n this.vertices.forEach(arr => arr = Mesh.translateVertices(arr, translationVector))\n }", "function drawSphere() {\r\n gl.bindBuffer(gl.ARRAY_BUFFER, sphereVertexPositionBuffer);\r\n gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, sphereVertexPositionBuffer.itemSize, \r\n gl.FLOAT, false, 0, 0);\r\n\r\n // Bind normal buffer\r\n gl.bindBuffer(gl.ARRAY_BUFFER, sphereVertexNormalBuffer);\r\n gl.vertexAttribPointer(shaderProgram.vertexNormalAttribute, \r\n sphereVertexNormalBuffer.itemSize,\r\n gl.FLOAT, false, 0, 0);\r\n gl.drawArrays(gl.TRIANGLES, 0, sphereVertexPositionBuffer.numItems); \r\n}", "function LinesMesh(name,scene,parent,source,doNotCloneChildren,/**\n * If vertex color should be applied to the mesh\n */useVertexColor,/**\n * If vertex alpha should be applied to the mesh\n */useVertexAlpha){if(scene===void 0){scene=null;}if(parent===void 0){parent=null;}var _this=_super.call(this,name,scene,parent,source,doNotCloneChildren)||this;_this.useVertexColor=useVertexColor;_this.useVertexAlpha=useVertexAlpha;/**\n * Color of the line (Default: White)\n */_this.color=new BABYLON.Color3(1,1,1);/**\n * Alpha of the line (Default: 1)\n */_this.alpha=1;if(source){_this.color=source.color.clone();_this.alpha=source.alpha;_this.useVertexColor=source.useVertexColor;_this.useVertexAlpha=source.useVertexAlpha;}_this._intersectionThreshold=0.1;var defines=[];var options={attributes:[BABYLON.VertexBuffer.PositionKind,\"world0\",\"world1\",\"world2\",\"world3\"],uniforms:[\"world\",\"viewProjection\"],needAlphaBlending:true,defines:defines};if(useVertexAlpha===false){options.needAlphaBlending=false;}if(!useVertexColor){options.uniforms.push(\"color\");}else{options.defines.push(\"#define VERTEXCOLOR\");options.attributes.push(BABYLON.VertexBuffer.ColorKind);}_this._colorShader=new BABYLON.ShaderMaterial(\"colorShader\",_this.getScene(),\"color\",options);return _this;}", "function sendDataViaTexture(gl, uniformLocation, uniformName, floatArray) {\n var texture = createDataTexture(gl, floatArray),\n textureUnit = 0;\n \n gl.activeTexture(gl.TEXTURE0 + textureUnit);\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.uniform1i(uniformLocation, textureUnit);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Feed Page: Renders contents of the Feed page on the Feed Tab for SpeedScore web app Designed as a functional component.
function FeedPage() { return ( <div id="feedModeTab" className="mode-page" role="tabpanel" aria-label="Feed Tab" tabIndex="0"> <h1 className="mode-page-header">Activity Feed</h1> <p className="mode-page-content">This page is under construction.</p> <img className="mode-page-icon" src={logo} alt="SpeedScore logo"></img> </div> ); }
[ "function displayFeedsUrlList() {\n const message = document.getElementById(\"feedsUrlMessage\");\n const headers = {\"Authorization\": getToken()};\n apiRequest(\"GET\", \"get_feeds_url.php\", null, headers, res => {\n const jsonRes = JSON.parse(res.responseText);\n for (const feed of jsonRes.feeds)\n addFeedUrlToList(feed.id, feed.url);\n message.innerHTML = \"\";\n message.className = \"\";\n }, err => handleRequestError(err.status, \"Erreur lors de la récupération des flux.\", message)\n );\n}", "render () {\n let contents = this.state.loading\n ? <p><em>Loading...</em></p>\n : FetchData.renderForecastsTable(this.state.forecasts);\n\n return (\n <div>\n <h1>Weather forecast</h1>\n <p>This component demonstrates fetching data from the server.</p>\n {contents}\n </div>\n );\n }", "fetch() {\n this._client.get(`/sales-channel-api/v1/sns/instagramfeed?media=${this.options.count}`, (responseText) => {\n this.el.outerHTML = responseText;\n });\n }", "function initializeArticleFeed() {\n\tvar feeds = document.querySelectorAll('[data-content-type=\\'cdp-article-feed\\']');\n\tforEach(feeds, function (index, feed) {\n\t\trenderArticleFeed(feed);\n\t});\n}", "function renderUserFeed(userPosts, mainDiv) {\n userPosts.sort(function (a, b) {\n return b.meta.published - a.meta.published;\n });\n for (let i = 0; i < userPosts.length; i++) {\n let section = document.createElement('section');\n section.setAttribute('id', userPosts[i].id + '-post');\n section.setAttribute('class', 'post');\n let h2 = document.createElement('h2');\n h2.textContent = userPosts[i].meta.author;\n h2.setAttribute('id', userPosts[i].id + '-post-title');\n h2.setAttribute('class', 'post-title');\n section.appendChild(h2);\n let date = new Date(userPosts[i].meta.published * 1000);\n let dateStr = date.toString();\n let datestr = document.createElement('p');\n datestr.textContent = dateStr.substring(0, 24);\n datestr.setAttribute('id', userPosts[i].id + '-post-published');\n datestr.setAttribute('class', 'post-published');\n section.appendChild(datestr);\n let img = document.createElement('img');\n img.setAttribute('id', userPosts[i].id + '-post-image');\n img.setAttribute('src', 'data:image/png;base64,' + userPosts[i].src);\n img.setAttribute('alt', userPosts[i].meta.description_text);\n img.setAttribute('class', 'post-image');\n section.appendChild(img);\n let post_description = document.createElement('p');\n post_description.textContent = userPosts[i].meta.description_text;\n post_description.setAttribute('id', userPosts[i].id + '-post-description_text');\n post_description.setAttribute('class', 'post-description_text');\n section.appendChild(post_description)\n let like = document.createElement('span');\n like.textContent = '❤ ' + userPosts[i].meta.likes.length;\n like.setAttribute('id', userPosts[i].id + '-post-like');\n like.setAttribute('class', 'post-likes');\n section.appendChild(like)\n let comment = document.createElement('span');\n comment.textContent = '💬 ' + userPosts[i].comments.length;\n comment.setAttribute('id', userPosts[i].id + '-post-comment-count');\n comment.setAttribute('class', 'post-comments-count');\n section.appendChild(comment)\n if (userPosts[i].comments.length > 0) {\n let show_comment = document.createElement('span');\n show_comment.textContent = '+';\n show_comment.setAttribute('id', userPosts[i].id + '-post-show-comment');\n show_comment.setAttribute('class', 'post-show-comments');\n section.appendChild(show_comment)\n } else {\n let show_comments = document.createElement('span');\n show_comments.textContent = '+';\n show_comments.setAttribute('id', userPosts[i].id + '-post-show-comment');\n show_comments.setAttribute('class', 'post-show-comments');\n show_comments.style.display = 'none';\n section.appendChild(show_comments);\n }\n let hide = document.createElement('span');\n hide.textContent = '-';\n hide.setAttribute('id', userPosts[i].id + '-post-hide-comment');\n hide.setAttribute('class', 'post-hide-comments');\n hide.style.display = 'none';\n section.appendChild(hide);\n mainDiv.appendChild(section);\n }\n}", "function publishStory() {\n FB.ui({\n method: 'feed',\n name: 'Test',\n caption: 'Restaurant',\n description: 'Tasty restaurant',\n link: 'http://apps.facebook.com/mobile-start/',\n picture: 'http://www.facebookmobileweb.com/hackbook/img/facebook_icon_large.png',\n actions: [{ name: 'Get Started', link: 'http://apps.facebook.com/mobile-start/' }],\n }, \n function(response) {\n alert('successfully posted to FB page and wall');\n });\n}", "function GADGET_RSS_Entry_Open(Entry)\n{\t\n\t//>> Clear Timers\n\tif (Timer_Interval)\n\t\tclearTimeout(Timer_Interval);\n\t\n\tif (Timer_Auto_Scroll)\n\t\tclearTimeout(Timer_Auto_Scroll);\n\n\t//>> Get Variables\n\t\t\n\tvar\tDisplay = \"Browser\";\n\tvar\tEntry_Disp = \"5\";\n\t\t\n\tvar Size = System.Gadget.Settings.read(\"Size\");\n\t\n\tSystem.Gadget.Settings.write(\"Entry_Open\", Entry);\n\t\n\t//>> Reset Current Entry Styles\n\t//var Entry_Count = parseInt(System.Gadget.document.getElementById(\"Entry_Count\").innerHTML);\n\tvar Entry_Count = parseInt(noOfFeeds);\n\tvar Page = System.Gadget.Settings.read(\"Page\");\n\t\n\tvar i = (Page * Entry_Disp) - Entry_Disp;\n\tvar Limit = Page * Entry_Disp;\n\tif (Limit > Entry_Count)\n\t\tLimit = Entry_Count;\n\t\t\n\twhile (i < Limit)\n\t{\n\t\tSystem.Gadget.document.getElementById(\"Feed_Entry_\" + i).className = Size + \"-Feed-Entry\";\n\t\tSystem.Gadget.document.getElementById(\"Feed_Entry_\" + i + \"_Close\").style.display = \"none\";\n\t\ti++;\n\t}\n\t\n\n\t\tvar xURL = System.Gadget.document.getElementById(\"Entry_\" + Entry + \"_Link\").innerHTML;\n\t\t\n\t\tvar\tInterval = 60;\n\t\t\t\n\t\tif (Interval != '' && Interval != \"Off\")\n\t\t{\n\t\t\tInterval = Interval * 60000;\n\t\t\tTimer_Interval = setTimeout(GADGET_RSS_Feed_Start, Interval);\n\t\t}\n\t\t\n\t\tvar Auto_Scroll = System.Gadget.Settings.read(\"Auto_Scroll\");\n\t\tif (Auto_Scroll == '')\n\t\t\tAuto_Scroll = 20;\n\t\t\n\t\tif (Auto_Scroll != '' && Auto_Scroll != \"Off\")\n\t\t{\n\t\t\tAuto_Scroll = Auto_Scroll * 1000;\n\t\t\tTimer_Auto_Scroll = setTimeout(GADGET_RSS_Auto_Scroll, Auto_Scroll);\n\t\t}\n\t\t\n\t\tShell.Run(xURL);\t\t\n\t//}\n}", "function themeFeedEntry(entry) {\n\t\tclasses = [ 'entry', 'well' ];\n\t\tif (new Date(entry.publishedDate).isToday()) {\n\t\t\tclasses.push('today');\n\t\t}\n\t\toutput = '<div class=\"' + classes.join(' ') + '\">';\n\t\toutput += '<h2 class=\"title\"><a href=\"' + entry.link + '\" data-eid=\"' + entry.eid + '\" rel=\"external\" target=\"_blank\">' + entry.title + '</a></h2>';\n\t\toutput += '<h2><small>' + entry.author + '</small></h2>';\n\t\toutput += '<p><small>' + entry.publishedDate + '</small></p>';\n\t\toutput += '<p>' + entry.contentSnippet + '</p>';\n\t\toutput += '<p><small>Tagged under ' + entry.categories.join(', ') + '</small></p>';\n\t\toutput += '<div class=\"actions\"><a class=\"btn twitter-share-button\" href=\"http://twitter.com/intent/tweet?text=' + encodeURIComponent(entry.title + ' ' + entry.link) + '&related=pennolson,amarnus\">Share on Twitter</a></div>';\n\t\toutput += '</div>';\n\t\treturn output;\n\t}", "function PostDetailsMain() {\n return (\n <div>\n <div className=\"row mt-5\">\n <h3 className=\"text-align-center text-dark font-weight-bold\">Post Data</h3>\n </div>\n <table className=\"table mt-5\">\n <thead className=\"thead-dark\">\n <tr>\n <th scope=\"col\">URL</th>\n <th scope=\"col\">Post Type</th>\n <th scope=\"col\">Date</th>\n <th scope=\"col\">Hashtags</th>\n <th scope=\"col\">Mentions</th>\n <th scope=\"col\">Preset</th>\n <th scope=\"col\">Compensation</th>\n </tr>\n </thead>\n {/* <PostDetails /> */}\n </table>\n </div>\n )\n}", "static feedPath() {\n return '/api/v1/feed/timeline/'\n }", "function FeedSummary(props) {\n\t var children = props.children,\n\t className = props.className,\n\t content = props.content,\n\t date = props.date,\n\t user = props.user;\n\t\n\t\n\t var classes = (0, _classnames2.default)('summary', className);\n\t var rest = (0, _lib.getUnhandledProps)(FeedSummary, props);\n\t var ElementType = (0, _lib.getElementType)(FeedSummary, props);\n\t\n\t if (!_lib.childrenUtils.isNil(children)) {\n\t return _react2.default.createElement(\n\t ElementType,\n\t (0, _extends3.default)({}, rest, { className: classes }),\n\t children\n\t );\n\t }\n\t\n\t return _react2.default.createElement(\n\t ElementType,\n\t (0, _extends3.default)({}, rest, { className: classes }),\n\t (0, _lib.createShorthand)(_FeedUser2.default, function (val) {\n\t return { content: val };\n\t }, user),\n\t content,\n\t (0, _lib.createShorthand)(_FeedDate2.default, function (val) {\n\t return { content: val };\n\t }, date)\n\t );\n\t}", "function render(msg)\n{\n document.getElementById('feeds').innerHTML = msg;\n}", "generateHTML() {\n return `<div class='aside-container aside-recent-posts'>\n <h4>${this.recentPostsSection.title}</h4>\n <div class=\"recent-posts\">\n ${this.generateRecentPosts()}\n </div>\n </div>`;\n }", "async function readAfeed() {\n let rssService = new RssService(process.env.MICRO_API_TOKEN);\n let rsp = await rssService.feed({\n name: \"bbc\",\n });\n console.log(rsp);\n}", "function loadOnScreen(){\n\tHeadingArray = getOnScreenHeadingArray();\n URLArray = getOnScreenURLArray();\n\t\n\tfor(var i = 0; i<HeadingArray.length; i++)\n\t getFeed(HeadingArray[i],URLArray[i]);\n}", "function _getTrendFeeds() {\n\n let query = {\n tag: 'steemovie',\n limit: 21,\n };\n\n steem.api.getDiscussionsByTrending(query, function (err, result) {\n app.trend_feeds = result;\n\n // Rendering process of image image\n trend_renderingImagePaths(result)\n });\n\n}", "async function fillWholePage(){\n const webpageHeight = document.body.offsetHeight;\n const windowHeight = window.innerHeight;\n if(windowHeight >= webpageHeight){\n await addContent(endPoint.movieCollectionURL(currentCategory,page++));\n fillWholePage();\n }\n}", "function rssFeed()\n{\n print( \"<?xml version=\\\"1.0\\\"?>\\n\" );\n print( \"<rss version=\\\"2.0\\\">\\n\" );\n print( \"\\t<channel>\\n\" );\n title = config.GENERAL.TITLE;\n print( \"\\t\\t<title>title</title>\\n\" );\n url = \"http://\"+_SERVER.SERVER_NAME._SERVER.SCRIPT_NAME;\n print( \"\\t\\t<link>\"+url+\"</link>\\n\" );\n print( \"\\t\\t<description>Recently changed pages on the title wiki.</description>\\n\" );\n print( \"\\t\\t<generator>Wiki v\"+config.PAWFALIKI_VERSION+\"</generator>\\n\" ); \n files = wikiReadDir(pageDir());\n details = [];\n for( i = 0 ; i < files.length ; i++ ){\n file = files[i];\n details[file] = FILE.filedate( file );\n }\n //arsort(details);\n //reset(details);\n item = 0;\n numItems = config.RSS.ITEMS;\n while ( list(key, val) = each(details) ) \n {\n title = basename(key);\n modtime = date( config.RSS.MODTIME_FORMAT, val );\n description = title+\" \"+modtime;\n print( \"\\t\\t<item>\\n\" );\n if (config.RSS.TITLE_MODTIME) \n print( \"\\t\\t\\t<title>description</title>\\n\" );\n else\n print( \"\\t\\t\\t<title>title</title>\\n\" );\n print( \"\\t\\t\\t<link>\"+url+\"?page=title</link>\\n\" ); \n print( \"\\t\\t\\t<description>\"+description+\"</description>\\n\" );\n print( \"\\t\\t</item>\\n\" ); \n item++;\n if (numItems!=-1&&item>=numItems)\n break;\n }\n print( \"\\t</channel>\\n\" );\n print( \"</rss>\\n\" );\n}", "function GADGET_RSS_Feed_End()\n{\n\tif (Feed_Http.readyState == null)\n\treturn;\n\t\n\tif (Feed_Http.readyState == 4) \n\t{\t\n\t\tif (Feed_Http.status == 200 && Feed_Http.responseText != '') \n\t\t{\t\t\t\n\t\t\t//>> Load Feed\n\t\t\tvar Feed = Feed_Http.responseXML;\n\t\t\tUTIL_XML_Load(Feed);\n\t\t\t\n\t\t\t//>> Parse Feed Into Containers\n\t\t\tvar i = 0;\n\t\t\tvar xString1 = '';\n\t\t\t\n\t\t\tvar xFile = XML_Doc.getElementsByTagName(\"rss\")[0];\n\t\t\tvar xFile_Item = xFile.getElementsByTagName(\"item\");\n\t\t\t\n\t\t\txString1 += '<div id=\"Entry_Count\">' + xFile_Item.length + '</div>';\n\t\t\t\n\t\t\twhile (i < xFile_Item.length)\n\t\t\t{\n\t\t\t\tvar xFile_Post = xFile_Item[i];\n\t\t\t\t\n\t\t\t\txString1 += '<div id=\"Entry_' + i + '\">';\n\t\t\t\txString1 += '<div id=\"Entry_' + i + '_Title\">' + xFile_Post.getElementsByTagName(\"title\")[0].text + '</div>';\n\t\t\t\txString1 += '<div id=\"Entry_' + i + '_Description\">' + xFile_Post.getElementsByTagName(\"description\")[0].text + '</div>';\n\t\t\t\txString1 += '<div id=\"Entry_' + i + '_Link\">' + xFile_Post.getElementsByTagName(\"link\")[0].text + '</div>';\n\t\t\t\txString1 += '<div id=\"Entry_' + i + '_Date\">' + xFile_Post.getElementsByTagName(\"pubDate\")[0].text + '</div>';\n\t\t\t\txString1 += '</div>';\t\t\t\t\n\t\t\t\ti++;\n\t\t\t}\n\t\t\tnoOfFeeds=i;\n\t\t\txString3 = xString1;\n\t\t\t//System.Gadget.document.getElementById(\"Gadget-Feed\").innerHTML = xString1;\n\t\n\t\t\tsecondFeed();\n\t\t\t\n\t\t}\t\t\t\n\t\telse\n\t\t{\n\t\t\tvar xString = '<br /><img src=\"../Images/BG/BG-Fail.png\" /><br /><strong>Connection Error</strong>';\n\t\t\txString += '<br /><div id=\"Button-Retry\" title=\"Retry?\" onclick=\"GADGET_RSS_Retry();\"></div>';\n\t\t\tSystem.Gadget.document.getElementById(\"Sec-Feed\").innerHTML = xString;\n\t\t}\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a default dashboards in user collection
function createDefaultDashboards(createUser, finalCallback) { async.waterfall([ function(wCallback) { // in other way, find can be find({collection: 'default'}) or find({collection: {$in: ['default']}}) Dashboard.find({"default": true, "creatorRole":"BP"}) .populate("widgets.widget") .lean() .sort("-__v") .exec(wCallback); }, function(findDashboards, wCallback) { async.each(findDashboards, function(dashboard, eCallback) { createNewDefaultDashboard(createUser,dashboard,eCallback); }, function(err){ if(err) { wCallback("Error occurred", null); } else { wCallback(null, createUser); } }); } ], function (err) { if(err) { finalCallback(err, null); } else { finalCallback(null, createUser); } }); }
[ "function DashboardCollection(data, group) {\n var self = [];\n self.$add = DashboardCollection.prototype.$add;\n Object.defineProperty(self, '$add', {\n enumerable: false,\n writable: false\n });\n self.$findDashboard = DashboardCollection.prototype.$findDashboard;\n Object.defineProperty(self, '$findDashboard', {\n enumerable: false,\n writable: false\n });\n self.applyDiff = DashboardCollection.prototype.applyDiff;\n Object.defineProperty(self, 'applyDiff', {\n enumerable: false,\n writable: false\n });\n self.group = group;\n Object.defineProperty(self, 'group', {\n enumerable: false,\n writable: true\n });\n self.push.apply(self, _.map(data, function(d) {\n return new Dashboard(d, group);\n }));\n return self;\n }", "constructor() { \n \n Dashboard.initialize(this);\n }", "function loadDashboard() {\n loadReservations();\n loadTables();\n }", "function createDashboardPanel(el) {\n var title = el.dataset.title;\n var elementId = el.dataset.id;\n\n var elementExists = $('#' + elementId);\n if (!elementExists) {\n var panel = document.createElement(\"div\");\n panel.setAttribute(\"id\", elementId);\n\n panel.classList.add('panel');\n panel.classList.add('panel-default');\n\n var panelHeader = document.createElement(\"div\");\n panelHeader.classList.add('panel-heading');\n\n var panelTitle = document.createElement(\"div\");\n panelTitle.classList.add('panel-title');\n panelTitle.innerText = title;\n\n var deleteIcon = document.createElement(\"i\");\n deleteIcon.classList.add('far');\n deleteIcon.classList.add('deleteIcon');\n deleteIcon.classList.add('fa-trash-alt');\n deleteIcon.classList.add('fa-fw');\n deleteIcon.classList.add('pull-right');\n deleteIcon.setAttribute('title', 'Remove Item');\n panelTitle.appendChild(deleteIcon);\n\n panelHeader.appendChild(panelTitle);\n\n panel.appendChild(panelHeader);\n\n var panelBody = document.createElement(\"div\");\n panelBody.classList.add('panel-body');\n\n panel.appendChild(panelBody);\n return panel;\n }\n}", "function getDashboard(labels, visible) {\n\tvar dashboard = Ti.UI.createDashboardView({\n\t\teditable: false,\n\t\ttop: 5,\n\t\tvisible: visible\n\t}),\n\n\tdata = [], i;\n\t\n\tif(Utils.isiPad()) {\n\t\tdashboard.rowCount = 5;\n\t\tdashboard.columnCount = 4;\n\t\tdashboard.top = 15;\n\t\tdashboard.height = Ti.UI.FILL;\n\t} else if(Ti.Platform.displayCaps.platformHeight < 568) {\n\t\tdashboard.rowCount = 3;\n\t\tdashboard.height = 350;\n\t} else {\n\t\tdashboard.rowCount = 4;\n\t\tdashboard.height = 430;\n\t}\n\n\t//iterate through the labels and add corresponding items to the dashboard\n\tfor(i = 0; i < labels.length; i++) {\n\t\tdata.push(getItem(labels[i]));\n\t}\n\n\tdashboard.setData(data);\n\t\n\t//when we click, this should happen\n\tdashboard.addEventListener('click', function(e) {\n\t\tif(e.item !== null) {\n\t\t\tRequestHandler.callMultiKeys(e.item.channel.toString());\n\t\t}\n\t});\n\n\treturn dashboard;\n}", "function getDashboardsByUser(currentUser, findNameMask, finalCallback) {\n var params = {$and: []};\n\n if(findNameMask) {\n params.$and.push(\n {title : new RegExp(findNameMask, \"i\")}\n );\n }\n\n permissionsUtils.getAppObjectByUser(currentUser, Dashboard, consts.APP_ENTITY_TYPE.DASHBOARD, params, \n function(err, foundDashboards, findUserTags, findObjectTags) {\n if(err) {\n finalCallback(err, null);\n } else {\n finalCallback(null, getDashboardsByCollection(foundDashboards));\n }\n });\n\n}", "function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"error: page dashboard => custom controller\");\n\t\t\tconsole.log(e);\n\t\t}\n\t}", "async function initUserStore() {\n console.log('Initiliazing user base...');\n (await slack.users.list()).members\n .filter(user => !user.deleted && !user.is_bot && !user.is_restricted)\n .forEach(async user => {\n const userRef = store.collection('users').doc(user.id);\n if (!(await userRef.get()).exists) {\n console.info(`[USER ADDED] ${user.id} : ${user.name}`);\n userRef.set({ ...user, score: 1, availablePoints: 0 });\n }\n });\n console.log('Done initializing');\n}", "function createDashboardFolderAndSave(savedDashboard, callback) {\n var awsAssetsKeyPrefix = utils.generateRandomString(16);\n getDashboardsByParams({awsAssetsKeyPrefix : awsAssetsKeyPrefix}, function (searchErr, searchResult) {\n if(searchErr) {\n callback(searchErr);\n }\n else {\n if(searchResult.length > 0) {\n awsAssetsKeyPrefix += utils.generateRandomString(4);\n }\n savedDashboard.awsAssetsKeyPrefix = awsAssetsKeyPrefix;\n savedDashboard.save(function (saveDashboardErr, updatedDashboard) {\n if (saveDashboardErr) {\n callback(saveDashboardErr, null);\n } else {\n callback(null, updatedDashboard);\n }\n });\n }\n });\n \n}", "create(req, res) {\n const userId = req.param('userId');\n\n if(req.token.id !== userId) {\n return res.fail('You don\\'t have permission to do this.');\n }\n\n const allowedParams = [\n 'type', 'name', 'context', 'uuid'\n ];\n\n const applianceData = lodash.pick(req.body, allowedParams);\n ApplianceService.createForUser(userId, applianceData)\n .then(res.success)\n .catch(res.fail);\n }", "getAllAdmins() {\n return this.getUserSets('ADMIN');\n }", "function _getListDashboardsForFlyout() {\n var listDashboards = DashboardsHelper.listDashboards.slice();\n listDashboards.splice(0, 0, { \"title\": _ALL_DASHBOARDS, \"id\": _ALL });\n // capitalise dashboards list\n for (var count = 0; count < listDashboards.length; count++) {\n listDashboards[count].title = CDHelper.capitaliseOnlyFirstLetter(listDashboards[count].title);\n };\n for (var count = 0 ; count < listDashboards.length; count++) {\n if (CockpitHelper.currentDashboard.id == listDashboards[count].id) {\n listDashboards.splice(count, 1);\n return listDashboards;\n }\n }\n return listDashboards;\n }", "function initUsers(userlist) {\n let online = document.getElementById('online');\n let offline = document.getElementById('offline');\n\n userlist.map(user => {\n let li = document.createElement('li');\n li.innerText = user.name;\n\n if (user.active) {\n online.appendChild(li);\n } else {\n offline.appendChild(li);\n }\n })\n}", "function createAdmin(callback) {\n AccessToken.destroyAll( function(err) {\n if (err) return callback(err);\n\n RoleMapping.destroyAll( function(err) {\n if (err) return callback(err);\n\n Roles.destroyAll( function(err) {\n if (err) return callback(err);\n\n Roles.create({\n name: 'admin'\n }, function(err, role) {\n if (err) return callback(err);\n //console.log('Created role:', role.name);\n\n role.principals.create({\n principalType: RoleMapping.USER,\n principalId: users.admin.username\n }, function(err, principal) {\n if (err) return callback(err);\n\n //console.log('Created principal:', principal.principalType);\n callback();\n });\n });\n });\n });\n });\n }", "function initUserData(){\n try{\n if(GLOBALS) {\n GLOBALS.userdata = GLOBALS.service.getUserData();\n } else {\n GLOBALS = {\n userdata: {}\n };\n }\n } catch(er){\n console.log(er);\n }\n\n // temporary - setting up sample userdata for view, if no userdata is present\n if (!(GLOBALS.userdata)) {\n GLOBALS.userdata = {\n meta: {\n title: \"Task Management App\"\n },\n list: [\n {\n _id: \"\",\n name: \"My Task List\",\n modified: \"\",\n cards: [\n {\n task:\"Explore Features\",\n description: \"verify features of app\",\n tags: ['inprocess'],\n users: ['qa'],\n completed: false\n },\n {\n task:\"New Features\",\n description: \"implement new app features\",\n tags: ['new','p2'],\n users: ['developer'],\n completed: false\n }\n ]\n }\n ]\n };\n }\n }", "function printDashboard(userObj) {\n console.log(userObj);\n}", "function getDashboardsByCollection(dashboards) {\n var collections = [];\n for(var i=0; i < dashboards.length; i++) {\n collections = _.union(collections, dashboards[i].collections);\n }\n\n var result = {};\n\n for(i=0; i < collections.length; i++) {\n var thisCollection = collections[i];\n result[thisCollection] = filterDashboardsByCollection(dashboards, thisCollection);\n }\n\n return result;\n}", "createNewCollection(){\n // return this.db.createCollection(name)\n }", "async function createUI() {\n const infectedHosts = await getInfectedHosts();\n infectedHosts.forEach(async (host) => {\n const payloads = await getPayloads(host);\n\n const hostDiv = createHostDiv();\n const hostLink = createHostLink(host);\n\n hostDiv.append(hostLink);\n $(\"#infected_hosts\").append(hostDiv);\n\n payloads.forEach(async (payloadObject) => {\n const userPayloadsDiv = createUserPayloadsDiv();\n const userPayloadsLink = createUserPayloadsLink(payloadObject);\n\n userPayloadsDiv.append(userPayloadsLink);\n\n const payload = await getPayload(host, payloadObject['payload_id']);\n\n const payloadDataDiv = $(\"<pre class=\\\"payload\\\"></pre>\");\n payloadDataDiv.append(payload);\n const containerDiv = $(\"<div class=\\\"container\\\"></div>\");\n containerDiv.css(\"display\", \"none\");\n containerDiv.append(userPayloadsDiv);\n containerDiv.append(payloadDataDiv);\n hostDiv.append(containerDiv);\n });\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
deleteUser to delete a bucket given its id.
function deleteUser(req, res) { User.remove({_id : req.params.id}, (err, result) => { res.json({ message: "Bucket successfully deleted!", result }); }); }
[ "deleteUser( id ) {\n fluxUserManagementActions.deleteUser( id );\n }", "function deleteUser(event) {\n let id = getUserId(event.target);\n fetch(url+\"/api/users/\"+id, {\n method: \"DELETE\",\n headers: {\n \"authorization\": jwt\n }\n }).\n then((response) => {\n if (response.ok) {\n updateStateAndRefresh(\"User \" + id + \" has been deleted.\", true);\n }\n else {\n updateStateAndRefresh(\"User \" + id + \" not deleted!\", false);\n }\n });\n}", "function userDelete(id, cb){\n User.findByIdAndDelete(id, function (err, user) {\n if (err) {\n if (cb) cb(err, null)\n return\n }\n console.log('Deleted User: ' + user);\n if (cb) cb(null, user)\n });\n}", "deleteUser (id, username, password) {\n return apiClient.deleteUser(storage.getToken(), id, username, password)\n }", "async function deleteUser(userId) {\n await fetch(`/api/users/${userId}`, {\n method: 'DELETE'\n });\n\n // Re-fetch users after deleting\n fetchUsers()\n }", "static deleteAction(userId, groupId){\n\t\tlet kparams = {};\n\t\tkparams.userId = userId;\n\t\tkparams.groupId = groupId;\n\t\treturn new kaltura.RequestBuilder('groupuser', 'delete', kparams);\n\t}", "function deleteUser(id) {\n // if it is NOT the same id return a list of all the users without that ID\n const updatedUsers_forDelete = usersInDanger_resc.filter(user => user.userID !== id);\n const deletedUser = usersInDanger_resc.filter(user => user.userID === id);\n setUsersInDanger_resc(updatedUsers_forDelete);\n console.log(deletedUser[0].userID);\n props.markSafe(deletedUser[0].userID);\n }", "deleteCardByUserIdWalletId(userId, walletId) {\n return http.delete(`/wallet/${userId}/${walletId}`);\n }", "function DeleteUser(id) {\n\tvar confirmed = confirm(\"Are you sure you want to remove this user?\");\n\t\n\tif (confirmed) {\n\t\t// We could make an AJAX call here. That goes a little beyond what is expected in CIT 336.\n\t\t// Instead, let's redirect them through some other actions.\n\t\twindow.location = '/?action=deleteuser&id=' + id;\n\t}\t\n}", "async delete(req, res) {\n try {\n //get user\n let user = await users.findOne({where: {username : req.params.username}})\n let user_id = user.id\n let tagList = await Tags\n .findAll({\n where: { tag: { [Op.in]: req.body.tags } }\n })\n await TagToUser\n .destroy({\n where: {\n user_id: user_id,\n tag_id: { [Op.in]: tagList.map(tag => tag.id) }\n }\n })\n .then(() => res.status(200).send({ message: \"tag deleted from user\" }))\n\n }catch(error){\n res.status(400).send()\n }\n }", "function deleteGrant(id) {\n return db(\"grants\").where({ id }).del();\n}", "removeUserFromGroup (id, userId) {\n assert.equal(typeof id, 'number', 'id must be number')\n assert.equal(typeof userId, 'number', 'userId must be number')\n return this._apiRequest(`/group/${id}/user/${userId}`, 'DELETE')\n }", "function deleteUser(req, res, next) {\n //Check if the id is valid and exists in db\n \n Users.findOne({\"_id\": req.query.id},\n\n function(err, result) {\n if (err){\n console.log(err);\n\n } \n //console.log(result);\n //If the user exists, delete the user and his/her reviews\n if(result){\n //Remove the user from the db\n Users.remove({\"_id\": req.query.id}, function(err, result){\n res.status(200);\n res.json({message: 'Accounts and Reviews Deleted!'});\n });\n\n //Remove all the users reviews\n Reviews.remove({\"userID\": req.query.id}, function(err, result){\n //res.json({message: 'Reviews Deleted!'});\n });\n \n\n \n } else { //return 404 status if userid does not exist\n res.status(404);\n return res.json({ error: 'Invalid: User does not exist' });\n }\n }); \n\n}", "async onClick(){\n const user = this.props.user;\n const response = await this.deleteUser(user);\n this.props.removeUser(user.id);\n }", "function delTag(req, res) {\n var errorCallback = function(err) {\n res.send({error: 'Unable to delete tag.'});\n };\n\n Model('findOne', {_id: req.params.id}, function(user) {\n // find the index of the tag to remove\n var tagIndex = user.tags.indexOf(decodeURI(req.params.tag));\n\n // check if tag was actually found then remove it\n if (tagIndex !== -1) {\n user.tags.splice(tagIndex, 1);\n }\n\n user.save(function(errSave) {\n if(errSave) {\n errorCallback();\n }\n\n res.send({success: 'Successfully deleted tag!'});\n });\n }, errorCallback);\n}", "admin_remove_user(user_id) {\n if (Roles.userIsInRole(Meteor.userId(), ['admin'])) {\n Meteor.users.remove(user_id);\n return \"OK\";\n }else { return -1; }\n }", "function deleteUserid(ev)\n{\n var iu = this.id.substring(\"delete\".length);\n var userid = document.getElementById('User' + iu).value;\n if (debug.toLowerCase() == 'y')\n {\n alert(\"Users.js: deleteUserid: {\\\"user name\\\"=\" + userid + \"}\");\n }\n var cell = this.parentNode;\n var row = cell.parentNode;\n var inputs = row.getElementsByTagName('input');\n for (var i = 0; i < inputs.length; i++)\n {\n var elt = inputs[i];\n var name = elt.name;\n var matches = /^([a-zA-Z_$@#]*)(\\d*)$/.exec(name);\n var column = matches[1].toLowerCase();\n var id = matches[2];\n elt.type = 'hidden';\n if (column == 'auth')\n {\n elt.value = '';\n }\n }\n this.form.submit();\n}", "static deleteUser(req, res) {\n return __awaiter(this, void 0, void 0, function* () {\n const { id } = req.params;\n try {\n yield User_1.default.findOneAndDelete({ _id: id });\n res.status(200).json({\n message: \"The user has been deleted\"\n });\n }\n catch (e) {\n res.status(500).json({ message: \"an internal error has been ocurred\" });\n }\n });\n }", "removeUser(userId) {\n for (let user of this.getUsers()) {\n if (user._id === userId) {\n this.users.splice(this.users.indexOf(user), 1);\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is called when the instance is stopped. It removes the listeners for termination events.
_stopListeningForTermination() { this._terminationEvents.forEach((eventName) => { process.removeListener(eventName, this._terminate); }); }
[ "_terminate() {\n if (this._instance) {\n this._instance.close();\n this._instance = null;\n this._stopListeningForTermination();\n this._options.onStop(this);\n }\n\n process.exit();\n }", "stopListening() {\n this._eventsNames.forEach((eventName) => {\n process.removeListener(eventName, this.handler);\n });\n }", "stop(){\n\t\tvar priv = PRIVATE.get(this);\n\t\tpriv.messenger.stopListenAll();\n\t\tpriv.messenger.disconnect();\n\t\tif (typeof priv.syncCrtlQProducer !== \"undefined\")\n\t\t{\n\t\t\tpriv.syncCrtlQProducer.shutdown();\n\t\t}\n\t\t\n\t\tlogger.info(\"stopped listening to channels\");\n\t}", "function notifyApplicationStopped() {\n if (!_isApplicationRunning) {\n return;\n }\n\n _isApplicationRunning = false;\n applicationEventListeners.forEach(function (listener) {\n listener('stopped');\n });\n}", "_startListeningForTermination() {\n this._terminationEvents.forEach((eventName) => {\n process.on(eventName, this._terminate);\n });\n }", "_destroy() {\n\t\tthis.workspaces_settings.disconnect(this.workspaces_names_changed);\n\t\tWM.disconnect(this._ws_number_changed);\n\t\tglobal.display.disconnect(this._restacked);\n\t\tglobal.display.disconnect(this._window_left_monitor);\n\t\tthis.ws_bar.destroy();\n\t\tsuper.destroy();\n\t}", "onShutdown() {\n this.particleSystems.forEach( e => e.dispose() );\n this.particleSystems.clear();\n }", "function stop_monitoring()\n {\n browser.idle.onStateChanged.removeListener(on_idle_state_change);\n }", "_destroyObservers() {\n this.observerList.forEach(observer => observer.destroy() );\n this.observerList = [];\n }", "function destroy() {\n\t\t\t// Iterate over each matching element.\n\t\t\t$el.each(function() {\n\t\t\t\t$el.removeData('breakpointEvents');\n\t\t\t});\n\t\t}", "destroy(callback) {\n const connections = Object.keys(this.namespace.connected);\n\n\n let self = this;\n this.print(`Disconnecting all sockets`);\n connections.forEach((socketID) => {\n this.print(`Disconnecting socket: ${socketID}`);\n self.namespace.connected[socketID].disconnect();\n });\n\n this.print(`Removing listeners`);\n this.namespace.removeAllListeners();\n callback(this.endpoint);\n }", "function _destroyLeaveAlertListener() {\n window.removeEventListener(\"beforeunload\", _leaveAlertEvent);\n }", "function destroy() {\n parent.removeEventListener(\"mousedown\", onDown);\n document.querySelector(\"body\").removeEventListener(\"mouseup\", onUp);\n parent.removeEventListener(\"mousemove\", onMove);\n console.log(\" ======== draggables destryed =========\");\n }", "dispose() {\n this.context = null;\n\n // remove all global event listeners when component gets destroyed\n window.removeEventListener('message', this.sendUpdateTripSectionsEvent);\n }", "destroy() {\n this.map.off('dragging', this.listenDragging, this);\n this.map.off('dragend', this.listenDragEnd, this);\n this.customLayer.setMap(null);\n }", "function stop (cb) {\n got.post(killURL, { timeout: 1000, retries: 0 }, (err) => {\n console.log(err ? ' Not running' : ' Stopped daemon')\n\n debug(`removing ${startupFile}`)\n startup.remove('hotel')\n\n cb()\n })\n}", "async stop () {\n if (this.status !== ServerStatus.OFFLINE &&\n this.status !== ServerStatus.STOPPING) {\n await this.container.stop();\n }\n }", "destroy() {\n if (this._destroyed) {\n throw new RuntimeError(404 /* RuntimeErrorCode.PLATFORM_ALREADY_DESTROYED */, ngDevMode && 'The platform has already been destroyed!');\n }\n this._modules.slice().forEach(module => module.destroy());\n this._destroyListeners.forEach(listener => listener());\n const destroyListeners = this._injector.get(PLATFORM_DESTROY_LISTENERS, null);\n if (destroyListeners) {\n destroyListeners.forEach(listener => listener());\n destroyListeners.clear();\n }\n this._destroyed = true;\n }", "function removeListeners() {\n removeEventListener('pointerup', onPointerUp, listenerOpts);\n removeEventListener('pointercancel', onPointerCancel, listenerOpts);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
pass this to the locationPicker component to change the selected day and call the API accordingly
selectLocation(selectedLocation){ this.callAPI(selectedLocation) }
[ "function changeDay(){\n $(date_picker).val($(this).data('day'));\n}", "function handleDay(e) {\n\t\tsetDay(e.target.value)\n\t}", "function clickDay() {\n let oldSelected = document.querySelector(\".selectedDayTile\");\n if (oldSelected != null) {\n oldSelected.classList.remove(\"selectedDayTile\");\n }\n this.classList.add(\"selectedDayTile\");\n let d = f(this.textContent);\n let monthYear = $(\"selectedMonth\").textContent.split(\" \");\n let month = f(String(monthNames.indexOf(monthYear[0]) + 1));\n let display = month + \" / \" + d + \" / \" + monthYear[1];\n $(\"selectedDate\").textContent = display;\n date = monthYear[1] + \"-\" + month + \"-\" + d;\n\n // populate time picker with available times for this day, then make\n // time section appear\n // first clear old hours\n $(\"amTable\").textContent = \"\";\n $(\"pmTable\").textContent = \"\";\n loadHours(date);\n $(\"timeContainer\").style.display = \"block\";\n }", "function updateChosenDate(inputDate){\n setChosenDate(inputDate);\n }", "_onDayDblTap() {\n this.execute();\n }", "setTodayDate(date) {\n let todayDate = new Date(+date);\n this.setProperties({ value: todayDate }, true);\n super.todayButtonClick(null, todayDate, true);\n }", "async changeState(cal) {\n this.setState({ chosenCal: cal });\n localStorage.setItem(\"chosenCalendar\", cal);\n this.getCalendarEvents(cal);\n }", "onSelect() {\n var currentDay = new Date($(\"#datepicker\").datepicker(\"getDate\"));\n getScore.get({\n yearNum: $(\"#datepicker\").datepicker(\"getDate\").getFullYear(),\n monthNum: (\"0\" + ($(\"#datepicker\").datepicker(\"getDate\").getMonth() + 1)).slice(-2),\n dayNum: (\"0\" + $(\"#datepicker\").datepicker(\"getDate\").getDate()).slice(-2)\n }, function(res) {\n $scope.scoreboards = updateScore(res);\n }, function() {\n $('.server-message').attr(\"style\", \"display: block\");\n });\n }", "function chooseDay(dir) {\n\t$.ajax({\n\t\turl: \"ServiceDaysServlet\",\n\t\tdataType: 'json',\n\t\tdata: {\n\t\t\trouteNumber: routeNumber,\n\t\t\tdirection: dir\n\t\t},\n\t\tsuccess: function(data) {\n\t\t\tselectDay(data);\n\t\t\t$(\"#leftDivInfo\").empty();\n\t\t\tgetTrips(dir);\n\t\t},\n\t\terror: function() {\n\t\t\talert(\"Κάτι πήγε στραβά παρακαλώ δοκιμάστε ξανά\");\n\t\t}\n\t});\n}", "function processChange(value) {\n //console.log(\"Calendar clicked\");\n //If we are working with the start input\n if(cntrl.getStartCal()) {\n cntrl.setSelectedStartDate(value); \n }\n //If we are working with the end input\n else {\n cntrl.setSelectedEndDate(value);\n }\n //Autoclose after selection\n cntrl.updateDateRange();\n }", "function updateState() {\n\t\t\tvar state = {\n\t\t\t\tday : scope.day,\n\t\t\t\tdriverName : scope.selectedDriverRun && scope.selectedDriverRun.driverName,\n\t\t\t\tstartRun : scope.selectedDriverRun && scope.selectedDriverRun.startRun,\t\t\t\t\n\t\t\t\tstore : scope.store\n\t\t\t};\t\n\t\t\t_.chain(state).extend(scope.mapOptions);\n\t\t\tparent.history.pushState(state, 'driverrun', '?' + jQuery.param(state));\n\t\t}", "function getVal(e)\n{\n //lert(document.getElementById(e.id).value);\n day = document.getElementById(e.id).value;\n var date = year +\"/\"+ (currPage + 1) + \"/\" + day ;\n document.getElementById(\"fdate\").value = date;\n loadTimePicker(getTimesNotAvailableFor(date));\n\n \n}", "function selectLocation(){\r\n currentlySelectedGridId = getRiskAddtlExposureListGrid();\r\n var xmlData = getXMLDataForGridName(currentlySelectedGridId);\r\n var addtlExpAddrId = xmlData.recordset(\"CADDRESSID\").value;\r\n if(isEmpty(addtlExpAddrId)){\r\n addtlExpAddrId = -1;\r\n }\r\n var selAddrUrl = getAppPath() + \"/policymgr/selectAddress.do?\" + commonGetMenuQueryString() + \"&type=RISK\"\r\n + \"&entityId=\" + xmlData.recordset(\"CRISKENTITYID\").value\r\n + \"&riskBaseRecordId=\" + xmlData.recordset(\"CRISKBASERECORDID\").value\r\n + \"&riskStatus=\" + xmlData.recordset(\"CRISKSTATUS\").value\r\n + \"&isFromExposure=Y&addtlExpAddrId=\"+addtlExpAddrId;\r\n var divPopupId = getOpenCtxOfDivPopUp().openDivPopup(\"\", selAddrUrl, true, true, \"\", \"\", 600, 500, \"\", \"\", \"\", false);\r\n}", "selectPublishedAt(day = 'past') {\n repoBlogForm.getFieldParentOf(repoBlogForm.getPublishedAtInput()).click();\n\n if (day === 'today') {\n repoDatePicker.getDatePickerToday().click();\n\n } else if (day === 'past') {\n repoDatePicker.getDatePickerPrevMonth().click();\n repoDatePicker.getDatePickerStartOfMonth().click();\n\n } else {\n repoDatePicker.getDatePickerNextMonth().click();\n repoDatePicker.getDatePickerEndOfMonth().click();\n }\n }", "function selectLocation(value) {\n value = value.toUpperCase();\n for (let i = 0; i < markers.length; i++) {\n const marker = markers[i];\n if (marker.name.toUpperCase() == value) {\n marker.getElement().click();\n map.flyTo([marker.getLatLng().lat, marker.getLatLng().lng], 10);\n }\n }\n}", "function datePickerHook() {\n $('.select-options li').each(function () {\n $(this).on('click', function () {\n let startMonth = document.getElementById('date-range--start-month')\n .value\n let startYear = document.getElementById('date-range--start-year').value\n let endMonth = document.getElementById('date-range--end-month').value\n let endYear = document.getElementById('date-range--end-year').value\n const facetDate = document.getElementsByClassName(\n 'facetwp-facet-publish_date'\n )[0]\n\n facetDate.querySelectorAll('.fs-option').forEach(function (el) {\n const startDate = new Date(startYear, startMonth, 1)\n const endDate = new Date(endYear, endMonth, 1)\n const elDate = new Date(\n el.getAttribute('data-value').slice(0, 4),\n el.getAttribute('data-value').slice(4, 6) - 1,\n 1\n )\n if (elDate >= startDate && elDate <= endDate) {\n el.click()\n }\n })\n })\n })\n }", "function changeDate(date)\n{\nmodalPicker = require('ui/common/helpers/modalPicker');\nmodalPicker = new modalPicker(Ti.UI.PICKER_TYPE_DATE,null,date.text); \n\nif(Titanium.Platform.osname == 'iphone') modalPicker.open();\nif(Titanium.Platform.osname == 'ipad') modalPicker.show({ view: date, });\n\n\n\tvar picker_closed = function() {\n\t\tif(modalPicker.result) { \n\t\t\tvar newDate = modalPicker.result.toDateString();\n\t\t\tdate.text = newDate;\n\t\t\tactivateSaveButton();\n\t\t}\n\t};\n\t\n\tif(Titanium.Platform.osname == 'iphone') modalPicker.addEventListener('close', picker_closed);\n\tif(Titanium.Platform.osname == 'ipad') modalPicker.addEventListener('hide', picker_closed);\n}", "setActiveLocation(location, showDataEntry) {\n let countryInfo = this.queryFeatures([location.lng, location.lat], this.refs.country.leafletElement);\n let countryFeature = (countryInfo && countryInfo.length > 0) ? countryInfo[0].feature : null;\n this.refs.map.leafletElement.panTo({lat: location.lat, lng: location.lng});//center the map at point\n Actions.invoke(Constants.ACTION_POPUP_INFO, {\n locationFeature: {\n properties: location\n },\n countryFeature,\n 'position': [location.lat, location.lng],\n 'showDataEntry': showDataEntry\n })\n }", "rangeCurrentHoveredDay (newHoveredDay) {\n if (!newHoveredDay) return;\n this.$emit('update-hovered-day', newHoveredDay);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
continuously create new child streams, calling handler on active
function substreamOnActive(parentStream, opts, handler) { const delay = opts.delay const next = createSubstreamer(parentStream, opts) setupListeners() function setupListeners () { let childStream = next() onStreamActive(parentStream, () => handler(childStream)) onStreamIdle(parentStream, delay, () => setupListeners()) } }
[ "function onStreamActive(stream, handler) {\n stream.once('data', handler)\n}", "function startStream (response) {\n\n\tchild.send('start'); \n\n\tresponse.writeHead(200, {\"Content-Type\": \"text/json\"});\n\tresponse.end('{\"status\":\"ok\"}');\n}", "EnumerateStreams() {\n\n }", "_next() {\n if (!this._current) {\n if (!this._streams.length) {\n this._enabled = false;\n return this.end();\n }\n this._current = new stream.Readable().wrap(this._streams.shift());\n this._current.on('end', () => {\n this._current = null;\n this._next();\n });\n this._current.pipe(this, { end: false });\n }\n }", "register(stream) {\n const streamState = new StreamInfo(stream);\n stream.on('end', this._streamEnd(streamState));\n stream.on('data', this._streamData(streamState));\n this._streams.push(streamState);\n this._ensureActiveTask();\n }", "_startEventStreams() {\n let commandService = this.getService('core', 'commandService');\n\n // Create a stream for all the Discord events\n Object.values(Discord.Constants.Events).forEach((eventType) => {\n let streamName = eventType + '$';\n this.streams[streamName] =\n Rx.Observable\n .fromEvent(\n this.discord,\n eventType,\n function (...args) {\n if (args.length > 1) {\n return args;\n }\n return args[0];\n },\n );\n this.logger.debug(`Created stream nix.streams.${streamName}`);\n });\n\n // Create Nix specific event streams\n this.streams.command$ =\n this.streams.message$\n .filter((message) => message.channel.type === 'text')\n .filter((message) => commandService.msgIsCommand(message));\n\n // Apply takeUntil and share to all streams\n for (let streamName in this.streams) {\n this.streams[streamName] =\n this.streams[streamName]\n .do((data) => this.logger.silly(`Event ${streamName}: ${data}`))\n .takeUntil(this.shutdown$)\n .share();\n }\n\n let eventStreams = Rx.Observable\n .merge([\n ...Object.values(this.streams),\n this.streams.guildCreate$.flatMap((guild) => this.onNixJoinGuild(guild)),\n this.streams.command$.flatMap((message) => commandService.runCommandForMsg(message)),\n ])\n .ignoreElements();\n\n return Rx.Observable.of('').merge(eventStreams);\n }", "function spawnCreated(data) {\n // Handler for direct messages from child\n handlerCreate({\n name: 'helloHandler',\n channel: listenChannel,\n message: 'hello',\n ents: [data.ent]\n });\n\n // Let's talk back to the child\n directMessage({\n ent: data.ent,\n channel: listenChannel,\n message: 'hello',\n data: {\n channel: listenChannel,\n color: favoriteColor,\n number: favoriteNumber\n }\n });\n}", "createStream (callback) {\n\t\tlet data = {\n\t\t\ttype: 'channel',\n\t\t\tname: RandomString.generate(10),\n\t\t\tteamId: this.team.id,\n\t\t\tmemberIds: [this.userData[1].user.id]\n\t\t};\n\t\tthis.apiRequest(\n\t\t\t{\n\t\t\t\tmethod: 'post',\n\t\t\t\tpath: '/streams',\n\t\t\t\tdata: data,\n\t\t\t\ttoken: this.userData[0].accessToken\t// first user creates the team\n\t\t\t},\n\t\t\t(error, response) => {\n\t\t\t\tif (error) { return callback(error); }\n\t\t\t\tthis.stream = response.stream;\n\t\t\t\tcallback();\n\t\t\t}\n\t\t);\n\t}", "function queueHandler(){\n\t\t//Copy queue and clear it\n\t\tif (addQueue.length == 0) return; //Exit queue handling if the queue is empty. Saving time and some memory\n\t\tvar currentQueue = [];\n\t\tfor (var i = 0; i < addQueue.length; i++){\n\t\t\tcurrentQueue.push(addQueue[i]);\n\t\t}\n\t\taddQueue = [];\n\t\t//Count current instance folders. Create the one that should follow\n\t\tvar folders = fs.readdirSync(torInstancesFolder);\n\t\tvar newFolderName = path.join(torInstancesFolder, 'tor-' + (folders.length + 1).toString()); //Index + 1\n\t\tfs.mkdirSync(newFolderName);\n\t\tvar thsDataFolderName = path.join(newFolderName, 'ths-data');\n\t\tfs.mkdirSync(thsDataFolderName);\n\t\tvar configFilePath = path.join(thsDataFolderName, 'ths.conf');\n\t\tfs.writeFileSync(configFilePath, JSON.stringify({services: currentQueue, bridges: bridges, transports: transports}, null, '\\t'));\n\n\t\tfor (var i = 0; i < currentQueue.length; i++){\n\t\t\tglobalServiceList.push(currentQueue[i]);\n\t\t}\n\t\tsaveConfig();\n\n\t\tvar spawnCount = 0;\n\n\t\tvar torErrorHandler = torProcessOptionsObj ? torProcessOptionsObj.torErrorHandler : undefined;\n\t\tvar torMessageHandler = torProcessOptionsObj ? torProcessOptionsObj.torMessageHandler : undefined;\n\t\tvar torControlMessageHandler = torProcessOptionsObj ? torProcessOptionsObj.torControlMessageHandler : undefined;\n\t\tvar torCommand = torProcessOptionsObj ? torProcessOptionsObj.torCommand : undefined;\n\n\t\tfunction spawnTor(){\n\t\t\tspawnCount++;\n\t\t\tif (spawnCount >= 10){\n\t\t\t\t//If errors happen 10 times in a row, stop spawning\n\t\t\t\tconsole.error('Queue mode deactivated in ths-pool. Please investigate the errors');\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tvar socksPort;\n\n\t\t\tif (socksDistribution.length > 0){\n\t\t\t\tsocksPort = socksDistribution[0];\n\t\t\t\tdrawControlAndSpawn();\n\t\t\t} else {\n\t\t\t\tgetRandomPort(function(err, _socksPort){\n\t\t\t\t\tif (err){\n\t\t\t\t\t\tconsole.error('Error while getting a random port: ' + err);\n\t\t\t\t\t\tspawnTor();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tsocksPort = _socksPort\n\t\t\t\t\tdrawControlAndSpawn();\n\t\t\t\t});\n\n\t\t\t}\n\n\t\t\tfunction drawControlAndSpawn(){\n\t\t\t\tgetRandomPort(function(err, controlPort){\n\t\t\t\t\tif (err){\n\t\t\t\t\t\tconsole.error('Error while getting a random port: ' + err);\n\t\t\t\t\t\tspawnTor();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (socksPort == controlPort){\n\t\t\t\t\t\tspawnTor();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (socksDistribution.length > 0){\n\t\t\t\t\t\tsocksDistribution.splice(0, 1);\n\t\t\t\t\t}\n\n\t\t\t\t\tvar torInstance = new ths(newFolderName, socksPort, controlPort, torErrorHandler, torMessageHandler, torControlMessageHandler, keysFolder);\n\t\t\t\t\tif (torCommand) torInstance.setTorCommand(torCommand);\n\t\t\t\t\ttorInstance.start(true, function(){\n\t\t\t\t\t\ttorProcesses.push(torInstance);\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tspawnTor();\n\t}", "function cycleStream(){\n //push the numbres to the array\n cycleCount_Array.push(cycleCount);\n cycleFollow_Array.push(cycleFollow);\n cycleFollow = cycleFollow / cycleCount;\n //check to see that there has been an increase if not then send 0\n if(typeof cycleFollow === 'undefined' || cycleFollow === null){\n cycleFollow = 0;\n }\n //emit this even\n io.sockets.emit('cycle',{count: cycleCount, follow: cycleFollow});\n //reset the numbers back to 0\n cycleCount = cycleFollow = 0;\n //loop the data\n setTimeout(function(){\n cycleStream();\n },5000);\n}", "gr(t) {\n return e => {\n this.Oe.enqueueAndForget(() => this.sr === t ? e() : (k(\"PersistentStream\", \"stream callback skipped by getCloseGuardedDispatcher.\"), Promise.resolve()));\n };\n }", "async function onProcMsg(msg) {\n msg = msg.toString()\n\n // log the stdout line\n this.logLine(msg)\n\n /* \n * STREAMLINK EVENTS\n */\n\n // Handle Streamlink Events: No stream found, stream ended\n\n REGEX_NO_STREAM_FOUND.lastIndex = 0\n REGEX_NO_CHANNEL.lastIndex = 0\n REGEX_STREAM_ENDED.lastIndex = 0\n\n if (REGEX_NO_STREAM_FOUND.test(msg)) {\n ipcServer.ipcSend(\n 'streamlink-event',\n Result.newError(\n `${msg}`,\n '@ StreamlinkInstance stdout'\n )\n )\n\n streamManager.closeStream(this.channelName)\n .catch(console.error)\n return\n \n }\n\n if (REGEX_NO_CHANNEL.test(msg)) {\n ipcServer.ipcSend(\n 'streamlink-event',\n Result.newError(\n `${msg}`,\n '@ StreamlinkInstance stdout'\n )\n )\n\n streamManager.closeStream(this.channelName)\n .catch(console.error)\n return\n }\n\n if (REGEX_STREAM_ENDED.test(msg)) {\n // send streamlink event on stream end event.\n // disabled for now; don't want a toast notification every\n // time a player is closed.\n //\n // ipcServer.ipcSend(\n // 'streamlink-event',\n // Result.newOk(`Stream ${this.channelName} closed`)\n // )\n\n ipcServer.ipcSend('streamlink-stream-closed', this.channelName)\n\n streamManager.closeStream(this.channelName)\n .catch(console.error)\n return\n }\n\n // Handle Streamlink Event: Invalid quality\n\n // match invalid quality option message.\n // use the available qualities list that is printed by streamlink to\n // decide on & launch the closest available stream quality to the user's preference.\n // eg. if available stream qualities are [480p, 720p, 1080p] and user's preference\n // is set to '900p', we'll look through the list, find that 720p is the\n // closest without going over, and attempt to launch at that quality instead of\n // failing to open anything.\n REGEX_STREAM_INVALID_QUALITY.lastIndex = 0\n if (REGEX_STREAM_INVALID_QUALITY.test(msg)) {\n // first, close the existing stream instance\n streamManager.closeStream(this.channelName)\n .catch(console.error)\n\n \n // match available qualities line\n // index 0 is the full match - contains both of the following groups\n // index 1 is group 1, always the string \"Available streams: \"\n // index 2 is group 2, string list of qualities. eg:\n // \"audio_only, 160p (worst), 360p, 480p, 720p60, etc...\"\n REGEX_AVAILABLE_QUALITIES.lastIndex = 0\n let availableQualMatch = REGEX_AVAILABLE_QUALITIES.exec(msg)\n\n // this shouldnt happen, but if it does, for now just fail\n if (availableQualMatch == null) {\n console.error('Err: availableQualMatch is null or undefined; no available quality options to choose from')\n return\n }\n\n // full match (string list of qualities) lives at index 2\n // turn it into an array of quality strings.\n // eg ['audio_only', '160p (worst)', '360p', '480p', '720p60', etc...]\n let availableStrs = availableQualMatch[2].split(', ')\n\n // build arrays of resolutions and framerates out of each quality string.\n // framerates default to 30 if not specified (eg a quality string of '480p'\n // will be represented in the arrays as [480] [30] - the indices will line up)\n let availableResolutions = []\n let availableFramerates = []\n\n availableStrs.forEach(qual => {\n // return the resolution string (match array index 0) if a match is found,\n // otherwise use the number 0 for the resolution and framerate if no match is found.\n\n // This is to turn things like 'audio_only' into an integer that we can easily ignore later,\n // but lets us keep the length and indicies of the availableResolutions array the\n // same as availableStrs so they line up as expected (as we'll need to access data\n // from availableStrs later).\n\n // match resolution string (and framerate string, if available) from quality string.\n // if match is null, no resolution or framerate were found.\n // match index 0 holds resolution string, index 1 holds framerate.\n // \n // example matches:\n // 'audio_only' -> null\n // '480p' -> ['480']\n // '1080p60' -> ['1080', '60']\n let m = qual.match(REGEX_NUMBERS_FROM_QUALITY_STR)\n\n // quality string contains no numbers, default resolution and framerate to 0.\n // we still store values for these unwanted qualities so the indices and\n // lengths of the arrays line up when we read from them later.\n if (m == null) {\n availableResolutions.push(0)\n availableFramerates.push(0)\n return\n }\n\n // match index 0: resolution string is a number\n // convert to int and store in resolutions array\n availableResolutions.push(parseInt(m[0]))\n\n // match index 1: framerate - if exists, convert to int and store; otherwise store 0.\n // unspecified framerate here can probably be assumed to be 30, but use 0 instead; same\n // effect when comparing.\n availableFramerates.push(m[1] ? parseInt(m[1]) : 0)\n })\n\n // get int versions of user's preferred resolution (retrieved from preferences or passed to instance open() call)\n let preferredResInt = parseInt(this.quality.match(REGEX_NUMBERS_FROM_QUALITY_STR)[0])\n let preferredFpsInt = parseInt(this.quality.match(REGEX_NUMBERS_FROM_QUALITY_STR)[1])\n\n // now that we've got an array of available qualities, we int compare our preferred quality\n // against each and determine the closest available option, which we then use when launching the stream.\n //\n // loop over in reverse order (highest to lowest quality) and compare each to preference.\n // Choose the first quality option that's lower than or equal to preferred.\n for (let i = availableResolutions.length - 1; i >= 0; i--) {\n // if target resolution is lower, open stream\n //\n // if target resolution is the same, make sure framerate is lower.\n // This is to avoid, for example, opening a 1080p60 stream if user's\n // preference is 1080p30, while still opening 1080p30 if the preference\n // is 1080p60 (and 1080p60 isnt available for the stream in question).\n // We will still open higher framerates at a lower fps; 720p60 will open when\n // the user preference is 1080p30 if it's the next lowest available quality.\n //\n // We're conservative to avoid poor performance or over-stressing\n // user's machine when they don't want to.\n \n // skip indices of resolution 0\n if (availableResolutions[i] === 0) continue\n if (\n // open this quality if resolution is lower than preference\n availableResolutions[i] < preferredResInt ||\n // open this quality if resolution is the same and fps is lower\n (availableResolutions[i] === preferredResInt &&\n availableFramerates[i] <= preferredFpsInt)\n ) {\n // the index of the current loop through availableResolutions will\n // correspond to the correct quality string in availableStrs\n let newQual = availableStrs[i].split(' ')[0]\n streamManager.launchStream(this.channelName, newQual)\n .catch(console.error)\n return\n }\n }\n\n // if we got here, no qualities could be used.\n // default to \"best\".\n //\n // this is in a timeout, as otherwise the newly opened process closes itself immediately. not sure why yet. \n setTimeout(() => {\n console.log('Could not find a suitable quality that is <= preferred. Defaulting to \"best\".')\n streamManager.launchStream(this.channelName, 'best')\n .catch(console.error)\n }, 1000) // 1 second\n }\n}", "function setupStreams() {\n // setup communication to page and plugin\n var pageStream = new LocalMessageDuplexStream({\n name: 'nifty-contentscript',\n target: 'nifty-inpage'\n });\n var pluginPort = extension.runtime.connect({ name: 'contentscript' });\n var pluginStream = new PortStream(pluginPort);\n\n // forward communication plugin->inpage\n pump(pageStream, pluginStream, pageStream, function (err) {\n return logStreamDisconnectWarning('DefiMask Contentscript Forwarding', err);\n });\n\n // setup local multistream channels\n var mux = new ObjectMultiplex();\n mux.setMaxListeners(25);\n\n pump(mux, pageStream, mux, function (err) {\n return logStreamDisconnectWarning('DefiMask Inpage', err);\n });\n pump(mux, pluginStream, mux, function (err) {\n return logStreamDisconnectWarning('DefiMask Background', err);\n });\n\n // connect ping stream\n var pongStream = new PongStream({ objectMode: true });\n pump(mux, pongStream, mux, function (err) {\n return logStreamDisconnectWarning('DefiMask PingPongStream', err);\n });\n\n // connect phishing warning stream\n var phishingStream = mux.createStream('phishing');\n phishingStream.once('data', redirectToPhishingWarning);\n\n // ignore unused channels (handled by background, inpage)\n mux.ignoreStream('provider');\n mux.ignoreStream('publicConfig');\n}", "function touchActivePidFile() {\n var stream = fs.createWriteStream(parent_dir + \"/db/pids/active_pids.txt\");\n stream.write(JSON.stringify({}, null, 2));\n stream.end();\n }", "streamHandshakeHandler(msg) {\n\n // Also his only role is to receive the message and log it. It doesn't even\n // do anything useful with it. Gods what a stupid handler.\n console.log(JSON.parse(msg.data));\n\n let start_msg = {\n \"client_id\": this.id,\n \"rover_id\": this.currentRoverId,\n \"cmd\": \"start\"\n };\n\n this.sendStreamMsg(start_msg);\n\n this.player = new jsmpeg(this.stream_socket, {canvas: this.canvas, autoplay: true});\n\n // Call the onopen as if nothing happened\n this.player.initSocketClient.bind(this.player)(null);\n }", "function eventLoop() {\n\tgetState()\n\tif (++updateCount % 5 == 0) {\n\t\t$.post(\"/browse\", {method: \"get-queue-contents\"}, onQueue, \"json\");\n\t}\n}", "_ensureActiveTask() {\n if (!this._activeStream) {\n const stream = this._findActiveTaskCandidate();\n this._activeStream = stream;\n // In some cases there may be no streams which we can make active\n if (stream) {\n this._writeTaskBuffer(stream);\n }\n }\n }", "consumeLogs () {\n try {\n this.tail = new Tail(this.logPath)\n } catch (err) {\n console.log('Error while opening log file.', err)\n return\n }\n\n console.log(`Ready to consume new logs from ${this.logPath} file.`)\n\n this.tail.on('line', (line) => {\n console.log('New log:', line)\n this.update(line)\n })\n\n this.tail.on('error', (error) => {\n console.log('Error during log parsing', error)\n })\n\n // Summary of most hit section, runs every 10 seconds\n setInterval(() => {\n this.summarizeTraffic()\n }, this.SUMMARY_INTERVAL * 1000)\n }", "async _startProcessing() {\n for (let i = 0; i < this._width; ++i) {\n let session = await this._reserve(i);\n this._processContinuously(session);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles user clicks on the period label.
currentPeriodClicked() { this.calendar.currentView = this.calendar.currentView == 'month' ? 'multi-year' : 'month'; }
[ "function displayPeriod() {\n \n if (checkStandard()) {\n $('#time-period').text(getPeriod());\n } else {\n $('#time-period').empty();\n }\n }", "function doManualClick()\n{\n // Clear interval\n if( interval != null )\n {\n clearInterval( interval ); \n interval = null;\n }\n \n // Make look old\n comfort.asof.innerHTML = 'As of the Last 30 Days'; \n \n // Hide sine wave\n // Show plot dot\n comfort.plot.setAttribute( 'opacity', 1 );\n comfort.chart.setAttribute( 'd', 'M0 0' ); \n comfort.chart.setAttribute( 'opacity', 0 ); \n \n kaazing = false;\n \n // Highlight selected interval\n setSelectedControlButton( '.refresh' ); \n}", "function processChange(value) {\n //console.log(\"Calendar clicked\");\n //If we are working with the start input\n if(cntrl.getStartCal()) {\n cntrl.setSelectedStartDate(value); \n }\n //If we are working with the end input\n else {\n cntrl.setSelectedEndDate(value);\n }\n //Autoclose after selection\n cntrl.updateDateRange();\n }", "_onDayDblTap() {\n this.execute();\n }", "function handleClick(){\n sanitizeDateInput();\n sanitizeDepDateInput();\n }", "function OnTimeSliderClick()\n{\n\t\n\tnDomain = DVD.CurrentDomain;\n\tif (nDomain == 2 || nDomain == 3) \n\t\treturn;\n\n\tlTitle = DVD.CurrentTitle;\n\ttimeStr = GetTimeSliderBstr();\n\n\tDVD.PlayAtTimeInTitle(lTitle, timeStr);\n\tDVD.PlayForwards(DVDOpt.PlaySpeed);\n}", "function attachDayClickHandler() {\n $('.' + settings.classDay)\n // add 'selected day' styling\n .on('click', function(event) {\n $('.' + settings.classDay).removeClass('active');\n $(event.target).addClass('active');\n })\n // display events for day\n .on('click', function(event) {\n const $target = $(event.target);\n const eventYear = $target.data('year');\n const eventMonth = $target.data('month');\n const eventDay = $target.data('day');\n displayEventsForDay(settings.classEvent, eventYear, eventMonth, eventDay);\n });\n}", "function evtRoutine1( sender, parms )\n {\n var rtn = Lansa.evtRoutine( this, COM_OWNER, \"#DIYSchedule.Click\", 149 );\n\n //\n // EVTROUTINE Handling(#DIYSchedule.Click)\n //\n rtn.Line( 149 );\n {\n\n //\n // #sys_web.Navigate( \"/images/lansatools/DIY-Workshops-Schedule.pdf\" New )\n //\n rtn.Line( 152 );\n Lansa.WEB().mthNAVIGATE( \"/images/lansatools/DIY-Workshops-Schedule.pdf\", \"NEW\" );\n\n }\n\n //\n // ENDROUTINE\n //\n rtn.Line( 154 );\n rtn.end();\n }", "function handleClickOnTimeline() {\r\n // Find clicked item\r\n var clickedContentItem = getContentItemOnMousePosition();\r\n\r\n // If no item found zoom out\r\n if (clickedContentItem === undefined) {\r\n clickedContentItem = Canvas.Breadcrumbs.decreaseDepthAndGetTheNewContentItem();\r\n }\r\n\r\n // Make sure root is not reached\r\n if (clickedContentItem !== undefined && clickedContentItem.id !== 0) {\r\n handleClickOnContentItem(clickedContentItem);\r\n }\r\n }", "function datePickerHook() {\n $('.select-options li').each(function () {\n $(this).on('click', function () {\n let startMonth = document.getElementById('date-range--start-month')\n .value\n let startYear = document.getElementById('date-range--start-year').value\n let endMonth = document.getElementById('date-range--end-month').value\n let endYear = document.getElementById('date-range--end-year').value\n const facetDate = document.getElementsByClassName(\n 'facetwp-facet-publish_date'\n )[0]\n\n facetDate.querySelectorAll('.fs-option').forEach(function (el) {\n const startDate = new Date(startYear, startMonth, 1)\n const endDate = new Date(endYear, endMonth, 1)\n const elDate = new Date(\n el.getAttribute('data-value').slice(0, 4),\n el.getAttribute('data-value').slice(4, 6) - 1,\n 1\n )\n if (elDate >= startDate && elDate <= endDate) {\n el.click()\n }\n })\n })\n })\n }", "function SEC_onButtonClick(event){SpinEditControl.onButtonClick(event)}", "function onMouseDownEvent()\n{\n let clickedTime = calculateClickedTime();\n let minute = (30 * clock.indicators.m.angle) / (Math.PI + 15);\n let hour = (6 * clock.indicators.h.angle) / (Math.PI + 3);\n let threshold = 0.25;\n\n if((clickedTime[0] < minute + threshold) && (clickedTime[0] > minute - threshold))\n {\n clock.minuteTimeChanger.highlightIndicator('red'); // threshold makes it easier to click on hand \n return;\n } \n if((clickedTime[1] < hour + threshold) && (clickedTime[1] > hour - threshold)) \n clock.hourTimeChanger.highlightIndicator('red'); \n}", "handleEndDateBox(e) {\n this.refs.endDateBox.show();\n }", "add_chgMonBtn_handler() {\n var prevbtn = document.getElementById(\"prev-month-btn\"),\n nextbtn = document.getElementById(\"next-month-btn\");\n prevbtn.addEventListener(\"click\", function (e) {\n this.change_month(-1);\n }.bind(this));\n\n nextbtn.addEventListener(\"click\", function (e) {\n this.change_month(1);\n }.bind(this));\n }", "function clickNormal(){\r\n\t\tdineroTotal+=1;\r\n\t\tdineroActual+=1;\r\n\t\tactivo=new Date().getTime()/1000;\r\n\t\tactualizarDinero();\r\n\t}", "function handleDay(e) {\n\t\tsetDay(e.target.value)\n\t}", "function poTabClicked()\n{\n\t$( \"#rfq_tab\" ).removeClass( 'tab_orange' );\n\t$( \"#rfq_tab\" ).addClass( 'tab_gray' );\n\t\n\t$( \"#quote_tab\" ).removeClass( 'tab_orange' );\n\t$( \"#quote_tab\" ).addClass( 'tab_gray' );\n\t\n\t$( \"#po_tab\" ).removeClass( 'tab_gray' );\n\t$( \"#po_tab\" ).addClass( 'tab_orange' );\n\t\n\t$( \"#invoice_tab\" ).removeClass( 'tab_orange' );\n\t$( \"#invoice_tab\" ).addClass( 'tab_gray' );\n\t\n\tselectedTab = \"PO\";\n\t\n\t $(\"#transet_label_content\").val(poText);\n\t $(\"#transet_titile\").text(\"PO Terms and Conditions\");\n\t\t\n\tif(poText==\"\")\n\t{\n\t\t$(\"#no_tc\").show();\n\t\t $(\"#tc_content\").hide();\n\t}\n\telse\n\t{\n\t\t$(\"#tc_content\").show(); \n\t\t $(\"#no_tc\").hide();\n\t}\n}", "function handleClick(evt) {\n const id = evt.target.id;\n let [categoryID, clueID] = id.split('-');\n let clue = categories[categoryID].clues[clueID];\n\n let clueText;\n if (clue.showing = false) {\n clueText = clue.question;\n clue.showing = 'showing question';\n } else if(clue.showing === 'showing question'){\n clueText = clue.answer;\n clue.showing = 'showing answer';\n } else {\n return;\n }\n $(`#${categoryID}-${clueID}`).html(clueText)\n}", "formattedSelectedPeriod() {\n return createSelector(slice, (state) => {\n if (\n state.selectedPeriod === PeriodEnum.CUSTOM &&\n state.fromDate &&\n state.toDate\n ) {\n const fromDateFormatted = lightFormat(state.fromDate, \"dd/MM/yy\");\n const toDateFormatted = lightFormat(state.toDate, \"dd/MM/yy\");\n return `${fromDateFormatted} - ${toDateFormatted}`;\n }\n\n return getPeriodLabel(state.selectedPeriod);\n });\n }", "function onClickDate(ob) {\n\tvar info = checkTime(parseInt(ob.innerHTML)) + \" - \" + checkTime((parseInt(MONTH) + 1)) + \" - \" + YEAR;\n\tdocument.getElementById(\"birthday\").value = info;\n\tdocument.getElementById(\"main\").style.display = \"none\";\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a promise to retrieve index html
function getIndexHtml(searchString) { var deferred = $q.defer(); $http.get(secSearchServiceBase + 'fetchIndex?url=' + searchString) .success(function(data) { deferred.resolve(data); }) .error(function(msg, status) { deferred.reject(msg); }) return deferred.promise; }
[ "async web (relativePath, systemPath, stripSlashes) {\n const indexNames = []\n const file = new File(join(systemPath, 'index.html'))\n try {\n await file.stat()\n } catch (err) {}\n const hasIndex = file.mode && file.isFile()\n if (hasIndex) {\n indexNames.push('index.html')\n }\n return handler(relativePath, systemPath, stripSlashes, false, !hasIndex, indexNames)\n }", "function allMenusHtml(req, res) {\n\n menus.getAllMenus()\n .then((results) => res.render('pages/index', results))\n .catch(err => {\n console.log('error in allMenusHtml: ', err);\n res.send('There was an error, sorry!')\n });\n}", "Index() {\n return this.http.request('GET', '/snapshots');\n }", "function display_index_page() {\n}", "async index() {\n return Type.all();\n }", "async function renderDataIndexDb(){\n dbPromised.then(function(db) {\n const tx = db.transaction('team', 'readonly');\n const store = tx.objectStore('team');\n return store.getAll();\n }).then(function(items) {\n cardFavorite(items)\n });\n}", "function renderBookIndex(req, res){\n let SQL = 'SELECT * FROM books';\n client.query(SQL)\n .then(results => {\n const booksArr = results.rows\n res.render('pages/index', {books: booksArr});\n })\n .catch((error) => {\n console.error(error);\n handleError(error, res);\n });\n}", "async index() {\n const { ctx, service } = this;\n\n // query value is string, should convert types.\n let { completed } = ctx.query;\n if (ctx.query.completed !== undefined) completed = completed === 'true';\n\n ctx.status = 200;\n ctx.body = await service.todo.list({ completed });\n }", "render(opts) {\n var _a;\n return __awaiter(this, void 0, void 0, function* () {\n if (opts.publicPath && opts.documentFilePath && opts.url !== undefined) {\n const url = new URL(opts.url);\n // Remove leading forward slash.\n const pathname = url.pathname.substring(1);\n const pagePath = resolve(opts.publicPath, pathname, 'index.html');\n if (pagePath !== resolve(opts.documentFilePath)) {\n // View path doesn't match with prerender path.\n let pageExists = this.pageExists.get(pagePath);\n if (pageExists === undefined) {\n pageExists = yield exists(pagePath);\n this.pageExists.set(pagePath, pageExists);\n }\n if (pageExists) {\n // Serve pre-rendered page.\n return readFile(pagePath, 'utf-8');\n }\n }\n }\n // if opts.document dosen't exist then opts.documentFilePath must\n const extraProviders = [\n ...(opts.providers || []),\n ...(this.providers || []),\n ];\n let doc = opts.document;\n if (!doc && opts.documentFilePath) {\n doc = yield this.getDocument(opts.documentFilePath);\n }\n if (doc) {\n extraProviders.push({\n provide: INITIAL_CONFIG,\n useValue: {\n document: opts.inlineCriticalCss\n // Workaround for https://github.com/GoogleChromeLabs/critters/issues/64\n ? doc.replace(/ media=\\\"print\\\" onload=\\\"this\\.media='all'\"><noscript><link .+?><\\/noscript>/g, '>')\n : doc,\n url: opts.url\n }\n });\n }\n const moduleOrFactory = this.moduleOrFactory || opts.bootstrap;\n const factory = yield this.getFactory(moduleOrFactory);\n const html = yield renderModuleFactory(factory, { extraProviders });\n if (!opts.inlineCriticalCss) {\n return html;\n }\n const { content, errors, warnings } = yield this.inlineCriticalCssProcessor.process(html, {\n outputPath: (_a = opts.publicPath) !== null && _a !== void 0 ? _a : (opts.documentFilePath ? dirname(opts.documentFilePath) : undefined),\n });\n // tslint:disable-next-line: no-console\n warnings.forEach(m => console.warn(m));\n // tslint:disable-next-line: no-console\n errors.forEach(m => console.error(m));\n return content;\n });\n }", "function writeHtml() {\n return gulp.src('index.html')\n .pipe(htmlreplace({\n 'js-bundle': 'bundle.js'\n })).pipe(useref())\n .pipe(gulp.dest('build/'));\n}", "function loadPage() {\n pageNumber++; // Increment the page number\n const options = {\n method: 'GET',\n uri: `https://doctor.webmd.com/results?so=&zip=${ZIP_CODE}&ln=Family%20Medicine&pagenumber=${pageNumber}`,\n headers: {\n 'User-Agent': 'Request-Promise',\n 'Authorization': 'Basic QWxhZGRpbjpPcGVuU2VzYW1l'\n },\n transform: body => {\n return cheerio.load(body);\n }\n };\n request(options)\n .then(async $ => {\n let results = await fetchResults($);\n return results;\n })\n .catch(err => console.error(err.message));\n }", "function getPartial(filename, req, type) {\n return new Promise(function (resolve, reject) {\n type = type ? type : \"partial\";\n let dir;\n if(type == \"partial\") {\n dir = \"partials\";\n }\n else if(type == \"page\") {\n dir = \"pages\";\n }\n\t\tif(filename) {\n\t\t\tif(filename.length - filename.lastIndexOf(\".html\") - 1 == 5) {\n\t\t\t\tfilename.slice(0, -5);\n\t\t\t}\n\t\t\tfs.readFile('public/html/' + dir + '/' + filename + \".html\", 'utf8', function(err, data) {\n\t\t\t\tif(!err) {\n\t\t\t\t\tif(req) {\n\t\t\t\t\t\tif(!req.renderData) {\n\t\t\t\t\t\t\treq.renderData = {};\n\t\t\t\t\t\t}\n if(type == \"partial\") {\n if(!req.renderData[filename])\n req.renderData[filename] = {};\n req.renderData[filename].partial = data;\n } else if(type == \"page\")\n req.renderData.pageContent = data;\n\t\t\t\t\t}\n return resolve(data);\n\t\t\t\t} else {\n\t\t\t\t\treturn reject(err);\n\t\t\t\t}\n\t\t\t});\n\t\t} else {\n\t\t\treturn reject(\"No filename provided\");\n\t\t}\n\t});\n}", "function goToLocalIndex(){\n if (getType(window.cordova.file.applicationDirectory) !== 'undefined'){\n var qs = { hybrid: 1 };\n var LOCAL_INDEX = `${window.cordova.file.applicationDirectory}www/${STARGATE_MANIFEST.start_url}`;\n loadUrl(queryfy(LOCAL_INDEX, qs));\n return LOCAL_INDEX;\n } else {\n LOG.warn('Missing cordova-plugin-file. Install it with: cordova plugin add cordova-plugin-file');\n }\n}", "function goToWebIndex(){\n var webUrl = getWebappStartUrl();\n loadUrl(webUrl);\n}", "function indexEquipment(){\n $('#all_equipment').on('click', function(event){\n event.preventDefault() \n // TODO: history.pushState(null, null, 'users/2/equipment')\n fetch(`/users/${userId()}/equipment.json`)\n .then(response => response.json())\n .then(allEquipment => {\n $('.container').html('')\n console.log('Asked data from index')\n allEquipment.forEach(equipment => {\n let newEquipment = new Equipment(equipment)\n let equipmentHtml = newEquipment.formatIndex()\n $('.container').append(equipmentHtml)\n })\n })\n \n })\n}", "function main(){\r\n return view.select({\r\n }).eachPage(async function page(records, fetchNextPage) {\r\n for(let i=0;i<records.length;i++){\r\n if(records[i].get('Working website') == null){\r\n await console.log(`Checking ${records[i].get('Name')}`);\r\n let page_html = await checkPage(records[i]);\r\n let str_p = 'Not Waiting';\r\n if(page_html != ''){\r\n str_p = 'Up'\r\n }else{\r\n str_p = 'Not up'\r\n }\r\n await console.log(`Website is ${str_p}`);\r\n await writeDataAT(records[i],str_p,page_html);\r\n }\r\n }\r\n await fetchNextPage();\r\n });\r\n}", "initializeIndex() {\n if (NylasEnv.config.get('threadSearchIndexVersion') !== INDEX_VERSION) {\n return this.clearIndex()\n .then(() => this.buildIndex(this.accountIds))\n }\n\n return this.buildIndex(this.accountIds);\n }", "static loadFormPages($, ownerDocument, firstFormHTML, progressBar, progressSpan) {\n const requests = [];\n for(let a = 0; a < firstFormHTML.length; a++) {\n const data = firstFormHTML[a];\n // load data from pages for other forms\n const formLinks = $(data, ownerDocument).find('.formeregistration a');\n if(formLinks.length) {\n progressBar['max'] = progressBar['max'] + formLinks.length;\n for(let i = 0; i < formLinks.length; i++) {\n const link = formLinks.eq(i).attr('href');\n const r = DexUtilities.getPokemonDexPage($, link.substring('/dex/'.length))\n .then((formHTML) => {\n progressBar.value = progressBar['value'] + 1;\n progressSpan.textContent = `Loaded ${progressBar['value']} of ${progressBar['max']} Pokemon`;\n return formHTML;\n }, (error) => {\n console.log(error);\n });\n requests.push(r);\n }\n }\n } // for\n\n return Promise.all(requests);\n }", "static async index (req, res) {\n const connector = await Connector.findOne({ _id: req.params.connectorId, isActive: true })\n if (!connector) {\n throw new NotFoundError('Connector')\n }\n const existingMenus = await PersistentMenu.find({ connector_id: connector._id })\n\n return renderOk(res, {\n results: existingMenus.map(m => m.serialize),\n message: existingMenus.length\n ? 'Persistent menus successfully rendered' : 'No Persistent menu',\n })\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ref : reference to 'then' function cb, ec, cn : successCallback, failureCallback, notThennableCallback
function thennable(ref, cb, ec, cn) { // Promises can be rejected with other promises, which should pass through if (state == 2) { return cn(); } if ((_typeof(val) == "object" || typeof val == "function") && typeof ref == "function") { try { // cnt protects against abuse calls from spec checker var cnt = 0; ref.call(val, function (v) { if (cnt++) return; val = v; cb(); }, function (v) { if (cnt++) return; val = v; ec(); }); } catch (e) { val = e; ec(); } } else { cn(); } }
[ "function thennable (ref, cb, ec, cn) {\n\t // Promises can be rejected with other promises, which should pass through\n\t if (state == 2) {\n\t return cn()\n\t }\n\t if ((typeof val == 'object' || typeof val == 'function') && typeof ref == 'function') {\n\t try {\n\n\t // cnt protects against abuse calls from spec checker\n\t var cnt = 0\n\t ref.call(val, function (v) {\n\t if (cnt++) return\n\t val = v\n\t cb()\n\t }, function (v) {\n\t if (cnt++) return\n\t val = v\n\t ec()\n\t })\n\t } catch (e) {\n\t val = e\n\t ec()\n\t }\n\t } else {\n\t cn()\n\t }\n\t }", "function ref(callback) {\n return {\n type: 'ref',\n callback: callback,\n }\n }", "enterCallableReference(ctx) {\n\t}", "constructor(ref){\n this.ref = ref;\n this.next = null;\n }", "function Reference() {}", "function assignRef(ref, value) {\n if (ref == null) return;\n\n if (typeCheck_dist_reachUtilsTypeCheck.isFunction(ref)) {\n ref(value);\n } else {\n try {\n ref.current = value;\n } catch (error) {\n throw new Error(\"Cannot assign value \\\"\" + value + \"\\\" to ref \\\"\" + ref + \"\\\"\");\n }\n }\n}", "getReferralCode (form_data, success_callback, failure_callback)\n {\n\n var url = '/global/crm/user/code/referral/system';\n return WebClient.basicPost(form_data, url, success_callback, failure_callback);\n }", "function callback(callback){\n callback()\n}", "function testAsyncCB(name,i)\n{\n return function (result, e, profile)\n {\n postResults(name,i, result, e, profile);\n };\n}", "function paymentSuccededCallback(result) {\n if (result.ErrorCode != 0) {\n //Call failed an error has occurred\n util.showErrors(\n result.ErrorCode,\n result.ErrorDescription,\n 'paymentSuccededCallback'\n );\n } else {\n //Call went good\n redirectToResponsePage(result);\n }\n }", "function ISREF(value) {\n if (!value) return false;\n return value.isRef === true;\n}", "static conduct(a, b, callback, on) {\r\n callback(a, b)\r\n\r\n }", "async checkIfRefExists(ref) {\n try {\n await this.api.git.getRef({ ...this.userInfo, ref });\n return true;\n }\n catch (error) {\n return false;\n }\n }", "function applyRef(instance, ref) {\n if (!ref) {\n return;\n }\n if (typeof ref === \"function\") {\n ref(instance);\n }\n else if (typeof ref === \"object\") {\n ref.current = instance;\n }\n}", "function onSuccess() {\n print(\"Url set successfully\");\n}", "onRef (ref) {\n this.childComponentFunctions = ref\n }", "visitReferencing_element(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function done(status,response,headersString){if(cache){if(isSuccess(status)){cache.put(url,[status,response,parseHeaders(headersString)]);}else{// remove promise from the cache\ncache.remove(url);}}resolvePromise(response,status,headersString);if(!$rootScope.$$phase)$rootScope.$apply();}", "exitCallableReference(ctx) {\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A utility function that makes interpolating variables into strings substantially cleaner
function format(string, vars) { if (vars) { for (var k in vars) { string = string.replace(new RegExp('\\{' + k + '\\}', 'g'), vars[k]); } } return string; }
[ "function buildString() {\n var outString = arguments[0];\n for(var i = 1; i < arguments.length; i++) {\n outString = outString.replace(new RegExp(\"\\\\$\\\\[\" + i + \"\\\\]\", \"g\"), arguments[i]);\n }\n return outString;\n }", "function threeStrings(x,y,z) {\n return x + \" \" + y + \" \" + z;\n}", "function echoTag(literals, ...substitutions) {\n let result = \"\";\n for (let i = 0; i < substitutions.length; i++) {\n result += literals[i];\n result += substitutions[i];\n }\n // add the last literal.\n result += literals[literals.length - 1];\n return result\n }", "function createValueString(fields) {\n const valueString = Object.values(fields).map( (_, index) => `$${index + 1}` ).join(', ');\n return valueString;\n}", "function printCool(name) {\n return `${name} is cool.`\n}", "function sc_stringAppend() {\n for (var i = 0; i < arguments.length; i++)\n\targuments[i] = arguments[i].val;\n return new sc_String(\"\".concat.apply(\"\", arguments));\n}", "function CONCATENATE() {\n for (var _len4 = arguments.length, values = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n values[_key4] = arguments[_key4];\n }\n\n // Combine into a single string value\n return values.reduce(function (acc, item) {\n return \"\" + acc + item;\n });\n}", "function describePerson (person){\r\n //return person.firstName +\" \"+ person.surname + \"is the \" + person.jobTitle;\r\n return `${person.firstName} ${person.surname} is the ${person.jobTitle}`\r\n}", "function ego (...s) {\n return `__egolatron_${s.join('')}__`\n }", "replaceVariableNames(thisParameter, fileName, variableList) {\n let result = \"\";\n let fileContents = thisParameter.fileOpsUtil\n .getContentFromFile(fileName)\n .split(os.EOL);\n\n logger.info(\n \"Single File Converter: Replacing variable in file : \" + fileName\n );\n fileContents.forEach((line) => {\n for (let variable in variableList) {\n let indices = [];\n let tempLine = line;\n let indexCounter = 0;\n\n while (\n tempLine.indexOf(\n variableList[variable].split(\":\")[0].toString()\n ) > -1\n ) {\n let indexOfVariable = tempLine.indexOf(\n variableList[variable].split(\":\")[0].toString()\n );\n if (\n indexOfVariable > -1 &&\n (tempLine.charAt(indexOfVariable - 1).toString() ==\n \"$\" ||\n tempLine.charAt(indexOfVariable - 1).toString() ==\n \"{\")\n ) {\n indices.push(indexCounter + indexOfVariable);\n }\n indexCounter +=\n indexOfVariable +\n variableList[variable].split(\":\")[0].toString().length;\n tempLine = tempLine.substring(\n indexOfVariable +\n variableList[variable].split(\":\")[0].toString()\n .length,\n tempLine.length\n );\n }\n\n indices.forEach((index) => {\n if (\n index > -1 &&\n (line.charAt(index - 1).toString() == \"$\" ||\n line.charAt(index - 1).toString() == \"{\")\n ) {\n //line = line.replace((variableList[variable].split(\":\")[0]).toString(), (variableList[variable].split(\":\")[1]).toString());\n line =\n line.substring(0, index) +\n variableList[variable].split(\":\")[1].toString() +\n line.substring(\n index +\n variableList[variable]\n .split(\":\")[0]\n .toString().length,\n line.length\n );\n }\n });\n\n if (\n line.includes(\n \"export \" +\n variableList[variable].split(\":\")[0].toString()\n ) ||\n line.startsWith(\n \"EXPORT \" +\n variableList[variable].split(\":\")[0].toString()\n )\n ) {\n while (\n line.includes(\n variableList[variable].split(\":\")[0].toString()\n )\n ) {\n line = line.replace(\n variableList[variable].split(\":\")[0].toString(),\n variableList[variable].split(\":\")[1].toString()\n );\n }\n }\n }\n result += line + os.EOL;\n });\n\n fs.writeFileSync(fileName, result, \"utf8\", function (err) {\n if (err) {\n logger.error(err);\n } else {\n logger.info(\n \"Single File Converter: Successfully changed variable in file : \" +\n fileName\n );\n }\n });\n }", "function echoReduce(strings, ...values) {\n // console.log(`Strings len=${strings.length} Values len=${values.length}`);\n // console.log(strings);\n // console.log(values);\n return strings.reduce((fullStr, value, idx) => {\n return `${fullStr}${idx > 0 ? values[idx - 1] : \"\"}${value}`\n });\n }", "static fillVariables2(varPath, vars) {\n if (typeof vars !== 'object' || Object.keys(vars).length === 0) {\n return varPath; // Nothing to fill\n }\n let pathKeys = getPathKeys(varPath);\n let n = 0;\n const targetPath = pathKeys.reduce((path, key) => {\n if (typeof key === 'number') {\n return `${path}[${key}]`;\n }\n else if (key === '*' || key.startsWith('$')) {\n return `${path}/${vars[n++]}`;\n }\n else {\n return `${path}/${key}`;\n }\n }, '');\n return targetPath;\n }", "function template(str, data) {\n return new Function(\"obj\",\n \"var p=[],print=function(){p.push.apply(p,arguments);};\" +\n\n // Introduce the data as local variables using with(){}\n \"with(obj){p.push('\" +\n\n // Convert the template into pure JavaScript\n str.replace(/[\\r\\t\\n]/g, \" \")\n .replace(/'(?=[^%]*%>)/g,\"\\t\")\n .split(\"'\").join(\"\\\\'\")\n .split(\"\\t\").join(\"'\")\n .replace(/<%=(.+?)%>/g, \"',$1,'\")\n .split(\"<%\").join(\"');\")\n .split(\"%>\").join(\"p.push('\")\n + \"');}return p.join('');\")(data || {});\n}", "function replace(format, params) {\n /*jslint unparam: true */\n return format.replace(/\\{([a-zA-Z]+)\\}/g, function (s, key) {\n return (typeof params[key] === 'undefined') ? '' : params[key];\n });\n }", "_evalExpression(exp) {\n exp = exp.trim();\n\n // catch special cases, with referenced properties, e.g. resourceGroup().location\n let match = exp.match(/(\\w+)\\((.*)\\)\\.(.*)/);\n if(match) {\n let funcName = match[1].toLowerCase();\n let funcParams = match[2];\n let funcProps = match[3].toLowerCase();\n if(funcName == 'resourcegroup' && funcProps == 'id') return 'resource-group-id'; \n if(funcName == 'resourcegroup' && funcProps == 'location') return 'resource-group-location'; \n if(funcName == 'subscription' && funcProps == 'subscriptionid') return 'subscription-id'; \n if(funcName == 'deployment' && funcProps == 'name') return 'deployment-name'; \n }\n \n // It looks like a function\n match = exp.match(/(\\w+)\\((.*)\\)/);\n if(match) {\n let funcName = match[1].toLowerCase();\n let funcParams = match[2];\n //console.log(`~~~ function: *${funcName}* |${funcParams}|`);\n \n if(funcName == 'variables') {\n return this._funcVariables(this._evalExpression(funcParams));\n }\n if(funcName == 'uniquestring') {\n return this._funcUniquestring(this._evalExpression(funcParams));\n } \n if(funcName == 'concat') {\n return this._funcConcat(funcParams, '');\n }\n if(funcName == 'parameters') {\n // This is a small cop out, but we can't know the value of parameters until deployment!\n // So we just display curly braces around the paramter name. It looks OK\n return `{{${this._evalExpression(funcParams)}}}`;\n } \n if(funcName == 'replace') {\n return this._funcReplace(funcParams);\n } \n if(funcName == 'tolower') {\n return this._funcToLower(funcParams);\n } \n if(funcName == 'toupper') {\n return this._funcToUpper(funcParams);\n } \n if(funcName == 'substring') {\n return this._funcSubstring(funcParams);\n } \n if(funcName == 'resourceid') {\n // Treat resourceId as a concat operation with slashes \n let resid = this._funcConcat(funcParams, '/');\n // clean up needed\n resid = resid.replace(/^\\//, '');\n resid = resid.replace(/\\/\\//, '/');\n return resid;\n } \n }\n\n // It looks like a string literal\n match = exp.match(/^\\'(.*)\\'$/);\n if(match) {\n return match[1];\n }\n\n // It looks like a number literal\n match = exp.match(/^(\\d+)/);\n if(match) {\n return match[1].toString();\n }\n\n // Catch all, just return the expression, unparsed\n return exp;\n }", "function formatParameters() {\n if (!this.params) return '';\n return '(' + this.params.map(function (param) {\n return formatParameter(param);\n }).join(', ') + ')';\n}", "get wizardInfos() {\n return `Hi! I am ${this.name}, I'm a student at Hogwarts School year ${this.schoolYear}, my house is ${this.house} and I'm taking these subjects at school: ${this.takenSubjects}`;\n }", "function StringUtils() {}", "function getPropertyInterpolationExpression(interpolation) {\r\n switch (getInterpolationArgsLength(interpolation)) {\r\n case 1:\r\n return Identifiers$1.propertyInterpolate;\r\n case 3:\r\n return Identifiers$1.propertyInterpolate1;\r\n case 5:\r\n return Identifiers$1.propertyInterpolate2;\r\n case 7:\r\n return Identifiers$1.propertyInterpolate3;\r\n case 9:\r\n return Identifiers$1.propertyInterpolate4;\r\n case 11:\r\n return Identifiers$1.propertyInterpolate5;\r\n case 13:\r\n return Identifiers$1.propertyInterpolate6;\r\n case 15:\r\n return Identifiers$1.propertyInterpolate7;\r\n case 17:\r\n return Identifiers$1.propertyInterpolate8;\r\n default:\r\n return Identifiers$1.propertyInterpolateV;\r\n }\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a random building height deviation value and return it. We use this to vary the building dimensions within the same block element.
function generateBuildingHeightDeviation() { return getRandomIntBetween(0, maxBuildingHeightDeviation); }
[ "randomHeight()\n{\n let r = this.randomRange(10,80);\n return r;\n}", "function heightGenerator() {\n randomTop = Math.floor(Math.random()*600);\n randomBottom = Math.floor(Math.random()*600);\n\n if (randomBottom > 120 && randomTop > 120 && (randomTop + randomBottom) > 500 && (randomTop + randomBottom) < 520) {\n return;\n } else {\n heightGenerator();\n }\n }", "function randomSize () {\n \n // get a random gaussian distribution\n let r = randomGaussian() * 2;\n\n // return the absolute value\n return abs(r * r);\n}", "function calculateHeight() {\n\t\treturn (val / capacity) * bottleHeight;\n\t}", "changeHeights() {\r\n //1) Initalize height of four corners to random value (between 0 and 1)\r\n this.vBuffer[2] = Math.random()*0.5;\r\n this.vBuffer[this.numVertices*3 - 1] = Math.random()*0.5;\r\n this.vBuffer[this.div*3 + 2] = Math.random()*0.5;\r\n this.vBuffer[this.numVertices*3 - 1 - this.div*3] = Math.random()*0.5;\r\n\r\n //Began recursion\r\n var roughness = 0.5;\r\n this.diamondAlgorithm(0,this.div,0,this.div,this.div,roughness);\r\n }", "function getHeight() {\n return 2;\n }", "function torchingTreesSteadyFlameHeight (species, dbh, trees) {\n return TorchingSteadyFlame[species].height[0] * Math.pow(dbh, TorchingSteadyFlame[species].height[1]) * Math.pow(trees, 0.4)\n}", "function getBleedHeightInPx() {\n // Creating temporary div with height set in mm and appending it to body\n const tempBleedDiv = document.createElement('div');\n tempBleedDiv.style.height = '8.82mm';\n document.body.appendChild(tempBleedDiv);\n \n // Getting new element's height in px and putting it in a variable\n const bleedHeightInPx = tempBleedDiv.offsetHeight;\n \n // Removing temporary div from the div as we no longer need it\n tempBleedDiv.remove();\n \n // Returning the value in px\n return bleedHeightInPx;\n }", "function setupHeights() {\n let heights = [];\n for (let i = 1; i <= num_elements; i++) {\n heights.push(Math.floor(i * height_scalar));\n }\n return heights;\n}", "get height() {\n // spec says it is a string\n return this.getAttribute('height') || '';\n }", "get estimatedHeight() {\n return -1\n }", "static getMaxHeight() { \n var result = Math.max(MainUtil.findAllRooms().map(room => (room.memory.console && room.memory.console.height)));\n return result || 10;\n }", "randomize(height, width){\n const speedRange = 1.75;\n const sizeRange = 3;\n this.x = Math.floor(Math.random()*width)\n this.y = Math.floor(Math.random()*height);\n this.speed = (Math.random()*speedMax)+speedMin;\n //this.size = (Math.random()*sizeRange)+1;\n }", "function generateBuildingBlock(\n\tgeometryParameters,\n\tposition,\n\tnumOfDivisions,\n\tbuildings\n ) {\n\t// If the building is tall or if we have less than 1 sub-division to generate, create a building\n\tif (isTall(geometryParameters.height) || numOfDivisions < 1) {\n\t // Generate a randomized maximum height deviation to use for our building\n\t var maxHeightDeviation = generateBuildingHeightDeviation();\n \n\t // Generate a random building height falling within our generated deviation\n\t var buildingHeight = getRandomIntBetween(\n\t\t geometryParameters.height - maxHeightDeviation,\n\t\t geometryParameters.height + maxHeightDeviation\n\t );\n \n\t // Generate the geometry and position maps to use when constructing our building\n \n\t var buildingGeometryParameters = {\n\t\t width: geometryParameters.width,\n\t\t height: buildingHeight,\n\t\t depth: geometryParameters.depth\n\t };\n \n\t var buildingPosition = {\n\t\t x: position.x,\n\t\t y: buildingGeometryParameters.height / 2 + curbHeight,\n\t\t z: position.z\n\t };\n \n\t // Generate a new building with the assigned position and geometry and add it to our\n\t // array of buildings\n\t var building = new Building(buildingGeometryParameters, buildingPosition);\n\t buildings.push(building.getMergedMesh());\n \n\t // Calculate the amount of buildings we've already generated\n\t var totalBuildingsBuilt = buildings.length;\n \n\t // Calculate the total number of buildings we're targeting to build (according to the amount of\n\t // sub-divisions assigned to our block)\n\t var totalBuildingsToBuild = Math.pow(2, blockSubdivisions);\n \n\t // If our block has no more buildings which need to be built, or if our building qualifies as\n\t // being a tall structure, we're done and we can merge the building mesh and add it to the scene\n\t if (\n\t\t totalBuildingsBuilt >= totalBuildingsToBuild ||\n\t\t isTall(buildingGeometryParameters.height)\n\t ) {\n\t\t scene.add(getMergedMesh(buildings));\n\t }\n\t \n\t} else {\n\t \n\t // Otherwise, we sub-divide our block into different components and generate a building whithin\n\t // each sub component block\n \n\t // Generate a randomized block 'slice' deviation to use\n\t var sliceDeviation = Math.abs(\n\t\t getRandomIntBetween(0, maxBuildingSliceDeviation)\n\t );\n \n\t // If our geometry depth is larger than our width, we slice the depth dimension in 2 and generate\n\t // 2 sub-divisions / building elements spread across our depth dimension\n\t if (geometryParameters.width <= geometryParameters.depth) {\n\t\t // Calculate the new depth geometry parameters we need to use to sub-divide this block\n\t\t var depth1 =\n\t\t\t Math.abs(geometryParameters.depth / 2 - sliceDeviation) -\n\t\t\t blockMargin / 2;\n\t\t var depth2 =\n\t\t\t Math.abs(-(geometryParameters.depth / 2) - sliceDeviation) -\n\t\t\t blockMargin / 2;\n \n\t\t // Calculate the new z coordinates we're going to use for our sub-division\n\t\t var z1 =\n\t\t\t position.z +\n\t\t\t sliceDeviation / 2 +\n\t\t\t geometryParameters.depth / 4 +\n\t\t\t blockMargin / 4;\n\t\t var z2 =\n\t\t\t position.z +\n\t\t\t sliceDeviation / 2 -\n\t\t\t geometryParameters.depth / 4 -\n\t\t\t blockMargin / 4;\n \n\t\t // Recursively generate the new sub-divided block elements and add them to the scene\n \n\t\t generateBuildingBlock(\n\t\t\t // Building geometry parameters\n\t\t\t {\n\t\t\t\twidth: geometryParameters.width,\n\t\t\t\theight: geometryParameters.height,\n\t\t\t\tdepth: depth1\n\t\t\t },\n\t\t\t // Building position\n\t\t\t {\n\t\t\t\tx: position.x,\n\t\t\t\tz: z1\n\t\t\t },\n\t\t\t // Decrement the total number of sub-divisions we need to perform\n\t\t\t numOfDivisions - 1,\n\t\t\t buildings\n\t\t );\n \n\t\t generateBuildingBlock(\n\t\t\t // Building geometry parameters\n\t\t\t {\n\t\t\t\twidth: geometryParameters.width,\n\t\t\t\theight: geometryParameters.height,\n\t\t\t\tdepth: depth2\n\t\t\t },\n\t\t\t // Building position\n\t\t\t {\n\t\t\t\tx: position.x,\n\t\t\t\tz: z2\n\t\t\t },\n\t\t\t // Decrement the total number of sub-divisions we need to perform\n\t\t\t numOfDivisions - 1,\n\t\t\t buildings\n\t\t );\n\t\t \n\t } else {\n\t\t \n\t\t // Slice the width dimension in 2 and generate 2 sub-divisions / building elements spread across our\n\t\t // width dimension\n \n\t\t // Calculate the new width geometry parameters we need to use to sub-divide this block\n\t\t var width1 =\n\t\t\t Math.abs(geometryParameters.width / 2 - sliceDeviation) -\n\t\t\t blockMargin / 2;\n\t\t var width2 =\n\t\t\t Math.abs(-(geometryParameters.width / 2) - sliceDeviation) -\n\t\t\t blockMargin / 2;\n \n\t\t // Calculate the new x coordinates to use as part of our positional parameters\n\t\t var x1 =\n\t\t\t position.x +\n\t\t\t sliceDeviation / 2 +\n\t\t\t geometryParameters.width / 4 +\n\t\t\t blockMargin / 4;\n\t\t var x2 =\n\t\t\t position.x +\n\t\t\t sliceDeviation / 2 -\n\t\t\t geometryParameters.width / 4 -\n\t\t\t blockMargin / 4;\n \n\t\t // Recursively generate the new sub-divided block elements and add them to the scene\n \n\t\t generateBuildingBlock(\n\t\t\t // Building geometry parameters\n\t\t\t {\n\t\t\t\twidth: width1,\n\t\t\t\theight: geometryParameters.height,\n\t\t\t\tdepth: geometryParameters.depth\n\t\t\t },\n\t\t\t // Building position\n\t\t\t {\n\t\t\t\tx: x1,\n\t\t\t\tz: position.z\n\t\t\t },\n\t\t\t // Decrement the total number of sub-divisions we need to perform\n\t\t\t numOfDivisions - 1,\n\t\t\t buildings\n\t\t );\n \n\t\t generateBuildingBlock(\n\t\t\t // Building geometry parameters\n\t\t\t {\n\t\t\t\twidth: width2,\n\t\t\t\theight: geometryParameters.height,\n\t\t\t\tdepth: geometryParameters.depth\n\t\t\t },\n\t\t\t // Building position\n\t\t\t {\n\t\t\t\tx: x2,\n\t\t\t\tz: position.z\n\t\t\t },\n\t\t\t // Decrement the total number of sub-divisions we need to perform\n\t\t\t numOfDivisions - 1,\n\t\t\t buildings\n\t\t );\n\t }\n\t}\n }", "getRandomBurrow() {\n\t\treturn Phaser.Utils.Array.GetRandom(this.burrowLocations);\n\t}", "function getRandomEnemySeed(chosenDifficulty){\n let maxEnemyCount;\n\n if(chosenDifficulty === 'easy'){\n maxEnemyCount = enemyList[0].difficulty[0].easy.length;\n }else if(chosenDifficulty === 'medium'){\n maxEnemyCount = enemyList[0].difficulty[1].medium.length;\n }\n\n return Math.floor(Math.random() * maxEnemyCount);\n}", "function diamond4() {\n return Math.floor(Math.random() * 11 + 1);\n }", "function genHeightChart(smart) {\n var patient = smart.patient;\n var pt = patient.read();\n var obv = smart.patient.api.fetchAll({\n \n // Note - I don't know how to sort results by time or anything. Someone\n // should figure that out\n type: 'Observation',\n query: {\n code: {\n $or: [\n 'http://loinc.org|8302-2', // Body height\n ]\n }\n } \n \n }); \n \n $.when(pt, obv).fail(onError);\n $.when(pt, obv).done(\n function(patient, obv) {\n\t\t\n\t\tvar byCodes = smart.byCodes(obv, 'code');\n\t\t\n\t\tvar height = byCodes('8302-2');\n\t\tvar retStruct = extractDateVal(height);\n\t\t\n\t\tplotD3Data(retStruct, \"Height\");\n }\n )\n}", "function getSize() {\n return randomFunction(minBubbleSize, maxBubbleSize);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function to simulate the Ruby splat argument syntax.
function get_splat_args( func, args ) { return Array.prototype.slice.call( args, func.length ); }
[ "function spreadForFunctionArgs(){\n multipleParams(1,2,3);\n\n let args = [1,2,3];\n multipleParams(...args);\n}", "function spread(func, args){\n return func(...args);\n}", "function logAsArray(...nums) {\n console.log(nums);\n}", "visitTypedargslist(ctx) {\r\n console.log(\"visitTypedargslist\");\r\n // TODO: support *args, **kwargs\r\n let length = ctx.getChildCount();\r\n let returnlist = [];\r\n let comma = [];\r\n let current = -1;\r\n if (ctx.STAR() === null && ctx.POWER() === null) {\r\n for (var i = 0; i < length; i++) {\r\n if (ctx.getChild(i).getText() === \",\") {\r\n comma.push(i);\r\n }\r\n }\r\n comma.push(length);\r\n for (var i = 0; i < comma.length; i++) {\r\n if (comma[i] - current === 2) {\r\n returnlist.push({\r\n type: \"Parameter\",\r\n name: this.visit(ctx.getChild(comma[i] - 1)),\r\n default: null,\r\n });\r\n current = current + 2;\r\n console.log(this.visit(ctx.getChild(comma[i] - 1)));\r\n } else {\r\n returnlist.push({\r\n type: \"Parameter\",\r\n name: this.visit(ctx.getChild(comma[i] - 3)),\r\n default: this.visit(ctx.getChild(comma[i] - 1)),\r\n });\r\n current = current + 4;\r\n }\r\n }\r\n } else {\r\n throw \"*args and **kwargs have not been implemented!\";\r\n }\r\n return returnlist;\r\n }", "visitVarargslist(ctx) {\r\n console.log(\"visitVarargslist\");\r\n // TODO: support *args, **kwargs\r\n let length = ctx.getChildCount();\r\n let returnlist = [];\r\n let comma = [];\r\n let current = -1;\r\n if (ctx.STAR() === null && ctx.POWER() === null) {\r\n for (var i = 0; i < length; i++) {\r\n if (ctx.getChild(i).getText() === \",\") {\r\n comma.push(i);\r\n }\r\n }\r\n comma.push(length);\r\n for (var i = 0; i < comma.length; i++) {\r\n if (comma[i] - current === 2) {\r\n returnlist.push({\r\n type: \"VarArgument\",\r\n name: this.visit(ctx.getChild(comma[i] - 1)),\r\n default: null,\r\n });\r\n current = current + 2;\r\n console.log(this.visit(ctx.getChild(comma[i] - 1)));\r\n } else {\r\n returnlist.push({\r\n type: \"VarArgument\",\r\n name: this.visit(ctx.getChild(comma[i] - 3)),\r\n default: this.visit(ctx.getChild(comma[i] - 1)),\r\n });\r\n current = current + 4;\r\n }\r\n }\r\n } else {\r\n throw \"*args and **kwargs have not been implemented!\";\r\n }\r\n return returnlist;\r\n }", "function packRestArguments(pattern, args) {\n if (pattern.all) {\n return [args];\n } else if (pattern.rest) {\n var firstArgs = _.head(args, pattern.args.length);\n var restArgs = _.tail(args, pattern.args.length);\n firstArgs.push(restArgs);\n return firstArgs;\n } else {\n return args;\n }\n }", "function comeArr(n1, n2, ...other) {\nconsole.log('n1:', n1) // 1\nconsole.log('n2:', n2) // 2\nconsole.log('other:', other) // [ 3, 4 ]\n}", "function myMultiParamFunction(param1, param2) {\n \n console.log(param1);\n console.log(param2);\n \n}", "function gather_w_def(def = \"no args passed\", ...rest){ \n console.log(\"first value passed: \", def );\n console.log(\"remaining values: \", rest);\n}", "function splitArguments() {\r\n var splitedArray, ii;\r\n if (!arguments[0]) {\r\n throw new WrongArgumentException(\"Can't parse arguments, cause it doesn't exist!\");\r\n }\r\n splitedArray = new Array();\r\n for (ii = 0; ii < arguments[0].length; ii++) {\r\n splitedArray.push(arguments[0][ii]);\r\n }\r\n return splitedArray;\r\n }", "static of(...args) {\n return List.from(args);\n }", "*execute() { yield* Array.from(arguments); }", "function contactPeople(method, ...people) {\n}", "function joinArrays(...args){\n\tlet res = [];\n\tfor (let i of args) res.push(...i);\n\treturn res;\n}", "ArgumentList() {\n const argumentList = [];\n do {\n argumentList.push(this.AssignmentExpression());\n } while (this._lookahead.type === \",\" && this._eat(\",\"));\n\n return argumentList;\n }", "function foo({ x, y }) {\n return { x, y };\n }", "function addParamArray(params, flag, paramArray) {\n paramArray.forEach(function(param){\n params.push('--' + flag +'=' + param);\n });\n}", "function sumArgs() {\r\n return [].reduce.call(arguments, function(a, b) {\r\n return a + b;\r\n });\r\n}", "function printer(...args) {\n console.log(...args);\n}", "function for_each(){\n var param_len = arguments[0].length;\n var proc = arguments[0];\n while(!is_empty_list(arguments[1])){\n var params = [];\n for(var j = 1; j < 1+param_len; j++) {\n params.push(head(arguments[j]));\n arguments[j] = tail(arguments[j]);\n }\n proc.apply(proc, params);\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=====| fAnimateWidth Function |===== Animates element's width
function fAnimateWidth (elem, eWidth) { tMx.to (elem, animTym, {css: {width: eWidth}, ease: easePower}); }
[ "set requestedWidth(value) {}", "updateWidth() {\n if (this.setupComplete) {\n let width = this.headerData.getWidth();\n this.width = '' + width;\n this.widthVal = width;\n $(`#rbro_el_table${this.id}`).css('width', (this.widthVal + 1) + 'px');\n }\n }", "function set_skill_percent(){\n $('.skill-percent-line').each(function() {\n var width = $(this).data( \"width\" );\n $( this ).animate({width: width+'%'}, 1000 );\n\n });\n}", "get width() {\n if ( !this.el ) return;\n\n return ~~this.parent.style.width.replace( 'px', '' );\n }", "function indexImgWidthFloor(ele) {\n ele.each(function() {\n console.log(min);\n $(this).width('49%');\n $(this).width(min);\n });\n }", "updateWidth() {\n if (!this.isMounted() || !controller.$contentColumn.length) return;\n\n const left = controller.$contentColumn.offset().left - $(window).scrollLeft();\n const padding = 18;\n let width = $(document.body).hasClass('ltr') ?\n left - padding :\n $(window).width() - (left + controller.$contentColumn.outerWidth()) - padding;\n if (cd.g.skin === 'minerva') {\n width -= controller.getContentColumnOffsets().startMargin;\n }\n\n // Some skins when the viewport is narrowed\n if (width <= 100) {\n this.$topElement.hide();\n this.$bottomElement.hide();\n } else {\n this.$topElement.show();\n this.$bottomElement.show();\n }\n\n this.$topElement.css('width', width + 'px');\n this.$bottomElement.css('width', width + 'px');\n }", "function updateRectWidth(rect, rectWidth, rectAmount, magnification) {\r\n // If the mouse is over this rect, add the magnification.\r\n if (rect.isMouseInRect) {\r\n rect.width = rectWidth + magnification;\r\n } else { // if not subtract the magnification divided by the remaining rects.\r\n rect.width = rectWidth - (magnification / (rectAmount - 1));\r\n }\r\n}", "function setContainerWidth() {\n // get width and store in zwiperContainerWidth var\n if (zwiperSettings.width === undefined) {\n zwiperContainerWidth = parseInt(zwiperContainer.offsetWidth, 10);\n zwiperContainer.style.width = zwiperContainerWidth + 'px';\n } else if (zwiperSettings.width.indexOf('px') !== -1) {\n zwiperContainerWidth = parseInt(zwiperSettings.width.replace('px', ''), 10);\n zwiperContainer.style.width = zwiperContainerWidth + 'px';\n } else if (zwiperSettings.width.indexOf('%') !== -1) {\n zwiperContainer.style.width = zwiperSettings.width;\n zwiperContainerWidth = zwiperContainer.offsetWidth;\n } else {\n zwiperContainerWidth = parseInt(zwiperSettings.width, 10);\n zwiperContainer.style.width = zwiperContainerWidth + 'px';\n }\n }", "function SlideHorizontallyTransition() {}", "function calculateWidth(){\n $('#jsGanttChartModal').css('width', ($(window).width() - 40) + 'px');\n $('#jsGanttChartDiv').css('maxHeight', ($(window).height() - 200) + 'px');\n calculateLeftWidth();\n }", "set width( w ) {\n if ( !this.el ) return;\n\n if ( w === 'default' ) {\n this.parent.style.width = this.opts.cols * this.charWidth + 'px';\n return;\n }\n\n this.parent.style.width = w + 'px';\n }", "updateHealth(health) {\n // width is defined in terms of the player's health\n this.width = health * 5;\n }", "[resetRowWidth]() {\n\t\tconst self = this;\n\t\tself.width(self[CURRENT_AVAILABLE_WIDTH] - self[INDENT_WIDTH]);\n\t}", "initWidth () {\n if (this.hasAttribute('width')) {\n var width = this.getAttribute('width');\n this.width = width;\n }\n let modalBody = this.shadowRoot.getElementById('modalId');\n modalBody.style.setProperty('--dialog-width', this.width);\n }", "_setImageSize() {\n this.images[0].style.width = this.container.offsetWidth + 'px';\n }", "resizeTaskWidth() {\n this.props.onUpdateTask(this.getWidthResizedTaskList(this.props.taskList))\n }", "updateMiddleWidth() {\n if(this.added) {\n var title = this.getJQueryObject().find(\".title\");\n var middle = title.find(\".middle\");\n var middlePadding = middle.outerWidth(true) - middle.width();\n var middleWidth = title.width() - middlePadding;\n\n // Wait 50ms to make sure every document change has been applied\n // Should probably be done in a more elegant way\n setTimeout(function() {\n title.children('div').each(function () {\n if(!$(this).hasClass(\"middle\")) {\n middleWidth -= $(this).outerWidth(true);\n }\n }).promise()\n .done( function() {\n middle.css(\"max-width\", middleWidth);\n });\n }, 50);\n }\n }", "set width(aValue) {\n this._logService.debug(\"gsDiggThumbnailDTO.width[set]\");\n this._width = aValue;\n }", "getCharWidth() {\n var el = document.createElement( 'span' );\n el.style.opacity = 0;\n el.innerHTML = 'm';\n this.parent.appendChild( el );\n var fontWidth = el.offsetWidth;\n this.parent.removeChild( el );\n return fontWidth;\n }", "function handleWindowResize() {\r\n width = window.innerWidth;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a list of all assignments for the given school ID.
getAssignments(schoolID) { return _get('/api/assignments', {school_id: schoolID}); }
[ "function getAssignmentsByCourseId(id) {\n return new Promise((resolve, reject) => {\n mysqlPool.query(\n 'SELECT * FROM assignments WHERE courseid = ?',\n [ id ],\n function (err, results) {\n if (err) {\n reject(err);\n } else {\n resolve(results);\n }\n }\n );\n });\n}", "function getAssignmentsByUserId(id) {\n return new Promise((resolve, reject) => {\n mysqlPool.query(\n 'SELECT * FROM assignments WHERE userid = ?',\n [ id ],\n (err, results) => {\n if (err) {\n reject(err);\n } else {\n resolve(results);\n }\n }\n );\n });\n}", "function getAllRouteSchoolsBySchoolId(schoolId) {\n var deferred = $q.defer();\n $http({\n url: '/api/RouteSchool/GetAllRouteSchoolsBySchoolId/' + schoolId,\n method: 'GET'\n //headers\n }).success(function (data) {\n deferred.resolve(data);\n }).error(function (data) {\n deferred.reject(data);\n })\n return deferred.promise;\n }", "function getHITAssignments(HITId) {\n return new Promise((resolve, reject) => {\n mturk.listAssignments(HITId, data => {\n resolve(data);\n });\n });\n}", "async function getEnrollmentsByCourseId(id) {\n const db = getDBReference();\n const collection = db.collection('users_courses');\n if (!ObjectId.isValid(id)) {\n return null;\n } else {\n const results = await collection\n .find({ \"courseId\": id })\n .toArray();\n if (!results) {\n return null;\n }\n studentList = []\n for (const result of results){\n studentList.push(result['studentId']);\n }\n return { students: studentList };\n }\n}", "function getSchoolsByName(schoolName) {\n const conditions = {\n schoolType: getTypeTerm(),\n state: getStateTerm()\n };\n return $.post(\"/api/schools/name/\" + schoolName, conditions);\n}", "function getAssignmentDetails (arr) {\n var arrOut = []\n arr.forEach(element => {\n arrOut.push(element.id)\n })\n return arrOut\n}", "function Assignment(name, m, student_id) {\n\tthis.name = name;\n\tthis.student_id = student_id;\n\tthis.grades = [] //array of Grade objects - empty to start off with\n}", "fetchSchoolYear(context, id) {\n return new Promise((resolve, reject) => {\n ApiService.init()\n ApiService.get(`/api/school-year/${id}/show`, {}).then(\n response => {\n resolve(response)\n },\n error => {\n reject(error)\n }\n )\n })\n }", "function getCourseAssignmentGrade(courseId, assignmentNames, callback) {\n var url = createUrl(\"gradereport_user_get_grades_table\", {\"userid\":getCookieByName(USERID), \"courseid\":courseId});\n if (url != null) {\n $.get(url, function (data, status) {\n var tabledata = data.tables[0].tabledata;\n var grades=[];\n for(var i = 1; i < tabledata.length; i++) {\n // searches for the name in the assignment\n // unfortunately there is no other way to concatenate assignment with grade\n assignmentNames.forEach(function(assignmentName){\n if(tabledata[i].itemname!=undefined)\n {\n if(tabledata[i].itemname.content.indexOf(assignmentName) != -1) {\n var currentGrade = new AssignmentGrade(courseId,assignmentName,true, tabledata[i].grade.content, tabledata[i].percentage.content);\n grades.push(currentGrade);\n }\n }\n });\n }\n callback(grades);\n }).fail(function () {\n callback(new Error(\"network error\"));\n });\n }\n else\n callback(new Error(\"invalid session error\"));\n}", "function getAllRouteSchoolsByRouteId(routeId) {\n var deferred = $q.defer();\n $http({\n url: '/api/RouteSchool/GetAllRouteSchoolsByRouteId/' + routeId,\n method: 'GET'\n //headers\n }).success(function (data) {\n deferred.resolve(data);\n }).error(function (data) {\n deferred.reject(data);\n })\n return deferred.promise;\n }", "function hGetMyAssignments(inst) {\n let sortedTasks = [];\n let assignedTasks = [];\n if (inst.uiState.get(\"assnSort\") == NAME_TXT) {\n sortedTasks = Tasks.find({owner:{$ne:Meteor.userId()}}, {sort:{createdAt:-1}});\n }\n else {\n sortedTasks = Tasks.find({owner:{$ne:Meteor.userId()}}, {sort:{name:1}});\n }\n sortedTasks.forEach((task)=>{\n if (task.assignees != null && task.assignees.indexOf(Meteor.user().username) >= 0)\n assignedTasks.push(task);\n });\n return assignedTasks;\n}", "function getCalendarsForCourse(id, cb) {\n pg.connect(constr, (err, client, done) => {\n // (2) check for an error connecting:\n if (err) {\n cb('could not connect to the database: ' + err);\n return;\n }\n\n // (3) make the query if successful:\n\n client.query(CalendarQuery, [id], (err, result) => {\n // call done to release the client back to the pool:\n done();\n\n // (4) check if there was an error querying database:\n if (err) {\n cb('could not connect to the database: ' + err);\n return;\n }\n\n // (5) check to see if user exists:\n if (result.rows.length == 0) {\n cb('No calendars yet.');\n return;\n }\n\n cb(undefined, result.rows);\n });\n });\n}", "function filterListByCourseId(sections, courseId) {\n\n console.log('sections: ', sections);\n console.log('Assignments: Filter list by course id: ', courseId);\n\n var filteredList = sections.filter((section) => {\n\n return section.course_id == courseId;\n\n });\n\n return filteredList;\n\n}", "getDelegates(schoolID) {\n return _get('/api/delegates', {school_id: schoolID});\n }", "extractAssignmentGrades(assignments) {\n return R.pluck('grade')(assignments);\n }", "function getTrainingSeriesAssignments(teamMemberId) {\n return db(\"TeamMember\")\n .join(\n \"RelationalTable\",\n \"TeamMember.teamMemberID\",\n \"RelationalTable.teamMember_ID\"\n )\n .join(\n \"TrainingSeries\",\n \"TrainingSeries.trainingSeriesID\",\n \"RelationalTable.trainingSeries_ID\"\n )\n .select(\n \"RelationalTable.trainingSeries_ID\",\n \"TrainingSeries.title\",\n \"RelationalTable.startDate\"\n )\n .where(\"RelationalTable.teamMember_ID\", teamMemberId);\n}", "function setCollegeAndCourse(courseId) {\n collegeArray.forEach((collegeMap) => {\n collegeMap.courses.filter((coursesMap) => {\n if (coursesMap.id == courseId) {\n college.value = collegeMap.id;\n college.innerHTML = `<option>${collegeMap.college}</option>`;\n document.getElementById(\n 'user-college'\n ).innerText = `${collegeMap.college}`;\n\n course.value = coursesMap.id;\n course.innerHTML = `<option>${coursesMap.course}</option>`;\n document.getElementById('user-course').innerText = `${coursesMap.id}`;\n }\n });\n });\n}", "getCourseIDs(studentID) {\n const courseInstanceDocs = CourseInstances.find({ studentID }).fetch();\n const courseIDs = courseInstanceDocs.map((doc) => doc.courseID);\n return _.uniq(courseIDs);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Queue a validation for new custom styles to batch style recalculations
enqueueDocumentValidation() { if (this['enqueued'] || !validateFn) { return; } this['enqueued'] = true; documentWait(validateFn); }
[ "reStyle() {\n console.log('restyle')\n this._destroyStyles();\n this._initStyles();\n }", "function addStyles() {\n\t styles.use();\n\t stylesInUse++;\n\t}", "function updateErrorIndicators() {\n $scope.$apply(() => {\n //Error count is external to the IDE. Although related to the validity state, they are both separate.\n $ctrl.errorCount = $ctrl.ide.querySelectorAll('.invalidLine, .invalidRule, .invalidToken').length;\n sheetForm.$setDirty(true);\n sheetForm.$setValidity('command-ide', $ctrl.ide.valid);\n });\n }", "_initStyles() {\n const styles = this.constructor.styles !== undefined ? this.constructor.styles : this.styles();\n if (!styles) { return }\n this.styleSheet = new ScreenStyle(styles, this.id);\n }", "addProductionRule() {\n this.productionRules.push({\n source: this.ruleSource,\n target: this.ruleTarget\n });\n this.ruleSource = '';\n this.ruleTarget = '';\n this.validSubmit = true;\n this.validateSubmit();\n }", "function genericFormatValidate(genericFv) {\n $('.' + genericFv.className).each(function() {\n var procEl = $(this);\n var reformat = false;\n \n //Check if element has another class\n var numClasses = 0;\n $.each(fvClasses, function(index, item) {\n if(procEl.hasClass(item.className)) numClasses++;\n });\n if(numClasses > 1) procEl.attr('data-fv-multiple', numClasses);\n \n //Set defaults\n if(genericFv.isRequired == undefined) genericFv.isRequired = false;\n if(genericFv.regex != undefined) genericFv.validationFn = function(value) {\n return (value.match(genericFv.regex));\n };\n \n var params = {};\n if(genericFv.params) {\n if(!(genericFv.params instanceof Array)) genericFv.params = [genericFv.params];\n for(var i = 0; i<genericFv.params.length; i++) {\n genericFv[genericFv.params[i]] = processes.getParam(procEl, genericFv.className, genericFv.params[i]);\n if(genericFv[genericFv.params[i]] == undefined && settings.showConsoleMessages) console.log('FV: #' + procEl.attr('id') + ' : Missing attribute data-' + genericFv.className + '-' + genericFv.params[i]);\n }\n }\n \n procEl.blur(function() {\n //Check for multiple classes\n if(!processes.getParam(procEl, genericFv.className, 'multiple')) {\n //Not multiple, proceed as usual\n processes.removeInvalid(procEl, genericFv.className);\n } else {\n //Mulitple classes. Check if the invalid element is the currently checked class\n if(procEl.hasClass('fvInv'+genericFv.className)) {\n processes.removeInvalid(procEl, genericFv.className);\n }\n } \n \n var cond2 = function(value) {return false;}\n if(!genericFv.isRequired) {\n cond2 = function(value) {return (to.NoWhiteSpace(value) == \"\");};\n }\n if(genericFv.validationFn && processes.isFunction(genericFv.validationFn)) {\n if(genericFv.validationFn(to.NoWhiteSpace(procEl.val())) || cond2(procEl.val())) {\n reformat = true;\n } else {\n processes.invalidElement(procEl, genericFv.className);\n }\n } else {\n reformat = true;\n }\n if(reformat) {\n if(genericFv.formattingFn && processes.isFunction(genericFv.formattingFn) && to.NoWhiteSpace(procEl.val()) != \"\") procEl.val(to.NoWhiteSpace(genericFv.formattingFn(procEl.val())));\n }\n });\n });\n }", "function send_update_style_event() {\n\tfor (i = 0; i < frames.length; i++) {\n\t\tframes[i].window.postMessage(\"update_style\", \"*\");\n\t}\n}", "function evAddCssRule (event) {\n\tvar $e = $(event.target);\n\tvar $p = $e.parents('div :first');\n\tvar $z = $e.parents('tr');\n\tvar zoneid = parseInt($z.attr('zoneid'));\t\n\t$p.before(zoneParamFormCssRow(zoneParamFormCssRule(zoneid, null)));\n}", "function batch_validate_appender(valset,classname,rule_message){\n\tvar batch = $(\".\"+classname);\n\tvar length = batch.length;\n\tvar isString = typeof rule_message.rules == \"string\";\n\tvar ids = [];\n\tfor(var i=0;i<length;i++){\n\t\tvar id = batch[i].id\n\t\tids.push(id);\n\t\tif(isString){\n\t\t\tvalset.rules[id]=rule_message.rules;\n\t\t\tvalset.messages[id] = upperFirstChar(id) + rule_message.messages;\n\t\t}else{\n\t\t\tif(!valset.rules[id]){[valset.rules[id],valset.messages[id]] = [{},{}];}\n\t\t\tfor(ind in rule_message.rules){\n\t\t\t\tvalset.rules[id][ind] = rule_message.rules[ind];\n\t\t\t\tvalset.messages[id][ind] = upperFirstChar(id) + rule_message.messages[ind];\n\t\t\t}\n\t\t}\n\t}\n\treturn ids;\n}", "function postValidate(isValid, errMsg, errElm, inputElm) {\n if (!isValid) {\n // Show errMsg on errElm, if provided.\n if (errElm !== undefined && errElm !== null\n && errMsg !== undefined && errMsg !== null) {\n errElm.html(errMsg);\n }\n // Set focus on Input Element for correcting error, if provided.\n if (inputElm !== undefined && inputElm !== null) {\n inputElm.addClass(\"errorBox\"); // Add class for styling\n inputElm.focus();\n }\n } else {\n // Clear previous error message on errElm, if provided.\n if (errElm !== undefined && errElm !== null) {\n errElm.html('');\n }\n if (inputElm !== undefined && inputElm !== null) {\n inputElm.removeClass(\"errorBox\");\n }\n }\n}", "disable_style() {\n this.enabledStyles.pop();\n }", "function add_update_style_event_listener() {\n\twindow.addEventListener(\"message\", function(event) {\n\t\tif (event.data == \"update_style\") {\n\t\t\tupdate_style();\n\t\t}\n\t});\n}", "function setInputValidityStatus () {\n if (dependantsInputNamesAndValidators.length > 0) {\n dependantsInputNamesAndValidators.map(function (dependantItem) {\n if (scopeForm[dependantItem.inputName]) {\n scopeForm[dependantItem.inputName].$setValidity(dependantItem.validatorName, dependantItem.validator());\n }\n });\n }\n }", "function defineDocumentStyles() {\r\n for (var i = 0; i < document.styleSheets.length; i++) {\r\n var mysheet = document.styleSheets[i],\r\n myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;\r\n config.documentStyles.push(myrules);\r\n }\r\n }", "function saveCustomStyle (fileName)\n{\n\tvar fileOut = \"\\n\";\n\t\t\t\n\tfor (var n = 0; n < gSTYLE_CLASS.length; n++)\n\t{\n\t\tvar bold = doAction('REQ_GET_FORMVALUE', gSTYLE_CLASS[n].formNameKey+\"Bold\", gSTYLE_CLASS[n].formNameKey+\"Bold\");\n\t\tvar italic = doAction('REQ_GET_FORMVALUE', gSTYLE_CLASS[n].formNameKey+\"Italic\", gSTYLE_CLASS[n].formNameKey+\"Italic\");\n\t\tvar fontSize = doAction('REQ_GET_FORMVALUE', gSTYLE_CLASS[n].formNameKey+\"FontSize\", gSTYLE_CLASS[n].formNameKey+\"FontSize\");\n\t\tvar fontFamily = doAction('REQ_GET_FORMVALUE', gSTYLE_CLASS[n].formNameKey+\"FontFamily\", gSTYLE_CLASS[n].formNameKey+\"FontFamily\");\n\n\t\tfileOut += \".\" + gSTYLE_CLASS[n].className + \" {\\n\"+\n\t\t\t\t\t\"font-family:\"+\n\t\t\t\t\tfontFamily+\";\\n\"+\n\t\t\t\t\t\"font-weight:\"+\n\t\t\t\t\t(bold ? bold : \"normal\")+\";\\n\"+\n\t\t\t\t\t\"font-style:\"+\n\t\t\t\t\t(italic ? italic : \"normal\")+\";\\n\"+\n\t\t\t\t\t\"font-size:\"+\n\t\t\t\t\tfontSize+\";\\n\"+\n\t\t\t\t\t\"}\\n\\n\";\n\t}\n\t\n\tvar written = doAction ('DATA_WRITEFILE', 'FileName', gSTYLES_DIR+fileName,'Data', fileOut, 'Size', \n\t\t\t\t\t\t\t\t\t\tfileOut.length, 'ObjectName', gPUBLIC,'Permissions',0644);\n}", "function insertEmptyStyleBefore(node, callback) {\n var style = document.createElement('style');\n style.setAttribute('type', 'text/css');\n var head = document.getElementsByTagName('head')[0];\n if (node) {\n head.insertBefore(style, node);\n } else {\n head.appendChild(style);\n }\n if (style.styleSheet && style.styleSheet.disabled) {\n head.removeChild(style);\n callback('Unable to add any more stylesheets because you have exceeded the maximum allowable stylesheets. See KB262161 for more information.');\n } else {\n callback(null, style);\n }\n}", "selectStyleThumbnail(style) {\n this.setState({ selectedStyle: style }, () => {\n this.checkOutOfStock();\n this.props.changeSelectedStyle(this.state.selectedStyle);\n // need to check quantity too once we change a style\n });\n }", "function markSuccessInput(input) {\n $(input).css('border-color', '#f0f0f0');\n}", "function applyStyleSafely_NumberToPixel(argmentsObj){\r\n \r\n //変更前状態を取得\r\n var previousAttribute = argmentsObj.$3targetElement.node().style.getPropertyValue(argmentsObj.attributeName);\r\n if(previousAttribute == \"\"){\r\n previousAttribute = null;\r\n }\r\n\r\n if(argmentsObj.styleDefinitionObj[argmentsObj.propertyName] === null){ //削除指定の場合\r\n argmentsObj.$3targetElement.style(argmentsObj.attributeName, null); //削除\r\n\r\n if(previousAttribute !== null){\r\n previousAttribute = parseFloat(previousAttribute); // \"0.0px\"(string) -> 0.0(number) 形式に変換\r\n }\r\n argmentsObj.prevReportObj[argmentsObj.propertyName] = previousAttribute;\r\n argmentsObj.renderedReportObj[argmentsObj.propertyName] = null;\r\n delete argmentsObj.boundObj[argmentsObj.propertyName];\r\n \r\n }else if(typeof argmentsObj.styleDefinitionObj[argmentsObj.propertyName] != 'number'){ //型がnumberでない場合\r\n var wrn = \"Wrong type specified in \\`\" + argmentsObj.propertyName + \"\\`. \" +\r\n \"specified type:\\`\" + (typeof (argmentsObj.styleDefinitionObj[argmentsObj.propertyName])) + \"\\`, expected type:\\`number\\`.\";\r\n console.warn(wrn);\r\n argmentsObj.failuredMessagesObj[argmentsObj.propertyName] = wrn;\r\n \r\n }else{ //型がnumber\r\n var pixcelNumberRegex = new RegExp(/^[-]?[0-9]+(\\.[0-9]+)?px$/);\r\n var applyThisAttribute = argmentsObj.styleDefinitionObj[argmentsObj.propertyName] + \"px\";\r\n\r\n if(!(pixcelNumberRegex.test(applyThisAttribute))){ //指定数値が `0.0px`形式にならない場合(ex: NaNを指定)\r\n var wrn = \"Invalid Number \\`\" + argmentsObj.styleDefinitionObj[argmentsObj.propertyName].toString() + \"\\` specified.\";\r\n console.warn(wrn);\r\n argmentsObj.failuredMessagesObj[argmentsObj.propertyName] = wrn;\r\n\r\n }else{\r\n argmentsObj.$3targetElement.style(argmentsObj.attributeName, applyThisAttribute);\r\n\r\n //適用可否チェック\r\n var appliedAttribute = window.getComputedStyle(argmentsObj.$3targetElement.node()).getPropertyValue(argmentsObj.attributeName);\r\n \r\n if(!(pixcelNumberRegex.test(appliedAttribute))){ // `0.0px`形式に設定できていない場合\r\n // 指数表記になるような極端な数値も、このルートに入る\r\n\r\n var wrn = \"Specified style in \\`\" + argmentsObj.propertyName + \"\\` did not applied. \" +\r\n \"specified style:\\`\" + applyThisAttribute + \"\\`, browser applied style:\\`\" + appliedAttribute + \"\\`.\";\r\n console.warn(wrn);\r\n argmentsObj.failuredMessagesObj[argmentsObj.propertyName] = wrn;\r\n\r\n argmentsObj.$3targetElement.style(argmentsObj.attributeName, previousAttribute); //変更前の状態に戻す\r\n\r\n }else{\r\n\r\n //適用されたstrke-widthと指定したstrke-widthの差分チェック\r\n if( Math.abs(parseFloat(appliedAttribute) - argmentsObj.styleDefinitionObj[argmentsObj.propertyName]) >= 0.1){\r\n var wrn = \"Specified style in \\`\" + argmentsObj.propertyName + \"\\` did not applied. \" +\r\n \"specified style:\\`\" + applyThisAttribute + \"\\`, browser applied style:\\`\" + appliedAttribute + \"\\`.\";\r\n console.warn(wrn);\r\n argmentsObj.failuredMessagesObj[argmentsObj.propertyName] = wrn;\r\n\r\n argmentsObj.$3targetElement.style(argmentsObj.attributeName, previousAttribute); //変更前の状態に戻す\r\n \r\n }else{ //適用された場合\r\n\r\n if(previousAttribute !== null){\r\n previousAttribute = parseFloat(previousAttribute); // \"0.0px\"(string) -> 0.0(number) 形式に変換\r\n }\r\n\r\n argmentsObj.prevReportObj[argmentsObj.propertyName] = previousAttribute;\r\n argmentsObj.renderedReportObj[argmentsObj.propertyName] = argmentsObj.styleDefinitionObj[argmentsObj.propertyName];\r\n argmentsObj.boundObj[argmentsObj.propertyName] = argmentsObj.styleDefinitionObj[argmentsObj.propertyName];\r\n }\r\n }\r\n }\r\n } \r\n }", "function validateRun (data, command) {\n // no additional validation necessary\n return true;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new CheckInSubEntityTeamCoach instance
function CheckInSubEntityTeamCoach(parameters) { var first_name = parameters.first_name, full_name = parameters.full_name, id = parameters.id, last_name = parameters.last_name, member_number = parameters.member_number, compliance_summary = parameters.compliance_summary, can_be_added_to_roster = parameters.can_be_added_to_roster, cannot_be_added_to_roster_reason = parameters.cannot_be_added_to_roster_reason, email_address = parameters.email_address, phone_number = parameters.phone_number; this.first_name = first_name; this.full_name = full_name; this.id = id; this.last_name = last_name; this.member_number = member_number; this.compliance_summary = compliance_summary; this.can_be_added_to_roster = can_be_added_to_roster; this.cannot_be_added_to_roster_reason = cannot_be_added_to_roster_reason; this.email_address = email_address; this.phone_number = phone_number; }
[ "function CheckInSubEntityTeamServicePersonnel(parameters) {\n var first_name = parameters.first_name, full_name = parameters.full_name, id = parameters.id, last_name = parameters.last_name, member_number = parameters.member_number, compliance_summary = parameters.compliance_summary, can_be_added_to_roster = parameters.can_be_added_to_roster, cannot_be_added_to_roster_reason = parameters.cannot_be_added_to_roster_reason, email_address = parameters.email_address, phone_number = parameters.phone_number, team_role = parameters.team_role;\n this.first_name = first_name;\n this.full_name = full_name;\n this.id = id;\n this.last_name = last_name;\n this.member_number = member_number;\n this.compliance_summary = compliance_summary;\n this.can_be_added_to_roster = can_be_added_to_roster;\n this.cannot_be_added_to_roster_reason = cannot_be_added_to_roster_reason;\n this.email_address = email_address;\n this.phone_number = phone_number;\n this.team_role = team_role;\n }", "function CheckInSubEntitySkaterCoach(parameters) {\n this.member_number = '';\n var first_name = parameters.first_name, id = parameters.id, last_name = parameters.last_name, compliance_summary = parameters.compliance_summary, ineligible = parameters.ineligible;\n this.first_name = first_name;\n this.id = id;\n this.last_name = last_name;\n this.compliance_summary = compliance_summary;\n this.ineligible = ineligible;\n }", "function CheckInSubEntitySkater(parameters) {\n var age = parameters.age, can_be_added_to_roster = parameters.can_be_added_to_roster, cannot_be_added_to_roster_reason = parameters.cannot_be_added_to_roster_reason, compliance_summary = parameters.compliance_summary, first_name = parameters.first_name, full_name = parameters.full_name, id = parameters.id, last_name = parameters.last_name, member_number = parameters.member_number, requirements_summary = parameters.requirements_summary;\n this.age = age;\n this.can_be_added_to_roster = can_be_added_to_roster;\n this.cannot_be_added_to_roster_reason = cannot_be_added_to_roster_reason;\n this.compliance_summary = compliance_summary;\n this.first_name = first_name;\n this.full_name = full_name;\n this.id = id;\n this.last_name = last_name;\n this.member_number = member_number;\n this.requirements_summary = requirements_summary;\n }", "async CreateInspectionCo(ctx, args) {\n args = JSON.parse(args);\n //store inspection Company data identified by inspectionCoId\n\n let inspectionCo = {\n id: args.userId,\n companyName: args.companyName,\n type: 'inspectionCo',\n projects: [],\n entity: 'user'\n };\n await ctx.stub.putState(args.userId, Buffer.from(JSON.stringify(inspectionCo)));\n\n //add inspectionCoId to 'inspectionCos' key\n const data = await ctx.stub.getState('inspectionCos');\n if (data) {\n let inspectionCos = JSON.parse(data.toString());\n inspectionCos.push(args.userId);\n await ctx.stub.putState('inspectionCos', Buffer.from(JSON.stringify(inspectionCos)));\n } else {\n throw new Error('inspectionCos not found');\n }\n\n // return inspectionCo object\n return inspectionCo;\n }", "function AbstractCheckInEntity(parameters) {\n var check_in_status = parameters.check_in_status, club = parameters.club, comment_count = parameters.comment_count, eligible = parameters.eligible, id = parameters.id, lts_summary = parameters.lts_summary, member_number = parameters.member_number, membership_status = parameters.membership_status, name = parameters.name;\n this.check_in_status = check_in_status;\n this.club = club;\n this.comment_count = comment_count;\n this.eligible = eligible;\n this.id = id;\n this.member_number = member_number;\n this.membership_status = membership_status;\n this.name = name;\n this.lts_summary = lts_summary;\n }", "createSecondTeam(callback) {\n\t\tconst testTeamCreator = new TestTeamCreator({\n\t\t\ttest: this,\n\t\t\tuserOptions: this.userOptions,\n\t\t\tteamOptions: Object.assign({}, this.teamOptions, {\n\t\t\t\tcreatorToken: this.users[1].accessToken\n\t\t\t}),\n\t\t\trepoOptions: Object.assign({}, this.repoOptions, {\n\t\t\t\tcreatorIndex: 0,\n\t\t\t\twithKnownCommitHashes: [this.repo.knownCommitHashes[2]]\n\t\t\t})\n\t\t});\n\t\ttestTeamCreator.create((error, response) => {\n\t\t\tif (error) { return callback(error); }\n\t\t\tthis.secondTeamCreator = response.users[0];\n\t\t\tthis.secondTeam = response.team;\n\t\t\tthis.secondRepo = response.repos[0];\n\t\t\tthis.secondTeamToken = testTeamCreator.teamOptions.creatorToken;\n\t\t\tcallback();\n\t\t});\n\t}", "createTeam (callback) {\n\t\tlet data = {\n\t\t\tname: RandomString.generate(10)\n\t\t};\n\t\tthis.apiRequest(\n\t\t\t{\n\t\t\t\tmethod: 'post',\n\t\t\t\tpath: '/companies',\n\t\t\t\tdata: data,\n\t\t\t\ttoken: this.userData[0].accessToken\t// first user creates it\n\t\t\t},\n\t\t\t(error, response) => {\n\t\t\t\tif (error) { return callback(error); }\n\t\t\t\tthis.team = response.team;\n\t\t\t\tthis.teamStream = response.streams[0];\n\t\t\t\tcallback();\n\t\t\t}\n\t\t);\n\t}", "function _createTeams() {\n gTeams = storageService.load('teams')\n storageService.store('teams', gTeams)\n}", "function createNewIntern (data, internData) {\n var myNewIntern = new Intern (data.id, data.name, data.email, internData.school);\n productionTeam.push(myNewIntern);\n console.log('Production Team', productionTeam);\n // prompts add another question function to see whether they want to add another or stop\n addAnother();\n}", "constructor() { \n \n TeamEventStatus.initialize(this);\n }", "async createVoter(ctx, args) {\n\n args = JSON.parse(args);\n\n //create a new voter\n let newVoter = await new Voter(ctx, args.voterId, args.registrarId, args.firstName, args.lastName);\n\n //update state with new voter\n await ctx.stub.putState(newVoter.voterId, Buffer.from(JSON.stringify(newVoter)));\n\n //query state for elections\n let currElections = JSON.parse(await this.queryByObjectType(ctx, 'election'));\n\n if (currElections.length === 0) {\n let response = { error: 'no elections. Run the init() function first.' };\n return response;\n }\n\n //get the election that is created in the init function\n let currElection = currElections[0];\n\n let votableItems = JSON.parse(await this.queryByObjectType(ctx, 'votableItem'));\n\n //generate ballot with the given votableItems\n await this.generateBallot(ctx, votableItems, currElection, newVoter);\n\n let response = { message: `voter with voterId ${newVoter.voterId} is updated in the world state` };\n return response;\n }", "putV3ProjectsIdServicesPivotaltracker(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = 56;*/ // Number |\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.putV3ProjectsIdServicesPivotaltracker(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }", "postV3ProjectsIdForkForkedFromId(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let forkedFromId = \"forkedFromId_example\";*/ // String | The ID of the project it was forked from\napiInstance.postV3ProjectsIdForkForkedFromId(incomingOptions.id, incomingOptions.forkedFromId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }", "putV3ProjectsIdServicesHipchat(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = 56;*/ // Number |\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.putV3ProjectsIdServicesHipchat(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }", "putV3ProjectsIdServicesCustomIssueTracker(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = 56;*/ // Number |\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.putV3ProjectsIdServicesCustomIssueTracker(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }", "init_teams(teams)\n {\n console.log(teams);\n this.teams = {};\n // insert each team object in the teams array\n Object.keys(teams).forEach((t, idx) =>\n {\n // this.teams.push(new this.team_class(this, team_name, teams[team_name], idx));\n this.teams[teams[t][\"name\"]] = new this.team_class(this, teams[t][\"name\"], teams[t][\"score\"], idx, teams[t][\"color\"]);\n });\n }", "postV3ProjectsIdMergeRequestSubscribableIdSubscription(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let subscribableId = \"subscribableId_example\";*/ // String | The ID of a resource\napiInstance.postV3ProjectsIdMergeRequestSubscribableIdSubscription(incomingOptions.id, incomingOptions.subscribableId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }", "postV3ProjectsIdLabelsSubscribableIdSubscription(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let subscribableId = \"subscribableId_example\";*/ // String | The ID of a resource\napiInstance.postV3ProjectsIdLabelsSubscribableIdSubscription(incomingOptions.id, incomingOptions.subscribableId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }", "constructor() { \n \n PatchedBankAccountCreateUpdate.initialize(this);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Proxy to a section instance
function sectionProxy(sectionName){ this.name = sectionName; this.add = function(key, value){ biro.sections[this.name].add(key, value); } this.currentState = function(){ return biro.sections[this.name].currentState; } this.clear = function(){ biro.sections[this.name].clear(); } this.length = function(){ return biro.sections[this.name].length(); } this.nextState = function(){ return biro.sections[this.name].nextState(); } this.transition = function(toState){ biro.sections[this.name].transition(toState); } }
[ "function sectionOn() { }", "function deeplinkToSection( ){\r\n\r\n\r\n $('.container').each(function () {\r\n // Helper variables\r\n var sectionIndex = 0;\r\n var deepLinkIndex = 0;\r\n var deepLinkSection = getDeepLinkSection();\r\n\r\n\r\n\r\n // Depending on the type of container,\r\n // set values for the selector we wil use\r\n // to find the section index.\r\n var containerSelector = \"\";\r\n var containerType = \"tabs\";\r\n\r\n if (isAccNav($(this))) {\r\n containerSelector = \"h3\";\r\n containerType = \"accordion\";\r\n } else if (isTabNav($(this))) {\r\n containerSelector = \"ul>li\";\r\n containerType = \"tabs\";\r\n }\r\n\r\n\r\n // Now we know what kind of container it is,\r\n // we can loop through the relevant sections\r\n // and check for a match against the hash value\r\n $(this).find(containerSelector).each(function () {\r\n\r\n if ($(this).data(\"sectionName\") === deepLinkSection) {\r\n deepLinkIndex = sectionIndex;\r\n return false;\r\n }\r\n\r\n sectionIndex++;\r\n });\r\n\r\n $(this)[containerType](\"option\", \"active\", deepLinkIndex);\r\n\r\n });\r\n\r\n }", "wrapSection (markup, className) {\n return `\n <section class=\"${className}\">\n <ol>\n <li>\n ${markup}\n </li>\n </ol>\n </section>`\n }", "function getSection( sectionPos ) {\r\n\t\treturn sections.eq( sectionPos );\r\n\t}", "function getSectionByAnchor(sectionAnchor){var section=$(SECTION_SEL+'[data-anchor=\"'+sectionAnchor+'\"]',container)[0];if(!section){var sectionIndex=typeof sectionAnchor!=='undefined'?sectionAnchor-1:0;section=$(SECTION_SEL)[sectionIndex];}return section;}", "function updateSectionOffset() {\n\n $.each(_.sectionElements, function(index) {\n\n if (index == 0) {\n _.sectionOffsets[index] = 0;\n } else {\n\n var lastSectionOffset = _.sectionOffsets[index - 1];\n var nextSectionOffset = _.sectionElements[index - 1].height();\n\n _.sectionOffsets[index] = Math.floor(lastSectionOffset + nextSectionOffset);\n }\n });\n }", "function changeSectionClass() {\n if (document.layers || document.all || document.getElementById) {\n var inc, endInc = arguments.length;\n // run through the args (objects) and set the visibility of each\n for (inc=0; inc<endInc; inc+=2) {\n // get a good object reference\n var elem = document.getElementById(arguments[inc]);\n var action = arguments[inc+1];\n if (action == \"hidden\") {\n // hide the object\n elem.className = \"section-hide\";\n } else if (action == \"visible\") {\n // show the object\n elem.className = \"section-show\";\n } else if (action == \"toggle\") {\n // toggle the object's visibility\n if (elem.className == \"section-show\") {\n elem.className = \"section-hide\";\n } else if (elem.className == \"section-hide\") {\n elem.className = \"section-show\";\n } else {\n //assume hidden as default (IE bug?)\n elem.className = \"section-show\";\n }\n }\n }\n }\n}", "visitTiming_point_section(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function moveTo(sectionAnchor,slideAnchor){var destiny=getSectionByAnchor(sectionAnchor);if(typeof slideAnchor!=='undefined'){scrollPageAndSlide(sectionAnchor,slideAnchor);}else if(destiny!=null){scrollPage(destiny);}}", "function addnewsection() {\n sectionNumber ++;\n\n //=======> Create Anther section\n let addSection = document.createElement('section');\n addSection.innerHTML = `\n <section id=\"section${sectionNumber}\" class=\"your-active-class\">\n <div class=\"landing__container\">\n <h2 id=\"se_${sectionNumber}\">Section ${sectionNumber}</h2>\n <p id=\"getActive_${sectionNumber}\">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi fermentum metus faucibus lectus pharetra dapibus. Suspendisse potenti. Aenean aliquam elementum mi, ac euismod augue. Donec eget lacinia ex. Phasellus imperdiet porta orci eget mollis. Sed convallis sollicitudin mauris ac tincidunt. Donec bibendum, nulla eget bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam nunc eu augue. Pellentesque maximus imperdiet elit a pharetra. Duis lectus mi, aliquam in mi quis, aliquam porttitor lacus. Morbi a tincidunt felis. Sed leo nunc, pharetra et elementum non, faucibus vitae elit. Integer nec libero venenatis libero ultricies molestie semper in tellus. Sed congue et odio sed euismod.</p>\n </div>\n </section>`;\n mainSection.appendChild(addSection);\n\n //=======> Create Anther item in navbar\n let addli = document.createElement('li');\n addli.innerHTML = `<li ><a id=\"li_${sectionNumber}\" onclick=\"scroll_to('section${sectionNumber}')\">Section ${sectionNumber}</a></li>`;\n mynavbar.appendChild(addli);\n}", "initLoad(){\n //Load Main config file\n var sectionData = '';\n\n if(typeof(this.section) == 'object'){\n var ObjKeys = Object.keys(this.section);\n if(ObjKeys.length > 0){\n if(this.section['params'] && Object.keys(this.section['params']).length > 0) this.extraPrms = this.section['params'];\n if(this.section['successCall']) this.successCallBack = this.section['successCall'];\n if(this.section['endpoint']) this.section = this.section['endpoint'];\n }\n }\n\n if(configArr[this.section]) sectionData = configArr[this.section];\n if(!sectionData) this.getResponse(false, {error: 'Unable to load configuration for selected page'});\n this.sectionObj = sectionData;\n }", "function getCurrentSection() {\r\n\t\tconst currentSectionPos = content.slick( \"slickCurrentSlide\" );\r\n\t\treturn sections.eq( currentSectionPos );\r\n\t}", "function SectionTable(sectionList) {\n this._sectionList = sectionList;\n}", "sections () {\n this.headers.forEach(h => {\n this.observer.observe(h)\n })\n }", "function FunH5oSemSection(eltStart) {\n this.ssArSections = [];\n this.ssElmStart = eltStart;\n /* the heading-element of this semantic-section */\n this.ssElmHeading = false;\n\n this.ssFAppend = function (what) {\n what.container = this;\n this.ssArSections.push(what);\n };\n this.ssFAsHTML = function () {\n var headingText = fnH5oGetSectionHeadingText(this.ssElmHeading);\n headingText = '<a href = \"#' + fnH5oGenerateId(this.ssElmStart) + '\">'\n + headingText\n + '</a>';\n return headingText + fnH5oGetSectionListAsHtml(this.ssArSections);\n };\n }", "function sortableSection(el){\n\tel.sortable({ \n\t\tconnectWith\t\t\t\t: '.mfn-sortable-row',\n\n\t\titems\t\t\t\t\t: '.mfn-wrap',\n\t\t\n\t\tforcePlaceholderSize\t: true, \n\t\tplaceholder\t\t\t\t: 'mfn-placeholder',\n\t\t\n\t\topacity\t\t\t\t\t: 0.9,\n\t\tcursor\t\t\t\t\t: 'move',\n\t\tcursorAt\t\t\t\t: {top: 20, left: 20},\n\t\tdistance\t\t\t\t: 5,\n\n\t\treceive\t\t\t\t\t: sortableSectionReceive\t// on drop into, NOT on update position after drag\n\t});\n}", "scrollToTab_() {\n this.anchorScroll_('tabs');\n }", "addNewSwitch(section, selectedSwitch) {\n this.Sections.addSwitch(section, selectedSwitch);\n this.sections = this.Sections.getSections();\n }", "finishSection () {\n // If we've reserved a section to encode a payload size, we need to go back and fill that in.\n let record = this.reservedSizeRecord;\n if (record !== null) {\n // Here we use the non-payload size we recorded before to get the payload size (see the reserveSize method below for more info).\n let size = this.totalSize - record.value;\n record.bytes = uLEB(size);\n record.value = size;\n this.totalSize += record.bytes.length; // Update the total size since we added some bytes to record the payload size.\n }\n\n // Now that we're completely done with this section, we're going to add it to its parent.\n //this.parent.parts = this.parent.parts.concat(this.parts);\n this.parent.totalSize += this.totalSize;\n\n // Finally, return the parent, so chaining can continue from there.\n return this.parent;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks for currently selected index and creates a label for a infolabel on hover.
function hoverOnState(handle){ var index = Index[indexSelected]; var code = index[year][handle.ST] var lawDescrip = lawCodeLabel(code); var labelText = "<h1><i>" + handle.State + "</i></h1><b><span style=float:right>" + year + "</span></b><p>" + lawDescrip + "</p>"; var infolabel = d3.select("#map-container") .append("div") .attr("class", "infolabel") //for styling label .html(labelText); //.moveToFront(); //add text }
[ "function updateSelectedLabels() {\n\t\t\t\n\t\t\t var selectedLabels = vis.selectAll('text.selectedLabel').data(selectedNodeData);\n\t\t\t \n\t\t\t selectedLabels.enter().append('svg:text')\n\t\t\t \t.attr('class', 'selectedLabel')\n\t\t\t \t.attr('dx', function(d) {\n\t\t\t \tif (arcs.centroid(d)[0] < 0) {\n\t\t\t \t\t\treturn -(fullWidth * .5) + 120;\n\t\t\t \t\t} else {\n\t\t\t \t\t\treturn (fullWidth * .5) - 120;\n\t\t\t \t\t}\n\t\t\t \t})\n\t\t\t \t.attr('dy', function(d) {\n\t\t\t \t\treturn arcs.centroid(d)[1] + 4;\n\t\t\t \t})\n\t\t\t \t.attr('fill', '#000')\n\t\t\t \t.attr('font-weight', 'bold')\n\t\t\t .attr('text-anchor', function(d) {\n\t\t\t \t\tif (arcs.centroid(d)[0] < 0) {\n\t\t\t \t\t\treturn 'end';\n\t\t\t \t\t} else {\n\t\t\t \t\t\treturn null;\n\t\t\t \t\t}\n\t\t\t })\n\t\t\t\t\t.on(\"click\", function(d) {\n\t\t\t\t\t\tif (d.node) {\n\t\t\t\t\t\t\treturn self.location = d.node.url;\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t .text(function(d) { return d.shortTitle; });\n\n\t\t\t\tselectedLabels.exit().remove();\n\t\t\t\t\n\t\t\t\tselectedLabels.attr('dx', function(d) {\n\t\t\t \tif (arcs.centroid(d)[0] < 0) {\n\t\t\t \t\t\treturn -(fullWidth * .5) + 120;\n\t\t\t \t\t} else {\n\t\t\t \t\t\treturn (fullWidth * .5) - 120;\n\t\t\t \t\t}\n\t\t\t \t})\n\t\t\t\t\t.attr('dy', function(d) {\n\t\t\t \t\treturn arcs.centroid(d)[1] + 4;\n\t\t\t \t})\n\t\t\t .attr('text-anchor', function(d) {\n\t\t\t \t\tif (arcs.centroid(d)[0] < 0) {\n\t\t\t \t\t\treturn 'end';\n\t\t\t \t\t} else {\n\t\t\t \t\t\treturn null;\n\t\t\t \t\t}\n\t\t\t })\n\t\t\t .text(function(d) { return d.shortTitle; });\n\t\t\t \t\n\t\t\t var selectedPointers = vis.selectAll('polyline.selectedPointer').data(selectedNodeData);\n\t\t\t \n\t\t\t selectedPointers.enter().append('svg:polyline')\n\t\t\t \t.attr('class', 'selectedPointer')\n\t\t\t \t.attr('points', function(d) {\n\t\t\t \t\tvar dx = arcs.centroid(d)[0];\n\t\t\t \t\tvar dy = arcs.centroid(d)[1];\n\t\t\t \t\tvar hw = fullWidth * .5;\n\t\t\t \t\tif (arcs.centroid(d)[0] < 0) {\n\t\t\t \t\t\treturn (125-hw)+','+dy+' '+(135-hw)+','+dy+' '+dx+','+dy;\n\t\t\t \t\t} else {\n\t\t\t \t\t\treturn (hw-125)+','+dy+' '+(hw-135)+','+dy+' '+dx+','+dy;\n\t\t\t \t\t}\n\t\t\t \t})\n\t\t\t \t.attr('stroke','#444')\n\t\t\t \t.attr('stroke-width',1);\n\t\t\t \t\n\t\t\t selectedPointers.exit().remove();\n\t\t\t \n\t\t\t selectedPointers.attr('points', function(d) {\n\t\t\t \t\tvar dx = arcs.centroid(d)[0];\n\t\t\t \t\tvar dy = arcs.centroid(d)[1];\n\t\t\t \t\tvar hw = fullWidth * .5;\n\t\t\t \t\tif (arcs.centroid(d)[0] < 0) {\n\t\t\t \t\t\treturn (125-hw)+','+dy+' '+(135-hw)+','+dy+' '+dx+','+dy;\n\t\t\t \t\t} else {\n\t\t\t \t\t\treturn (hw-125)+','+dy+' '+(hw-135)+','+dy+' '+dx+','+dy;\n\t\t\t \t\t}\n\t\t\t \t});\n\n\t\t\t}", "function mouseOverTeam(index) {\n vm.expandedInfo = vm.odds[index];\n vm.showExpandedInfo = true;\n }", "drawTip() {\n let tipLocationInfo;\n\n if (this.lastHitInfo) {\n tipLocationInfo = this.lastHitInfo;\n } else if (this.defaultSelectItemInfo) {\n tipLocationInfo = this.getItem(this.defaultSelectItemInfo, false);\n } else if (this.defaultSelectInfo && this.options.selectLabel.use) {\n tipLocationInfo = this.getItem(this.defaultSelectInfo, false);\n } else {\n tipLocationInfo = null;\n }\n\n this.drawTips?.(tipLocationInfo);\n }", "function showCurrentInfoBox() {\n\n var desc = current.address + '<br>';\n\n desc += '<strong>' + current.phone + '</strong><br><br>';\n desc += '<img src=\"' + current.ratingimage + '\"> <small>Based on ' + current.reviews + ' reviews</small><br>';\n desc += '<a href=\"' + current.url + '\">Read Reviews on Yelp</a>';\n\n var html = '<table><tr><td valign=\"top\"><img src=\"' + current.photo + '\"></td><td valign=\"top\" style=\"padding-left: 5px\">' + desc + '</td></tr></table>';\n\n $('#name').html(current.title);\n\n $('#yelpLink').html('<a href=\"' + current.url + '\">Read Reviews on Yelp</a>');\n $('#bingLink').html('<a href=\"http://www.bing.com/maps/?v=2&where1=' + current.url_address + '\">Map it on Bing</a>');\n $('#address').html(current.address);\n\n createInfobox(current.latitude, current.longitude, current.title, html);\n }", "labelCurrentTrack() {\n\t\tlet labl = 'empty';\n\t\tif (this.trks[tpos].usedInstruments.length === 1) {\n\t\t\tif (this.trks[tpos].hasPercussion) {\n\t\t\t\tlabl = 'Percussion';\n\t\t\t} else {\n\t\t\t\tlabl = getInstrumentLabel(this.trks[tpos].usedInstruments[0]);\n\t\t\t}\n\t\t} else if (this.trks[tpos].usedInstruments.length > 1) {\n\t\t\tlabl = 'Mixed Track';\n\t\t}\n\t\tthis.trks[tpos].label = `${labl} ${this.getLabelNumber(labl)}`;\n\t}", "function dealWithLabelsAndSelection(){\n\t\tif(interactive){\n\t\t\tcurrentZoomLevel=pompeiiMap.getZoom();\n\t\t\tif(currentZoomLevel< INSULA_VIEW_ZOOM){\n\t\t\t\tremoveInsulaLabels();\n\t\t\t\tdisplayInsulaLabels();\n\t\t\t}\n\t\t\telse if(currentZoomLevel>=INSULA_VIEW_ZOOM) {\n\t\t\t\tremoveInsulaLabels();\n\t\t\t\tdisplayInsulaLabels();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdisplayInsulaLabels();\n\t\t\t}\n\t\t}\n\t}", "function hoverOutState(){\n\td3.select(\".infolabel\").remove(); //remove info label\n}", "highlightSelected() {\n\n this.highlighter.setPosition(this.xStart + this.selected * this.distance, this.yPosition + this.highlighterOffsetY);\n\n }", "function drawInfoButtons(infoButtons)\n{\n\tinfoButtons.text(\"i\");\n}", "function drawCountryDetails(xPos, yPos){\n textAlign(LEFT, TOP);\n fill(0);\n if (yPos > 105 && yPos < 885){\n var selectedCountry = floor((yPos - 105) / 14);\n textSize(24);\n text(topRefugeesTable.getString(selectedCountry, 'Country'), 750, 105);\n textSize(12);\n text('Refugees: ' + nfc(topRefugeesTable.getNum(selectedCountry, 'Refugees'), 0), 750, 135);\n text('IDPs: ' + nfc(topRefugeesTable.getNum(selectedCountry, 'IDPs'), 0), 750, 150);\n text('Stateless: ' + nfc(topRefugeesTable.getNum(selectedCountry, 'Stateless'), 0), 750, 165);\n text('Total: ' + nfc(topRefugeesTable.getNum(selectedCountry, 'Total'), 0), 750, 180);\n }\n}", "function hiLiteLabel(axis, clicked){\r\n d3.selectAll(\".aText\")\r\n .filter(\".\" + axis)\r\n .filter(\".active\")\r\n .classed(\"inactive\", true)\r\n \r\n clicked.classed(\"inactive\", false).classed(\"active\", true);\r\n}", "function showTip(oSel, sFldName) {\n var sTip = \"One or more keywords separated by commas\";\n if (oSel.children[oSel.selectedIndex].text.match(/list/))\n\tdocument.getElementsByName(sFldName)[0].title = sTip;\n else\n\tdocument.getElementsByName(sFldName)[0].title = \"\";\n}", "showInfo() {\n let sp = 25; // Spacing\n push();\n // Vertical offset to center text with the image\n translate(this.x * 2, this.y - 50);\n textAlign(LEFT);\n textSize(20);\n textStyle(BOLD);\n text(movies[this.id].title, 0, 0);\n textStyle(NORMAL);\n text(\"Directed by \" + movies[this.id].director, 0, 0 + sp);\n text(\"Written by \" + movies[this.id].writer, 0, 0 + sp * 2);\n text(\"Year: \" + movies[this.id].year, 0, 0 + sp * 3);\n text(\"Running time: \" + movies[this.id].time + \" min\", 0, 0 + sp * 4);\n // Index of the movie / total movies in the dataset\n text(\"(\" + (this.id + 1) + \"/\" + nMovies + \")\", 0, 0 + sp * 5);\n pop();\n }", "function mouseoverHandler (d) {\n tooltip.transition().style('opacity', .9)\n tooltip.html('<p>' + d[\"country\"] + '</p>' );\n }", "function highlightFeature(e) {\n\tvar layer = e.target;\n\n\t// style to use on mouse over\n\tlayer.setStyle({\n\t\tweight: 2,\n\t\tcolor: '#666',\n\t\tfillOpacity: 0.7\n\t});\n\n\t\n\t\n\tinfo_panel.update(layer.feature.properties)\n\t\n\n\t\n\n\t\n\n}", "function addHover(){\n var hover = $('#hover');\n\n $('.icon').on(\"mouseover\", function(){\n var current = $(this);\n var coords = current.offset();\n var details = current.data(\"titles\");\n if(details.length > 0){\n hover.show()\n .html(details)\n .offset({left: coords.left+60, top: coords.top});\n }\n\n });\n $('.icon').on(\"mouseleave\", function(){\n hover.hide();\n });\n\n $('.performer').on(\"mouseover\", function(){\n var current = $(this);\n var coords = current.offset();\n var width = current.width();\n hover.show()\n .html(current.data('specialty'));\n hover.offset({left: coords.left+width/2-hover.width()/2, top: coords.top});\n });\n $('.performer').on(\"mouseleave\", function(){\n hover.hide();\n });\n}", "function handleHover(data) {\n var flightInfo = $('#flight-info')\n var pn;\n data.points.forEach((point, index) => {\n pn = point.pointNumber;\n var flight = currentData[pn];\n $('#ref-id').html(flight.ref);\n $('#fatalities').html(flight.fat);\n $('#date').html(flight.date);\n $('#aircraft').html(flight.plane_type);\n $('#location').html(flight.country);\n $('#airline').html(flight.airline);\n $('#phase').html(flight.phase.split('_').join(' '));\n if (flight.meta.toLowerCase() != \"unknown\") {\n $('#meta').html((flight.meta.split('_').join(' ')));\n $('#cause').html(\"- \" + flight.cause);\n } else {\n $('#meta').html(\"Unknown\");\n }\n $('#certainty').html(flight.cert);\n $('#story-label').html(\"STORY\");\n $('#story').html( flight.notes);\n if (flight.notes !== \"\") {\n $('#story-label').css('display', 'inline-block');\n $('#story').css('display', 'inline-block');\n } else {\n $('#story-label').css('display', 'none');\n $('#story').css('display', 'none');\n }\n })\n $('#hover-helper').css('display', 'none');\n flightInfo.css('display', 'inline-block');\n }", "function hoverInstructionsFixedPos(id_name,option){\n if (option == \"2\") \n $(eval(id_name)).hide(); \n else \n $(eval(id_name)).show(); \n}", "function updateLabelsText(xy, xPos, labelsText) {\n // setup chosenAxis by xy\n var chosenAxis = (xy === \"x\") ? chosenXAxis : chosenYAxis;\n // change text tag\n var enterlabelsText = null; labelsText.enter()\n .append(\"text\");\n // change text tag\n enterlabelsText = labelsText.enter()\n .append(\"text\")\n .merge(labelsText)\n .attr(\"x\", xPos)\n .attr(\"y\", (d,i) => (i+1)*axisPadding)\n .attr(\"value\", d => d) // value to grab for event listener\n .classed(\"active\", d => (d === chosenAxis) ? true:false)\n .classed(\"inactive\", d => (d === chosenAxis) ? false:true)\n .text(d => labelsTitle[d])\n .on(\"click\", updateChart);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
October 27, 2018 9:37 PM Instructions: / Write a function called "findMaxLengthOfThreeWords". Given 3 words, "findMaxLengthOfThreeWords" returns the length of the longest word. var output = findMaxLengthOfThreeWords('a', 'be', 'see'); console.log(output); // > 3 Notes: / The static function function Math.max() returns the highestvalued number passed into it Syntax Math.max(value1, value2, value3) the length property sets or returns the number of element in an array or string
function findMaxLengthOfThreeWords(word1, word2, word3) { return Math.max(word1.length, word2.length, word3.length); }
[ "function ThirdGreatest(strArr) { \n\n//Find the lengths of the strings\n var stringLengths = [];\n for (i=0; i < strArr.length; i++) {\t\t\t\t\t\t\t\t\t//Loop goes through each element in the string returning the lengths into a new array\n stringLengths[i] = strArr[i].length;\n }\n\n var unsortedLengths = stringLengths.slice(0);\t\t\t\t\t\t\t//A clone of stringLengths is made so that stringLengths can be sorted\n\n//Sort the lengths\n var sortedLengths = stringLengths.sort(function(a, b) {\t\t\t\t//Array of stringLengths is then sorted into ascending order\n return a - b;\n })\n\n//Find the third greatest\n var thirdGreatestSize = sortedLengths[sortedLengths.length - 3];\t\t//The third greatest string length will be third from the last in the array\n\n//Match the lengths with the original lengths array to find the index\n for (i=0; i < sortedLengths.length; i++) {\t\t\t\t\t\t\t//The loop will then go through the unsorted string lengths array\n\t if (unsortedLengths[i] === thirdGreatestSize) {\t\t\t\t\t//If a match is made with the greatest size then the index of it is stored\n\t var indexOfThird = i;\n\t }\n }\n\n//Use the found index to return the correct word\n return strArr[indexOfThird]\n}", "getSongsLongestWords(song) {\n const words = song.split(' ');\n let one = '',\n two = '',\n temp;\n words.forEach(word => {\n if (word.length > two.length) {\n if (word.length > one.length) {\n temp = one;\n one = word;\n two = temp;\n } else {\n two = word;\n }\n }\n })\n return `${one} ${two}`;\n }", "function maxLength(txt){\n let nLines = txt.split('\\n');\n let i = 0;\n let max = nLines[0];\n \n while(i < nLines.length){\n if(max.length < nLines[i].length){\n max = nLines[i];\n }\n i++;\n }\n return max.length;\n}", "function longestWord(phrasesArray) {\n\n// declare an maxIndex variable and initialize it to 0\n var maxIndex = 0;\n// declare a maxLength variable and initialize it to 0\n var maxLength = 0;\n// FOR EACH phrase in the array\n nbPhrases = phrasesArray.length;\n\n for(var index = 0; index < nbPhrases; index++) {\n// find the length of the phrase\n phraseLength = phrasesArray[index].length;\n// IF the length is bigger than max_length\n if(phraseLength >= maxLength) {\n// set maxIndex to the value of the index of the current phrase\n maxIndex = index;\n// set maxLength to the value of the length of the current phrase\n maxLength = phraseLength;\n }\n }\n\n // RETURN the phrase of phrases_array stocked at index number max_index\n return phrasesArray[maxIndex];\n}", "function maxofThree(a,b,c){\n return max(max(a,b),c);\n \n }", "function biggestOfThree (a,b,c){\n\tif (a > b){\n\t\tif (a > c){\n\t\t\treturn a;\n\t\t} else {\n\t\t\treturn c;\n\t\t} \n\t\t}\n\t\tif (c > b) {\n\t\t\treturn c;\n\t\t} else {\n\t\t\treturn b;\n\t\t}\n\t}", "function wordsLongerThanThree(str) {\n // TODO: your code here \n str = str.split(\" \");\n return filter(str, function(value){\n return value.length > 3;\n });\n}", "function setMaxCharacterCount() {\n if ($(\".word\").width() <= 335) {\n return 8;\n } else if ($(\".word\").width() <= 425) {\n return 9;\n } else if ($(\".word\").width() <= 490) {\n return 10;\n } else if ($(\".word\").width() <= 510) {\n return 11;\n } else {\n return 12;\n }\n }", "function LongestWord(sen) {\n let longest = \"\";\n sen.split(\" \").forEach((element) => {\n if (element.length > longest.length) longest = element;\n });\n return longest;\n}", "function longerString(x1, x2, x3, x4) {\n if (length1(x1) > length1(x2) && length1(x1) > length1(x3) &&\n length1(x1) > length1(x4)) {\n return x1;\n } else if ((length1(x1) < length1(x2) && length1(x2) > length1(x3)) &&\n length1(x2) > length1(x4)) {\n return x2;\n } else if ((length1(x1) < length1(x3) && length1(x3) > length1(x2)) &&\n length1(x3) > length1(x4)) {\n return x3;\n } else\n return x4;\n}", "function LongestWord_2(sen) {\n sen = sen.replace(/[.,\\/#!$%\\^&\\*;:{}=\\-_`~()|]/g, \"\");\n\n let longest = \"\";\n sen.split(\" \").forEach((element) => {\n if (element.length > longest.length) longest = element;\n });\n return longest;\n}", "countBigWords(input) {\n // Set a counter equal to 0\n let counter = 0;\n // Split the input into words\n let temp = input.split(\" \");\n // Determine the length of each word by iterating over the array\n //If the word is greater than 6 letters, add 1 to a counter\n // If the word is less than or equal to 6 letters, go on to next word\n for(let i = 0; i < temp.length; i++) {\n if (temp[i].length > 6) {\n counter++;\n }\n }\n // Output the counter\n return counter;\n }", "function getMaxWidth(arr)\n{\n let max = textWidth(arr[0]);\n\n for (let i = 1; i < arr.length; i++)\n {\n let w = textWidth(arr[i]);\n if (w > max)\n {\n max = w;\n }\n }\n return max;\n}", "function getLength(string){\n\n\n}", "function findLongestWord(txt) {\n let strArrayA = txtNoPunctuation(txt);\n let strArrayB = cleanTxt(strArrayA);\n \n let orderedArray = strArrayB.sort(function (wordA, wordB){\n return wordB.length - wordA.length || wordA.localeCompare(wordB);\n });\n \n let filterArray = orderedArray.filter((item, pos, ary) => {\n return !pos || item != ary[pos - 1];\n });\n\n return filterArray.filter((i, index) => (index < 10));\n}", "function longestSentence(longString) {\n let sentencesObj = {};\n let sentenceArr = longString.split(/([.!?])/);\n\n for (let i = 0; i < sentenceArr.length; i += 2) {\n let indSentence = sentenceArr[i].trimStart().concat(sentenceArr[i + 1]);\n let wordArr = indSentence.split(\" \");\n sentencesObj[wordArr.length] = indSentence;\n }\n\n let biggestKey = Math.max(...Object.keys(sentencesObj));\n\n console.log(`Longest sentence: \"${sentencesObj[biggestKey]}\"`);\n console.log(`The longest sentence has ${biggestKey.toString()} words.`)\n }", "function MaximumProductOfThree(arr) {\n let maxArr = [];\n for (let i = 0; i < arr.length; i++) {\n let maxNum = Math.max(...arr);\n maxArr.push(maxNum);\n if (maxArr.length === 3) {\n return maxArr[0] * maxArr[1] * maxArr[2];\n }\n }\n return \"error\";\n}", "function findShort(inputString){\n splitString = inputString.split(' ')\n shortestLength = splitString[0].length\n\n for (let word of splitString) {\n if (word.length < shortestLength) {\n shortestLength = word.length\n }\n }\n return shortestLength\n }", "function topThreeWords(text) {\n\n const words = text.split(/[ .,/]/);\n\n let occur = {};\n\n words.forEach(word => {\n const w = word.toLowerCase();\n if (w.match(/[a-z]/)) {\n occur[w] = (occur[w] || 0) + 1;\n }\n });\n\n let top1 = 0;\n let top2 = 0;\n let top3 = 0;\n\n let result = [];\n\n for (let key in occur) {\n const value = occur[key];\n if (value > top1) {\n top3 = top2;\n top2 = top1;\n top1 = value;\n result.unshift(key);\n } else if (value > top2) {\n top3 = top2;\n top2 = value;\n result.splice(1, 0, key);\n } else if (value > top3) {\n top3 = value;\n result.splice(2, 0, key);\n }\n }\n\n return result.slice(0, 3);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take an array of numbers and make them strings
function stringItUp(arr){ return arr.map(number => number.toString()) }
[ "function numToString(array) {\n let strings = array.map(function(num) {\n return num.toString();\n });\n return strings;\n}", "toNumberString() {\n return this.toSortedArrayNumber().join(\",\");\n }", "function arrayToString()\n{\n\tif ( ! arguments.length ) { return '/' + this.map( mapValue ).join( '/' ) ; } // jshint ignore:line\n\telse { return '/' + Array.prototype.slice.apply( this , arguments ).map( mapValue ).join( '/' ) ; } // jshint ignore:line\n}", "function integerTostring(number) {\n let numberArry = [];\n do {\n let remainder = number % 10; //the last number to the array \n number = Math.floor(number / 10); // remove the last number and prepare a new number for next loop\n \n numberArry.push(remainder); //the last number to the array \n \n } while (number > 0);\n \n return numberArry.reverse().join(''); //because of push method, the array needs to be reversed \n}", "fixedStrings (array, digits = 4) {\n array = this.convertArray(array, Array) // Only Array stores strings.\n return array.map((n) => n.toFixed(digits))\n }", "function arrToStr(arr) {\n\t//initialize resulting string\n\tvar res = \"Array[\";\n\t//loop thru array elements\n\tfor( var index = 0; index < arr.length; index++ ){\n\t\tres += (index > 0 ? \", \" : \"\") + objToStr(arr[index]);\n\t}\n\treturn res + \"]\";\n}", "function digitalize(num){\n let v=num.toString();\n console.log(Array.from(v));\n}", "function coefficientToString(a) { // 497\n var s, z, // 498\n i = 1, // 499\n j = a.length, // 500\n r = a[0] + ''; // 501\n // 502\n for ( ; i < j; ) { // 503\n s = a[i++] + ''; // 504\n z = LOG_BASE - s.length; // 505\n for ( ; z--; s = '0' + s ); // 506\n r += s; // 507\n } // 508\n // 509\n // '0' // 510\n for ( j = r.length; r.charCodeAt(--j) === 48; ); // 511\n // 512\n return r.slice( 0, j + 1 || 1 ); // 513\n } // 514", "function pluralize(array) {\n let pluralString = [];\n\n for (let i = 0; i < array.length; i++) {\n pluralString.push(`${array[i]}s`);\n }\n return pluralString;\n}", "function arrayElemsToString(arr, delim) {\n if (delim === undefined)\n delim = \" \";\n var ret = \"\";\n for (var i = 0;i < arr.length; ++i) {\n ret += arr[i];\n if (i < arr.length - 1)\n ret += delim;\n }\n return ret;\n}", "function toArray(num) {\n\tconst a = num.toString().split(\"\");\n\treturn a.map(x => parseInt(x));\n}", "function bit_to_ascii(array) {\n var num = 0;\n var n;\n for (n = 0; n < 8; n++) {\n if (array[n] == '1') {\n num += Math.pow(2, 7 - n);\n console.log(num);\n }\n }\n return String.fromCharCode(num);\n}", "function print34to41() {\n const array = []\n for(let i = 34; i < 42; i++) {\n array.push(i);\n }\n return array.map(item => `<p class=\"output\">${item}</p>`).join(\"\");\n}", "function textList(array) {\n return array.join();\n}", "function stringsAndNumbers(){\n return strings.concat(numbers);\n}", "function convertToBaby(array) {\nconst babyArray = []\nfor (let i = 0; i < array.length; i++) {\n babyArray.push(`baby ` + array[i]);\n}\nreturn babyArray;\n}", "function composeRanges(nums) {\n\n let stringArr = [];\n let firstNum = nums[0];\n let prevNum = nums[0];\n let currStr = `${nums[0]}`;\n\n if(nums.length === 0){\n return [];\n }\n\n for(let x = 1; x < nums.length; x++){\n\n if(nums[x] - 1 === prevNum){\n currStr = `${firstNum}->${nums[x]}`;\n\n } else {\n stringArr.push(currStr);\n currStr = `${nums[x]}`;\n firstNum = nums[x];\n }\n\n prevNum = nums[x];\n }\n\n stringArr.push(currStr);\n\n return stringArr;\n}", "function encode_arr(arr) {\n var arr_out = []\n for (let i of arr) {\n arr_out.push(encoder(i))\n }\n return arr_out\n}", "function pluralize(arr) {\n //return new array with an 's'\n const newArr = [];\n for (let i = 0; i < arr.length; i++) {\n newArr.push(arr[i] + 's')\n }\n return newArr\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Custom type guard for FileTypeDeclaration. Returns true if node is instance of FileTypeDeclaration. Returns false otherwise. Also returns false for super interfaces of FileTypeDeclaration.
function isFileTypeDeclaration(node) { return node.kind() == "FileTypeDeclaration" && node.RAMLVersion() == "RAML10"; }
[ "function hasTypeAnnotation (path: NodePath): boolean {\n if (!path.node) {\n return false;\n }\n else if (path.node.typeAnnotation) {\n return true;\n }\n else if (path.isAssignmentPattern()) {\n return hasTypeAnnotation(path.get('left'));\n }\n else {\n return false;\n }\n}", "is_image() {\n if (\n this.file_type == \"jpg\" ||\n this.file_type == \"png\" ||\n this.file_type == \"gif\"\n ) {\n return true;\n }\n return false;\n }", "function isTypeScriptFile(fileName) {\n return /\\.tsx?$/i.test(fileName || '');\n}", "function isDefinitionFile(fileName) {\n return /\\.d\\.tsx?$/i.test(fileName || '');\n}", "function cs_contains_invalid_file_types(files, accepted_file_types){\r\n\t\r\n\tvar uploaded_files = files;\r\n\t\r\n\tvar invalid_file_types = 0;\r\n\t\r\n\tfor(var i = 0; i < uploaded_files.length; i++){\r\n\t\tif(!cs_validate_file_type(uploaded_files[i], accepted_file_types))\r\n\t\t\tinvalid_file_types++;\r\n\t}\r\n\t\r\n\treturn (invalid_file_types > 0) ? true : false;\r\n\t\r\n}", "isValidTypeScriptFile(handlerFile) {\n //replaces the last occurance of `.js` with `.ts`, case insensitive\n const typescriptHandlerFile = handlerFile.replace(/\\.js$/gi, \".ts\");\n return super.isValidFile(typescriptHandlerFile);\n }", "removeImportAndDetectIfType() {\n this.tokens.removeInitialToken();\n if (\n this.tokens.matchesContextual(_keywords.ContextualKeyword._type) &&\n !this.tokens.matches1AtIndex(this.tokens.currentIndex() + 1, _types.TokenType.comma) &&\n !this.tokens.matchesContextualAtIndex(this.tokens.currentIndex() + 1, _keywords.ContextualKeyword._from)\n ) {\n // This is an \"import type\" statement, so exit early.\n this.removeRemainingImport();\n return true;\n }\n\n if (this.tokens.matches1(_types.TokenType.name) || this.tokens.matches1(_types.TokenType.star)) {\n // We have a default import or namespace import, so there must be some\n // non-type import.\n this.removeRemainingImport();\n return false;\n }\n\n if (this.tokens.matches1(_types.TokenType.string)) {\n // This is a bare import, so we should proceed with the import.\n return false;\n }\n\n let foundNonType = false;\n while (!this.tokens.matches1(_types.TokenType.string)) {\n // Check if any named imports are of the form \"foo\" or \"foo as bar\", with\n // no leading \"type\".\n if ((!foundNonType && this.tokens.matches1(_types.TokenType.braceL)) || this.tokens.matches1(_types.TokenType.comma)) {\n this.tokens.removeToken();\n if (\n this.tokens.matches2(_types.TokenType.name, _types.TokenType.comma) ||\n this.tokens.matches2(_types.TokenType.name, _types.TokenType.braceR) ||\n this.tokens.matches4(_types.TokenType.name, _types.TokenType.name, _types.TokenType.name, _types.TokenType.comma) ||\n this.tokens.matches4(_types.TokenType.name, _types.TokenType.name, _types.TokenType.name, _types.TokenType.braceR)\n ) {\n foundNonType = true;\n }\n }\n this.tokens.removeToken();\n }\n return !foundNonType;\n }", "hasInheritance(node) {\n let inherits = false;\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n if (match_1.default(child, 'extends', 'implements')) {\n inherits = true;\n }\n }\n return inherits;\n }", "function check(...types) {\n for (const type of types) {\n if (type === currentToken().type) {\n return true;\n }\n }\n return false;\n }", "function isFieldType(template_name, field_name, field_type)\n{\n for(var i = 0; i < field_type.length; i++) {\n var row_of_fields = field_type[i];\n if(row_of_fields[0]==template_name)\n {\n for(var j = 1; j < row_of_fields.length; j++) {\n if(field_name==row_of_fields[j])\n return true;\n }\n return false;\n }\n }\n return false;\n}", "function isTransformableDecl (decl) {\n\treturn !customPropertyRegExp.test(decl.prop) && customPropertiesRegExp.test(decl.value);\n}", "function canContain(block, node) {\n if (node.object === 'inline' || node.object === 'text') {\n return LEAFS[block.type];\n }\n const types = acceptedBlocks(block);\n return types && types.indexOf(node.type) !== -1;\n}", "function isValidFileSize(type, file) {\n const supportedFile = supportedFileMap[type];\n return file.size < supportedFile.maxSize;\n}", "function isObjectPattern(node) {\n return node.type === \"ObjectPattern\";\n}", "visitType_declaration(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function isRecordTypeExportAble (recordType)\n{\n\t\n\tvar ssoTypesAndCustomFields = ssoRecordTypeMap(recordType); \n\tif (typeof ssoTypesAndCustomFields === 'object') \n\t{\n\t\treturn ssoTypesAndCustomFields.hasOwnProperty('export_oa_field');\t\t\n\t}\n\telse \n\t{\n\t\treturn false; \n\t}\n\n}", "function verifyMimeType(execptedMimeType, test) {\n return function (err, file) {\n test.expect(2);\n if (err) {\n throw err;\n }\n var stream = fs.createReadStream(file);\n magic(stream, function (err, mime, output) {\n if (err) {\n throw err;\n }\n test.equal(mime.type, execptedMimeType);\n var targetFile = path.join(tempfile, path.basename(file));\n var writeStream = fs.createWriteStream(targetFile);\n output.pipe(writeStream);\n writeStream.on(\"finish\", function () {\n var source = fs.readFileSync(file);\n var target = fs.readFileSync(targetFile);\n test.ok(source.equals(target), \"Source and target file contents must match.\");\n test.done();\n });\n });\n }\n}", "check_type(parent_var_type, node, curr_var_type) {\n if (parent_var_type !== curr_var_type) {\n if (!this.invalid_semantic_programs.includes(this._current_ast.program)) {\n this.invalid_semantic_programs.push(this._current_ast.program);\n } // if\n this.output[this.output.length - 1].push(new NightingaleCompiler.OutputConsoleMessage(SEMANTIC_ANALYSIS, ERROR, `Type mismatch error: tried to perform an operation on [${curr_var_type}] with [${parent_var_type}] at ${node.getToken().lineNumber}:${node.getToken().linePosition}`) // OutputConsoleMessage\n ); // this.output[this.output.length - 1].push\n this.verbose[this.verbose.length - 1].push(new NightingaleCompiler.OutputConsoleMessage(SEMANTIC_ANALYSIS, ERROR, `Type mismatch error: tried to perform an operation on [${curr_var_type}] with [${parent_var_type}] at ${node.getToken().lineNumber}:${node.getToken().linePosition}`) // OutputConsoleMessage\n ); // this.verbose[this.verbose.length - 1].push\n this._error_count += 1;\n return false;\n } // if\n return true;\n }", "function hasRequiredNodes(node) {\n\t\t\tif (typeof node !== 'object') {\n\t\t\t\tthrow \"hasRequiredNodes: Expected argument node of type object, \" + typeof node + \" given.\";\n\t\t\t}\n\n\t\t\tif (node.hasChildNodes()) {\n\t\t\t\tfor (var i = 0, len = node.childNodes.length; i < len; i++) {\n\t\t\t\t\tif (options.nodeTypes.indexOf(node.childNodes[i].nodeType) !== -1) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}", "function isNodeOutputFS(compiler) {\n\treturn (\n\t\tcompiler.outputFileSystem &&\n\t\tcompiler.outputFileSystem.constructor &&\n\t\tcompiler.outputFileSystem.constructor.name === 'NodeOutputFileSystem'\n\t);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
stream_append appends first argument stream and second argument stream. In the result, null at the end of the first argument stream is replaced by the second argument stream stream_append throws an exception if the first argument is not a stream. Lazy? Yes: the result stream forces the actual append operation
function stream_append(xs, ys) { return is_null(xs) ? ys : pair(head(xs), () => stream_append(stream_tail(xs), ys)); }
[ "function mergeStreams(streams) {\n streams = streams.filter(function(e) {return !!e});\n if (!streams || streams.length == 0) {\n return;\n }\n if (streams.length == 1) {\n return streams[0];\n }\n var result = merge(streams[0], streams[1]);\n for (var i = 2; i < streams.length; i++) {\n result.add(streams[i]);\n }\n return result;\n}", "function concat(stream, callback) {\n var data = [];\n stream.on('data', function (chunk) {\n data.push(chunk);\n });\n\n stream.on('end', function () {\n callback(null, data.join(''));\n });\n}", "function joined(stringStream) {\n return takeUntil(\n (x) => x.length === 0,\n stringStream\n )[0].reduce((x, y) => x.concat(y));\n}", "mergeStreamInfo() {\n for(var key in this.extraStreamInfo) {\n if (!this.extraStreamInfo.hasOwnProperty(key)) {\n continue;\n }\n this.streamInfo[key] = this.extraStreamInfo[key];\n }\n }", "function lowWrite(stream, data) {\n return new Promise((resolve, reject) => {\n if (stream.write(data)) {\n process.nextTick(resolve);\n } else {\n stream.once(\"drain\", () => {\n stream.off(\"error\", reject);\n resolve();\n });\n stream.once(\"error\", reject);\n }\n });\n}", "function is_stream(xs) {\n return is_null(xs) || (is_pair(xs) && is_list(stream_tail(xs)));\n}", "function combined_stream_from_groups(groups, URLfunc) {\n /*\n * Record the stream created for the last group.\n * This will be drained last, and when ended, we must\n * also end the output.\n */\n var last = null;\n\n /*\n * Reduce the stream of groups into a single stream that receives\n * all events from all of the group-specific streams.\n */\n const out = new DataStream();\n groups.reduce(\n /* Reducer function, piping to output */\n function(out, group) {\n /*\n * Since all the substreams are piped to the output without\n * ending the output, we must still explicitly end it,\n * which we do once we encounter the sentinel.\n */\n last = fetch_as_JSON_stream(URLfunc(group));\n return last.pipe(out, {end: false});\n },\n /* Initial output, an empty DataStream. */\n out\n ).then(\n (out) => last.on('end', () => { out.end(); }) // XXX Simplify?\n );\n return out;\n}", "function wrap(stream) {\n stream.on('error', error => {\n gutil.log(gutil.colors.red(error.message));\n gutil.log(error.stack);\n if (watching) {\n gutil.log(gutil.colors.yellow('[aborting]'));\n stream.end();\n } else {\n gutil.log(gutil.colors.yellow('[exiting]'));\n process.exit(1);\n }\n ringBell();\n });\n return stream;\n}", "function smash(files) {\n var s = new stream.PassThrough({encoding: \"utf8\", decodeStrings: false}),\n q = queue(1),\n fileMap = {};\n\n // Streams the specified file and any imported files to the output stream. If\n // the specified file has already been streamed, does nothing and immediately\n // invokes the callback. Otherwise, the file is streamed in chunks, with\n // imports expanded and resolved as necessary.\n function streamRecursive(file, callback) {\n if (file in fileMap) return void callback(null);\n fileMap[file] = true;\n\n // Create a serialized queue with an initial guarding callback. This guard\n // ensures that the queue does not end prematurely; it only ends when the\n // entirety of the input file has been streamed, including all imports.\n var c, q = queue(1).defer(function(callback) { c = callback; });\n\n // The \"error\" and \"end\" events can be sent immediately to the guard\n // callback, so that streaming terminates immediately on error or end.\n // Otherwise, imports are streamed recursively and chunks are sent serially.\n readStream(file)\n .on(\"error\", c)\n .on(\"import\", function(file) { q.defer(streamRecursive, file); })\n .on(\"data\", function(chunk) { q.defer(function(callback) { s.write(chunk, callback); }); })\n .on(\"end\", c);\n\n // This last callback is only invoked when the file is fully streamed.\n q.awaitAll(callback);\n }\n\n // Stream each file serially.\n files.forEach(function(file) {\n q.defer(streamRecursive, expandFile(file, defaultExtension));\n });\n\n // When all files are streamed, or an error occurs, we're done!\n q.awaitAll(function(error) {\n if (error) s.emit(\"error\", error);\n else s.end();\n });\n\n return s;\n}", "function pipeAndWrap (res, stream) {\n res.on('close', function () { stream.emit('close') })\n stream.httpVersion = res.httpVersion\n stream.headers = res.headers\n stream.trailers = res.trailers\n stream.setTimeout = res.setTimeout.bind(res)\n stream.method = res.method\n stream.url = res.url\n stream.statusCode = res.statusCode\n stream.socket = res.socket\n return res.pipe(stream)\n}", "function list_to_stream(xs) {\n return is_null(xs)\n ? null\n : pair(head(xs),\n () => list_to_stream(tail(xs)));\n}", "function addChunksAndExpect(expect, streamParser, chunks, expected) {\n let isDone = false;\n chunks.forEach((chunk, i) => {\n const ret = streamParser.addChunk(chunk);\n if (streamParser.done) {\n isDone = true;\n }\n if (isDone) {\n expect(ret).toEqual(expected);\n expect(streamParser.done).toBe(true);\n expect(streamParser.result).toEqual(expected);\n } else {\n expect(ret).toBe(null);\n expect(streamParser.done).toBe(false);\n expect(streamParser.result).toBe(null);\n }\n });\n\n const ret = streamParser.addEOF();\n expect(ret).toEqual(expected);\n expect(streamParser.done).toBe(true);\n expect(streamParser.result).toEqual(expected);\n}", "function applyFilters(err, stream, options, callback) {\r\n /**\r\n * Join raw chunks.\r\n * @param err\r\n * @param stream\r\n * @param callback\r\n */\r\n function compress(err, stream, callback) {\r\n if (err) {\r\n callback(err);\r\n return;\r\n }\r\n var out = [];\r\n stream.forEach(function(chunk) {\r\n if (chunk.op == 'raw' && out.length && \r\n out[out.length-1].op == 'raw') {\r\n out[out.length-1].value = \r\n (out[out.length-1].value + chunk.value);\r\n } else {\r\n out.push(chunk);\r\n }\r\n });\r\n callback(undefined, out);\r\n }\r\n \r\n if (err) {\r\n callback(err);\r\n return;\r\n }\r\n \r\n compress(err, stream, function(err, stream) {\r\n // collect filters without nested filters\r\n collected = [];\r\n nested = false;\r\n buffer = [];\r\n huntFor = \"\";\r\n huntId = undefined;\r\n for ( var i = 0; i < stream.length; i++) {\r\n if (stream[i].op == 'filter') {\r\n if (huntFor) nested = true;\r\n huntFor = stream[i].value;\r\n huntId = i;\r\n buffer = [];\r\n } else if (stream[i].op == \"end\" \r\n && stream[i].value == huntFor) {\r\n Array.prototype.push.apply(collected, buffer);\r\n } else if (huntFor && stream[i].op == \"raw\") {\r\n buffer.push({id:i, \r\n value: stream[i].value, \r\n filter: huntFor,\r\n fId: huntId});\r\n }\r\n }\r\n \r\n if (collected.length) {\r\n var actions = collected.map(function(sign) {\r\n return function(callback) {\r\n (options.filters[sign.filter] || \r\n options.filters.undefinedFilter)\r\n (sign.value, function(err, value) {\r\n callback(err, value, sign.id, sign.fId);\r\n });\r\n };\r\n });\r\n parallel(actions, function(results) {\r\n var toKill = []; // filter chunks\r\n results.forEach(function(result) {\r\n if (result.type === 'success') {\r\n var value = result.values[0];\r\n var id = result.values[1];\r\n var fId = result.values[2];\r\n stream[id].value = value;\r\n stream[fId].op = \"TO_KILL\";\r\n }\r\n });\r\n cleanup(err, stream, \"TO_KILL\", function(err, stream) {\r\n nested ? applyFilters(err, stream, options, callback) \r\n : callback(undefined, stream);\r\n });\r\n });\r\n } else { // no filters - just do callback\r\n callback(undefined, stream);\r\n }\r\n });\r\n}", "_stream(connection, obj, stream, options) {\n options = options || {}\n return new Promise((resolver, rejecter) => {\n stream.on('error', rejecter)\n stream.on('end', resolver)\n connection.query(obj.sql, obj.bindings).stream(options).pipe(stream)\n })\n }", "combineResults(prev, next = []) {\n return prev.concat(next)\n }", "function concatSubDirStreams(baseDir, createStream) {\n var streams = mapSubDir(baseDir, createStream);\n return eventStream.concat.apply(null, streams);\n}", "function concat(source) {\n return accumulatable(function accumulateConcat(next, initial) {\n function nextAppend(a, b) {\n if(b === end) return accumulate(a, next, initial);\n\n return a === null ? b : append(a, b);\n }\n\n accumulate(source, nextAppend, null);\n });\n}", "function tail(stream) /* forall<a> (stream : stream<a>) -> stream<a> */ {\n return stream.tail;\n}", "function appendBytes() {\n for (var i = 0; i < arguments.length; i++) {\n final.push(arguments[i]);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build router configuration array based on metadata used for the toolbar. IMPORTANT: router has to be configured before the first sync!
function configureRouter(root, metaData) { var i, item, routerConfig = {}; for (i = 0; i < metaData.length; i++) { item = metaData[i]; routerConfig[item.id] = { name: item.name, isDefault: (item.id === 'home'), canEnter: item.canEnter ? item.canEnter : null, enter: item.enter ? item.enter : null, exit: item.exit ? item.exit : null }; } return root.configure(routerConfig); }
[ "merge(router) {\n for (var route of router.routes) {\n this.routes.push(route);\n }\n }", "_register(config, routes, parentRoute) {\n routes = routes ? routes : this._routes;\n for (let i = 0; i < config.length; i++) {\n let { onEnter, onExit, path, outlet, children, defaultRoute = false, defaultParams = {} } = config[i];\n let [parsedPath, queryParamString] = path.split('?');\n let queryParams = [];\n parsedPath = this._stripLeadingSlash(parsedPath);\n const segments = parsedPath.split('/');\n const route = {\n params: [],\n outlet,\n path: parsedPath,\n segments,\n defaultParams: parentRoute ? Object.assign({}, parentRoute.defaultParams, defaultParams) : defaultParams,\n children: [],\n fullPath: parentRoute ? `${parentRoute.fullPath}/${parsedPath}` : parsedPath,\n fullParams: [],\n fullQueryParams: [],\n onEnter,\n onExit\n };\n if (defaultRoute) {\n this._defaultOutlet = outlet;\n }\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n if (typeof segment === 'string' && segment[0] === '{') {\n route.params.push(segment.replace('{', '').replace('}', ''));\n segments[i] = PARAM;\n }\n }\n if (queryParamString) {\n queryParams = queryParamString.split('$').map((queryParam) => {\n return queryParam.replace('{', '').replace('}', '');\n });\n }\n route.fullQueryParams = parentRoute ? [...parentRoute.fullQueryParams, ...queryParams] : queryParams;\n route.fullParams = parentRoute ? [...parentRoute.fullParams, ...route.params] : route.params;\n if (children && children.length > 0) {\n this._register(children, route.children, route);\n }\n this._outletMap[outlet] = route;\n routes.push(route);\n }\n }", "getRoutingSettings() { \n\n\t\treturn this.apiClient.callApi(\n\t\t\t'/api/v2/routing/settings', \n\t\t\t'GET', \n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\tnull, \n\t\t\t['PureCloud OAuth'], \n\t\t\t['application/json'],\n\t\t\t['application/json']\n\t\t);\n\t}", "remoteConfig() {\n const configs = Object.assign({}, Remote_1.RemoteConfig);\n configs.uri = this.apiUrl();\n return configs;\n }", "createRouter() {\n this.router = new Router(this);\n }", "loadRoutes() {\n this._routes = this.loadConfigFile('routes') || function() {};\n }", "get routes() {\n return JSON.parse(JSON.stringify(this._routes));\n }", "_initialize() {\n if ( this._initialized ) {\n return;\n }\n\n this._log(2, `Initializing Routes...`);\n\n //Add routing information to crossroads\n // todo: handle internal only routes\n // An internal only route can be used to keep track of UI state\n // But it will never update the URL\n // You can't use .go() to get to an internal route\n // You can only get it via directly calling dispatch(route, params)\n //\n let routes = this.routes;\n\n for (let route of routes) {\n this._log(3, `Initializing >> ${route.name}`);\n\n // Set basename\n route.set_basename(this._basename);\n // Set crossroads_route\n route._crossroads = this.crossroads.addRoute(route.path, this._make_crossroads_shim(route));\n }\n\n this._log(3, `Initialized ${routes.length} routes`);\n this._initialized = true;\n }", "function routehelperConfig() {\n this.config = {\n // These are the properties we need to set\n $routeProvider: undefined,\n resolveAlways: {},\n };\n\n this.$get = () => ({\n config: this.config,\n });\n }", "function setup(router) {\n var _this = this;\n\n //middleware for routing\n router.onNavigate(function (path) {\n\n //leave real time connection in thread\n if (_socket2.default.inRoom) _socket2.default.leaveRoom();\n\n //clear view on route change --> maybe put an animation\n (0, _helpers.spinner)();\n });\n\n //set up root handler '/'\n router.onRoot((0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee() {\n var res, resp;\n return _regenerator2.default.wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n router.location = 'random';\n _context.next = 3;\n return (0, _groups.getAuth)(main);\n\n case 3:\n res = _context.sent;\n _context.next = 6;\n return res.json();\n\n case 6:\n resp = _context.sent;\n\n (0, _group2.default)(main, 0, resp);\n\n case 8:\n case 'end':\n return _context.stop();\n }\n }\n }, _callee, _this);\n })));\n\n //route for user view and settings '/user/:username'\n router.add(/user\\/(.*)/, function (username) {\n router.location = 'user';\n (0, _user2.default)(username);\n //user view\n console.log('user');\n });\n\n //search '/search/:search'\n router.add(/search\\/(.*)/, function (search) {\n router.location = 'search';\n search = search.replace(/_/g, ' ');\n //search view\n (0, _search2.default)(search);\n console.log('search');\n });\n\n //route for pagination on groups '/:group/:page'\n router.add(/(.*)\\/t\\/(.*)/, function () {\n var _ref2 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee2(group, thread) {\n var res, resp;\n return _regenerator2.default.wrap(function _callee2$(_context2) {\n while (1) {\n switch (_context2.prev = _context2.next) {\n case 0:\n router.location = group;\n _socket2.default.joinRoom(thread);\n group = group ? group : '/';\n _context2.next = 5;\n return (0, _groups.getAuth)('/' + group + '/');\n\n case 5:\n res = _context2.sent;\n _context2.next = 8;\n return res.json();\n\n case 8:\n resp = _context2.sent;\n\n if (!(!resp.allowed && group != \"/404/\")) {\n _context2.next = 11;\n break;\n }\n\n return _context2.abrupt('return');\n\n case 11:\n //setup thread view\n (0, _thread2.default)(thread);\n\n case 12:\n case 'end':\n return _context2.stop();\n }\n }\n }, _callee2, _this);\n }));\n\n return function (_x, _x2) {\n return _ref2.apply(this, arguments);\n };\n }());\n\n //route for pagination on groups '/:group/:page'\n router.add(/(.*)\\/(.*)/, function () {\n var _ref3 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee3(group, page) {\n var res, resp;\n return _regenerator2.default.wrap(function _callee3$(_context3) {\n while (1) {\n switch (_context3.prev = _context3.next) {\n case 0:\n router.location = group;\n group = '/' + group + '/';\n _context3.next = 4;\n return (0, _groups.getAuth)(group);\n\n case 4:\n res = _context3.sent;\n _context3.next = 7;\n return res.json();\n\n case 7:\n resp = _context3.sent;\n\n if (!(!resp.allowed && group != \"/404/\")) {\n _context3.next = 10;\n break;\n }\n\n return _context3.abrupt('return');\n\n case 10:\n\n //setup group once again -- squiggles are a string -> int type conversion\n (0, _group2.default)(group, ~~page, resp);\n\n case 11:\n case 'end':\n return _context3.stop();\n }\n }\n }, _callee3, _this);\n }));\n\n return function (_x3, _x4) {\n return _ref3.apply(this, arguments);\n };\n }());\n\n //route for group (page:0) '/:group' || if integer --> pagination for FP\n router.add(/(.*)/, function () {\n var _ref4 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee4(group) {\n var res, resp;\n return _regenerator2.default.wrap(function _callee4$(_context4) {\n while (1) {\n switch (_context4.prev = _context4.next) {\n case 0:\n router.location = group;\n group = '/' + group + '/';\n _context4.next = 4;\n return (0, _groups.getAuth)(group);\n\n case 4:\n res = _context4.sent;\n _context4.next = 7;\n return res.json();\n\n case 7:\n resp = _context4.sent;\n\n if (!(!resp.allowed && group != \"/404/\")) {\n _context4.next = 10;\n break;\n }\n\n return _context4.abrupt('return');\n\n case 10:\n //setup group\n (0, _group2.default)(group, 0, resp);\n\n case 11:\n case 'end':\n return _context4.stop();\n }\n }\n }, _callee4, _this);\n }));\n\n return function (_x5) {\n return _ref4.apply(this, arguments);\n };\n }());\n}", "$registerRouter() {\n this.$container.singleton('Adonis/Core/Route', () => {\n return this.$container.use('Adonis/Core/Server').router;\n });\n }", "getRoutes() {\n let routes = [];\n this.getGroups().forEach(group => {\n routes = routes.concat(group.routes);\n });\n if (this.fallback) {\n routes = routes.concat(this.fallback.routes);\n }\n return routes;\n }", "loadAppConfig() {\n // Load tools\n this.tools = Tools.map((t) => new t());\n EventBus.$emit(\"ui-set-tools\", this.tools);\n\n // Load menu\n this.menu = Menu;\n EventBus.$emit(\"ui-set-menu\", this.menu);\n }", "async fetchRoutingTable(data) {\n const {\n routes\n } = await this.service.getDefaultRoutes({\n lang: data.lang\n }).then(n => Object(_adapter__WEBPACK_IMPORTED_MODULE_2__[\"toDefaultRoutes\"])(n));\n const {\n routes: routesFromApi\n } = await this.service.getRoutesFromApi({\n store_id: data.storeId\n }).then(n => Object(_adapter__WEBPACK_IMPORTED_MODULE_2__[\"toRoutesFromApi\"])(n));\n routes.pages = routes.pages.concat(routesFromApi);\n return routes;\n }", "function config() {\n\toutlet(0, 'host', addr_broadcast);\n\toutlet(0, 'port', iotport);\n\toutlet(0, '/config');\n}", "routes() {\n const routes = [];\n\n for (let i = 1; i <= 6; i++) {\n routes.push('/projects/' + i)\n }\n\n return routes\n }", "function loadRoutes(routeConfigs, baseUrl, onDuplicateRoutes) {\n handleDuplicateRoutes(routeConfigs, onDuplicateRoutes);\n const res = {\n // To be written by `genRouteCode`\n routesConfig: '',\n routesChunkNames: {},\n registry: {},\n routesPaths: [(0, utils_1.normalizeUrl)([baseUrl, '404.html'])],\n };\n // `genRouteCode` would mutate `res`\n const routeConfigSerialized = routeConfigs\n .map((r) => genRouteCode(r, res))\n .join(',\\n');\n res.routesConfig = `import React from 'react';\nimport ComponentCreator from '@docusaurus/ComponentCreator';\n\nexport default [\n${indent(routeConfigSerialized)},\n {\n path: '*',\n component: ComponentCreator('*'),\n },\n];\n`;\n return res;\n}", "function createTopo(){\n\tif(globalDeviceType==\"Mobile\"){\n\t\tloading(\"show\");\n\t}\n\n\tvar qry = getStringJSON(globalMAINCONFIG[pageCanvas]);\n\n\t$.ajax({\n\t\turl: getURL(\"ConfigEditorTopo\", \"JSON\"),\n//\t\turl: \"https://\"+CURRENT_IP+\"/cgi-bin/Final/RM_CGI_AutoComplete/AutoCompleteCgiQuerryjayson/FindResource2.cgi\",\n\t\tdata : {\n\t\t\t\"action\": \"savetopomap\",\n\t\t\t\"query\": qry\n\t\t},\n\t\tmethod: 'POST',\n\t\tproccessData: false,\n\t\tdataType: 'html',\n\t\tsuccess: function(data) {\n\t\t\tif(data){\n\t\t\t\tif(globalDeviceType==\"Mobile\"){\n\t\t\t\t\talert(\"Configuration successfully converted to topo file and is now ready to be downloaded.\");\n\t\t\t\t\ttopoMapVar = data;\n\t\t\t\t}\n//\t\t\t\tconvertTopoToXml(Name);\n\t\t\t\tdownloadFileWeb('topo');;\n\t\t\t}else{\n\t\t\t\talert(\"Something went wrong, config convertion failed.\");\n\t\t\t}\n\t\t\tif(globalDeviceType==\"Mobile\"){\n\t\t\t\tloading('hide');\n\t\t\t}\n\t\t}\n\t});\n}", "createRouteTable() {\n this.routeTable = new Map();\n for (const [controllerMethod, annotations] of this.annotations) {\n const accepts = [];\n let method = null;\n for (const annotation of annotations) {\n switch (annotation.name) {\n case 'method':\n method = annotation.args[0];\n break;\n case 'accept':\n accepts.push(annotation.args[0]);\n break;\n }\n }\n if (method === null) {\n throw new Error('Controller method ' + controllerMethod + ' was annotated, but it needs a @method annotation to actually do anything');\n }\n if (!this.routeTable.has(method)) {\n this.routeTable.set(method, {\n accepts: new Map(),\n default: null\n });\n }\n const route = this.routeTable.get(method);\n if (accepts.length === 0) {\n route.default = controllerMethod;\n }\n else {\n for (const mime of accepts) {\n if (mime === '*') {\n route.default = controllerMethod;\n }\n else {\n route.accepts.set(mime, controllerMethod);\n }\n }\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check if x,y is 4 connected
function is4Connected (x, y) { var c = getConnections(x, y); for (var key in c) { // console.log("$$border : "+key); if (c[key] == null) { console.log("border : "+key); delete c[key]; }; }; if ((c._n == null || c._n.color != null) && (c._s == null || c._s.color != null) && (c._e == null || c._e.color != null) && (c._w == null || c._w.color != null)) { //debug console.log("has full 4 connection"); return true; }; return false; }
[ "function is4SameColor (x, y, color) {\r\n\t\tvar c = getConnections(x, y);\r\n\r\n\t\tfor (var key in c) {\r\n\t\t\t// console.log(\"$$border : \"+key);\r\n\t\t\tif (c[key] == null) {\r\n\t\t\t\tconsole.log(\"border : \"+key);\r\n\t\t\t\tdelete c[key];\r\n\t\t\t};\r\n\t\t};\r\n\r\n\t\tif ((c._n == null || c._n.color == color) && (c._s == null || c._s.color == color) && (c._e == null || c._e.color == color) && (c._w == null || c._w.color == color)) {\r\n\t\t\treturn true;\r\n\t\t};\r\n\t\treturn false;\r\n\t}", "function checkMeshConnectivity({points, delaunator: {triangles, halfedges}}) {\n // 1. make sure each side's opposite is back to itself\n // 2. make sure region-circulating starting from each side works\n let r_ghost = points.length - 1, s_out = [];\n for (let s0 = 0; s0 < triangles.length; s0++) {\n if (halfedges[halfedges[s0]] !== s0) {\n console.log(`FAIL _halfedges[_halfedges[${s0}]] !== ${s0}`);\n }\n let s = s0, count = 0;\n s_out.length = 0;\n do {\n count++; s_out.push(s);\n s = TriangleMesh.s_next_s(halfedges[s]);\n if (count > 100 && triangles[s0] !== r_ghost) {\n console.log(`FAIL to circulate around region with start side=${s0} from region ${triangles[s0]} to ${triangles[TriangleMesh.s_next_s(s0)]}, out_s=${s_out}`);\n break;\n }\n } while (s !== s0);\n }\n}", "hasMultipleConnections() {\n let result = false;\n this.getConnections().forEach(connection => {\n this.getConnections().forEach(_connection => {\n if (_connection.id !== connection.id) {\n if (_connection.source.node === connection.source.node) {\n if (_connection.target.node === connection.target.node) {\n result = true;\n }\n }\n }\n })\n });\n return result;\n }", "isConnected(node1, node2) {\r\n for (let index = 0; index < this.edgeList.length; index++) {\r\n if ((this.edgeList[index].startNode === node1 &&\r\n this.edgeList[index].endNode === node2) ||\r\n (this.edgeList[index].endNode === node1 &&\r\n this.edgeList[index].startNode === node2)) {\r\n return true;\r\n }\r\n\r\n }\r\n return false;\r\n }", "function checkCorner4(cube) {\n if( ((cube[up][2][0] == 'R') && (cube[right][2][0] == 'W') && (cube[back][0][0] == 'G')) || ((cube[up][2][0] == 'W') && (cube[right][2][0] == 'G') && (cube[back][0][0] == 'R')) || ((cube[up][2][0] == 'G') && (cube[right][2][0] == 'R') && (cube[back][0][0] == 'W')) ) return true;\n else return false;\n}", "__hasOccupiedNeighbours(colour, x, y){\n if (x - 1 > -1) {\n if(this.board.get(x-1, y) === colour){\n return true;\n }\n }\n if (y - 1 > -1) {\n if(this.board.get(x, y-1) === colour){\n return true;\n }\n }\n if (x + 1 < this.size) {\n if(this.board.get(x+1, y) === colour){\n return true;\n }\n }\n if (y + 1 < this.size) {\n if(this.board.get(x, y+1) === colour){\n return true;\n }\n }\n return false;\n }", "function conway(cell, neighbors) {\n if (numberOfLiveNeighbors(neighbors) >= 2\n){\n return true;\n }\n return false;\n}", "function checkAdjacentTiles(x1, y1) {\n if((x1>=0)&&(y1>=0)&&(x1<columns)&&(y1<rows)) //Verify if coordinates do not fall outside of the gridMatrix.\n return gridMatrix[x1+y1*columns];\n}", "getNeighborsOnOff(y, x) {\n const results = [];\n for (let i = y - 1; i <= y + 1; i++) {\n for (let j = x - 1; j <= x + 1; j++) {\n // When getting neighbors for the first or last row/column on a non-infinite board, many\n // neighbors are non-existent so for our purposes, assume they are off\n if (i < 0 || i >= this.numRows || j < 0 || j >= this.numColumns) {\n results.push(false);\n continue;\n }\n // Skip counting the current cell among its neighbors\n if (i !== y || j !== x) {\n results.push(this.cells[i][j].classList.contains('on'));\n }\n }\n }\n return results;\n }", "function connected(p , q){\n return root(p) === root(q);\n }", "oppositeColors(x1,y1,x2,y2){\r\n if(this.getColor(x1,y1) !== 0 && this.getColor(x2,y2) !== 0 && this.getColor(x1,y1) !== this.getColor(x2,y2)){\r\n return true;\r\n }\r\n return false;\r\n }", "function areAdjacent(squareOne, squareTwo) { \n if (squareOne.x < squareTwo.x + 2 &&\n squareOne.x > squareTwo.x - 2 &&\n squareOne.y < squareTwo.y + 2 &&\n squareOne.y > squareTwo.y - 2) {\n return true;\n } else {\n return false;\n }\n}", "hasSumInARow(x,y,targetCount){\r\n return (this.north(x, y, 1,targetCount) || this.northEast(x, y, 1,targetCount) || this.east(x, y, 1,targetCount) || this.southEast(x, y, 1,targetCount) || this.south(x, y, 1,targetCount) || this.southWest(x, y, 1,targetCount) || this.west(x, y, 1,targetCount) || this.northWest(x, y, 1,targetCount));\r\n }", "function isClearRoute(x1, y1, x2, y2) {\n\n var smallX = (x1 <= x2) ? x1 : x2,\n bigX = (x1 > x2) ? x1 : x2,\n smallY = (y1 <= y2) ? y1 : y2,\n bigY = (y1 > y2) ? y1 : y2;\n\n var coordinates = [];\n for (var y = smallY; y < bigY + 1; ++y) {\n for (var x = smallX; x < bigX + 1; ++x) {\n coordinates.push([x, y]);\n }\n }\n return !containsWall(coordinates);\n }", "function hasLiberty (x, y) {\r\n\t\tvar c = getConnections(x, y);\r\n\t\tvar color = (matrix[x][y] == 'black') ? 'white' : 'black';\r\n\r\n\t\tif ((c._n != null && c._n.color == null) || (c._s != null && c._s.color == null) || (c._e != null && c._e.color == null) || (c._w != null && c._w.color == null)) {\r\n\t\t\t//debug\r\n\t\t\tconsole.log(\"has at least one liberty\");\r\n\t\t\treturn true;\r\n\t\t};\r\n\t\treturn false;\r\n\t}", "function checkRow(xy, wb) {\n\n var col = xy[1];\n var length = 1; // start at length 1 since player just put down a piece\n\n // check one side\n while(col > 1) {\n col -= 1;\n if(checkTile([xy[0], col], wb)) {\n length += 1;\n } else {\n break; // encountered another color\n }\n }\n\n if(length >= 5) return true;\n\n col = xy[1]; // reset\n\n // check other side\n while(col < 15) {\n col += 1;\n if(checkTile([xy[0], col], wb)) {\n length += 1;\n } else {\n break;\n }\n }\n\n if(length >= 5) return true;\n\n // no win yet\n return false;\n\n}", "function checkIntersections(_collection) {\n for (let a = 0; a < _collection.length; a++) {\n for (let b = a + 1; b < _collection.length; b++) {\n let moleculeA = molecules[_collection[a]];\n let moleculeB = molecules[_collection[b]];\n if (obj.lineState) {\n stroke(125, 100);\n line(moleculeA.position.x, moleculeA.position.y, moleculeB.position.x, moleculeB.position.y);\n };\n moleculeA.isIntersecting(moleculeB) ? (moleculeA.changeColor(), moleculeB.changeColor()) : null;\n }\n }\n}", "function pointIsInCanvas(x, y, w, h) {\n return x >= 0 && x <= w && y >= 0 && y <= h;\n}", "areDiagonallyAdjacent(tile1, tile2) {\r\n // Dos tiles son diagonalmente adyacentes si están separados por una distancia de una\r\n // unidad en ambos ejes. Si la distancia en cualquiera de los ejes fuera 0 ya no sería\r\n // una adyacencia diagonal, y si la distancia fuera más de 1 ya no sería una adyacencia.\r\n return Math.abs(tile1.x - tile2.x) == 1 && Math.abs(tile1.y - tile2.y) == 1;\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns list of colors including the one at the coordinate and all the surrounding ones.
getSurroundingColors(coord) { var colors = []; for (var x = coord.x - 1; x <= coord.x + 1; x++) { for (var y = coord.y - 1; y <= coord.y + 1; y++) { var color = this.getColor(new Coord(x, y)); if (color !== null) { colors.push(color); } } } return colors; }
[ "function getColor(grid, x, y) {\n var idx = round((y * grid.width + x) * 4);\n var c = [grid.pixels[idx], grid.pixels[idx+1], grid.pixels[idx+2]];\n return c;\n}", "function getColors(){\n var rgb = mixerBottle.attr('style').replace('background-color: rgb(', '').replace(')', '').split(',');\n return rgb.map(x => parseInt(x));\n }", "function get_colors(triangles){\n\tconst probs = [0.5,0.2,0.1,0.1,0.1];\n\tvar color_assignments = [];\n\tvar used_colors,new_probs;\n\tfor(var i=0;i<triangles.length;i++){\n\t\tused_colors = []\n\t\tfor(var j=0;j<color_assignments.length;j++){\n\t\t\tif(is_neighbor(triangles[i], triangles[j])){\n\t\t\t\tused_colors.push(color_assignments[j]);\n\t\t\t}\n\t\t}\n\t\tconsole.log(used_colors);\n\t\tnew_probs = [];\n\t\tfor(var j=0;j<5;j++){\n\t\t\tif(!used_colors.includes(j)){\n\t\t\t\tnew_probs.push(probs[j]);\n\t\t\t} else {\n\t\t\t\tnew_probs.push(0);\n\t\t\t}\n\t\t}\n\t\tconsole.log(new_probs);\n\t\tcolor_assignments.push(random_choice(new_probs));\n\t}\n\treturn(color_assignments);\n}", "function colorizePoints() {\n points.forEach(function(d) {\n let closest = findClosestCentroid(d);\n d.fill = closest.fill;\n });\n }", "_colors(points) {\n engine.trace(`getting colors from '${ this._name }' at ${ points.length } point${ points.length === 1 ? '' : 's' }...`);\n\n let shot = sharp(this._file);\n let meta = null;\n\n return shot.metadata()\n\n .then(results => {\n meta = results;\n return shot.raw().toBuffer();\n })\n\n .then(data => {\n let colors = [];\n let matched = points.length > 0;\n\n for (let i = 0; i < points.length; i++) {\n let point = points[i];\n let delta = meta.channels * (meta.width * point.y + point.x);\n let slice = data.slice(delta, delta + meta.channels);\n let found = { x: point.x, y: point.y, c: { r: slice[0], g: slice[1], b: slice[2] } };\n\n matched &= _.isEqual(point, found);\n colors.push(found);\n }\n\n return { colors: colors, matched: matched ? true : false };\n })\n\n .catch(err => engine.error('failure getting colors'))\n .finally(() => engine.trace('got colors'));\n }", "function flag_color(flag_index, i){\n return colors[flag_index][i % colors[flag_index].length]\n}", "function color_for_value(val, all_values){\n\n // colors for map, in increasing darkness\n var color_range = [\"#4e8a21\", \"#91b52b\", \n \"#faec37\", \"#e78b21\", \"#da1903\"];\n\n // find all uniq values in all_values, return them sorted\n var counts = _.sortBy(_.uniq(_.values(all_values)), \n function(a){ return a; } \n );\n\n // pop zeros, will plot as blank regions\n //if(counts[0] == 0 ){ counts.shift() }\n\n // find the index of the given value in \n // the sorted collection of all values\n index_of_val = _.indexOf(counts, val); \n\n // use the index of the value to calculate \n // the index of the corresponding color\n color_index = Math.floor(\n (index_of_val / counts.length) * color_range.length\n );\n\n return color_range[color_index];\n}", "function twenty0neGuns() {\n var crimeColors = [];\n for (var i = 0; i < unique_crime.length; i++) {\n crimeColors.push(color());\n }\n return crimeColors;\n}", "function colorGameCells(coords, color) {\n colorCells(coords, color, 'cell');\n}", "function color() {\n\tfor (var i = 0; i < num; i++) {\n\t\tcoloring.push(randomize());\n\t}\n}", "getNeighborsOnOff(y, x) {\n const results = [];\n for (let i = y - 1; i <= y + 1; i++) {\n for (let j = x - 1; j <= x + 1; j++) {\n // When getting neighbors for the first or last row/column on a non-infinite board, many\n // neighbors are non-existent so for our purposes, assume they are off\n if (i < 0 || i >= this.numRows || j < 0 || j >= this.numColumns) {\n results.push(false);\n continue;\n }\n // Skip counting the current cell among its neighbors\n if (i !== y || j !== x) {\n results.push(this.cells[i][j].classList.contains('on'));\n }\n }\n }\n return results;\n }", "function determineColors(d, zipList, treemapFilters) {\n zip = d.properties.ZCTA5CE10\n if (treemapFilters.length == 1 && zipList.indexOf(zip) > -1) {\n return(determineColor(treemapFilters[0]));\n }\n else if (treemapFilters.length == 0 && zipList.length == 0) {\n return unfilter(d);\n }\n else if (zipList.length == 51) {\n return unfilter(d);\n }\n else if (zipList.indexOf(zip) > -1) {\n return \"yellow\";\n }\n else {\n return \"grey\";\n }\n}", "function getHex(x, y, hexArr) {\r\n\r\n // collisionDetect_tri(x, y, hexArr[0], hexArr[1], hexArr[2]);\r\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 }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 }", "function redlistcolor(codein)\r\n{\r\n switch(codein)\r\n {\r\n case \"EX\":\r\n\t\t\treturn ('rgb(0,0,180)');\r\n //return ('rgb(0,0,0)');\r\n case \"EW\":\r\n\t\t\treturn ('rgb(60,50,135)');\r\n //return ('rgb(80,80,80)');\r\n case \"CR\":\r\n\t\t\treturn ('rgb(210,0,10)');\r\n case \"EN\":\r\n\t\t\treturn ('rgb(125,50,00)');\r\n case \"VU\":\r\n\t\t\treturn ('rgb(85,85,30)');\r\n case \"NT\":\r\n\t\t\treturn ('rgb(65,120,0)');\r\n case \"LC\":\r\n\t\t\treturn ('rgb(0,180,20)');\r\n case \"DD\":\r\n\t\t\treturn ('rgb(80,80,80)');\r\n //return ('rgb(60,50,135)');\r\n case \"NE\":\r\n\t\t\treturn ('rgb(0,0,0)');\r\n //return ('rgb(0,0,190)');\r\n default:\r\n\t\t\treturn ('rgb(0,0,0)');\r\n }\r\n}", "distinctColorFromNumber(num){\n return this.distinctColors[num % this.distinctColors.length];\n }", "function ComplementaryRGBColor(rgb_array){\n // white minus this color = Complementary / Opposite \n var color_r = 255 - rgb_array[0];\n var color_g = 255 - rgb_array[1];\n var color_b = 255 - rgb_array[2];\n\n return [color_r, color_g, color_b];\n}", "getAdjacent(tile) {\n\t\t\n\t\tconst index = tile.getIndex();\n\t\t\n\t\tconst col = index % this.width;\n\t\tconst row = Math.floor(index / this.width);\n\n\t\tconst first_row = Math.max(0, row - 1);\n\t\tconst last_row = Math.min(this.height - 1, row + 1);\n\n\t\tconst first_col = Math.max(0, col - 1);\n\t\tconst last_col = Math.min(this.width - 1, col + 1);\n\n\t\tconst result = []\n\n\t\tfor (let r = first_row; r <= last_row; r++) {\n\t\t\tfor (let c = first_col; c <= last_col; c++) {\n\t\t\t\tconst i = this.width * r + c;\n\t\t\t\tif (i != index) {\n\t\t\t\t\tresult.push(this.tiles[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}", "function currentColor() {\n\treturn new Color({red: color.red, green: color.green, blue: color.blue})\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
cast the spell, apply the condition, create and set flag
async function castSpell() { try { await game.dnd5e.rollItemMacro(spellName); } catch (err) { return null; } gm_macro.execute("apply", condition, target.id); let globalDmg = { targetId: target.data._id, meleeAtk: bonuses.mwak.damage, rangeAtk: bonuses.rwak.damage, meleeSpell: bonuses.msak.damage, rangeSpell: bonuses.rsak.damage, isSet: false }; myToken.setFlag(flagScope, actorId, globalDmg); }
[ "function setWarlockSpell() {\n className = warlockName;\n if (actor.items.find(i => i.name === `${warlockSpell}`)) {\n spellName = warlockSpell;\n castSpell();\n } else {\n ui.notifications.error(\n \"Selected actor does not have the \" + warlockSpell + \" spell.\"\n );\n console.log(\"Selected actor does not have the \" + warlockSpell + \" spell.\");\n return null;\n }\n}", "spellCheck() {\n if (!this.isSpellChecking) return\n \n // Wait for the dictionary to be loaded.\n if (this.dictionary == null) {\n return;\n }\n\n if (this.currently_spellchecking) {\n \treturn;\n }\n\n if (!this.contents_modified) {\n \treturn;\n }\n\n console.log(\"spell check!\")\n\n this.currently_spellchecking = true;\n var session = this.editor.getSession();\n this.clearSpellCheckMarkers()\n\n try {\n \t var Range = ace.require('ace/range').Range\n \t var lines = session.getDocument().getAllLines();\n \t for (var i in lines) {\n \t // Check spelling of this line.\n \t var misspellings = this.misspelled(lines[i]);\n\n \t // Add markers and gutter markings.\n \t if (misspellings.length > 0) {\n \t session.addGutterDecoration(i, \"misspelled\");\n \t }\n \t for (var j in misspellings) {\n \t var range = new Range(i, misspellings[j][0], i, misspellings[j][1]);\n \t // console.log(\"missspell: \", misspellings[j])\n \t \n \t this.markers_present[this.markers_present.length] =\n \t session.addMarker(range, \"misspelled\", \"typo\", true);\n \t }\n \t }\n \t} finally {\n \t\tthis.currently_spellchecking = false;\n \t\tthis.contents_modified = false;\n \t}\n }", "function setRangerSpell() {\n className = rangerName;\n if (actor.items.find(i => i.name === `${rangerSpell}`)) {\n spellName = rangerSpell;\n castSpell();\n } else {\n ui.notifications.error(\n \"Selected actor does not have the \" + rangerSpell + \" spell.\"\n );\n console.log(\"Selected actor does not have the \" + rangerSpell + \" spell.\");\n return null;\n }\n}", "function spellCheck() {\r\n\twith(currObj);\r\n\tvar query;\r\n\t\r\n\tif(currObj.spellingResultsDiv)\r\n\t{\r\n\t\tcurrObj.spellingResultsDiv.parentNode.removeChild(currObj.spellingResultsDiv);\r\n\t\tcurrObj.spellingResultsDiv = null;\r\n\t}\r\n\t\r\n\tif(currObj.config['useIcons'])\r\n\t{\r\n\t\tcurrObj.actionSpan.innerHTML = \"<img src=\\\"\" + currObj.config['imagePath'] + \"images/spellcheck.png\\\" width=\\\"16\\\" height=\\\"16\\\" title=\\\"Check Spelling &amp; Preview\\\" alt=\\\"Check Spelling &amp; Preview\\\" border=\\\"0\\\" />\";\r\n\t}\r\n\telse\r\n\t{\r\n\t\tcurrObj.actionSpan.innerHTML = \"<a class=\\\"check_spelling\\\">Check Spelling &amp; Preview</a>\";\r\n\t}\r\n\t\r\n\tif(currObj.config['useIcons'])\r\n\t{\r\n\t\tcurrObj.statusSpan.innerHTML = \"<img src=\\\"\" + currObj.config['imagePath'] + \"images/working.gif\\\" width=\\\"16\\\" height=\\\"16\\\" title=\\\"Checking...\\\" alt=\\\"Checking...\\\" border=\\\"0\\\" />\";\r\n\t}\r\n\telse\r\n\t{\r\n\t\tcurrObj.statusSpan.innerHTML = \"Checking...\";\r\n\t}\r\n\tquery = currObj.objToCheck.value;\r\n\tquery = query.replace(/\\r?\\n/gi, \"<br />\");\r\n\t\r\n\tcp.call(currObj.config['spellUrl'], 'spellCheck', spellCheck_cb, query, currObj.config['varName']);\r\n}", "knows_spell(spell){\n\t\treturn this.spells.hasOwnProperty(spell.symbol);\n\t}", "chooseSpell(event) {\n this.kind = event.target.getAttribute(\"id\");\n document.querySelector(\".spell-page\").style.display = \"none\";\n document.querySelector(\".task-page\").style.display = \"block\";\n this.task = new _task__WEBPACK_IMPORTED_MODULE_0__[\"default\"]();\n this.task.generate();\n }", "handleElectron4SpellCheck(text) {\n if (!this.currentSpellchecker) return true;\n\n if (isMac) {\n return !this.isMisspelled(text);\n }\n\n this.spellCheckInvoked.next(true);\n\n let result = this.isMisspelled(text);\n if (result) this.spellingErrorOccurred.next(text);\n return !result;\n }", "async function setSpellItem (spellInput, actorID, spellBook, spellPack, spellPackIndex) {\n console.log(\"sbc | START SETTING SPELL\"); \n \n const actor = await game.actors.get(actorID);\n\n // We can find a specific entry in the compendium by its name\n try {\n \n let entry = await spellPack.index.find(e => e.name === capitalize(spellInput.name));\n\n console.log(\"entry: \" + entry);\n\n // Given the entity ID of \"Acid Splash\" we can load the full Entity from the compendium\n await spellPack.getEntity(entry._id).then(spell => {\n console.log(spell);\n\n spell.data.data.spellbook = spellBook;\n spell.data.data.level = spellInput.level;\n spell.data.data.uses.value = +spellInput.uses.value;\n spell.data.data.uses.max = +spellInput.uses.max;\n spell.data.data.uses.per = spellInput.uses.per;\n spell.data.data.save.dc = spellInput.saveDC.toString();\n spell.data.data.effectNotes = spellInput.effectNotes;\n spell.data.data.atWill = spellInput.atWill;\n \n \n // TESTS\n let spells = [\n spell,\n spell\n ];\n \n actor.createEmbeddedEntity(\"OwnedItem\", spells);\n \n //actor.createEmbeddedEntity(\"OwnedItem\", spell);\n \n console.log(\"sbc | FINISH SETTING SPELL\");\n });\n } catch (error) {\n console.log(\"sbc | Error: Spell '\" + spellInput.name + \"' could not be parsed!\");\n ui.notifications.info(\"sbc | Error: Spell '\" + spellInput.name + \"' could not be parsed!\")\n \n }\n \n}", "function populateSpellData() {\n spellData = [];\n spellData['list'] = [];\n var i = 0;\n\n spellData['list'].push('Lightning');\n spellData['lightning'] = [];\n spellData['lightning']['creation time'] = 30;\n spellData['lightning']['spell factory'] = 1;\n spellData['lightning']['creation cost'] =\n [15000, 16500, 18000, 20000, 22000, 24000];\n spellData['lightning']['research cost'] =\n [ 0, 200000, 500000, 1000000, 2000000, 8000000];\n spellData['lightning']['research time'] =\n [ 0, 24, 48, 72, 96, 336];\n spellData['lightning']['laboratory level'] =\n [ 0, 1, 2, 3, 6, 8];\n // Spell-specific information\n spellData['lightning']['data'] = [\n 'radius',\n 'random radius',\n 'strikes',\n 'strike time',\n 'total damage',\n 'strike damage'\n ];\n spellData['lightning']['radius'] = 2;\n spellData['lightning']['random radius'] = 3.5;\n spellData['lightning']['strikes'] = 6;\n spellData['lightning']['strike time'] = 0.4;\n spellData['lightning']['total damage'] =\n [ 300, 330, 360, 390, 420, 450];\n spellData['lightning']['strike damage'] = [];\n for (i = 0; i < spellData['lightning']['total damage'].length; i ++) {\n var dam = spellData['lightning']['total damage'][i] /\n spellData['lightning']['strikes'];\n spellData['lightning']['strike damage'].push(dam);\n }\n\n spellData['list'].push('Healing');\n spellData['healing'] = [];\n spellData['healing']['creation time'] = 30;\n spellData['healing']['spell factory'] = 2;\n spellData['healing']['creation cost'] =\n [15000, 16500, 18000, 20000, 22000, 24000];\n spellData['healing']['research cost'] =\n [ 0, 300000, 600000, 1200000, 2400000, 4800000];\n spellData['healing']['research time'] =\n [ 0, 24, 48, 72, 120, 168];\n spellData['healing']['laboratory level'] =\n [ 0, 2, 4, 5, 6, 7];\n // Spell-specific information\n spellData['healing']['data'] = [\n 'radius',\n 'pulses',\n 'pulse time',\n 'total healing',\n 'pulse healing'\n ];\n spellData['healing']['radius'] = 5;\n spellData['healing']['pulses'] = 40;\n spellData['healing']['pulse time'] = 0.3;\n spellData['healing']['total healing'] =\n [ 600, 800, 1000, 1200, 1400, 1600];\n spellData['healing']['pulse healing'] = [];\n for (i = 0; i < spellData['healing']['total healing'].length; i ++) {\n var heal = spellData['healing']['total healing'][i] /\n spellData['healing']['pulses'];\n spellData['healing']['pulse healing'].push(heal);\n }\n\n spellData['list'].push('Rage');\n spellData['rage'] = [];\n spellData['rage']['creation time'] = 45;\n spellData['rage']['spell factory'] = 3;\n spellData['rage']['creation cost'] =\n [23000, 25000, 27000, 30000, 33000];\n spellData['rage']['research cost'] =\n [ 0, 450000, 900000, 1800000, 3000000];\n spellData['rage']['research time'] =\n [ 0, 48, 72, 120, 168];\n spellData['rage']['laboratory level'] =\n [ 0, 3, 4, 5, 6];\n // Spell-specific information\n spellData['rage']['data'] = [\n 'radius',\n 'pulses',\n 'pulse time',\n 'boost time',\n 'damage boost'\n ];\n spellData['rage']['radius'] = 2;\n spellData['rage']['pulses'] = 40;\n spellData['rage']['pulse time'] = 0.3;\n spellData['rage']['boost time'] = 1;\n spellData['rage']['damage boost'] =\n [ 1.3, 1.4, 1.5, 1.6, 1.8];\n\n spellData['list'].push('Jump');\n spellData['jump'] = [];\n spellData['jump']['data'] = [\n 'radius',\n 'pulses',\n 'pulse time',\n 'boost time'\n ];\n spellData['jump']['creation time'] = 45;\n spellData['jump']['spell factory'] = 4;\n spellData['jump']['creation cost'] =\n [23000, 29000];\n spellData['jump']['research cost'] =\n [ 0, 4000000];\n spellData['jump']['research time'] =\n [ 0, 120];\n spellData['jump']['laboratory level'] =\n [ 0, 6];\n // Spell-specific information\n spellData['jump']['radius'] = 5;\n spellData['jump']['boost time'] = 1;\n spellData['jump']['pulse time'] =\n [ 0.3, 0.3];\n spellData['jump']['pulses'] = \n [ 30, 60];\n\n spellData['list'].push('Freeze');\n spellData['freeze'] = [];\n spellData['freeze']['creation time'] = 45;\n spellData['freeze']['spell factory'] = 5;\n spellData['freeze']['creation cost'] =\n [26000, 29000, 31000, 33000];\n spellData['freeze']['research cost'] =\n [ 0, 4000000, 6000000, 8000000];\n spellData['freeze']['research time'] =\n [ 0, 120, 240, 336];\n spellData['freeze']['laboratory level'] =\n [ 0, 8, 8, 8];\n // Spell-specific information\n spellData['freeze']['data'] = [\n 'radius',\n 'freeze time'\n ];\n spellData['freeze']['radius'] = 2;\n spellData['freeze']['freeze time'] =\n [ 4, 5, 6, 7];\n\n spellData['list'].push(\"Santa's Surprise\");\n spellData['santas surprise'] = [];\n spellData['santas surprise']['creation time'] = 1500;\n spellData['santas surprise']['spell factory'] = 1;\n spellData['santas surprise']['creation cost'] =\n [25000];\n spellData['santas surprise']['research cost'] =\n [ 0];\n spellData['santas surprise']['research time'] =\n [ 0];\n spellData['santas surprise']['laboratory level'] =\n [ 0];\n // Spell-specific information\n spellData['santas surprise']['data'] = [\n 'radius',\n 'random radius',\n 'strikes',\n 'strike time',\n 'total damage',\n 'strike damage'\n ];\n spellData['santas surprise']['radius'] = 1;\n spellData['santas surprise']['random radius'] = 4;\n spellData['santas surprise']['strikes'] = 5;\n spellData['santas surprise']['strike time'] = 0.1;\n spellData['santas surprise']['total damage'] =\n [ 1500];\n spellData['santas surprise']['strike damage'] = [];\n for (i = 0; i < spellData['santas surprise']['total damage'].length; i ++) {\n var dam = spellData['santas surprise']['total damage'][i] /\n spellData['santas surprise']['strikes'];\n spellData['santas surprise']['strike damage'].push(dam);\n }\n}", "function validateSpell (data, command) {\n var invalidMsg = 'Invalid Command - (' + command.member.displayName() + ' SPELL): ';\n var spell = new Spell(command.name, data);\n\n if (!command.name) {\n throw new Error(invalidMsg + 'command must include a spell name.');\n } else if (!spell.is_set) {\n throw new Error(invalidMsg + 'spell name ' + command.name + ' not found.');\n } else if (!command.target.name) {\n throw new Error(invalidMsg + 'command must include a target.');\n }\n\n if (command.member.type === 'character') {\n if (!spell.learned[command.member.job] || spell.level > command.member.level) {\n throw new Error(invalidMsg + 'this character cannot cast this spell.');\n }\n }\n \n return true;\n }", "function Quest(Type, Name, Level, Experience, Item) {\n function mainQuest() {\n var main = (Type == true) ? \"Main Quest\":\"Side Quest\";\n return main \n }\n this.questType = mainQuest();\n this.questName = Name;\n this.questLevel = Level;\n this.questExperience = Experience;\n this.questItem = Item;\n \n}", "function holdAccessory(side, army, job){\n var holds = [];\n switch(army){\n case '步兵':\n holds = ['NO', '飾品', '尊爵不凡的鞋子', '鞋子', '妖步'];\n break;\n case '槍兵':\n holds = ['NO', '飾品', '尊爵不凡的鞋子', '鞋子', '妖步'];\n break;\n case '騎兵':\n holds = ['NO', '飾品', '妖步'];\n break;\n case '飛兵':\n holds = ['NO', '飾品', '妖步'];\n break;\n case '弓兵':\n holds = ['NO', '飾品', '鞋子'];\n break;\n case '刺客':\n holds = ['NO', '飾品', '鞋子'];\n break;\n case '水兵':\n holds = ['NO', '飾品', '尊爵不凡的鞋子', '鞋子', '妖步'];\n break;\n case '法師':\n holds = ['NO', '飾品', '鞋子'];\n break;\n case '魔物':\n holds = ['NO', '飾品', '鞋子'];\n break;\n case '僧侶':\n holds = ['NO', '飾品', '鞋子'];\n break;\n case '龍':\n holds = ['NO', '飾品', '鞋子', '妖步'];\n break;\n }\n /* add new cases to new heros */\n /*\n switch(job){\n case '':\n holds.push('');\n break;\n }\n */\n // add hero name to type for char specials\n if(side == 'offense'){\n if(combat.offChar.NAME[0] == 'S')\n holds.push(combat.offChar.NAME.split('SP')[1]);\n else\n holds.push(combat.offChar.NAME);\n }\n else if(side == 'defense'){\n if(combat.defChar.NAME[0] == 'S')\n holds.push(combat.defChar.NAME.split('SP')[1]);\n else\n holds.push(combat.defChar.NAME);\n }\n\n return holds;\n}", "function conditional(){\n disjunction();\n if (globalTP < tokens.length && (tokens[globalTP] == \"bicond\" || tokens[globalTP] == \"cond\")){\n globalTP+=1;\n disjunction();\n }\n}", "function checkWords(element){\n\tconsole.log(\"=======Checking Words=========\");\n\tvar wordspace = element.parentNode.parentNode.getElementsByClassName(\"wordspace\")[0]; // get the wordspace associated with the card\n\tvar cards = wordspace.getElementsByClassName(\"thiscard\"); // get all the cards\n\tfor(var i=0; i < cards.length; i++){ // loop all the cards that have been added\n\t\tvar cardword = cards[i].getElementsByClassName(\"cardword\")[0]; // get the word on the card\n\t\t// if the card is not shown, then it is not required.\n\t\tif(!allRequired(cards[i]) || ( cardword.style.display != \"none\" && cardword.value == \"\")){\n\t\t\t// thats not ok\n\t\t\tcards[i].className = \"thiscard form-group has-error\";\n\t\t}else if(cardword.style.display == \"none\"){ // verify that the word should be shown\n\t\t\t// thats fine, verify this one \n\t\t\tcards[i].className = \"thiscard form-group has-success\";\n\t\t}else{\n\t\t\t(function(currentCard, card_word){ // create a function that holds the scope for us.\n\t\t\tAjax(\"../Lux/Assets/query.php\", {query:{type:\"word\", word: card_word.value.toLowerCase()}},\n\t\t\t function(data){\n\t\t\t\tif(data[1].length == 0){\n\t\t\t\t\tconsole.log(\"There is no data found\");\n\t\t\t\t\tcurrentCard.className = \"thiscard form-group has-error\";\n\t\t\t\t}else{\n\t\t\t\t\tconsole.log(\"Data was found\");\n\t\t\t\t\tfor(key in data[1]){\n\t\t\t\t\t\tconsole.log(\"Setting Attributes\");\n\t\t\t\t\t\tcard_word.setAttribute(\"syllable\", data[1][key][\"syllable\"]);\n\t\t\t\t\t\tcard_word.setAttribute(\"pron\", data[1][key][\"pron\"]);\n\t\t\t\t\t\tvar audio = currentCard.getElementsByClassName(\"cardaudio\")[0];\t\n\t\t\t\t\t\tif(data[1][key][\"audio\"] != undefined && audio.files.length == 0 && audio.files[0] == undefined){// && audio.files[0].recorded != true){\n\t\t\t\t\t\t\tconsole.log(\".....................................Audio file found on server, no audio file found in browser\");\n\t\t\t\t\t\t\taudio.files[0] = {\"name\":data[1][key][\"audio\"], \"set\":true};\n\t\t\t\t\t\t\tcurrentCard.getElementsByClassName(\"cardaudio_label\")[0].innerHTML = data[1][key][\"audio\"];\t\n\t\t\t\t\t\t}else if(data[1][key][\"audio\"] == undefined){\n\t\t\t\t\t\t\tconsole.log(\".....................................NO Audio file found on server\");\n\t\t\t\t\t\t\taudio.files[0] = {\"set\":false};\n\t\t\t\t\t\t\tcurrentCard.getElementsByClassName(\"cardaudio_label\")[0].innerHTML = \"Click to Select File\";\t\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\tconsole.log(audio.files[0]); \n\t\t\t\t\t\t}\n\t\t\t\t\t\tvar image = currentCard.getElementsByClassName(\"cardimage0\")[0];\n\t\t\t\t\t\tif(image.files.length == 0 && image.files[0] == undefined){\n\t\t\t\t\t\t\tif(data[1][key][\"image\"] != undefined){\n\t\t\t\t\t\t\t\timage.files[0] = {\"name\":data[1][key][\"image\"], \"set\":true};\n\t\t\t\t\t\t\t\tcurrentCard.getElementsByClassName(\"cardimage0_label\")[0].innerHTML = data[1][key][\"audio\"];\t\n\t\t\t\t\t\t\t}else if(data[1][key][\"image\"] == undefined){\n\t\t\t\t\t\t\t\tconsole.log(data[1][key]);\n\t\t\t\t\t\t\t\timage.files[0] = {\"set\":false};\n\t\t\t\t\t\t\t\tcurrentCard.getElementsByClassName(\"cardimage0_label\")[0].innerHTML = \"Click to Select File\";\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconsole.log(\"Changing This Cards format\");\n\t\t\t\t\tconsole.log(currentCard);\n\t\t\t\t\tcurrentCard.className = \"thiscard form-group has-success\";\n\t\t\t\t}\n\t\t\t });\n\t\t\t})(cards[i], cardword);\n\t \n\t\t}\n\t}\t\n}", "function massHysteria(c, d) {\n let c = cats;\n let d = dogs;\n\n if (d.raining === true && c.raining === true) {\n console.log ('DOGS AND CATS LIVING TOGETHER! MASS HYSTERIA!')\n }\n }", "function autoTrigger(type){\n\tautoTriggerTab = \"false\";\n\tif(type == 'deviceSanity'){\n\t\tdevSanFlag = \"true\";accSanFlag = \"false\";connSanFlag = \"false\";\n\t\tlinkSanFlag = \"false\";enableFlagSan = \"false\";\n\t\tLoadImageFlag = \"false\";\n\t\tLoadConfigFlag = \"false\";\n\t}else if(type == 'accessSanity'){\n\t\tdevSanFlag = \"false\";accSanFlag = \"true\";connSanFlag = \"false\";\n\t\tlinkSanFlag = \"false\";enableFlagSan = \"false\";\n\t\tLoadImageFlag = \"false\";\n\t\tLoadConfigFlag = \"false\";\n\t}else if(type == 'connectivity'){\n devSanFlag = \"false\";accSanFlag = \"false\";connSanFlag = \"true\";\n linkSanFlag = \"false\";enableFlagSan = \"false\";\n LoadImageFlag = \"false\";\n LoadConfigFlag = \"false\";\n\t}else if(type == 'linksanity'){\n devSanFlag = \"false\";accSanFlag = \"false\";connSanFlag = \"false\";\n linkSanFlag = \"true\";enableFlagSan = \"false\";\n LoadImageFlag = \"false\";\n LoadConfigFlag = \"false\";\n\t}else if(type == 'enableint'){\n devSanFlag = \"false\";accSanFlag = \"false\";connSanFlag = \"false\";\n linkSanFlag = \"false\";enableFlagSan = \"true\";\n LoadImageFlag = \"false\";\n LoadConfigFlag = \"false\";\n\t}else if(type == 'loadImage'){\n devSanFlag = \"false\";accSanFlag = \"false\";connSanFlag = \"false\";\n linkSanFlag = \"false\";enableFlagSan = \"false\";\n LoadImageFlag = \"true\";\n LoadConfigFlag = \"false\";\n\t}else if(type == 'loadConfig'){\n devSanFlag = \"false\";accSanFlag = \"false\";connSanFlag = \"false\";\n linkSanFlag = \"false\";enableFlagSan = \"false\";\n LoadImageFlag = \"false\";\n LoadConfigFlag = \"true\";\n\t}\n\tif(checkFromSanity.toString() == \"true\"){\n\t\tautoTriggerTab = \"true\";\n\t\tcheckFromSanity = \"false\";\n\t\tclearTimeout(TimeOut);\n\t\tsanityQuery(type);\n\t}else {\n\t\tautoTriggerTab == \"false\";\n\t\tcheckFromSanity = \"false\";\n\t\tclearTimeout(TimeOut);\n\t\tsanityQuery(type);\n\t}\n}", "function priority(){\r\n\r\n turn = 2;\r\n \r\n if(array_attack_StringList.length != 0){\r\n \r\n if(search_in_array('1_king_',array_attack_StringList) == 1){\r\n decide_attack('1_king_');\r\n }\r\n else if(search_in_array('2_king_',array_defence_StringList) == 1){\r\n decide_defence('2_king_');\r\n }\r\n else if(search_in_array('1queenn',array_attack_StringList) == 1){\r\n decide_attack('1queenn');\r\n }\r\n else if(search_in_array('2queenn',array_defence_StringList) == 1){\r\n \r\n decide_defence('2queenn');\r\n }\r\n else if(search_in_array('1eleph1',array_attack_StringList) == 1){\r\n decide_attack('1eleph1');\r\n }\r\n else if(search_in_array('2eleph1',array_defence_StringList) == 1){\r\n decide_defence('2eleph1');\r\n }\r\n else if(search_in_array('1eleph2',array_attack_StringList) == 1){\r\n decide_attack('1eleph2');\r\n }\r\n else if(search_in_array('2eleph2',array_defence_StringList) == 1){\r\n decide_defence('2eleph2');\r\n }\r\n else if(search_in_array('1horse1',array_attack_StringList) == 1){\r\n decide_attack('1horse1');\r\n }\r\n else if(search_in_array('2horse1',array_defence_StringList) == 1){\r\n decide_defence('2horse1');\r\n }\r\n else if(search_in_array('1horse2',array_attack_StringList) == 1){\r\n decide_attack('1horse2');\r\n }\r\n else if(search_in_array('2horse2',array_defence_StringList) == 1){\r\n decide_defence('2horse2');\r\n }\r\n else if(search_in_array('1camel1',array_attack_StringList) == 1){\r\n \r\n decide_attack('1camel1');\r\n }\r\n else if(search_in_array('2camel1',array_defence_StringList) == 1){\r\n decide_defence('2camel1');\r\n }\r\n else if(search_in_array('1camel2',array_attack_StringList) == 1){\r\n decide_attack('1camel2');\r\n }\r\n else if(search_in_array('2camel2',array_defence_StringList) == 1){\r\n decide_defence('2camel2');\r\n }\r\n else if(search_in_array('1slave1',array_attack_StringList) == 1){\r\n \r\n decide_attack('1slave1');\r\n }\r\n else if(search_in_array('2slave1',array_defence_StringList) == 1){\r\n decide_defence('2slave1');\r\n }\r\n else if(search_in_array('1slave2',array_attack_StringList) == 1){\r\n decide_attack('1slave2');\r\n }\r\n else if(search_in_array('2slave2',array_defence_StringList) == 1){\r\n decide_defence('2slave2');\r\n }\r\n else if(search_in_array('1slave3',array_attack_StringList) == 1){\r\n decide_attack('1slave3');\r\n }\r\n else if(search_in_array('2slave3',array_defence_StringList) == 1){\r\n decide_defence('2slave3');\r\n }\r\n else if(search_in_array('1slave4',array_attack_StringList) == 1){\r\n decide_attack('1slave4');\r\n }\r\n else if(search_in_array('2slave4',array_defence_StringList) == 1){\r\n decide_defence('2slave4');\r\n }\r\n else if(search_in_array('1slave5',array_attack_StringList) == 1){\r\n decide_attack('1slave5');\r\n }\r\n else if(search_in_array('2slave5',array_defence_StringList) == 1){\r\n \r\n decide_defence('2slave5');\r\n }\r\n\r\n else if(search_in_array('1slave6',array_attack_StringList) == 1){\r\n decide_attack('1slave6');\r\n }\r\n else if(search_in_array('2slave6',array_defence_StringList) == 1){\r\n decide_defence('2slave6');\r\n }\r\n else if(search_in_array('1slave7',array_attack_StringList) == 1){\r\n \r\n decide_attack('1slave7');\r\n }\r\n else if(search_in_array('2slave7',array_defence_StringList) == 1){\r\n\r\n decide_defence('2slave7');\r\n }\r\n else if(search_in_array('1slave8',array_attack_StringList) == 1){\r\n decide_attack('1slave8');\r\n }\r\n else if(search_in_array('2slave8',array_defence_StringList) == 1){\r\n decide_defence('2slave8');\r\n }\r\n else{\r\n \r\n decide_else('_______');\r\n }\r\n }\r\n else{\r\n \r\n document.getElementById(\"won\").style.zIndex = 1;\r\n disable_all();\r\n }\r\n}", "function spellCheck_cb(new_data)\r\n{\r\n\twith(currObj);\r\n\tnew_data = new_data.toString();\r\n\tvar isThereAMisspelling = new_data.charAt(0);\r\n\tnew_data = new_data.substring(1);\r\n\t\t\r\n\tif(currObj.spellingResultsDiv)\r\n\t{\r\n\t\tcurrObj.spellingResultsDiv.parentNode.removeChild(spellingResultsDiv);\r\n\t}\r\n\t\r\n\tcurrObj.spellingResultsDiv = document.createElement('DIV');\r\n\tcurrObj.spellingResultsDiv.className = 'edit_box';\r\n\tcurrObj.spellingResultsDiv.style.width = currObj.objToCheck.style.width;\r\n\tcurrObj.spellingResultsDiv.style.height = currObj.objToCheck.style.height;\r\n\tcurrObj.spellingResultsDiv.innerHTML = new_data;\r\n\t\r\n\tcurrObj.objToCheck.style.display = \"none\";\r\n\tcurrObj.objToCheck.parentNode.insertBefore(currObj.spellingResultsDiv,currObj.objToCheck);\r\n\tcurrObj.statusSpan.innerHTML = \"\";\r\n\t\r\n\tif(currObj.config['useIcons'])\r\n\t{\r\n\t\tcurrObj.actionSpan.innerHTML = \"<a class=\\\"resume_editing\\\" onclick=\\\"setCurrentObject(\" + currObj.config['varName'] + \"); \" + currObj.config['varName'] + \".resumeEditing();\\\"><img src=\\\"\" + currObj.config['imagePath'] + \"images/page_white_edit.png\\\" width=\\\"16\\\" height=\\\"16\\\" title=\\\"Resume Editing\\\" alt=\\\"Resume Editing\\\" border=\\\"0\\\" /></a>\";\r\n\t}\r\n\telse\r\n\t{\r\n\t\tcurrObj.actionSpan.innerHTML = \"<a class=\\\"resume_editing\\\" onclick=\\\"setCurrentObject(\" + currObj.config['varName'] + \"); \" + currObj.config['varName'] + \".resumeEditing();\\\">Resume Editing</a>\";\r\n\t}\r\n\t\t\r\n\tif(isThereAMisspelling != \"1\")\r\n\t{\r\n\t\tif(currObj.config['useIcons'])\r\n\t\t{\r\n\t\t\tcurrObj.statusSpan.innerHTML = \"<img src=\\\"\" + currObj.config['imagePath'] + \"images/accept.png\\\" width=\\\"16\\\" height=\\\"16\\\" title=\\\"No Misspellings Found\\\" alt=\\\"No Misspellings Found\\\" border=\\\"0\\\" />\";\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tcurrObj.statusSpan.innerHTML = \"No Misspellings Found\";\r\n\t\t}\r\n\t\tcurrObj.objToCheck.disabled = false;\r\n\t}\r\n}", "_hasDamage(type) {\n if (type === \"weapon\") {return true};\n // if (!this.data.data.causeDamage) {return false};\n if (type === \"power\" && this.data.data.causeDamage === true) {return true};\n return false;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check for session data and if not there, use SSO mechanism to log user in and retrieve the user info from the SSO identity provider
function ssoSession(req, res, next, config) { var ssoToken = 'ssoSessionId'; // name of sso session ID parameter // if we have a session, everything is fine console.log('check if session is there ...'); // FIXME debugging output // check if session is there if (req.session && req.session.username) { console.log(' --> YES, session there!'); // FIXME debugging output next(); return; } // no session there => SSO process kicks in ... // check if we got an SSO token console.log('check for SSO token ...'); // FIXME debugging output if (req.query[ssoToken]) { console.log(' --> YES, got SSO token: ' + req.query[ssoToken]); // FIXME debugging output // fetch user info console.log(' --> fetching user info ...'); // FIXME debugging output request(config.identityProvider.getIdUrl.replace('${SSO_TOKEN}', req.query[ssoToken]), function(err, response, data) { console.log(' --> response from id.json: ' + JSON.stringify(data)); // FIXME debugging output if (!err && response.statusCode == 200) { console.log(' --> GOT user info: ' + JSON.stringify(data)); // FIXME debugging output data = JSON.parse(data); req.session.username = 'USER' + data.username; } else { console.log(' --> ERROR at fetching user info (status code: ' + response.statusCode + ') with SSO token ' + req.query[ssoToken]); // FIXME debugging output } next(); return; }); } else { // no SSO token and no session => ask SSO identity provider for identity console.log('no SSO token => redirect to SSO auth ...'); // FIXME debugging output res.redirect(config.identityProvider.authUrl.replace('${TARGET}', encodeURIComponent(config.appTarget))); } }
[ "function loginUser(){\n\tif(gActiveToken != null){\n\t\tvalidateToken();\n\t}\n}", "function initLogin() {\n\t// first time page loaded login\n\t\n\t//do background login\n\t$.ajax({\n\t\turl : \"/GlobalInfoServlet\",\n\t\ttype : \"POST\",\n\t\tsuccess : function(jsonResult){\n\n if(!jsonResult.success){\n displayError(jsonResult.detail);\n return;\n }\n\t\t\n\t\t\t//can not determined if still in session\n\t\t\tif(jsonResult.detail.sessionUser != null){\n\n //already has session in server, fill back information\n\n\t\t\t\tGlobalInfo.sessionUser(jsonResult.detail.sessionUser);\n\t\t\t\t\n\t\t\t\tif(GlobalInfo.sessionUser().randomUser){\n\t\t\t\t\ttoast(\"login as random user:\"+\n\t\t\t\t\t\t\tGlobalInfo.sessionUser().userName+\n\t\t\t\t\t\t\t\",\\n idBytes:\"+GlobalInfo.sessionUser().idBytes);\n\t\t\t\t}\n\n\t\t\t\tGlobalInfo.userDescriptionMaxLength=jsonResult.detail.userDescriptionMaxLength;\n\t\t\t\tGlobalInfo.fileUploadLimitByte=jsonResult.detail.fileUploadLimitByte;\n\t\t\t\t\n\t\t\t\tfillSessionField();\n\t\t\t\treturn;\n\t\t\t}else if(GlobalInfo.sessionUser()!=null){\n //no session in server side,\n //try to use last info stored in local variable\n //check fields first\n var localInfo=GlobalInfo.sessionUser();\n if(verifyIdBytes(localInfo.idBytes)&&\n verifyUserName(localInfo.userName)&&\n verifyDescription(localInfo.description)){\n \n userLogin(localInfo,true);\n return;\n }\n\n //try new random login\n }\n\n\t\t\t// generate random user ,and try to login\n\t\t\tvar randomUserName = \"guest_\" + randomSuffix(6);\n\n\t\t\t$(\"#inputUserName\").val(randomUserName);\n\n\t\t\tvar sha1 = $.sha1(randomUserName+randomSuffix(6));\n\n\t\t\t$(\"#inputUserIdBytes\").val(sha1);\n\n var description=DEFAULT_USER_DESCRIPTION;\n\n $(\"#inputUserDescription\").val(description);\n\n\t\t\tuserLogin({userName:randomUserName, \n idBytes:sha1 ,\n description:description},\n true);\n\t\t\t\n\t\t\t},\n\t\tdataType : \"json\"\n\t});\n\n\n\t\n}", "function getSession(request, response) {\n\tvar session = request.session;\n\tconsole.log(\"SESSION: \", session);\n\tif (!session.sfdcAuth) {\n\t\tresponse.status(401).send('No active session');\n\t\treturn null;\n\t}\n\treturn session;\n}", "function initTokenSession(req, res, next) {\n const provider = getProviderToken(req.path);\n return user.createSession(req.user._id, provider, req)\n .then(function(mySession) {\n return Promise.resolve(mySession);\n })\n .then(function (session) {\n session.delivered = Date.now();\n res.status(200).json(session);\n }, function (err) {\n return next(err);\n });\n }", "function getUser() {\n var userInSession = apejs.session.getAttribute('user');\n if(userInSession) {\n return userInSession;\n } else { // let's use the remember-me cookie to get user from db\n var cookies = apejs.cookies;\n\n if(!cookies)\n return false;\n \n // find the user cookie\n var userCookie = false;\n for(var i=0; i<cookies.length; i++) {\n if(cookies[i].getName().equals(\"user\")) {\n userCookie = cookies[i];\n }\n }\n\n if(!userCookie) // no user cookie found\n return false;\n\n // get the token (value of cookie)\n var token = userCookie.getValue();\n\n // make sure the token is not an empty string :)\n if(token.equals(\"\") || !token)\n return false;\n\n var t = token.split(':');\n var username = t[0];\n var hashedPassword = t[1];\n\n // check if it exists in datastore\n var arr = rdf.query('users.ttl', 'select * where { ?s a foaf:Person; cov:username ?username; cov:password ?password. FILTER(?username = '+JSON.stringify(''+username)+' && ?password = '+JSON.stringify(''+hashedPassword)+')}')\n\n if(!arr.length) // doesn't exist\n return false;\n\n apejs.session.setAttribute('user', arr[0]);\n\n return arr[0];\n }\n }", "function check () {\n\t\tconst localToken = localStorage.getItem(TOKEN)\n\t\tconst localUser = localStorage.getItem(USER)\n\t\tif (localToken === null) return Promise.resolve(false)\n\t\tif (localUser !== null) return Promise.resolve(localUser)\n\t\treturn api.auth(localToken)\n\t\t\t.then(setUserCredentials)\n\t\t\t.catch(blockAuthentication)\n\n\t\tfunction setUserCredentials (whoami) {\n\t\t\tif (!whoami) throw new Error('Invalid credentials')\n\t\t\textend(user, whoami)\n\t\t\tRaven.setUserContext({\n\t\t\t\temail: user.email,\n\t\t\t\tid: user.id\n\t\t\t})\n\t\t\tuser.authenticated = true\n\t\t}\n\n\t\tfunction blockAuthentication (err) {\n\t\t\tuser.authenticated = false\n\t\t\t// Pass the error up if we're logging in\n\t\t\tif (loggingIn) throw err\n\t\t\tswitch (err.statusCode) {\n\t\t\t\tcase 401:\n\t\t\t\tcase 403:\n\t\t\t\t\trouter.redirect('/login')\n\t\t\t\t\tbreak\n\t\t\t\tdefault:\n\t\t\t\t\tthrow err\n\t\t\t}\n\t\t}\n\t}", "function authAware(req, res, next) {\n if (req.session.oauth2tokens) {\n req.oauth2client = getClient();\n req.oauth2client.setCredentials(req.session.oauth2tokens);\n }\n\n next();\n\n // Save credentials back to the session as they may have been\n // refreshed by the client.\n if (req.oauth2client) {\n req.session.oauth2tokens = req.oauth2client.credentials;\n }\n }", "async componentDidMount() {\n try {\n // returns a promise, rest of app will wait for this response\n // from amplify auth with cognito\n //await Auth.currentSession();\n // if 200 OK from above with session info then execute next\n //this.userHasAuthenticated(true);\n\n // if OK pull role from cognito custom attribute and store in state\n //this.userHasPermission(\"admin\");\n } catch ( err ) {\n\n /*\n if (err !== \"No current user\") {\n // eslint-disable-next-line\n alert(err);\n }\n */\n }\n // loading user session is asyn process, we need to make sure\n // that our app does not change state when it first loads\n // we wait to render until isAuthenticating is false\n this.setState({\n //isAuthenticating: false\n });\n }", "loadUserSession() {\n const storedUserSession = localStorage.getItem('userSession');\n const userSession = storedUserSession\n ? UserSession.deserialize(storedUserSession)\n : null;\n\n this.userSession = userSession;\n this.resetRenewalTimer(userSession);\n this.emit('user-session-changed', userSession);\n }", "function loggedInCheck() {\n // ajax call to check that user has a valid, i.e. non-expired, login cookie\n // if cookie is valid, show logged in user controls\n var loggedIn = true;\n if ( loggedIn ) {\n showUserControls();\n }\n else {\n hideUserControls();\n }\n}", "function login() {\n const OKTA_clientId = '0oa6fm8j4G1xfrthd4h6';\n const redirectUri = window.location.origin;\n\n const config = {\n logo: '//logo.clearbit.com/cdc.gov',\n language: 'en',\n features: {\n registration: false, // Enable self-service registration flow\n rememberMe: false, // Setting to false will remove the checkbox to save username\n router: true, // Leave this set to true for the API demo\n },\n el: \"#okta-login-container\",\n baseUrl: `https://hhs-prime.okta.com`,\n clientId: `${OKTA_clientId}`,\n redirectUri: redirectUri,\n authParams: {\n issuer: `https://hhs-prime.okta.com/oauth2/default`\n }\n };\n\n new OktaSignIn(config).showSignInToGetTokens({ scopes: ['openid', 'email', 'profile'] })\n .then(function (tokens) {\n const jwt = tokens.accessToken.value;\n window.sessionStorage.setItem('jwt', jwt);\n window.location.replace(`${window.location.origin}/daily-data/`);\n });\n}", "requireAuth(req, res, next) {\n if (!req.session.userId) {\n return res.redirect('/signin');\n }\n next();\n }", "init() {\r\n\r\n this.configure();\r\n console.log(\"authAzure user: \")\r\n console.log(this.user());\r\n \r\n if (this.user()) {\r\n console.log('already signed in.');\r\n // Check if the current ID token is still valid based on expiration date\r\n if (this.checkIdToken()) {\r\n // set accessToken\r\n console.log('Acquiring accessing token ...')\r\n this.acquireToken().then (accessToken => {\r\n this.accessToken = accessToken \r\n console.log('accessToken: '+ this.accessToken); \r\n store.dispatch('auth/loginSuccess'); \r\n });\r\n }\r\n } else {\r\n console.log('not signed in');\r\n } \r\n }", "function profileHandler(err, resp, body) {\n var profile = profileParser(body), query = {};\n if (profile.error) return console.error(\"Error returned from Google: \", profile.error); //TODO: improve\n\n //Find profile using unique identity provider's id\n query[session.provider + '.id'] = profile.id;\n User.findOne(query, function(err, data) {\n if (err) return console.error(err); //TODO: improve\n if(data === null) { //profile not found\n data = {};\n data[session.provider] = profile;\n user = new User(data);\n } else { //profile found -> update user\n user = data;\n user[session.provider] = profile;\n }\n //Save new or updated user\n user.save(function(err, data){\n if (err) return console.error(err); //TODO: improve\n user = data; //so as to have an _id\n //Find token\n Token.findOne({access : token.access_token }, function(err, data) {\n if (err) return console.error(err); //TODO: improve\n if(data === null) {\n data = {\n user_id: user._id,\n provider: session.provider,\n agent: session.agent,\n address: session.address,\n //updated,\n expires: token.expires_in || token.expires, //Google uses expires_in, Facebook uses expires\n access: token.access_token\n //refresh: ''\n };\n new Token(data).save();\n //TODO: remove expired tokens?\n }\n });\n session.remove(); //.exec();\n //Also purge sessions older than 24 hours\n Session.where('created').lte(Date.now() - 24*60*60*1000).remove().exec();\n });\n });\n }", "function doWhenLoggedIn() {\n console.log(\"in doWhenLoggedIn appUser: \" + JSON.stringify(appUser));\n if (appUser.firstName !== \"\" && appUser.lastName !== \"\") {\n addUserToDb();\n }\n\n // empty current stock ticker\n $(\"#stock-input\").val(\"\");\n\n // check user watchlist\n renderUserWatchlist();\n }", "function setUser(responseBody) {\n var valid = responseBody && responseBody.data;\n var newUser;\n log.debug('Setting the user based on', responseBody);\n if (!valid) {\n log.warn('Did not get back a valid user record.', responseBody);\n user.data = {};\n user.isAuthenticated = false;\n user.meta = {};\n } else {\n // Figure out if the user is signed in. If so, update user.data and\n // user.meta.\n if (responseBody.isAuthenticated) {\n log.info('response body is', responseBody);\n log.info('response body data is', responseBody.data);\n log.info('response body meta is', responseBody.meta);\n user.data = responseBody.data;\n user.meta = responseBody.meta;\n if (user.meta.token) {\n koastHttp.saveToken({\n token: user.meta.token,\n expires: user.meta.expires\n });\n }\n authenticatedDeferred.resolve();\n }\n user.isAuthenticated = responseBody.isAuthenticated;\n }\n user.isReady = true;\n return user.isAuthenticated;\n }", "_checkAuthenticationStatus()\n {\n // First, check if we have the appropriate authentication data. If we do, check it.\n // If we don't, trigger an event to inform of login require.\n if (this._token.value === '')\n {\n Radio.channel('rodan').trigger(RODAN_EVENTS.EVENT__AUTHENTICATION_LOGINREQUIRED);\n }\n else\n {\n var authRoute = Radio.channel('rodan').request(RODAN_EVENTS.REQUEST__SERVER_GET_ROUTE, 'auth-me');\n var request = new XMLHttpRequest();\n request.onload = (event) => this._handleAuthenticationResponse(event);\n request.ontimeout = (event) => this._handleTimeout(event);\n request.open('GET', authRoute, true);\n request.setRequestHeader('Accept', 'application/json');\n this._setAuthenticationData(request);\n request.send();\n }\n }", "appSignIn() {\r\n\r\n if (!msalApp) {\r\n return null\r\n }\r\n\r\n console.log('appSignIn')\r\n this.login().then( () => {\r\n if ( this.user()) {\r\n console.log('user signed in');\r\n // Automaticaly assign accessToken\r\n this.acquireToken().then (accessToken => {\r\n this.accessToken = accessToken \r\n console.log('accessToken: '+ this.accessToken); \r\n store.dispatch('auth/loginSuccess'); \r\n }); \r\n } else {\r\n console.error('Failed to sign in');\r\n store.dispatch('auth/loginFailure'); \r\n } \r\n });\r\n\r\n}", "function getLoginUser() {\n\t\tlet getUserDetails = localStorageService.getLoggedInUserInfo();\n\t\tlet userDetails = JSON.parse(getUserDetails);\n\t\tlet loginUserGroup = userDetails.userGroup;\n\t\tif (loginUserGroup !== 'Administrator' && loginUserGroup !== 'Manager') {\n\t\t\tvm.reporter = userDetails.userId;\n\t\t\tvm.reporterList = []; // If User not admin than hide reporter list dropdown\n\t\t} else {\n\t\t\t/* Get reporters list */\n\t\t\tgetUsers();\n\t\t}\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CUANDO PULSAS ICONO FLECHA /$icoArrow.on("click", scrollearHero);
function scrollearHero(){ $("#logo path").css("fill","white"); $hero.css("height", "30vh").css("marginTop","100px"); var altBegins = $(".batmanBegins").offset().top - $(".mainHeader .mainNav").height()-50; $("html,body").animate({scrollTop:altBegins},1500); $(".hero h1:nth-of-type(2)").css("top", "57%").css("font-size","1.3rem"); $(".hero h1:nth-of-type(1)").css("top", "52%").css("font-size","1.2rem"); $icoArrow.css("display", "none"); $(".hero div").css("display", "block").css("opacity", "1"); $(".wrapperHero").css("transform", "translateY(-80%)") }
[ "function megaMenuIcon() {\r\n\r\n var icons = document.querySelectorAll('.top-menu i');\r\n icons.forEach(element => {\r\n element.addEventListener('click', function (e) {\r\n if (e.target.classList.contains('fa-angle-down')) {\r\n e.target.classList.remove('fa-angle-down');\r\n e.target.classList.add('fa-angle-up');\r\n } else {\r\n e.target.classList.remove('fa-angle-up');\r\n e.target.classList.add('fa-angle-down');\r\n\r\n }\r\n });\r\n });\r\n}", "function clickMovieArrow(e) {\r\n $(e).click((event)=>{\r\n let target = $(event.target);\r\n if(target.is('.movie-next')) {\r\n showMovieSlides(1);\r\n } else {\r\n showMovieSlides(-1);\r\n }\r\n });\r\n}", "setEventToHamburgerIcon() {\n\n document.getElementById(\"hamburgerIcon\").addEventListener(\"click\", () => {\n let res = document.getElementById(\"myTopnav\");\n if (res.className === \"huge-topnav\") {\n res.className += \" responsive\";\n } else {\n res.className = \"huge-topnav\";\n }\n });\n\n }", "function makeGoToCoralReefButton() {\n\n // Create the clickable object\n goToCoralReefButton = new Clickable();\n \n goToCoralReefButton.text = \"Click here to go to the interactive reef\";\n goToCoralReefButton.textColor = \"#365673\"; \n goToCoralReefButton.textSize = 37; \n\n goToCoralReefButton.color = \"#8FD9CB\";\n\n // set width + height to image size\n goToCoralReefButton.width = 739;\n goToCoralReefButton.height = 84;\n\n // places button on the page \n goToCoralReefButton.locate( width/2 - goToCoralReefButton.width/2 , height * (3/4));\n\n //Clickable callback functions, defined below\n goToCoralReefButton.onPress = goToCoralReefButtonPressed;\n goToCoralReefButton.onHover = beginButtonHover;\n goToCoralReefButton.onOutside = beginButtonOnOutside;\n}", "function imojieClick(emojie) {\n gMeme.lines.push({\n txt: `${emojie}`,\n size: 20,\n align: 'left',\n color: 'red',\n x: 250,\n y: 300\n }, )\n gMeme.selectedLineIdx = gMeme.lines.length - 1\n drawImgText(elImgText)\n}", "function tourButtonClick() {\n\tstartButtonClick();\n\tstartIntro();\n}", "function viewHeroes() {\n //en cliquant sur le bouton, on ouvre la carte d'infos\n const buttonView = document.getElementsByClassName(\"cardBtn\");\n\n //les consts sont les elements qui doivent etre affiches dans la carte\n const nameCard = document.getElementsByClassName(\"name\");\n const signaleticsCard = document.getElementsByClassName(\"signaletics\");\n const longDescriptionCard = document.getElementsByClassName(\"description\");\n const imgCard = document.getElementsByClassName(\"image\");\n\n //\"Array.from\" copiée à partir d'un objet semblable à un tableau\n //Et il est affile a une boucle afin de chercher tout ce qu'on a besoin\n Array.from(document.querySelectorAll(\".cardBtn\")).forEach((btn, i) => {\n //\"addEventListener()\" met en place une fonction qui appelle un événement spécifié qui sera délivré à la cible\n btn.addEventListener(\"click\", () => {\n //les \"let\" comprennent sont les evenements delivres\n let nameModal = document.querySelector(\".modal-title\");\n let signaleticsModal = document.querySelector(\".signaleticsModal\");\n let descriptionModal = document.querySelector(\".cardModal\");\n let imgModal = document.querySelector(\".imgModal\");\n //on change les infos en texte afin de les lire \n nameModal.innerText = nameCard[i].innerText;\n signaleticsModal.innerText = signaleticsCard[i].innerText;\n descriptionModal.innerText = longDescriptionCard[i].innerText;\n imgModal.src = imgCard[i].src;\n })\n });\n }", "function addIconClickListener(callBack) {\n browserAction.onClicked.addListener(callBack);\n}", "#addOnHelpIconClickEventListener() {\n const questionMarkDiv = this.qm;\n if (questionMarkDiv) {\n questionMarkDiv.addEventListener('click', () => {\n this.#triggerEventOnGuideBridge(this.ELEMENT_HELP_SHOWN)\n })\n }\n }", "onListenButtonClick() {\n this.micIcon.classList.add(\"hidden\");\n this.loader.classList.remove(\"hidden\");\n window.character.listen();\n }", "function clickMusicArrow(e) {\r\n $(e).click((event)=>{\r\n let target = $(event.target);\r\n if(target.is('.next')) {\r\n showMusicSlides(1);\r\n } else {\r\n showMusicSlides(-1); \r\n }\r\n });\r\n}", "setUpStartingPlayerClick(event) {\n const { changeCurrentPlayer, setCurrentPlayer, opponentChoice } = this.player\n const icon = event.target\n const bottomIcons = Array.from(document.querySelectorAll(\".bottom-container__iconcont\"))\n this.removeSetTimeOuts()\n this.startGame()\n changeH4Text(\"Let\\'s see who is better\", \"25px\")\n if (icon.classList.contains(\"1\")) {\n setCurrentPlayer(\"O\")\n bottomIcons[1].style.color = \"#7cb0d4\"\n bottomIcons[0].style.color = \"black\"\n // Player 2 should start this time:\n if (this.gameType === \"humancomputer\") {\n // First we let the computer randomly choose a grid to speed up the game:\n this.takeTurn(opponentChoice(this.board.origBoard), this.player.currentPlayer)\n // Then it's the other player's turn:\n changeCurrentPlayer()\n }\n } else if (icon.classList.contains(\"0\")) {\n setCurrentPlayer(\"X\")\n bottomIcons[0].style.color = \"#7cb0d4\"\n bottomIcons[1].style.color = \"black\"\n }\n // Should run this regardless of which icon is clicked (currentPlayer will change anyway)\n if (this.gameType === \"computercomputer\") {\n // First the computer chooses a random grid, then it's the opponent's turn with the minimax algorithm.\n changeH4Text(\"Let\\'s see who is the better A.I...\", \"20px\")\n this.takeTurn(opponentChoice(this.board.origBoard), this.player.currentPlayer)\n changeCurrentPlayer()\n this.opponentsTurn(this.player.currentPlayer, 900)\n }\n }", "clickListener(e) {\n if (this.selectedMapCube !== null && this.selectedMapCube != this.selectedCube) {\n this.enhancedCubes = [];\n this.scaffoldingCubesCords = null;\n this.selectedCube = this.selectedMapCube;\n let directions = this.ref.methods.getDirections(this.selectedMapCube);\n // this.ref.updateRoom(this.selectedMapCube, directions);\n this.ref.room.navigateToRoom(this.selectedMapCube, directions, true);\n this.repaintMapCube(ref.cubes, \"\", [], null, false, this.selectedMapCube);\n //this.repaintMapCube(hoverCubeArr, this.selectedMapCube.label);\n }\n }", "function makeCoralReefButton() {\n\n // Create the clickable object\n coralReefButton = new Clickable();\n \n coralReefButton.text = \"Click here to see your coral reef!\";\n coralReefButton.textColor = \"#365673\"; \n coralReefButton.textSize = 37; \n\n coralReefButton.color = \"#8FD9CB\";\n\n // set width + height to image size\n coralReefButton.width = 994;\n coralReefButton.height = 90;\n\n // places the button on the page \n coralReefButton.locate( width/2 - coralReefButton.width/2 , height * (3/4));\n\n // // Clickable callback functions, defined below\n coralReefButton.onPress = coralReefButtonPressed;\n coralReefButton.onHover = beginButtonHover;\n coralReefButton.onOutside = beginButtonOnOutside;\n}", "function manScrobbleButton()\r\n{\r\n\tvar manScrobbButton = document.getElementById(\"lastfm-man-scrobble\");\r\n\tmanScrobbButton.addEventListener(\"click\", scrobbleManual, false);\r\n}", "function gifClicked() {\n largeGifAppears(this);\n automatedSpeech();\n}", "function rotateArrow(){\n let scroll = $(window).scrollTop();\n if (scroll > 200) {\n $('.downArrow').addClass('upArrowed');\n } else {\n $('.downArrow').removeClass('upArrowed');\n }\n }", "turnOnIcon(icon) {\n\t\ticon.selected = true;\n\t}", "function displayHero() {\n document.getElementById(\"hero\").style[\"top\"] = hero.hy + \"px\";\n document.getElementById(\"hero\").style[\"left\"] = hero.hx + \"px\";\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert `obj` to an integer (if `base` is given `obj` must be a string and `base` is the base for the conversion (default is 10))
[symbols.call](obj=0, base=null) { let result; if (base !== null) { if (typeof(obj) !== "string" || !_isint(base)) throw new TypeError("int() requires a string and an integer"); result = parseInt(obj, base); if (result.toString() == "NaN") throw new TypeError("invalid literal for int()"); return result; } else { if (typeof(obj) === "string") { result = parseInt(obj); if (result.toString() == "NaN") throw new TypeError("invalid literal for int()"); return result; } else if (typeof(obj) === "number") return Math.floor(obj); else if (obj === true) return 1; else if (obj === false) return 0; throw new TypeError("int() argument must be a string or a number"); } }
[ "function binaryToBaseTen(binaryNumber) {\n //your code here\n}", "function convertBase( str, baseOut, baseIn, sign ) { // 549\n var d, e, j, r, x, xc, y, // 550\n i = str.indexOf( '.' ), // 551\n rm = ROUNDING_MODE; // 552\n // 553\n if ( baseIn < 37 ) str = str.toLowerCase(); // 554\n // 555\n // Non-integer. // 556\n if ( i >= 0 ) { // 557\n str = str.replace( '.', '' ); // 558\n y = new BigNumber(baseIn); // 559\n x = y['pow']( str.length - i ); // 560\n // 561\n // Convert str as if an integer, then restore the fraction part by dividing the result // 562\n // by its base raised to a power. Use toFixed to avoid possible exponential notation. // 563\n y['c'] = toBaseOut( x.toFixed(), 10, baseOut ); // 564\n y['e'] = y['c'].length; // 565\n } // 566\n // 567\n // Convert the number as integer. // 568\n xc = toBaseOut( str, baseIn, baseOut ); // 569\n e = j = xc.length; // 570\n // 571\n // Remove trailing zeros. // 572\n for ( ; xc[--j] == 0; xc.pop() ); // 573\n if ( !xc[0] ) return '0'; // 574\n // 575\n if ( i < 0 ) { // 576\n --e; // 577\n } else { // 578\n x['c'] = xc; // 579\n x['e'] = e; // 580\n // sign is needed for correct rounding. // 581\n x['s'] = sign; // 582\n x = div( x, y, DECIMAL_PLACES, rm, baseOut ); // 583\n xc = x['c']; // 584\n r = x['r']; // 585\n e = x['e']; // 586\n } // 587\n d = e + DECIMAL_PLACES + 1; // 588\n // 589\n // The rounding digit, i.e. the digit after the digit that may be rounded up. // 590\n i = xc[d]; // 591\n j = baseOut / 2; // 592\n r = r || d < 0 || xc[d + 1] != null; // 593\n // 594\n r = rm < 4 // 595\n ? ( i != null || r ) && ( rm == 0 || rm == ( x['s'] < 0 ? 3 : 2 ) ) // 596\n : i > j || i == j && // 597\n ( rm == 4 || r || rm == 6 && xc[d - 1] & 1 || rm == ( x['s'] < 0 ? 8 : 7 ) ); // 598\n // 599\n if ( d < 1 || !xc[0] ) { // 600\n xc.length = 1; // 601\n j = 0; // 602\n // 603\n if (r) { // 604\n // 605\n // 1, 0.1, 0.01, 0.001, 0.0001 etc. // 606\n xc[0] = 1; // 607\n e = -DECIMAL_PLACES; // 608\n } else { // 609\n // 610\n // Zero. // 611\n e = xc[0] = 0; // 612\n } // 613\n } else { // 614\n xc.length = d; // 615\n // 616\n if (r) { // 617\n // 618\n // Rounding up may mean the previous digit has to be rounded up and so on. // 619\n for ( --baseOut; ++xc[--d] > baseOut; ) { // 620\n xc[d] = 0; // 621\n // 622\n if ( !d ) { // 623\n ++e; // 624\n xc.unshift(1); // 625\n } // 626\n } // 627\n } // 628\n // 629\n // Determine trailing zeros. // 630\n for ( j = xc.length; !xc[--j]; ); // 631\n } // 632\n // 633\n // E.g. [4, 11, 15] becomes 4bf. // 634\n for ( i = 0, str = ''; i <= j; str += DIGITS.charAt( xc[i++] ) ); // 635\n // 636\n // Negative exponent? // 637\n if ( e < 0 ) { // 638\n // 639\n // Prepend zeros. // 640\n for ( ; ++e; str = '0' + str ); // 641\n str = '0.' + str; // 642\n // 643\n // Positive exponent? // 644\n } else { // 645\n i = str.length; // 646\n // 647\n // Append zeros. // 648\n if ( ++e > i ) { // 649\n for ( e -= i; e-- ; str += '0' ); // 650\n } else if ( e < i ) { // 651\n str = str.slice( 0, e ) + '.' + str.slice(e); // 652\n } // 653\n } // 654\n // 655\n // No negative numbers: the caller will add the sign. // 656\n return str; // 657\n } // 658", "function baseConverter(decNumber, base) {\r\n\tvar nStack = new Stack(),\r\n\t\tn,\r\n\t\tbaseString = '';\r\n\t\tdigits = '0123456789ABCDEF';\r\n\r\n\twhile (decNumber > 0 ) {\r\n\t\tn = Math.floor(decNumber % base);\r\n\t\tnStack.push(n);\r\n\t\tdecNumber = Math.floor(decNumber / base);\r\n\t}\r\n\r\n\twhile (!nStack.isEmpty()) {\r\n\t\tbaseString += digits[nStack.pop()];\r\n\t}\r\n\r\n\treturn baseString;\r\n}", "function floorInBase(n,base){return base*Math.floor(n/base)}", "function safeParseInt(v,base){if(v.slice(0,2)==='00'){throw new Error('invalid RLP: extra zeros');}return parseInt(v,base);}", "function floorInBase(n,base){return base*Math.floor(n/base);}", "function toAInt(v) {\n\tif (!(v instanceof AInt))\n\t\treturn new AInt(v);\n\treturn v;\n}", "function makeInt(n) {\n return parseInt( n, 10);\n}", "function INT(x) { return Math.floor(x) }", "function toDecimal(num, from_base){\r\n\tvar multiplier = 1;\r\n\tvar output = 0;\r\n\r\n\t// Error checking\r\n\tcheckBase(from_base);\r\n\tfor (var i = num.length - 1; i >= 0; --i){\r\n\t\tvar digit = num[i].charCodeAt(0) - 48;\r\n\t\tif(digit > 9){\r\n\t\t\tdigit = digit - 7;\r\n\t\t}\r\n\r\n\t\tif(digit >= from_base || digit < 0){\r\n\t\t\tthrow \"Something is wrong: num is invalid for that base. In toDecimal.\";\r\n\t\t}\r\n\t\toutput = output + (digit * multiplier);\r\n\t\tmultiplier = multiplier * from_base;\r\n\t}\r\n\treturn output;\r\n}", "function parseShort(str, base) {\r\n\tvar n = parseInt(str, base);\r\n\treturn (n << 16) >> 16;\r\n}", "function uintToBaseN(number, base) {\n if (base < 2 || base > 62 || number < 0) {\n return '';\n }\n var output = '';\n do {\n output = BaseNSymbols.charAt(number % base).concat(output);\n number = Math.floor(number / base);\n } while (number > 0);\n return output;\n}", "function safeParseInt(value) {\n if (!value) {\n return 0;\n }\n if (ok(value, tyString)) {\n return parseInt(value, 10);\n }\n if (ok(value, tyNumber)) {\n return value;\n }\n return 0;\n }", "function prefixToBase(c)\n\t{\n\t\tif (c === CP_b || c === CP_B) {\n\t\t\t/* 0b/0B (binary) */\n\t\t\treturn (2);\n\t\t} else if (c === CP_o || c === CP_O) {\n\t\t\t/* 0o/0O (octal) */\n\t\t\treturn (8);\n\t\t} else if (c === CP_t || c === CP_T) {\n\t\t\t/* 0t/0T (decimal) */\n\t\t\treturn (10);\n\t\t} else if (c === CP_x || c === CP_X) {\n\t\t\t/* 0x/0X (hexadecimal) */\n\t\t\treturn (16);\n\t\t} else {\n\t\t\t/* Not a meaningful character */\n\t\t\treturn (-1);\n\t\t}\n\t}", "function _toAbsLength(base, value) {\n\tif (typeof value == 'string' && value.charAt(value.length - 1) == '%') {\n\t\tvar s = value.substring(0, value.length - 1);\n\t\treturn base * Number(s) / 100;\n\t}\n\treturn Number(value);\n}", "function parseTriple(str, base) {\r\n\tvar n = parseInt(str, base);\r\n\treturn (n << 8) >> 8;\r\n}", "function parseSliceInt(value, start, length) {\n let binary = parseDecToBin(parseInt(value).toString(2)).padStart(8, \"0\").slice(start, start + length);\n if (binary.includes(\"1\")) {\n return parseInt(binary, 2);\n }\n return 0;\n}", "function calculateID(info){\n\t// Hash object name\n\tvar hash = updateHash(info.name, 0);\n\n\t// Hash object attributes\n\thash = updateHash(info.isSettings, hash);\n\thash = updateHash(info.isSingleInst, hash);\n\n\t// Hash field information\n\tfor (var n = 0; n < info.fields.length; n++){\n\t\thash = updateHash(info.fields[n].name, hash);\n\t\thash = updateHash(info.fields[n].numElements, hash);\n\t\thash = updateHash(info.fields[n].type, hash);\n\n\t\tif (info.fields[n].type == 7){ // enum\n\t\t\tvar options = info.fields[n].options;\n\t\t\tfor (var m = 0; m < options.length; m++){\n\t\t\t\thash = updateHash(options[m], hash);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Done\n\treturn hash & 0xFFFFFFFE;\n}", "function geTenConToStr(int){\n if(int<10){\n return numWithWords.get(int);\n }\n return geTenConToStr(Math.floor(int/10))+numWithWords.get(int%10);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
LC Status Details Page : Fill the LC Details based on Response
function fillTheLCStatusDetailsPage(LcDetails_ResponseObject) { document.getElementById("Loc_Details_Trade_Id_Value").innerHTML = LcDetails_ResponseObject.Trade_Id; document.getElementById("Loc_Details_Loc_Id_Value").innerHTML = LcDetails_ResponseObject.Lc_Id; document.getElementById("Loc_Details_Buyer_Name_Value").innerHTML = LcDetails_ResponseObject.Buyer; document.getElementById("Loc_Details_Seller_Name_Value").innerHTML = LcDetails_ResponseObject.Seller; document.getElementById("Loc_Details_Buyer_Bank_Name_Value").innerHTML = LcDetails_ResponseObject.Bank; document.getElementById("Loc_Details_Shipment_Value").innerHTML = LcDetails_ResponseObject.Shipment; document.getElementById("Loc_Details_Shipment_Count_Value").innerHTML = LcDetails_ResponseObject.ShipmentCount; document.getElementById("Loc_Details_Loc_Amount_Value").innerHTML = LcDetails_ResponseObject.Amount; document.getElementById("Loc_Details_Status_Value").innerHTML = LcDetails_ResponseObject.Current_Status; document.getElementById("Loc_Details_Expiry_Date_Value").innerHTML = LcDetails_ResponseObject.Expiry_Date; }
[ "function fillTheShipmentStatusDetailsPage(TradeDetails_ResponseObject) {\n\n document.getElementById(\"Shipment_Details_TA_Id_Value\").innerHTML = TradeDetails_ResponseObject.Trade_Id;\n document.getElementById(\"Shipment_Details_Buyer_Name_Value\").innerHTML = TradeDetails_ResponseObject.Buyer;\n document.getElementById(\"Shipment_Details_Seller_Name_Value\").innerHTML = TradeDetails_ResponseObject.Seller;\n document.getElementById(\"Shipment_Details_Shipment_Value\").innerHTML = TradeDetails_ResponseObject.Shipment;\n document.getElementById(\"Shipment_Details_Shipment_Count_Value\").innerHTML = TradeDetails_ResponseObject.ShipmentCount;\n document.getElementById(\"Shipment_Details_Amount_Value\").innerHTML = TradeDetails_ResponseObject.Amount;\n document.getElementById(\"Shipment_Details_Status_Value\").innerHTML = TradeDetails_ResponseObject.Current_Status;\n\n }", "function loadStatus(page) {\n $(\".page\").css(\"display\", \"none\");\n $(\"#\" + page + \"_status\").css(\"display\", \"block\");\n\n // Clear the page and add the loading sign (this request can take a few seconds)\n $(\"#\" + page + \"_status\").html('<i class=\"fa fa-spinner fa-pulse fa-3x fa-fw center\"></i>');\n\n sendMessage(\"agent/status/\" + page, \"\", \"post\",\n function(data, status, xhr){\n $(\"#\" + page + \"_status\").html(DOMPurify.sanitize(data));\n\n // Get the trace-agent status\n sendMessage(\"agent/getConfig/apm_config.receiver_port\", \"\", \"GET\",\n function(data, status, xhr) {\n var apmPort = data[\"apm_config.debug.port\"];\n if (apmPort == null) {\n apmPort = \"5012\";\n }\n var url = \"http://127.0.0.1:\"+apmPort+\"/debug/vars\"\n $.ajax({\n url: url,\n type: \"GET\",\n success: function(data) {\n $(\"#apmStats > .stat_data\").html(ejs.render(apmTemplate, data));\n },\n error: function() {\n $(\"#apmStats > .stat_data\").text(\"Status: Not running or not on localhost.\");\n }\n })\n }, function() {\n $(\"#apmStats > .stat_data\").html(\"Could not obtain trace-agent port from API.\");\n })\n },function(){\n $(\"#\" + page + \"_status\").html(\"<span class='center'>An error occurred.</span>\");\n });\n}", "function reportStatus(theReason) {\n\tprint(\"thereason is \" + theReason);\n var reason = { \n \"reason\" : theReason\n } \n cocoon.sendPage(\"wagger-status-pipeline\", reason);\n}//reportStatus ", "function updateStatus() {\n Packlink.ajaxService.get(\n checkStatusUrl,\n /** @param {{logs: array, finished: boolean}} response */\n function (response) {\n let logPanel = document.getElementById('pl-auto-test-log-panel');\n\n logPanel.innerHTML = '';\n for (let log of response.logs) {\n logPanel.innerHTML += writeLogMessage(log);\n }\n\n logPanel.scrollIntoView();\n logPanel.scrollTop = logPanel.scrollHeight;\n response.finished ? finishTest(response) : setTimeout(updateStatus, 1000);\n }\n );\n }", "function renderSitesStatus() {\n\t// send the request\n\tvar obj = {};\n\tvar url = HOME + '/query';\n\tobj['action'] = 'displaySitesStatus';\n\tscanner.POST(url, obj, true, postRenderSitesStatus, null, null, 0);\n}", "#statusContent() {\n var driverID = this.serverKey + '_driver';\n var stateID = this.serverKey + '_state';\n var experimentID = this.serverKey + '_experiment';\n var numCompletedID = this.serverKey + '_numCompleted';\n var numQueuedID = this.serverKey + '_numQueued';\n var dateTimeID = this.serverKey + '_dateTime';\n var topContent = '<p>Driver: <span id=\"'+driverID+'\">[driver name]</span> | Queue State: <span id=\"'+stateID+'\">[state]</span> | Experiment: <span id=\"'+experimentID+'\">[experiment]</span> | Completed: <span id=\"'+numCompletedID+'\">[#]</span> | Queue: <span id=\"'+numQueuedID+'\">[#]</span> | Time: <span id=\"'+dateTimeID+'\">[time] [date]</span></p>';\n\n var driverStatusID = this.serverKey + '_driverStatus';\n var bottomContent = '<p><span id=\"'+driverStatusID+'\"></span></p>';\n var content = topContent + '<hr>' + bottomContent;\n\n return content;\n }", "function loadTrackstatusData() {\n var path = [{ url: 'project/trackStatus/trackStatusData.json', method: \"GET\" }];\n PPSTService.getJSONData(path).then(function (response) {\n $scope.statusListData = response[0].data; // data for track status\n //$scope.loaderFlag = false;\n trackStatusService.dataChange();\n //trackStatusService.getChange();\n }).catch(function (err) {\n console.error(\"error fecthing tracj status data\");\n });\n }", "function FormInfoUT_Rsp(object) {\n\n let Strings = \"<ul><li></li>\", Strings1 = \"<ul><li>Cash</li><li>SRS-IA</li><li>CPEOA-IA</li><li>CPESA-IA</li></ul>\", a = 0, arry = [];\n\n const Monthly_Rsp_Left = $(\"#Regular_Savings_Plan_Left\");\n const Monthly_Rsp_Content = $(\"#Regular_Savings_Plan_Content\");\n const Quarterly_Rsp_Left = $(\"#Regular_Savings_Plan_Left1\");\n const Quarterly_Rsp_Content = $(\"#Regular_Savings_Plan_Content1\");\n const Regular_Savings_Plan_title = $(\".Regular_Savings_Plan_title\");\n const Regular_Savings_Plan_p = $(\"#Regular_Savings_Plan p\");\n Monthly_Rsp_Left.empty();\n Monthly_Rsp_Content.empty();\n Quarterly_Rsp_Left.empty();\n Quarterly_Rsp_Content.empty();\n Regular_Savings_Plan_p.empty();\n\n //判断可现实\n if (object[\"approved\"]) {\n //Monthly Regular Savings Plan Charges\n var Monthly_Rsp_Charges = Arry_data(object[\"monthlyRSP\"]);\n var Arry = Characters_of_the_adapter(Monthly_Rsp_Charges, Strings, Strings1);\n Monthly_Rsp_Left.append(Arry[0]);\n Monthly_Rsp_Content.append(Arry[1]);\n Strings = \"<ul><li></li>\";\n Strings1 = \"<ul><li>Cash</li><li>SRS-IA</li><li>CPEOA-IA</li><li>CPESA-IA</li></ul>\";\n //Quarterly Regular Savings Plan Charges\n var Quarterly_Rsp_Charges = Arry_data(object[\"quarterlyRSP\"]);\n var Arry = Characters_of_the_adapter(Quarterly_Rsp_Charges, Strings, Strings1);\n Quarterly_Rsp_Left.append(Arry[0]);\n Quarterly_Rsp_Content.append(Arry[1]);\n //\n Regular_Savings_Plan_p.append(\"<span>Learn more about Regular Savings Plan</span>\");\n Regular_Savings_Plan_p.css(\"paddingTop\", \"0\");\n Regular_Savings_Plan_p.click(function () {\n window.open(object[\"learnMoreURL\"]);\n });\n\n Regular_Savings_Plan_title.show();\n Monthly_Rsp_Left.show();\n Monthly_Rsp_Content.show();\n Quarterly_Rsp_Left.show();\n Quarterly_Rsp_Content.show();\n }\n else {\n Regular_Savings_Plan_title.hide();\n Monthly_Rsp_Left.hide();\n Monthly_Rsp_Content.hide();\n Quarterly_Rsp_Left.hide();\n Quarterly_Rsp_Content.hide();\n Regular_Savings_Plan_p.append(\"The fund is not available for normal savings plans<br/><span>click here</span> to see RSP approved list of funds\");\n Regular_Savings_Plan_p.css(\"paddingTop\", \"42%\");\n Regular_Savings_Plan_p.click(function () {\n window.open(object[\"approvedListURL\"]);\n });\n }\n }", "function handleResponse(data) {\r\n var parsedResponse = JSON.parse(data.currentTarget.response);\r\n console.log(parsedResponse.items);\r\n var parsedItems = Object.values(parsedResponse.items);\r\n var itemTimeslotArray = buildTimeslotArray(parsedItems);\r\n // pageConstructor(parsedItems, itemTimeslotArray);\r\n console.log(parsedItems);\r\n var currentDate = getDateForm();\r\n var paramForm = getParamForm();\r\n// console.log(currentDate);\r\n htmlConstructor(parsedItems, itemTimeslotArray, currentDate, paramForm);\r\n}", "function getDetail(){\n console.log('Now for each page');\n\n companiesArr = companyListObj.companiesArr;\n companyList = companyListObj.companyListBuf;\n\n this.eachThen(companyList, function(res){\n console.log('Company: '+res.data.company);\n getCompanyDetail.call(this, res.data.businessId);\n }).then(function(){\n this.run(goNextPage);\n });\n}", "function retrieveLcDetails_FromMongoDB(Lc_Id, Client_Request, currentUser, currentUserType) {\n\n var xmlhttp;\n var httpRequestString = webServerPrefix;\n\n xmlhttp = new XMLHttpRequest();\n httpRequestString += \"Client_Request=\" + Client_Request;\n httpRequestString += \"&\";\n httpRequestString += \"Lc_Id=\" + Lc_Id;\n\n xmlhttp.open(\"POST\", httpRequestString, true);\n xmlhttp.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n xmlhttp.setRequestHeader(\"accept\", \"application/json\");\n\n // Wait for Async response and Handle it in web page\n\n xmlhttp.onreadystatechange = function () {\n\n if (this.status == 200) {\n\n if (this.readyState == 4) {\n\n //Parse the JSON Response Object\n\n responseObject = JSON.parse(this.response);\n\n if (bDebug == true) {\n\n alert(\"All the LC Details for LC Id => \" + Lc_Id + \" : \" + responseObject);\n }\n\n // Check the inclusiveness of Lc-Id ( to see if it belongs to Current User )\n\n if (currentUser != null && currentUser != undefined && currentUserType != null && currentUserType != undefined) {\n\n if (currentUser == responseObject[currentUserType]) {\n\n fillTheLCStatusDetailsPage(responseObject);\n\n } else {\n\n alert(\"LC_Id : \" + Lc_Id +\" doesn't belong to Current user : \" + currentUser);\n }\n\n } else {\n\n alert(\"Incorrect User Name/Type in current User Context\");\n }\n\n } else {\n\n if (bDebug == true) {\n\n alert(\"Intermediate Success Response while placing RetrieveLCDetails call :=> Status : \" + this.status + \" readyState : \" + this.readyState);\n }\n }\n\n } else {\n\n alert(\"Failure to place RetrieveLCDetails call :=> Status : \" + this.status + \" readyState : \" + this.readyState);\n }\n\n };\n\n if (bDebug == true) {\n\n alert(\"Retrieving the LC detais from mongoDB => httpRequest : \" + httpRequestString);\n }\n xmlhttp.send();\n\n }", "function getPatientInfo(qr) {\n setQr(qr);\n alert(\"The patient: \" + qr + \" has been scanned and added into the system\");\n }", "function GetShiftDetails() {\r\n $scope.HideValidationDiv();\r\n var data = JSON.stringify({ 'CompanyId': $scope.CompanyId });\r\n $http({\r\n method: 'GET',\r\n url: '/api/Admin/GetCompanyWiseShiftDetails',\r\n params: { requestParam: data }\r\n }).then(function (responseData) {\r\n if (responseData.status == 202) {\r\n $scope.ErrorMsg = responseData.data;\r\n angular.element('#idReqValidation').show();\r\n return;\r\n }\r\n if (responseData.data == '') {\r\n return;\r\n }\r\n $scope.ShiftListOri = $scope.ShiftList = JSON.parse(responseData.data);\r\n ListToScopeVariable($scope.ShiftList);\r\n });\r\n }", "function displayTrailResults(trailResponseJson) {\n $('.js-trail-results').empty();\n let result = trailResponseJson.trails.length;\n if (trailResponseJson.trails.length === 0) {\n $('.js-trail-results').text('No trails found. Please try a different address.');\n } else {\n $('.js-trail-results').append(trailResponseJson.trails.map((trail) => \n `<li><h3>${trail.name}</h3></li>\n <li><i>${trail.summary}</i></li>\n <li>Difficulty: ${trail.difficulty}</li>\n <li>Location: ${trail.location}</li>\n <li>Condition: ${trail.conditionStatus}</li>\n <li>Length: ${trail.length} miles </li>\n <li><a href=\"${trail.url}\" target=\"_blank\">More Details</a></li>`));\n };\n $('.results').text(result);\n}", "function handleCreateActivityResponse(status) {\n\tif (status.errCode === 1){\n window.location = '/?methodType=createActivity&errCode=' + status.errCode;\n } else if (status.errCode === 6){\n //missing required parameter\n var errMsg = 'Error: ' + status.message;\n if (status.message == 'null time1') {\n \terrMsg = 'Error: Null Start Time';\n } else if (status.message == 'null time2') {\n \terrMsg = 'Error: Null End Time';\n }\n $('#missingParams').html(errMsg);\n $('#missingParams').show();\n $('body').scrollTop(0);\n //window.location = '/#create_activity_page?errCode=' + status.errCode;\n }\n\t// window.location = '/';\n}", "function retrieveStatus(){\n request(icecastUrl, function (error, response, body) {\n // If error, log it\n var mountpointList = JSON.parse(body).icestats.source;\n // Check for all three mountpoints\n checkStatus(mountpointList, 'listen');\n checkStatus(mountpointList, 'hub');\n checkStatus(mountpointList, 'harrow');\n });\n}", "function updateStatus() {\n\tchrome.extension.sendRequest(\n\t\t\t{type: \"status?\"}\n\t\t, function(response) {\n\t\t\t$(\"ws_status\").textContent=response.ws_status;\n\t\t\t$(\"pn_status\").textContent=response.pn_status;\n\t\t\t});\t\t\n}", "function HandleStatus(data, response)\n{\n console.log(response);\n\n //Update selects\n FillUserCars();\n}", "function decode_light_control_status(data) {\n\tdata.command = 'bro';\n\tdata.value = 'light control status - ';\n\n\t// Examples\n\t//\n\t// D1 D2\n\t// 11 01 Intensity=1, Lights=on, Reason=Twilight\n\t// 21 02 Intensity=2, Lights=on, Reason=Darkness\n\t// 31 04 Intensity=3, Lights=on, Reason=Rain\n\t// 41 08 Intensity=4, Lights=on, Reason=Tunnel\n\t// 50 00 Intensity=5, Lights=off, Reason=N/A\n\t// 60 00 Intensity=6, Lights=off, Reason=N/A\n\t//\n\t// D1 - Lights on/off + intensity\n\t// 0x01 : Bit0 : Lights on\n\t// 0x10 : Bit4 : Intensity 1\n\t// 0x20 : Bit5 : Intensity 2\n\t// 0x30 : Bit4+Bit5 : Intensity 3\n\t// 0x40 : Bit6 : Intensity 4\n\t// 0x50 : Bit4+Bit6 : Intensity 5\n\t// 0x60 : Bit5+Bit6 : Intensity 6\n\t//\n\t// D2 - Reason\n\t// 0x01 : Bit0 : Twilight\n\t// 0x02 : Bit1 : Darkness\n\t// 0x04 : Bit2 : Rain\n\t// 0x08 : Bit3 : Tunnel\n\t// 0x10 : Bit4 : Garage\n\n\tconst mask1 = bitmask.check(data.msg[1]).mask;\n\tconst mask2 = bitmask.check(data.msg[2]).mask;\n\n\tconst parse = {\n\t\tintensity : null,\n\t\tintensity_str : null,\n\t\tintensities : {\n\t\t\tl1 : mask1.bit4 && !mask1.bit5 && !mask1.bit6 && !mask1.bit8,\n\t\t\tl2 : !mask1.bit4 && mask1.bit5 && !mask1.bit6 && !mask1.bit8,\n\t\t\tl3 : mask1.bit4 && mask1.bit5 && !mask1.bit6 && !mask1.bit8,\n\t\t\tl4 : !mask1.bit4 && !mask1.bit5 && mask1.bit6 && !mask1.bit8,\n\t\t\tl5 : mask1.bit4 && !mask1.bit5 && mask1.bit6 && !mask1.bit8,\n\t\t\tl6 : !mask1.bit4 && mask1.bit5 && mask1.bit6 && !mask1.bit8,\n\t\t\tl0 : !mask1.bit4 && !mask1.bit5 && !mask1.bit6 && mask1.bit8,\n\t\t},\n\n\t\tlights : mask1.bit0,\n\t\tlights_str : 'lights on: ' + mask1.bit0,\n\n\t\treason : null,\n\t\treason_str : null,\n\t\treasons : {\n\t\t\ttwilight : mask2.bit0 && !mask2.bit1 && !mask2.bit2 && !mask2.bit3 && !mask2.bit4 && !mask2.bit8,\n\t\t\tdarkness : !mask2.bit0 && mask2.bit1 && !mask2.bit2 && !mask2.bit3 && !mask2.bit4 && !mask2.bit8,\n\t\t\train : !mask2.bit0 && !mask2.bit1 && mask2.bit2 && !mask2.bit3 && !mask2.bit4 && !mask2.bit8,\n\t\t\ttunnel : !mask2.bit0 && !mask2.bit1 && !mask2.bit2 && mask2.bit3 && !mask2.bit4 && !mask2.bit8,\n\t\t\tgarage : !mask2.bit0 && !mask2.bit1 && !mask2.bit2 && !mask2.bit3 && mask2.bit4 && !mask2.bit8,\n\t\t\tnone : !mask2.bit0 && !mask2.bit1 && !mask2.bit2 && !mask2.bit3 && !mask2.bit4 && mask2.bit8,\n\t\t},\n\t};\n\n\t// Loop intensity object to obtain intensity level\n\tfor (const intensity in parse.intensities) {\n\t\tif (parse.intensities[intensity] === true) {\n\t\t\t// Convert hacky object key name back to integer\n\t\t\tparse.intensity = parseInt(intensity.replace(/\\D/g, ''));\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Loop reason object to obtain reason name\n\tfor (const reason in parse.reasons) {\n\t\tif (parse.reasons[reason] === true) {\n\t\t\tparse.reason = reason;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Append prefixes to log strings\n\tparse.intensity_str = 'intensity: ' + parse.intensity;\n\tparse.reason_str = 'reason: ' + parse.reason;\n\n\tupdate.status('rls.light.intensity', parse.intensity, false);\n\tupdate.status('rls.light.lights', parse.lights, false);\n\tupdate.status('rls.light.reason', parse.reason, false);\n\n\t// Assemble log string\n\tdata.value += parse.intensity_str + ', ' + parse.lights_str + ', ' + parse.reason_str;\n\n\treturn data;\n}", "function scrapeStatus() {\n return new Promise((resolve, reject) => {\n request(mtaStatusUrl, (err, response, responseHtml) => {\n if (err) {\n reject(err);\n }\n\n const $ = cheerio.load(responseHtml);\n\n let results = {\n subway: []\n };\n\n $('#subwayDiv').find('tr').each((index, row) => {\n // First row is irrelevant.\n if (index !== 0) {\n\n results.subway.push({\n name: $(row).find('img').attr('alt').replace(/subway|\\s/ig, ''),\n status: $(row).find('span[class^=\"subway_\"]').text(),\n });\n }\n });\n\n // Write to the local cache.\n fs.writeFile(__dirname + cachedData, JSON.stringify(results), (err) => {\n // @todo: handle error\n });\n\n resolve(results);\n });\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
drawDiamondOdd only applies for odd rows and cols
function drawDiamondOdd (rowIndex, colIndex, rows, length) { if (rowIndex <= (rows - 1)/2){ return ((colIndex === (length-1)/2 - rowIndex)|| (colIndex === (length-1)/2 + rowIndex)); } else { return ((colIndex === (length-1)/2 - (rows - 1 - rowIndex))|| (colIndex === (length-1)/2 + (rows - 1 - rowIndex))); } }
[ "function drawDiamond(lineCount) {\n var middleP, fullStatsArr;\n var starsArr = Array(lineCount).fill(0).map((u, i) => { return i + 1; });\n if (lineCount % 2 == 0) {\n middleP = lineCount / 2;\n fullStatsArr = starsArr.slice(0, middleP).concat(starsArr.slice(0, middleP).reverse());\n } else {\n middleP = Math.round(lineCount / 2);\n fullStatsArr = starsArr.slice(0, middleP).concat(starsArr.slice(0, middleP - 1).reverse());\n }\n // console.log(starsArr);\n var result = fullStatsArr.reduce((p, c) => {\n p = p + ' '.repeat(lineCount - c) + '*'.repeat(c + c - 1) + '\\n';\n return p;\n }, \"\");\n console.log(result);\n}", "function diamond(G, x, y, size, offset){\n var avg = \n average(mapValue(G, x, y - size, max), // top\n mapValue(G, x - size, y, max), // left\n mapValue(G, x, y + size, max), // bottom\n mapValue(G, x + size, y, max)); // right\n G[x][y] = avg + offset;\n}", "function drawTile(x, y, color, hasOdds) {\n var h = 2 * s;\n var w = Math.sqrt(3) / 2 * s * 2;\n ctx.beginPath();\n ctx.moveTo(x, y);\n ctx.lineTo(x + w / 2, y + s / 2);\n ctx.lineTo(x + w / 2, y + s + s / 2);\n ctx.lineTo(x, y + h);\n ctx.lineTo(x - w / 2, y + s + s / 2);\n ctx.lineTo(x - w / 2, y + s / 2);\n ctx.closePath();\n ctx.fillStyle = color;\n ctx.fill();\n ctx.stroke();\n // Draw odds piece\n if (hasOdds) {\n ctx.beginPath();\n ctx.arc(x, y + h / 2, s / 3.2, 0, 2 * Math.PI);\n ctx.closePath();\n ctx.fillStyle = '#f5f5dc';\n ctx.fill();\n ctx.stroke();\n }\n }", "function twoHalfsGrid(dice, i) {\n\tdice.dataset.orderId = i;\n\tif (i % 2 == 0) {\n\t\tdice.classList.add('position-split-2', 'is-left');\n\t} else {\n\t\tdice.classList.add('position-split-2', 'is-right');\n\t}\n}", "function decorateBoard() {\n\n // Traverses the 2D array and draws elements based on array value.\n for (let row = 0; row < board.length; row++) {\n for (let col = 0; col < board[row].length; col++) {\n const dimension = board[row][col];\n if (dimension == 1) {\n drawSprite(col * cellWidth, row * cellWidth);\n }\n }\n }\n\n}", "function drawSquareSideHouse() {\n moveForward(50);\n turnRight(90);\n}", "function diamond4() {\n return Math.floor(Math.random() * 11 + 1);\n }", "function drawChessboard(size){\nvar board = \"\".repeat(size);\nfor(var i = 0; i < size; i++){\n for(var a = 0; a < size; a++){\n board += (a % 2) == (i % 2) ? \" \" : \"#\";\n }\n board += \"\\n\";\n}console.log(board);\n}", "function diagonal(x,y){\nif (x < 300 && y < 200){\n ctx.strokeStyle = 'green'\n} else {\n ctx.strokeStyle = 'red'\n}\nctx.beginPath();\nctx.moveTo(x,y);\nctx.lineTo(x+100,y+100);\nctx.stroke();\n}", "function drawConsolePyramid(height) {\n console.log(\" \".repeat(height) + \"*\");\n for (let i = 1; i < height; i++) {\n\n console.log(\" \".repeat(height - i) + \"*\".repeat(i) + \"*\".repeat(i) + \" \".repeat(height - i));\n }\n}", "function drawConsoleBox(w, h) {\n\n for (let i = 0; i < 1; i++) {\n console.log(\"+\" + \"-\".repeat(w) + \"+\");\n }\n for (let j = 0; j < h; j++) {\n console.log(\"|\" + \" \".repeat(w) + \"|\");\n }\n for (let i = 0; i < 1; i++) {\n console.log(\"+\" + \"-\".repeat(w) + \"+\");\n }\n}", "function diamond3() {\n return Math.floor(Math.random() * 11 + 1);\n }", "drawHTMLBoard() {\r\n\t\tfor (let column of this.spaces) {\r\n\t\t\tfor (let space of column) {\r\n\t\t\t\tspace.drawSVGSpace();\r\n\t\t\t}\t\r\n\t\t}\r\n\t}", "function generate(side, cornA, cornB) {\r\n for (let i = 1; i - 1 < 100; i++) {\r\n for (let j = 1; j - 1 < 100; j++) {\r\n let pixel = document.createElement(\"div\");\r\n pixel.classList.add(\"pixel\");\r\n let x = cornA + i * (side / 100);\r\n let y = cornB + j * (side / 100);\r\n let c = Math.round(x ** 2 + y ** 2);\r\n if (c % 3 === 0) {\r\n pixel.style.backgroundColor = \"red\";\r\n } else if (c % 2 == 0) {\r\n pixel.style.backgroundColor = \"blue\";\r\n } else {\r\n pixel.style.backgroundColor = \"black\";\r\n }\r\n let selectedRow = document.querySelector(`.row${j}`);\r\n selectedRow.appendChild(pixel);\r\n }\r\n }\r\n}", "function dottedLine(x, y, w, h) {\r\n fill(\"grey\");\r\n rect(x, y - 4, 800, 5);\r\n for (line = 0; line < 15; line++) {\r\n lineSegment(line * 80 + 1, y, 40, 5);\r\n }\r\n}", "function printPyramid(height) {\n for ( var row = 1; row <= height; row++){\n var space = \"\";\n var hash = \"\";\n var space_count = height - row;\n var hash_count = height - space_count;\n for (var i = space_count; i > 0; i--)\n space += \" \";\n for (var j = 0; j <= hash_count; j++)\n hash += \"#\"\n console.log(space, hash);\n }\n}", "function draw_layer(num_neur, x_pos, diam) {\n let ver_dist = height / (num_neur+1);\n for (let i = 1; i <= num_neur; i++) {\n fill(255, 255, 255);\n stroke(0);\n circle(x_pos, ver_dist * i, diam);\n }\n}", "function drawBoard(size) {\r\n if (size <= 1) {\r\n alert(\"Specified grid size MUST >= 2!\");\r\n return;\r\n }\r\n \r\n var startx = GAP_SIZE;\r\n var starty = GAP_SIZE;\r\n\r\n for (var row = 0; row < size; ++row) {\r\n for (var col = 0; col < size; ++col) {\r\n drawLine(startx, starty + UNIT_SIZE*row, startx + UNIT_SIZE*(size-1), starty + UNIT_SIZE*row);\r\n drawLine(startx + UNIT_SIZE*col, starty, startx + UNIT_SIZE*col, starty + UNIT_SIZE*(size-1));\r\n }\r\n }\r\n for (var row = 0; row < size; ++row) {\r\n var patch = 0;\r\n if (row >= 10) {\r\n patch = GAP_SIZE/8;\r\n }\r\n drawText(row, GAP_SIZE/8*3-patch, GAP_SIZE/7*8+UNIT_SIZE*row);\r\n }\r\n for (var col = 0; col < size; ++col) {\r\n var patch = 0;\r\n if (col >= 10) {\r\n patch = GAP_SIZE/8;\r\n }\r\n drawText(col, GAP_SIZE/8*7+UNIT_SIZE*col-patch, GAP_SIZE/3*2);\r\n }\r\n \r\n // mark the center an key positions\r\n var radius = STONE_RADIUS/3;\r\n var color = \"black\";\r\n drawCircle(getCanvasPos(board.getPosition((GRID_SIZE-1)/2, (GRID_SIZE-1)/2)), radius, color);\r\n drawCircle(getCanvasPos(board.getPosition(WIN_SIZE-1, WIN_SIZE-1)), radius, color);\r\n drawCircle(getCanvasPos(board.getPosition(GRID_SIZE-WIN_SIZE, WIN_SIZE-1)), radius, color);\r\n drawCircle(getCanvasPos(board.getPosition(WIN_SIZE-1, GRID_SIZE-WIN_SIZE)), radius, color);\r\n drawCircle(getCanvasPos(board.getPosition(GRID_SIZE-WIN_SIZE, GRID_SIZE-WIN_SIZE)), radius, color);\r\n}", "changeColorOfCellsToWhite(){\n for(let y = 0; y < this.height; y++){\n for (let x = 0; x < this.width; x++){\n document.getElementById(`${y}-${x}`).style.backgroundColor = 'white';\n const div = document.createElement('div');\n div.className = 'circle';\n div.className = `${y}-${x}`;\n document.getElementById(`${y}-${x}`).appendChild(div);\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this is the equation evaluator input equation string like ma and inputs like ["m", "G"] this is pretty slow. don't do it in a tight loop this function is recursive. it cuts up the equation and analyzes each part separately.
function evaluateExpression(equation, inputs) { //I'm pretty sure this removes all whitespace. equation = equation.replace(/\s/g, ""); //if equation is an input (like 't'), return the value for that input. if (equation in inputs) { return inputs[equation]; } //make each variable x like (x) so that 5(x) can work //to avoid infinite recursion, make sure each substring like (((x))) is turned into (x) for (var variable in inputs) { var prevLength = 0; while (prevLength!=equation.length) { //it looks like this will only go through the loop once, but actually the length of equation might change before the end of the loop prevLength = equation.length; equation = equation.replace("("+variable+")", variable);//first remove parenthesis from ((x)), if they exist } equation = equation.replace(variable, "("+variable+")");//then add parenthesis back } //if start with - or $ (my negative replacement), negate entire expression if (equation.indexOf("-")==0 || equation.indexOf("$")==0) { return -1*evaluateExpression(equation.slice(1), inputs); } for (var i=1; i<equation.length; i++) {//phantom multiplication (first char cannot have a phantom *) //5(3) should become 5*(3) //5cos(3) should become 5*cos(3) if (equation.charAt(i)=="(") { var insertionIndex = i; //size of unary operation for (var size=MAX_FUNCTION_LENGTH; size>=MIN_FUNCTION_LENGTH; size--) { if (i>=size) { var charsBefore = equation.slice(i-size,i); if (charsBefore in functions) { insertionIndex = i-size; break; } } } if (insertionIndex) { var prevChar = equation.charAt(insertionIndex-1); if (prevChar=="*" || prevChar=="+" || prevChar=="/" || prevChar=="-" || prevChar=="^" || prevChar=="(") { } else { equation=equation.slice(0,insertionIndex).concat("*",equation.slice(insertionIndex)); i++; } } } } //parenthesis //get rid of all parentheses while (equation.indexOf("(")>=0) { //use for (a*(m+a)) and (a+m)*(a+a). thus you can't just take the first '(' and last ')' and you can't take the first '(' and first ')' parentheses. You have to make sure the nested parentheses match up //start at the first '(' var startIndex = equation.indexOf("("); var endIndex = startIndex+1; var nestedParens = 0; //find end index //stop when outside of nested parentheses and the character is a ')' while (equation.charAt(endIndex)!=")" || nestedParens) { if (equation.charAt(endIndex)==")") { nestedParens--; } if (equation.charAt(endIndex)=="(") { nestedParens++; } endIndex++; } //find what's in the parentheses and also include the parenthesis. var inParens = equation.slice(startIndex+1, endIndex); var includingParens = equation.slice(startIndex, endIndex+1); var value = evaluateExpression(inParens, inputs); //size of unary operation //in range. Must enumerate backwards so acos(x) does not get interpreted as a(cos(x)) for (var size=4; size>=2; size--) { if (startIndex>=size) { var charsBefore = equation.slice(startIndex-size, startIndex); if (charsBefore in functions) { value = functions[charsBefore](value); includingParens=equation.slice(startIndex-size, endIndex+1); break; } } } if (includingParens==equation) {//like (5) or cos(3) return value; } else { //replace in equation. equation = equation.replace(includingParens, value); } } //done with parentheses //deal with negatives. replace with dollar sign //this is so 4/-7 doesn't get interpreted as (4/)-7, which could raise a divide by zero error equation = equation.replace("*-", "*$"); equation = equation.replace("--", "+");//minus negative is plus equation = equation.replace("+-", "-");//add negative is minus equation = equation.replace("/-", "/$"); equation = equation.replace("(-", "($"); //now the divide and conquer algorithm (or whatever this is) //check if equation contains any operations like "+", "-", "/", etc. if (equation.indexOf("+")>=0) { //start at zero and add from there var sum = 0; var toAdd = equation.split("+");//divide for (var operand in toAdd) { sum += evaluateExpression(toAdd[operand], inputs);//conquer } //everything has been taken care of. return sum; } if (equation.indexOf("-")>=0) { var diff = 0; var toSub = equation.split("-"); var first = true; //if looking at the first operand, it's positive. Subtract all others. //this is much easier in Haskell //first:toSum = first - (sum toSub) for (var op in toSub) { if (first) diff = evaluateExpression(toSub[op], inputs); else diff -= evaluateExpression(toSub[op], inputs); first=false; } return diff; } if (equation.indexOf("*")>=0) { var multiple = 1;//start with one (multiplicative identity) var toMultiply = equation.split("*"); for (var factor in toMultiply) { multiple *= evaluateExpression(toMultiply[factor], inputs); } return multiple; } if (equation.indexOf("/")>=0) { var quot = 0; var toDiv = equation.split("/"); var first = true; for (var op in toDiv) { if (first) quot = evaluateExpression(toDiv[op], inputs); else quot /= evaluateExpression(toDiv[op], inputs); first=false; } return quot; } if (equation.indexOf("^")>=0) { var exp = 0; var toPow = equation.split("^"); var first = true; for (var op in toPow) { if (first) exp = evaluateExpression(toPow[op], inputs); else exp = Math.pow(exp, evaluateExpression(toPow[op], inputs)); first=false; } return exp; } //no function. assume it's a number (base 10 of course) var value = parseFloat(equation, 10); if (equation.charAt(0)=="$") {//negative value = parseFloat(equation.slice(1), 10) * -1; } return value; }
[ "parseExpressionByOperator(expression, operator, index) {\n //startingIndex will be the index of where the expression slice will begin\n let startingIndex = index;\n //endingIndex will be the index of where expression slice ends.\n let endingIndex = index;\n const validOperators = ['-', '+', '/', '*']\n //if the next char is a -, we want to increment the ending index by 1 because we want to include the - as part of the number. \n if(expression[endingIndex + 1] === \"-\"){\n endingIndex += 1;\n }\n\n //increment endingIndex as long as the char at endingIndex + 1 is a number or equal to .\n while(!isNaN(expression[endingIndex + 1]) || expression[endingIndex + 1] === \".\"){\n endingIndex += 1;\n };\n //decrement startingIndex as long as the char at startingIndex - 1 is a number or equal to .\n while(!isNaN(expression[startingIndex - 1]) || expression[startingIndex - 1] === \".\"){\n startingIndex -= 1;\n };\n //will check if the startingIndex - 1 is a - and if startingIndex - 2 is a valid operator, or if the starting index is 1 because we also want to \n //include the - to denote the number as a negative.\n if(expression[startingIndex - 1] === \"-\" && (startingIndex === 1 || validOperators.includes(expression[startingIndex - 2]))){\n startingIndex -= 1;\n };\n //beginningExpression will be the string beginning expression up and not including the startingIndex\n let beginningExpression = expression.slice(0, startingIndex);\n //the expressionSlice will be the string starting at the startingIndex and including the endingIndex.\n let expressionSlice = expression.slice(startingIndex, endingIndex + 1);\n //the endingExpression string will be anything after the endingIndex + 1.\n let endingExpression = expression.slice(endingIndex + 1);\n\n //depending on what the operator is, we will send the expressionSlice to the respective function and make returned value equal to expressionSlice. 5*2 will return 10\n switch (operator) {\n case \"*\":\n expressionSlice = this.multiplicationCalculation(expressionSlice);\n break;\n case \"/\":\n expressionSlice = this.divisionCalculation(expressionSlice);\n break;\n case \"-\":\n expressionSlice = this.substractionCalculation(expressionSlice);\n break;\n case \"+\":\n expressionSlice = this.additionCalculation(expressionSlice);\n break;\n }\n //the function will return a new string with all the expressions concatenated.\n return beginningExpression.concat(expressionSlice, endingExpression);\n }", "function calculate(equation){\n return eval(equation);\n}", "function lce_read_expr(input)\n{\n\tif (typeof input != 'string')\n\t{\n\t\treturn undefined;\n\t}\n\n\tvar i,j;\n\tvar current = undefined;\n\tvar temp;\n\tvar stack = [];\n\tvar MODE_EXPR = 0; // main mode, determines all type for all other expressions\n\tvar MODE_VARLIST = 1; // handles the function abstraction type, which has a restricted character set(meta-meanings)\n\tvar mode = MODE_EXPR;\n\tvar varstart = 0;\n\t\n\tfor (i = 0; i < input.length; i++)\n\t{\n\t\tif (mode == MODE_EXPR)\n\t\t{\n\t\t//recursively handle any parenthesis\n\t\t\tif (input[i] == '(')\n\t\t\t{\n\t\t\t\tj = findCloseBalance(input, i);\n\t\t\t\tif (j == -1)\n\t\t\t\t{\n\t\t\t\t\talert(\"Error: imbalance of parenthesis.\");\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\ttemp = lce_read_expr(input.substr(i+1, j-i-1));\n\t\t\t\tif (current == undefined)\n\t\t\t\t{\n\t\t\t\t\tcurrent = temp;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcurrent = new lce_expr_app(current, temp);\n\t\t\t\t}\n\t\t\t\ti = j;\n\t\t\t\tvarstart = i + 1;\n\t\t\t}\n\t\t\t// detect the beginning of a functional abstraction\n\t\t\telse if (input[i] == '\\\\')\n\t\t\t{\n\t\t\t\tif (input.substr(i+1,6) == 'lambda')\n\t\t\t\t{\n\t\t\t\t\ti += 7;\n\t\t\t\t\tstack.push(new stack_pair(mode, current));\n\t\t\t\t\tmode = MODE_VARLIST;\n\t\t\t\t\tcurrent = new lce_expr_abs();\n\t\t\t\t\tvarstart = i;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// look for variable names and applications\n\t\t\telse if ((input[i].match(/\\s/) && strip_ws(input.substr(varstart,i+1-varstart)) != \"\")\n\t\t\t\t|| (i + 1 == input.length && strip_ws(input.substr(varstart,i+1-varstart)) != \"\"))\n\t\t\t{\n\t\t\t\tif (current == undefined)\n\t\t\t\t{\n\t\t\t\t\tcurrent = new lce_expr_var(input.substr(varstart,i+1-varstart));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcurrent = new lce_expr_app(current, new lce_expr_var(input.substr(varstart,i+1-varstart)));\n\t\t\t\t}\n\t\t\t\tvarstart = i;\n\t\t\t}\n\t\t}\n\t\telse if (mode == MODE_VARLIST)\n\t\t{\n\t\t\t//detect the end of the variable list\n\t\t\tif (input[i] == '.')\n\t\t\t{\n\t\t\t\tif (current.varlist.length == 0)\n\t\t\t\t{\n\t\t\t\t\talert(\"Error: lambda without any bound variables.\");\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\tstack.push(new stack_pair(mode, current));\n\t\t\t\tmode = MODE_EXPR;\n\t\t\t\tcurrent = undefined;\n\t\t\t\tvarstart = i + 1;\n\t\t\t}\n\t\t\t// detect illegal characters\n\t\t\telse if (input[i] == '\\\\' || input[i] == '(' || input[i] == ')')\n\t\t\t{\n\t\t\t\talert(\"Error: Illegal character, '\\\\', '(', ')' in variable list.\");\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\t// detect variable names and add to list\n\t\t\telse if ((input[i].match(/\\s/) && strip_ws(input.substr(varstart,i+1-varstart)) != \"\")\n\t\t\t\t|| ((i + 1 == input.length || input[i + 1] == '.') && strip_ws(input.substr(varstart,i+1-varstart)) != \"\"))\n\t\t\t{\n\t\t\t\tcurrent.addVar(input.substr(varstart,i+1-varstart));\n\t\t\t\tvarstart = i;\n\t\t\t}\n\t\t}\n\t}\n\n\t// unstack all stored partial results and combine into final result\n\twhile (stack.length > 0)\n\t{\n\t\tif (stack[stack.length - 1].mode == MODE_EXPR)\n\t\t{\n\t\t\tif (stack[stack.length - 1].expr != undefined)\n\t\t\t{\n\t\t\t\tif (current == undefined)\n\t\t\t\t{\n\t\t\t\t\tcurrent = stack[stack.length - 1].expr;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcurrent = new lce_expr_app(stack[stack.length - 1].expr, current);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (stack[stack.length - 1].mode == MODE_VARLIST)\n\t\t{\n\t\t\tif (current == undefined)\n\t\t\t{\n\t\t\t\talert(\"Error: abstraction without sub-expression.\");\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tstack[stack.length - 1].expr.subexpr = current;\n\t\t\tcurrent = stack[stack.length - 1].expr;\n\t\t}\n\t\tstack.pop();\n\t}\n\t\n\treturn current;\n}", "calculateBrackets() {\n //this section is to handle multiplication bracket notation. Example \"5(10)\" should equal 50\n let sliceIndex = this.calculation.search(/[0-9]\\(/) //find instances of digit followed by open bracket\n if (sliceIndex > -1) {\n this.calculation = this.calculation.slice(0, sliceIndex+1) + \"*\" + this.calculation.slice(sliceIndex + 1); // add a \"*\" between them so function picks it up\n this.calculateBrackets(); //restart function to check for multiple instances\n };\n\n let openBracket = this.calculation.lastIndexOf(\"(\"); //this will target innermost parentheses and solve the expression within, removing 1 layer from the equation\n let closeBracket = this.calculation.indexOf(\")\", openBracket);\n if (openBracket !== -1 && closeBracket !== -1) { // in this case, there are brackets that need sorting\n let expressionSlice = this.calculation.slice(openBracket+1, closeBracket); //slice that contains the expression \n\n let arrayExpression = [...this.calculation] //convert to array for splice purposes\n arrayExpression.splice(openBracket, closeBracket - openBracket + 1, this.calculateAddition(expressionSlice)); // replace expression including brackets with the result\n this.calculation = arrayExpression.join(\"\") // convert back to string\n this.calculateBrackets(); //repeat to check for more parentheses\n }\n }", "parseEquation() {\n let lhs = [this.parseTerm()];\n while (true) {\n const next = this.tok.peek();\n if (next == \"+\") {\n this.tok.consume(next);\n lhs.push(this.parseTerm());\n }\n else if (next == \"=\") {\n this.tok.consume(next);\n break;\n }\n else\n throw new ParseError(\"Plus or equal sign expected\", this.tok.pos);\n }\n let rhs = [this.parseTerm()];\n while (true) {\n const next = this.tok.peek();\n if (next === null)\n break;\n else if (next == \"+\") {\n this.tok.consume(next);\n rhs.push(this.parseTerm());\n }\n else\n throw new ParseError(\"Plus or end expected\", this.tok.pos);\n }\n return new Equation(lhs, rhs);\n }", "function calculate() {\n if (operator == 1) {\n currentInput = eval(memory) * eval(currentInput);\n }\n if (operator == 2) {\n currentInput = eval(memory) / eval(currentInput);\n }\n if (currentInput == memory / 0) {\n currentInput = \"ERROR! You can't divide by zero.\";\n }\n if (operator == 3) {\n currentInput = eval(memory) + eval(currentInput);\n }\n if (operator == 4) {\n currentInput = eval(memory) - eval(currentInput);\n }\n if (operator == 5) {\n currentInput = Math.pow(memory, currentInput);\n }\n if (operator == 6) {\n var num = currentInput;\n currentInput = memory * Math.pow(10, currentInput);\n if (num > 15) {\n currentInput = memory + \"e\" + num;\n }\n }\n\n operator = 0; // clear operator\n memory = \"0\"; // clear memory\n displayCurrentInput();\n}", "function MEXQ_InputQuestion(el_input){\n console.log(\"--- MEXQ_InputQuestion ---\")\n //console.log(\"el_input.id: \", el_input.id)\n // el_input.id = el_input.id: idMEXq_1_1\n //const q_number_str = (el_input.id) ? el_input.id[10] : null;\n const el_id_arr = el_input.id.split(\"_\")\n const partex_pk = (el_id_arr && el_id_arr[1]) ? Number(el_id_arr[1]) : null;\n const q_number = (el_id_arr && el_id_arr[2]) ? Number(el_id_arr[2]) : null;\n\n if (partex_pk && q_number){\n // open-question input has a number (8)\n // multiplechoice-question has one letter, may be followed by a number as score (D3)\n let new_max_char = \"\", new_max_score_str = \"\", new_max_score = \"\", msg_err = \"\";\n const input_value = el_input.value;\n\n console.log(\" input_value: \", input_value)\n // lookup assignment, create if it does not exist\n const p_dict = mod_MEX_dict.partex_dict[partex_pk];\n if (!(q_number in p_dict.a_dict)){\n p_dict.a_dict[q_number] = {};\n };\n const q_dict = p_dict.a_dict[q_number];\n\n// - split input_value in first charactes and the rest\n const first_char = input_value.charAt(0);\n const remainder = input_value.slice(1);\n\n console.log(\" first_char: \", first_char)\n console.log(\" remainder: \", remainder)\n// check if first character is a letter or a number => is multiple choice when a letter\n // !!Number(0) = false, therefore \"0\" must be filtered out with Number(first_char) !== 0\n const is_multiple_choice = (!Number(first_char) && Number(first_char) !== 0 );\n\n if(is_multiple_choice){\n new_max_char = (first_char) ? first_char.toUpperCase() : \"\";\n const remainder_int = (Number(remainder)) ? Number(remainder) : 0;\n new_max_score_str = (remainder_int > 1) ? remainder : \"\";\n } else {\n new_max_score_str = input_value;\n };\n\n console.log(\" is_multiple_choice: \", is_multiple_choice)\n console.log(\" >> new_max_score_str: \", new_max_score_str)\n// +++++ when input is question:\n if (!mod_MEX_dict.is_keys_mode){\n if (new_max_char){\n // Letter 'A' not allowed, only 1 choice doesn't make sense,\n // also X,Y,Z not allowed because 'x' value is used for blank\n if(!\"BCDEFGHIJKLMNOPQRSTUVW\".includes(new_max_char)){\n msg_err = loc.err_list.Character + \" '\" + first_char + \"'\" + loc.err_list.not_allowed +\n \"<br>\" + loc.err_list.character_mustbe_between;\n };\n };\n// - validate max_score\n if (new_max_score_str){\n new_max_score = Number(new_max_score_str);\n // the remainder / modulus operator (%) returns the remainder after (integer) division.\n if (!new_max_score || new_max_score % 1 !== 0 || new_max_score < 1 || new_max_score > 99) {\n if (msg_err) {msg_err += \"<br><br>\"}\n msg_err += loc.Maximum_score + \" '\" + new_max_score_str + \"'\" + loc.err_list.not_allowed +\n \"<br>\" + loc.err_list.maxscore_mustbe_between;\n };\n };\n\n// - show message when error, restore input in element\n if (msg_err) {\n const old_max_char = (q_dict.max_char) ? q_dict.max_char : \"\";\n const old_max_score = (q_dict.max_char) ?\n // '1' is default max_score when max_char, don't show a_dict\n (q_dict.max_score > 1) ? q_dict.max_score : \"\" :\n (q_dict.max_score) ? q_dict.max_score : \"\";\n const old_value = old_max_char + old_max_score;\n el_input.value = (old_value) ? old_value : null;\n\n el_mod_message_container.innerHTML = msg_err;\n $(\"#id_mod_message\").modal({backdrop: false});\n set_focus_on_el_with_timeout(el_mod_message_btn_cancel, 150 )\n } else {\n\n// - put new value in element\n const new_value = new_max_char + ( (new_max_score) ? new_max_score : \"\" );\n\n el_input.value = new_value;\n add_or_remove_class(el_input, \"border_invalid\", !el_input.value)\n\n// - put new value in mod_MEX_dict.p_dict.a_dict.q_dict\n q_dict.max_char = (new_max_char) ? new_max_char : \"\";\n q_dict.max_score = (new_max_score) ? new_max_score : 0;\n }\n\n MEXQ_calc_max_score(partex_pk);\n\n// +++++ when input is keys:\n // admin mode - keys - possible answers entered by requsr_role_admin\n } else {\n\n //console.log(\"q_dict: \", q_dict)\n\n const max_char_lc = (q_dict.max_char) ? q_dict.max_char.toLowerCase() : \"\";\n\n //console.log(\"max_char_lc\", max_char_lc)\n //console.log(\"is_multiple_choice\", is_multiple_choice)\n //console.log(\"mod_MEX_dict.partex_dict\", mod_MEX_dict.partex_dict)\n\n// answer only has value when multiple choice question. one or more letters, may be followed by a number as minimum score (ca3)\n if (!q_dict.max_char){\n el_mod_message_container.innerHTML = loc.err_list.This_isnota_multiplechoice_question;\n $(\"#id_mod_message\").modal({backdrop: false});\n set_focus_on_el_with_timeout(el_mod_message_btn_cancel, 150 )\n } else {\n\n if (input_value){\n let new_keys = \"\", min_score = null, pos = -1;\n for (let i = 0, len=input_value.length; i < len; i++) {\n const char = input_value[i];\n // !!Number(0) = false, therefore \"0\" must be filtered out with Number(first_char) !== 0\n const is_char = (!Number(char) && Number(char) !== 0 )\n if(!is_char){\n msg_err += loc.Key + \" '\" + char + \"'\" + loc.err_list.not_allowed + \"<br>\";\n } else {\n const char_lc = char.toLowerCase();\n //console.log(\"char_lc\", char_lc)\n //console.log(\"max_char_lc\", max_char_lc)\n // y, z are not allowed because 'x' value is used for blank\n if(!\"abcdefghijklmnopqrstuvwx\".includes(char_lc)){\n msg_err += loc.Key + \" '\" + char + \"'\" + loc.err_list.not_allowed + \"<br>\";\n } else if ( new_keys.includes(char_lc)) {\n msg_err += loc.Key + \" '\" + char + \"' \" + loc.err_list.exists_multiple_times + \"<br>\";\n } else if (char_lc > max_char_lc ) {\n msg_err += loc.Key + \" '\" + char + \"'\" + loc.err_list.not_allowed + \"<br>\";\n } else {\n new_keys += char_lc;\n }\n }\n } // for (let i = 0, len=input_value.length; i < len; i++) {\n// - show message when error, delete input in element and in mod_MEX_dict.keys_dict\n if (msg_err){\n msg_err += loc.err_list.key_mustbe_between_and_ + max_char_lc + \"'.\";\n el_input.value = null;\n q_dict.keys = \";\"\n\n el_mod_message_container.innerHTML = msg_err;\n $(\"#id_mod_message\").modal({backdrop: false});\n set_focus_on_el_with_timeout(el_mod_message_btn_cancel, 150 )\n\n } else {\n// - put new new_keys in element and in mod_MEX_dict.keys_dict\n el_input.value = (new_keys) ? new_keys : null;\n q_dict.keys = (new_keys) ? new_keys : \"\";\n }\n// - delete if input_value is empty\n } else {\n q_dict.keys = \"\";\n };\n }; // if (!is_multiple_choice)\n };\n MEXQ_calc_amount_maxscore()\n } ; // if (q_number)\n }", "function evaluate(expression) {\n var i = 1,\n temp = [];\n // Evaluate all the multiplication and division first.\n while (i < expression.length) {\n // The end of the context is reached.\n // Break out of the while loop.\n if (/\\)/.exec(expression[i])) {\n i = expression.length;\n continue;\n }\n // The first item of the triplet is an open parenthesis.\n // Open a new context.\n if (/\\(/.exec(expression[i - 1])) {\n expression.splice((i - 1), 1);\n // Create a new evaluation context.\n expression = evaluate(expression);\n }\n // Check for multiplication or division.\n if (/[\\*\\\\]/.exec(expression[i])) {\n // The last item of the triplet is an open parenthesis.\n if (/\\(/.exec(expression[i + 1])) {\n // Open a new context and evaluate it.\n temp = evaluate(expression.slice((i + 2)));\n // Slice the known expression up to the new context and concat it\n // with the evaluated new context array.\n expression = expression.slice(0, (i + 1)).concat(temp);\n }\n // We move through each triplet in the array and evaluate.\n expression.splice((i - 1), 3, operate(expression[i], expression[i - 1], expression[i + 1]));\n }\n // If the operator isn't multiplication or division, move to the next triplet.\n else {\n i += 2;\n }\n }\n // Evaluate the addition and subtraction.\n i = 1;\n while (i < expression.length) {\n // The end of the context is reached.\n // Break out of the while loop.\n if (/\\)/.exec(expression[i])) {\n expression.splice(i, 1);\n return expression;\n }\n // The first item of the triplet is an open parenthesis.\n // Open a new context.\n if (/\\(/.exec(expression[i - 1])) {\n expression.splice((i - 1), 1);\n // Create a new evaluation context.\n expression = evaluate(expression);\n }\n expression.splice((i - 1), 3, operate(expression[i], expression[i - 1], expression[i + 1]));\n }\n return expression;\n }", "function getOps(str){\r\n let operands=[];\r\n let str2=str.replace(/\\w+(?=\\s)/,\"\").replace(/\\s/g,\"\");\r\n operands=(/,/.test(str2))?str2.split(','):str2.split();\r\n if (operands[0]!=\"\"){\r\n let i=0;\r\n let opsnumber=operands.length;\r\n console.log(\"this a test \"+operands[0].toUpperCase);\r\n for(i; i<opsnumber;i++){\r\n if (/\\[.*\\]/.test(operands[i])) {operands.push('M')}\r\n else if (segmentRegisters.includes(operands[i].toUpperCase())){operands.push('RS')}\r\n else if (wordRegisters.includes(operands[i].toUpperCase())) { operands.push('RX')}\r\n else if (byteRegisters.includes(operands[i].toUpperCase())){operands.push('Rl')}\r\n else (operands.push('I'))\r\n }\r\n }\r\n return operands\r\n }", "function doMath(s) {\n s = s.split(\" \");\n\n for(i=0; i<s.length; i++) {\n var el = s[i];\n for(j=0; j<el.length; j++) {\n if(isNaN(el[j])) {\n s[i] = el[j] + String.fromCharCode(97 + i) + el.slice(0, j) + el.slice(j + 1);\n }\n }\n }\n\n s = s.sort().map(function(el){return parseInt(el.slice(2))});\n var result = s[0];\n s.shift();\n\n var operation = {\n \"0\": function addition(a,b) {\n return a+b;\n },\n \"1\": function subtraction(a,b) {\n return a-b;\n }, \n \"2\": function multiplication(a,b) {\n return a*b;\n }, \n \"3\": function division(a,b) {\n return a/b;\n }\n }\n\n while(s.length>0) {\n var n = Math.min(s.length, 4);\n for(i=0; i<n; i++) {\n result = operation[i](result, s[i]);\n }\n s = s.slice(n);\n }\n \n return Math.round(result);\n}", "function split(text, IACB) { //IACB see crawl function definition\n\t\tconst arr = protectNumbers(text, IACB)\n\t\t\t.split(/([\\^*/+\\-])/)\n\t\t\t.filter(o => o.length > 0)\n\t\t\t.map(o => unprotectNumbers(o));\n\n\t\t//text is now split into array of strings, iterate through it and parse them\n\t\tconst arr2 = [];\n\t\tarr.forEach(function(o) {\n\t\t\t//try if it's a number\n\t\t\tlet num = Number(o);\n\t\t\tif(!isNaN(num) && isFinite(num)) {arr2.push(num); return;}\n\n\t\t\t//if it's an operator, let it be\n\t\t\tif(o.match(/^[\\^*/+\\-]$/)) {arr2.push(o); return;}\n\n\t\t\t//else we'll assume it's a unit\n\t\t\telse {\n\t\t\t\t//identify number that is right before the unit (without space or *)\n\t\t\t\tlet firstNum = o.match(/^[+\\-]?[\\d\\.]+(?:e[+\\-]?\\d+)?/);\n\t\t\t\tif(firstNum) {\n\t\t\t\t\tfirstNum = firstNum[0];\n\t\t\t\t\to = o.slice(firstNum.length); //strip number from the unit\n\t\t\t\t\tnum = Number(firstNum);\n\t\t\t\t\tif(isNaN(num) || !isFinite(num)) {throw convert.msgDB['ERR_NaN'](firstNum);} //this could occur with extremely large numbers (1e309)\n\t\t\t\t\t//if you have number and unit tightly together, they should have the same power; we achieve that by wrapping them in brackets array\n\t\t\t\t\tarr2.push([Number(num), '*', parsePrefixUnitPower(o)]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t//identification of the unit itself and its power\n\t\t\t\tarr2.push(parsePrefixUnitPower(o));\n\t\t\t}\n\t\t});\n\t\treturn arr2;\n\t}", "function parseEquations(rawEquations){\n for(var i = 0; i < rawEquations.length; i++){\n let eq = rawEquations[i];\n let reacts = parseEquationComponents(eq[EQUATION_PROPERTY_REACTANTS]);\n let prods = parseEquationComponents(eq[EQUATION_PROPERTY_PRODUCTS]);\n makeEquation(eq[EQUATION_PROPERTY_ID], reacts, prods);\n }\n}", "function evalNextParenthesizedExpression(expr){\n //find first and last index of subexpression\n let subexprStart = expr.indexOf(expr.find(element => (/^-?\\($/).test(element)));\n let subexprEnd;\n let bracketCount = 1;\n for (let index = subexprStart+1; index < expr.length; index++) {\n if ((/\\(/).test(expr[index])){\n bracketCount++;\n } else if(expr[index]===')') {\n bracketCount--;\n if (bracketCount===0) {\n subexprEnd = index;\n break;\n }\n } \n }\n\n //split array in it's parts with evaluated subexpr;\n const negative = expr[subexprStart][0] === '-';\n const subexpr = expr.slice(subexprStart+1, subexprEnd) \n const returnValue = [...expr.slice(0, subexprStart), \n (negative)?(operate('*', -1, evaluateInput(subexpr))):evaluateInput(subexpr), \n ...expr.slice(subexprEnd+1) ];\n return returnValue;\n \n}", "function checkDecimal(key, equation) {\n let sliced = \"\"; \n\n if (equation.includes(\" \")) { // if there is an operator, checks for\n for (i = equation.length - 1; i >= 0; i--) { // decimal from last operator to\n if (equation[i] == \" \") { // end of string and then extracts\n sliced = equation.slice(i); // that portion\n break; \n }\n }\n if (sliced.includes(\".\")) { // returns if decimal is in sliced portion\n return;\n }\n } else if (equation.includes(\".\")) { // only triggers if equation did not have an operator\n return; \n }\n\n // checks for recent calc and clears old result instead of adding decimal to end of it\n if (equalsPressed == true) { \n document.getElementById(\"displayText\").innerHTML = \"0\" + key; \n equalsPressed = false; \n } else {\n if (equation[equation.length -1] == \" \") { // if decimal after operator, also adds 0\n document.getElementById(\"displayText\").innerHTML = equation + \"0\" + key;\n } else {\n document.getElementById(\"displayText\").innerHTML = equation + key; \n }\n }\n}", "function chkFormula(obj,measName){\r\n\t\r\n\t//1. Hallamos la medida 1, el operarador y la medida2 (o number)\r\n\tvar formula = obj.value;\r\n\tif (formula == \"\"){\r\n\t\talert(MSG_MUST_ENTER_FORMULA);\r\n\t\treturn false;\r\n\t}\r\n\tvar esp1 = formula.indexOf(\" \");\r\n\tvar formula2 = formula.substring(esp1+1, formula.length);\r\n\tvar meas1 = formula.substring(0,esp1);\r\n\tvar op = formula2.substring(0,1);\r\n\tvar meas2 = formula2.substring(2, formula2.length);\r\n\t\r\n\t//2. Verificamos la medida1 exista\r\n\tif (!chkMeasExist(meas1)){\r\n\t\tif (esp1 < 0){\r\n\t\t\talert(formula + \": \" + MSG_MEAS_OP1_NAME_INVALID);\r\n\t\t}else {\r\n\t\t\talert(meas1 + \": \" + MSG_MEAS_OP1_NAME_INVALID);\r\n\t\t}\r\n\t\tobj.focus();\t\t\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\t//3. Verificamos el operador sea valido\r\n\tif (op != '/' && op != '-' && op != '+' && op != '*'){\r\n\t\talert(op + \": \" + MSG_OP_INVALID);\r\n\t\tobj.focus();\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\t//4. Verificamos la medida2 exista\r\n\tif (!chkMeasExist(meas2)){//Si no existe como medida talvez sea un numero\r\n\t\tif (isNaN(meas2)){\r\n\t\t\talert(meas2 + \": \" + MSG_MEAS_OP2_NAME_INVALID);\r\n\t\t\tobj.focus();\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\t\r\n\t//5. Verificamos no se utilice el nombre de la propia medida como un operando de la formula.\r\n\tif (measName == meas1 || measName == meas2){\r\n\t\talert(measName + \": \" + MSG_MEAS_NAME_LOOP_INVALID);\r\n\t\tobj.focus();\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\treturn true;\r\n}", "function evaluator() {\n state.seg = segments['intro']; // starting from intro\n var block_ix = 0;\n\n // use global state to synchronize\n var handlers = {\n text : function(text) {\n var $text = $('<p></p>').appendTo($main);\n var timeoutid;\n var line_ix = 0;\n var char_ix = 0;\n state.status = 'printing';\n $triangle.hide();\n var text_printer = function() {\n var line = text.lines[line_ix];\n if (!line) {\n clearTimeout(timeoutid);\n $text.append('<br/>');\n // peek if next block is a branch block\n var next = get_next();\n if (next && next.type == 'branches') {\n next_block()\n } else {\n state.status = 'idle';\n $triangle.show();\n }\n return;\n }\n var interval = state.print_interval;\n if (char_ix < line.length) {\n var c = line[char_ix++];\n if (c == ' ') {\n c = '&nbsp;';\n }\n $text.append(c);\n } else {\n $text.append('<br/>');\n line_ix += 1;\n char_ix = 0;\n interval *= 6; // stop a little bit longer on new line\n }\n timeoutid = setTimeout(text_printer, interval);\n }\n timeoutid = setTimeout(text_printer, state.print_interval);\n },\n branches : function(branches) {\n var $ul = $('<ul class=\"branches\"></ul>').appendTo($main);\n state.status = 'branching'\n settings.cheated = false;\n var blur_cb = function(e) {\n settings.cheated = true;\n };\n $(window).on('blur', blur_cb);\n\n\n $.each(branches.cases, function(ix, branch){\n if (branch.pred == '?' || eval(branch.pred)) {\n var span = $('<span></span>').text(branch.text).data('branch_index', ix);\n $('<li></li>').append(span).appendTo($ul);\n }\n });\n $('li span', $ul).one('click', function(e){\n state.choice = parseInt( $(this).data('branch_index') );\n $(window).off('blur', blur_cb);\n clean_main();\n next_block();\n return false;\n });\n },\n code : function(code) {\n var control = new function() {\n var self = this;\n this.to_label = function(label) {\n self.next_label = label;\n };\n this.jump_to = function(segname) {\n self.next_seg = segname;\n }\n // extra functions\n this.clean_main = clean_main;\n this.reset = function() {\n settings = {}; // need to clean up the settings.\n constants.usual_print = 20; // on following playthrough, have faster printing\n self.jump_to('intro');\n };\n };\n eval(code.code);\n // handle the outcome\n if (control.next_seg) {\n state.seg = segments[control.next_seg];\n if (!state.seg) throw \"invalid segment jump:\" + control.next_seg;\n // jumping into label in another segment\n if (control.next_label) {\n var next = state.seg.labels[control.next_label]\n if (!next)\n throw \"invalid seg+label jump:\" + control.next_seg + \":\" + control.next_label;\n next_block(next);\n } else {\n next_block(state.seg[0]);\n }\n return;\n } else if (control.next_label) {\n var next = state.seg.labels[control.next_label];\n if (!next) throw \"invalid lable jump:\" + control.next_label;\n next_block(next);\n } else {\n next_block();\n }\n },\n label : function(label) {\n if (label.jump) {\n var next = state.seg.labels[label.name];\n if (!next) throw \"invalid jump label:\" + label.name;\n next_block(next);\n } else {\n next_block();\n }\n }\n\n };\n\n function clean_main() {\n $main.empty();\n }\n\n function handle_block() {\n console.log(\"doing block:\")\n console.log(state.block);\n handlers[state.block.type](state.block);\n }\n\n function get_next() {\n var block_in_seg = state.seg.indexOf(state.block);\n return state.seg[block_in_seg+1];\n }\n\n function next_block(block) {\n state.block = block || get_next();\n\n // necessary resets\n state.print_interval = constants.usual_print;\n handle_block();\n }\n\n function global_click_callback(e) {\n if (state.status == 'idle') {\n next_block();\n } else if (state.status == 'printing') {\n state.print_interval /= 5;\n }\n return false;\n }\n $(document).on('click', global_click_callback);\n\n // kick off\n state.block = state.seg[0];\n\n // !!!!!!!!!! DEBUG JUMP\n // state.seg = segments['puzzle'];\n // state.block = state.seg.labels['q1'];\n\n handle_block();\n}", "function parseExpression() {\n let expr;\n //lookahead = lex();\n // if (!lookahead) { //significa que es white o undefined\n // lookahead = lex();\n // }\n if (lookahead.type == \"REGEXP\") {\n expr = new Regexp({type: \"regex\", regex: lookahead.value, flags: null});\n lookahead = lex();\n return expr;\n } else if (lookahead.type == \"STRING\") {\n expr = new Value({type: \"value\", value: lookahead.value});\n lookahead = lex();\n if (lookahead.type === 'LC' || lookahead.type === 'DOT') return parseMethodApply(expr);\n return expr;\n } else if (lookahead.type == \"NUMBER\") {\n expr = new Value({type: \"value\", value: lookahead.value});\n lookahead = lex();\n if (lookahead.type === 'LC' || lookahead.type === 'DOT') return parseMethodApply(expr);\n return expr;\n } else if (lookahead.type == \"WORD\") {\n const lookAheadValue = lookahead;\n lookahead = lex();\n if (lookahead.type == 'COMMA' && lookahead.value == ':') {\n expr = new Value({type: \"value\", value: '\"' + lookAheadValue.value + '\"'});\n return expr;\n }\n if (lookahead.type == 'DOT') {\n expr = new Word({type: \"word\", name: lookAheadValue.value});\n return parseApply(expr);\n }\n expr = new Word({type: \"word\", name: lookAheadValue.value});\n return parseApply(expr);\n } else if (lookahead.type == \"ERROR\") {\n throw new SyntaxError(`Unexpected syntax line ${lineno}, col ${col}: ${lookahead.value}`);\n } else {\n throw new SyntaxError(`Unexpected syntax line ${lineno}, col ${col}: ${program.slice(offset, offset + 10)}`);\n }\n}", "getEquationArray(amt1, eqstring='= ') {\n const line1 = this.getAmt1StringUnits(amt1);\n const line2 = eqstring + this.getAmt2StringUnits(amt1);\n return [line1, line2];\n }", "function calculateFactor(tokenQueue, trigMode) {\n console.log(tokenQueue);\n /* Functions names that may appear in the factor. */\n var funcNames = [\"inv\",\"fact\", \"sin\", \"cos\", \"tan\", \"sqrt\"];\n var value;\n var token = tokenQueue.shift();\n\n /* Case expression wrapped in parenthesis */\n if (token == \"(\") {\n value = calculateExpressionRecursive(tokenQueue, trigMode);\n // If a string is returned then it is an error message, return the message.\n if(typeof value == \"string\"){\n return value;\n }\n if (tokenQueue.shift() != \")\") { /* It true, mismatched parenthesis */\n value = \"ERR: SYNTAX\";\n }\n /* Case function call */\n } else if (funcNames.includes(token)) {\n if (tokenQueue.shift() == \"(\") {\n var funcString = token;\n var funcParam = calculateExpressionRecursive(tokenQueue, trigMode);\n value = evaluateFunction(funcString, funcParam, trigMode);\n // If a string is returned then it is an error message, return the message.\n if(typeof funcParam == \"string\"){\n return funcParam;\n }\n if (tokenQueue.shift() != \")\") {\n value = \"ERR: SYNTAX\";\n }\n } else {\n value = \"ERR: SYNTAX\";\n }\n\n /* Case two expressions wrapped in a power function*/\n } else if (token == \"pow\") {\n if (tokenQueue.shift() == \"(\") {\n /* Evaluate first and second expression in pow */\n var expr1val = calculateExpressionRecursive(tokenQueue, trigMode);\n // If a string is returned then it is an error message, return the message.\n if(typeof expr1val == \"string\"){\n return expr1val;\n }\n if (tokenQueue.shift() == \",\") {\n var expr2val = calculateExpressionRecursive(tokenQueue, trigMode);\n // If a string is returned then it is an error message, return the message.\n if(typeof expr2val == \"string\"){\n return expr2val;\n }\n value = Math.pow(expr1val, expr2val);\n if (tokenQueue.shift() != \")\") {\n value = \"ERR: SYNTAX\";\n }\n } else { /* If no comma, then input here is wrong */\n value = \"ERR: SYNTAX\";\n }\n } else { /* missing parenthesis */\n value = \"ERR: SYNTAX\";\n }\n\n /* Case number */\n } else if (!isNaN(token)) {\n value = parseFloat(token);\n } else {\n value = \"ERR: SYNTAX\"\n }\n return value;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
createGamePage() : Game page creating function Creates the game page based on level returns a element with game header, left panel and right panel
function createGamePage(){ //The main container for the game var levelDiv = createDiv(); levelDiv.classList.add('mainContainer'); //Adding the game header with home, back, learn and speaker icon levelDiv.appendChild(createGameLevelHeader(level)); //Making sure the body is fit to fixed height toggleFixedHeight(true); //Create left and right panels of the game var leftElement = createLeftPanel(level); var rightElement = createRightPanel(level); if(rightElement ==undefined) { return undefined; } //Based on portrait and landscape mode append the panels so that in //portrait the question elements followed by keyboard is shown if(window.innerWidth > window.innerHeight) { levelDiv.appendChild(leftElement); levelDiv.appendChild(rightElement); } else { levelDiv.appendChild(rightElement); levelDiv.appendChild(leftElement); } //Returns the game page with game header, left and right panels return levelDiv; }
[ "function createGamePage() {\n var gamePage = document.createElement('main');\n gamePage.classList.add('game-board');\n gamePage.innerHTML = getGamePageStructure();\n body.appendChild(gamePage);\n showRecentGames(deck.player.name, '.win-game-list-one');\n}", "function loadGamePage(lvl) {\n\n //Update the level number in global variable\n level = lvl;\n\n //The level is going to start now so initialise the correct items to zero\n itemCorrect = 0;\n\n //Create the game content\n var gameContent = createGamePage();\n\n //If game content is not created the display level not ready message\n if(gameContent === undefined) {\n updateTeddyDialogueMessage(teddyDialogues.gameLevelNotExists);\n level = 0;\n return;\n } else {\n //Clear the page\n document.body.innerHTML = \"\";\n //Append the game page to the main page\n document.body.appendChild(gameContent);\n }\n}", "function createGamePageTemplate(results) {\r\n let gamePageContainer = createDomElement('div', 'game-page-container');\r\n gamePageContainer.append(getQnaContent(results));\r\n document.body.append(gamePageContainer);\r\n}", "function createHighScorePageTemplate() {\r\n let highScorePageContainer = createDomElement('div', 'high-score-page-container');\r\n\r\n let highScoreContainer = createDomElement('div', 'highscore-container');\r\n\r\n let highScoreTitle = createDomElement('div', 'highscore-title');\r\n highScoreTitle.innerHTML = 'Highscore';\r\n\r\n let homePageBtn = createDomElement('div', 'go-home-btn-container');\r\n homePageBtn.innerHTML = 'Go Home';\r\n homePageBtn.setAttribute('onclick', 'clearPageAndDisplayHomePage(\"high-score-page-container\")');\r\n\r\n highScoreContainer.append(highScoreTitle, getHighScoreForUsers(), homePageBtn);\r\n\r\n highScorePageContainer.append(highScoreContainer);\r\n document.body.append(highScorePageContainer);\r\n}", "function GamesPage() {\n utils.Controller.call(this);\n this.el.prop('id', 'games_page');\n\n this.header = new Header('small');\n this.header.append_to(this);\n this.game_list = new GameList('tiles');\n this.game_list.append_to(this);\n\n this.layout = new GamesPageLayout();\n this.layout.header = this.header;\n this.layout.game_list = this.game_list;\n this.layout.update();\n }", "function createHomePageTemplate() {\r\n let homePageContainer = createDomElement('div', 'home-page-container');\r\n let homePageContent = createDomElement('div', 'home-page-content');\r\n\r\n let homePageTitleContainer = createDomElement('div', 'home-page-title-container');\r\n homePageTitleContainer.innerHTML = 'Trivia game';\r\n\r\n let homePagePlayBtn = getPlayButton();\r\n homePagePlayBtn.setAttribute('onclick', 'clearPageAndStartGame(\"home-page-container\")');\r\n\r\n let homePageHighScoreBtn = createDomElement('div', 'home-page-highscore-btn', 'HighScore', 'highscore-btn');\r\n homePageHighScoreBtn.innerHTML = 'HighScore';\r\n homePageHighScoreBtn.setAttribute('onclick', 'clearPageAndShowHighScore(\"home-page-container\")');\r\n\r\n homePageContent.append(homePageTitleContainer, homePagePlayBtn, homePageHighScoreBtn);\r\n homePageContainer.append(homePageContent);\r\n document.body.append(homePageContainer);\r\n}", "function loadLevelSelectionPage(){\n //Clearing the content on the page\n document.body.innerHTML = \"\";\n\n //Adding the level selction page statuc content\n document.body.appendChild(createLevelSelectionPage());\n\n //Making score to zero in back flow to level selection page\n score=0;\n\n //Resetting the timer\n resetTimer();\n}", "function createWelcomePage(name) {\n var parent = document.querySelector('.content');\n var newSection = document.createElement('section');\n newSection.classList.add('game-explanation');\n newSection.innerHTML = getWelcomePageStructure(name);\n parent.appendChild(newSection);\n}", "function definePageElements(){\n playerContainer = document.getElementsByClassName(\"hero\")[0];\n var temp = playerContainer.getElementsByTagName(\"span\");\n for(var i = 0; i < temp.length; i++){\n switch(temp[i].className){\n case \"health\":\n playerHpDisplay = temp[i];\n break;\n case \"mana\":\n playerManaDisplay = temp[i];\n break;\n default:\n console.log(\"Unidentified player span \" + temp[i].name);\n }\n }\n actions = [];\n actionLogDisplay = document.getElementById(\"action-log\");\n starter = document.getElementsByClassName(\"starter\")[0];\n temp = document.getElementById(\"fight-button\");\n gameContainer = document.getElementById(\"game-container\");\n addEvent(temp,'click',startGame,false);\n dragonCanvas = document.getElementById(\"dragon-info\");\n dragonCanvasContext = dragonCanvas.getContext('2d');\n temp = null;\n}", "function createElements() {\n var page = document.getElementById('page-content-wrapper');\n\n var img = document.createElement('img');\n img.setAttribute(\"class\", \"picture\");\n img.setAttribute(\"src\", \"../img/profile/\" + current.pic);\n\n var name = document.createElement('h2');\n name.setAttribute(\"class\", \"user-name\");\n name.innerHTML = current.name;\n\n var username = document.createElement('h3');\n username.setAttribute(\"class\", \"username-tag\");\n username.innerHTML = current.username;\n\n\n //Appends the element to the parent element\n current.win.appendChild(name);\n current.win.appendChild(username);\n current.win.appendChild(img);\n page.appendChild(current.win);\n }", "function create_scoreboard( player )\n{\n\tvar section = document.createElement('div');\n\tvar name_section = document.createElement('div');\n\tvar first_section = document.createElement('div');\n\tvar second_section = document.createElement('div');\n\tvar third_section = document.createElement('div');\n\n\t$(section).addClass('scoreboard');\n\t$(name_section).addClass('inner_scoreboard');\n\t$(first_section).addClass('inner_scoreboard');\n\t$(second_section).addClass('inner_scoreboard');\n\t$(third_section).addClass('inner_scoreboard');\n\n\tname_section.textContent = player.name;\n\tfirst_section.textContent = '';\n\tsecond_section.textContent = '';\n\tthird_section.textContent = '';\n\n\tplayer.section = section;\n\tplayer.nameSection = name_section;\n\tplayer.firstSection = first_section;\n\tplayer.secondSection = second_section;\n\tplayer.thirdSection = third_section;\n\n\t$(section).append(name_section);\n\t$(section).append(first_section);\n\t$(section).append(second_section);\n\t$(section).append(third_section);\n\n\t$('.game').append(section);\n\thighlightPlayer(players.players[0]);\n\tdimPlayer(players.players[1]);\n\t\n}", "function LevelCreator(){\n var universe = new Universe();\n \n universe.nav = new LevelCreatorNav();\n \n universe.init = function (world, graphics) {\n this.nav.init(world, graphics);\n graphics.addTask(new LevelGraphics(world));\n graphics.disableDebug();\n \n world.getCamera().setFocusObj(this.wizard);\n world.getCamera().setScaleBounds(1.0, 2.0);\n world.getCamera().setTileSize(this.tileSize);\n \n this.wizard.init(world);\n \n for (var i = 0; i < this.data.length; i++) {\n for (var j = 0; j < this.data[i].unit.length; j++) {\n var ud = this.data[i].unit[j];\n this.addUnit(ud.type - 1, \n (i * this.tileSize * this.sliceSize) + (ud.x * this.tileSize), \n ud.y);\n }\n }\n };\n \n universe.wizard = {\n x: 0,\n y: 0,\n pos : {x: 0, y:0},\n speed: 2,\n init: function (world) {\n this.x = world.getCamera().canvasWidth / 2;\n this.y = world.getCamera().canvasHeight / 2;\n },\n update: function (world) {\n var ctrl = world.getController();\n if (ctrl.a) this.x -= this.speed;\n if (ctrl.d) this.x += this.speed;\n if (ctrl.w) this.y -= this.speed;\n if (ctrl.s) this.y += this.speed;\n \n var mouse = ctrl.current;\n if (mouse !== null) {\n var cam = world.getCamera();\n this.pos.x = Math.trunc((mouse.offsetX / 2 + cam.x) / world.getUniverse().tileSize);\n this.pos.y = Math.trunc((mouse.offsetY / 2 + cam.y) / world.getUniverse().tileSize);\n }\n \n if (ctrl.isDown) {\n world.getUniverse().setBlock(this.pos.x, this.pos.y, \n universe.nav.blockBrush());\n }\n }\n };\n \n /**\n * The main game loop. Called dt/1000 times a second.\n * @param {Universe} world The entire universe\n */\n universe.update = function(world){\n this.wizard.update(world);\n };\n \n return universe;\n}", "function startGame() {\n removeWelcomePage();\n createGamePage();\n createCards();\n}", "createLayout(){\n const container = createComponent('div', {class: 'container'})\n const pageContent = createComponent('div', {id: 'pageContent', class: 'my-5'})\n const welcomeImage = createComponent('img', {src: \"./images/home.png\", style: \"max-width: 100%\"})\n pageContent.append(welcomeImage)\n nav()\n container.append(pageContent)\n document.getElementById('app').append(container)\n }", "function drawPage() {\n\t\n\tif ( !(ERROR_FOUND) ) {\n\t\t// first, draw a menu if there is one\n\t\tif ( CURRENT_PAGE.menu != null ) {\n\t\t \tdrawMenu();\n\t\t}\n\n\t\tdocument.getElementById(\"page_contents\").innerHTML = CURRENT_PAGE.html;\n\t}\n\n}", "function AddGamePanel( appid )\n{\n\t// Check to see if the panel exists or not\n\tvar oPanel = $( '#game_' + appid );\n\n\tif( oPanel ) // Panel exists... maybe make sure it's visible?\n\t{\n\t\treturn true;\n\t}\n\n\t// Else create..\n\tvar app = GetAppInfo( appid );\n\tif( !app )\n\t\treturn false;\n\n\tvar oParent = $('#GamesContainer');\n\tvar oButton = $.CreatePanel('Button', oParent, 'game_' + app.appid );\n\toButton.AddClass('GameRow');\n\toButton.AddClass('StatsRow');\n\n\t// Logo image\n\tvar oImage = $.CreatePanel('Image', oButton, '' );\n\toImage.SetAttributeString( 'logo', app.logo );\n\toImage.AddClass('LogoImage');\n\n\t$.RegisterEventHandler('ReadyPanelForDisplay', oButton, onReadyForDisplay );\n\t$.RegisterEventHandler('PanelDoneWithDisplay', oButton, onDoneWithDisplay );\n\n\t// Title wrapper panel\n\tvar oWrapperPanel = $.CreatePanel('Panel', oButton, '' );\n\toWrapperPanel.AddClass('TextCol');\n\n\t// Title\n\tvar oLabel = $.CreatePanel('Label', oWrapperPanel, '' );\n\toLabel.text = app.name;\n\toLabel.AddClass('Title');\n\n\t// Playtime\n\tvar oPlaytime = $.CreatePanel('Label', oWrapperPanel, '' );\n\tvar strHrs = '';\n\n\tif( app.hours_forever )\n\t\tstrHrs += app.hours_forever + \" hrs on record\";\n\n\tif( app.hours )\n\t{\n\t\tif( strHrs.length > 0 )\n\t\t\tstrHrs += ' / ';\n\t\tstrHrs += app.hours + \" last two weeks\";\n\t}\n\n\toPlaytime.text = strHrs;\n\toPlaytime.AddClass('Playtime');\n\n\tvar fnContextMenu = CreateContextMenu( app, g_rgBucket );\n\n\n\t//$.RegisterKeyBind( oButton, 'steampad_a', fnContextMenu );\n\t$.RegisterEventHandler('Activated', oButton, fnContextMenu );\n\n\n}", "function createLockLevelPopUp(){\n\t\t\t\t\t\t\tvar levelChoose=new lib.levelChooseBoard();\n\t\t\t\t\t\t\tlevelChoose.x=myStage/2-levelChoose.nominalBounds.width/2;\n\t\t\t\t\t\t\tlevelChoose.y=myStage/2-levelChoose.nominalBounds.height/2;\n\t\t\t\t\t\t\tstage.addChild(levelChoose);\n\t\t\t\t\t\t}", "function main(){\n \n stage.removeAllChildren();\n scenes.push(page1Create());\n scenes.push(page2Create());\n scenes.push(page3Create());\n scenes.push(page4Create());\n sindex = 0;\n stage.addChild(scenes[sindex]); \n}", "function loadRoomSelectionPage() {\n //Clear the current content\n document.body.innerHTML = \"\";\n\n //Append the static content of room selection page\n document.body.appendChild(createRoomSelectionPage());\n\n //Reset the timer in case the flow comes from game pages\n resetTimer();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an existing MountTarget resource's state with the given name, ID, and optional extra properties used to qualify the lookup.
static get(name, id, state, opts) { return new MountTarget(name, state, Object.assign(Object.assign({}, opts), { id: id })); }
[ "function MountTarget(props) {\n return __assign({ Type: 'AWS::EFS::MountTarget' }, props);\n }", "static get(name, id, state, opts) {\n return new Key(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "static get(name, id, state, opts) {\n return new ServiceLinkedRole(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "static get(name, id, state, opts) {\n return new Resolver(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "static get(name, id, state, opts) {\n return new Snapshot(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "static get(name, id, state, opts) {\n return new Record(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "static get(name, id, state, opts) {\n return new Host(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "function startResourceGet(id) {\n return { type: START_RESOURCE_GET,\n id: id};\n}", "static get(name, id, state, opts) {\n return new ContainerPolicy(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "static get(name, id, state, opts) {\n return new JavaAppLayer(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "getById(id) {\n return tag.configure(FieldLink(this).concat(`(guid'${id}')`), \"fls.getById\");\n }", "_findResource(id) {\n return this.template.resources.find(res => {\n // Simple match on substring is possible after \n // fully resolving names & types\n return res.fqn.toLowerCase().includes(id.toLowerCase());\n });\n }", "function getResource() {\n r = $resource(OpenmrsSettings.getContext() + \"/ws/rest/v1/location/:uuid\",\n {uuid: '@uuid'},\n {query: {method: \"GET\", isArray: false}}\n );\n return new dataMgr.ExtendedResource(r,true,resourceName,false,\"uuid\",null);\n }", "static get(name, id, opts) {\n return new DisasterRecoveryConfig(name, undefined, Object.assign(Object.assign({}, opts), { id: id }));\n }", "static get(name, id, state) {\n return new Domain(name, state, { id });\n }", "static get(name, id, state, opts) {\n return new EipAssociation(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "static get(name, id, state, opts) {\n return new KeySigningKey(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "function ResourceKey(id, name) {\n this.id = id;\n this.name = name;\n }", "static get(name, id, state, opts) {\n return new ReplicationInstance(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a pushToken function for a given type
function pushToken(type) { return function (v) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var startColumn = opts.startColumn || column - String(v).length; delete opts.startColumn; var endColumn = opts.endColumn || startColumn + String(v).length - 1; delete opts.endColumn; var start = { line: line, column: startColumn }; var end = { line: line, column: endColumn }; tokens.push(Token(type, v, start, end, opts)); }; }
[ "function createFieldToken(field, id, type){\n \n // Get field value and token container\n \n let value = $(field).val();\n let container = $(field).siblings('.token-container');\n let tokenNo = $(container).find('.token').length + 1;\n \n // If token container doesn't exist, create it\n \n if(container.length == 0){\n \n // Create token container\n \n container = $('<div></div>');\n $(container).addClass('token-container');\n \n // Add token container after field\n \n $(field).after(container);\n \n }\n \n if(id == '' || $(container).find('input[value=\"' + id + '\"]').length == 0){\n \n // Create token\n \n let token = $('<span></span>');\n $(token).addClass('token');\n \n // Add HTML\n \n let html = value + '<button type=\"button\" class=\"exit\"></button>';\n html += '<input type=\"hidden\" name=\"token' + tokenNo + '-id\" value=\"' + id + '\">';\n html += '<input type=\"hidden\" name=\"token' + tokenNo + '-type\" value=\"' + type + '\">';\n $(token).html(html);\n \n // Add token to end of token container\n \n $(container).append(token);\n \n // Set event handlers\n \n setTokenHandlers(token);\n \n }\n \n // Clear field value and focus on field\n \n $(field).val('');\n $(field).focus();\n $(field).siblings('.autocomplete-list').hide();\n \n}", "function pushlex(type, info) {\n var result = function(){\n lexical = new CSharpLexical(indented, column, type, null, lexical, info)\n };\n result.lex = true;\n return result;\n }", "function createAction(type) {\n function actionCreator(payload) {\n return {\n type: type,\n payload: payload\n };\n }\n\n actionCreator.toString = function () {\n return \"\".concat(type);\n };\n\n actionCreator.type = type;\n return actionCreator;\n}", "function registerCallback(type, func) {\n if( callbacks.hasOwnProperty(type) == false ) {\n callbacks[type] = [];\n }\n callbacks[type].push(func);\n }", "function createToken(payload){\r\n return jwt.sign(payload, SECRET_KEY, {expiresIn})\r\n}", "function createToken(){\n\t\t\treturn crypto.randomBytes(16).toString(\"hex\");\n\t\t}", "function createToken(user) {\n var token = jsonwebtoken.sign({\n firstname: user.firstname,\n lastname: user.lastname,\n username: user.username,\n usertype: user.usertype,\n email: user.email\n }, secretKey);\n return token;\n}", "pushToken(token) {\n this.stack.push(token);\n }", "function createCustomerType(axios$$1, customerType) {\n return restAuthPost(axios$$1, 'customertypes/', customerType);\n }", "static registerType(type) { ShareDB.types.register(type); }", "static async newCompanyToken(req, created_company) {\n\t\t// push new company inside request.companies\n\t\treq.companies.push({ id: created_company.id })\n\t\t// new object for token\n\t\tlet newToken = {\n\t\t\tuser: req.user,\n\t\t\tcompanies: req.companies\n\t\t}\n\t\t// sign and return new token\n\t\treturn jwt.sign(newToken, process.env.JWT_SECRET)\n\t}", "function createFieldToken(field){\n \n createFieldToken(field, '', '');\n \n}", "defaultToken(){}", "register (name: string, callback: Callback, type: CallbackKind = 'didSave') {\n if (typeof callback !== 'function') {\n throw new Error('callback must be a function')\n }\n if (type !== 'didSave' && type !== 'willSave') {\n throw new Error('type must be a willSave or didSave')\n }\n if (type === 'willSave') {\n const cb: WillSaveCallback = ((callback: any): WillSaveCallback)\n this.willSaveCallbacks.add(cb)\n return new Disposable(() => {\n if (this.willSaveCallbacks) {\n this.willSaveCallbacks.delete(cb)\n }\n })\n }\n\n const cb: DidSaveCallback = ((callback: any): DidSaveCallback)\n this.didSaveCallbacks.set(name, cb)\n return new Disposable(() => {\n if (this.didSaveCallbacks) {\n this.didSaveCallbacks.delete(name)\n }\n })\n }", "function factory (type, config, load, typed) {\n // create a new data type\n function MyType (value) {\n this.value = value\n }\n MyType.prototype.isMyType = true\n MyType.prototype.toString = function () {\n return 'MyType:' + this.value\n }\n\n // define a new data type\n typed.addType({\n name: 'MyType',\n test: function (x) {\n // test whether x is of type MyType\n return x && x.isMyType\n }\n })\n\n // return the construction function, this will\n // be added to math.type.MyType when imported\n return MyType\n}", "createJWT () {\n const token = {\n iat: parseInt(Date.now() / 1000),\n exp: parseInt(Date.now() / 1000) + 20 * 60, // 20 minutes\n aud: this.mqtt.project\n }\n return jwt.sign(token, fs.readFileSync(this.device.key.file), { algorithm: this.device.key.algorithm })\n }", "static create_token({ organizationId, createToken }) {\n return new Promise(\n async (resolve) => {\n try {\n resolve(Service.successResponse(''));\n } catch (e) {\n resolve(Service.rejectResponse(\n e.message || 'Invalid input',\n e.status || 405,\n ));\n }\n },\n );\n }", "_createType (name) {\n\n\t\tif ( name !== undefined) AssertUtils.isString(name);\n\n\t\tconst getNoPgTypeResult = NoPgUtils.get_result(NoPg.Type);\n\n\t\treturn async data => {\n\n\t\t\tdata = data || {};\n\n\t\t\tif ( name !== undefined ) {\n\t\t\t\tdata.$name = '' + name;\n\t\t\t}\n\n\t\t\tconst rows = await this._doInsert(NoPg.Type, data);\n\n\t\t\tconst result = getNoPgTypeResult(rows);\n\n\t\t\tif ( name !== undefined ) {\n\t\t\t\tawait this.setupTriggersForType(name);\n\t\t\t}\n\n\t\t\treturn result;\n\n\t\t};\n\n\t}", "function Token(value,type,currLineNumber)\n\t{\n\t\tthis.value = value;\n\t\tthis.type = type;\n\t\tthis.currLineNumber = currLineNumber;\n\t\tthis.getValue = function() \n\t\t{\n\t\t\treturn this.value;\n\t\t};\n\t\tthis.getType = function()\n\t\t{\n\t\t\treturn this.type;\n\t\t};\n\t\tthis.getLN = function()\n\t\t{\n\t\t\treturn this.currLineNumber;\n\t\t};\n\t}", "register(steamID, username, action){\n const sid = new SteamID(steamID);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
options: object with any of the following keys followUpUrl: the url to redirect to after success currency: the three letter capitalized currency code to use amount: a preselected donation amount, if > 0 the first step will be skipped outstandingFields: the names of step 2 form fields that aren't satisfied by the values in the member hash. donationBands: an object with three letter currency codes as keys location: a hash of location values inferred from the user's request member: an object with fields that will prefill the form akid: the actionkitid (akid) to save with the user request recurringDefault: either 'donation', 'recurring', or 'only_recurring' pageId: the ID of the plugin's page database record. and array of numbers, integers or floats, to display as donation amounts
initialize (options = {}) { this.initializeCurrency(options.currency, options.donationBands) this.initializeSticky(); this.initializeBraintree(); this.handleFormErrors(); this.changeStep(1); this.donationAmount = 0; this.followUpUrl = options.followUpUrl; this.initializeSkipping(options); this.pageId = options.pageId; if (!this.isMobile()) { this.selectizeCountry(); $(window).on('resize', () => this.policeHeights()); } this.insertActionKitId(options.akid); this.insertSource(options.source); this.initializeRecurring(options.recurringDefault); this.updateButton(); $('.fundraiser-bar__open-button').on('click', () => this.reveal()); }
[ "function createPaymentOptions() {\n\teditCashHistoryFundRowId = null;\n\tresetCashSection();\n\tshowTotalPaymentAndDue(); /* Disable the guest user more info and create account box */\n\tvar paymentOptionTypes = JSON.parse(localStorage.getItem(\"fundingSourceTypes\"));\n\tvar cashPaymentOptions = new Array();\n\tfor(var paymentOptionIndex in paymentOptionTypes) {\n\t\tvar paymentOptionType = paymentOptionTypes[paymentOptionIndex];\n\t\tvar paymentOptionSourcesJsonType = paymentOptionType.jsonType;\n\t\tvar paymentOptionTenderType = paymentOptionType.tenderType;\n\t\tif(paymentOptionSourcesJsonType === jsonTypeConstant.PROMOCREDIT){\n\t\t\tif(parseBoolean(localStorage.getItem(\"registerUser\"))) {\n\t\t\t\tvar visiblePromoCodeInputId = getVisiblePromoCodeBoxId();\n\t\t\t\t$(\"#\" + visiblePromoCodeInputId).val(\"\");\n\t\t\t\t$(\"#promoCodeSection\").show();\n\t\t\t} else {\n\t\t\t\t$(\"#discountAndPromoCodeReg\").show();\n\t\t\t\t$(\"#promoCodeBox\").show();\n\t\t\t}\n\t\t\t$(\"#errorPromoCodeRes\").hide();\n\t\t\t$(\"#summuryPromoCode\").hide();\n\t\t\t$('#checkoutPromoCodeAmount').hide();\n\t\t\tvar visiblePromoCodeInputId = getVisiblePromoCodeBoxId();\n\t\t\t$(\"#\" + visiblePromoCodeInputId).removeClass(\"error_red_border\");\n\t\t\tsubmitBtnEnableUI('checkoutApply');\n\t\t\tvalidationTracking = UNVALIDATED;\n\t\t\tlastPromoCode = \"\";\n\t\t\tregisterEventsForPromoCode();\n\t\t}\n\t\t/* if payment method is cash (create cash options) else create card option */\n\t\tif (paymentOptionTenderType && paymentOptionTenderType.toUpperCase() === tenderTypeConstant.CASH) {\n\t\t\tcashPaymentOptions.push(paymentOptionType);\n\t\t}\n\t}\n\tif (cashPaymentOptions.length > 0) {\n\t\t$(\"#checkoutCreditsCoverAllAmountDue\").hide();\n\t\t$(\"#cardPaymentOptionsContainer\").show();\n\t\t$(\"#cashDataMainContainer\").show(); /* Show CASH ribbon on screen */\n\t\tcreateCashPaymentOption(cashPaymentOptions.sort(sortByFundingSourceType));\n\t}\n\texpandSingleFundingSource();\n\t\n}", "function showRegFormOFPromoCode() {\n\tvar totalDueAmt = getFormatedNumber($(\"#amountDueTotal\").text(), false);\n\tvar totalPaymentAmt = getFormatedNumber($(\"#cashSummaryTotalAmount\").text(), false);\n\tif (!$('#chkPromoCode').is(\":checked\")) {\n\t\tvar arg0 = '<a href=\"javascript:void(0)\" class=\"blue_link\" onclick=\"showTermsUrl()\">';\n\t\tvar arg1 = '</a>';\n\t\tmessage = formatMessage(messages['checkout.guestUserPromoCodeRegisterTermCond'], arg0, arg1);\n\t\t$(\"#chkPromoCode\").prop('checked', true);\n\t\t$(\"#chkPromoCodeIcon\").removeClass(\"add_bill_inactiv_chkbox_icon flt_lft\");\n\t\t$(\"#chkPromoCodeIcon\").addClass(\"add_bill_activ_chkbox_icon flt_lft\");\n\t\t/* clearing promocode and password whenever expanding discount and promo section. Bug 4865*/\n\t\t$('#promoCodeDiscount1').val('');\n\t\t$('#passwordPromoCode').val('');\n\t\t$(\"#frmGuestPromoCodeRes\").show();\n\t\t$(\"#checkoutDiscountPromoTermsCond\").html(message);\n\t\t/* Show the check box for marketing Opt in */\n\t\tcreateOptInMsgAorBSection(\"chkOptInEnhCreatProfPromo\", \"optInEhnChkCreatProfPromo\", messages['createAccount.optInEnh']);\n\t\tif($(\"#additional_info_box\").is(\":visible\")) {\n\t\t\tfillPromoRegisterFromAdditionalInfo();\n\t\t} else if($(\"#createAccountBoxChkOut\").is(\":visible\")) {\n\t\t\tfillPromoRegisterFromCreateProfile();\n\t\t}\n\t\t/* To be called from create_acc_guest.js*/\n\t\tvalidateCheckoutRegistrationFields();\n\t\tenableCheckoutRegisterBtn();\n\t} else {\n\t\toffPromoCodeRegisterScreen();\n\t\t/* Fill the data in \"Create Profile\" area on click of Cancel or unmark of check box and if incase of \n\t\t * atleast 1 schedule payment if user clicked \"Register\" button then also same*/\n\t\tif (totalPaymentAmt > totalDueAmt || isRegisterSelected) {\n\t\t\tfillCreateProfileFromPromoRegister();\n\t\t} else if(totalPaymentAmt === totalDueAmt || $(\"#panel\"+jsonTypeConstant.DEBIT).is(\":visible\") || $(\"#panel\"+jsonTypeConstant.CREDIT).is(\":visible\")) {\n\t\t\tfillAdditionalInfoFromPromoRegister();\n\t\t}\n\t\tcancelBtnOfPromoCode();\n\t}\n}", "paymentMethodOptions() {\n const {settings, invoices, setProp} = this.props;\n const selectedPaymentMethod = invoices.get('paymentMethod');\n const achAvailable = settings.getIn(['achInfo', 'accountNumber']);\n const ccAvailable = settings.get(['ccInfo', 'number']);\n // Determine payment options\n const paymentOptions = [];\n if (achAvailable) {\n paymentOptions.push({value: 'bank-account', name: 'Bank account'});\n // ACH only, select it\n if (!ccAvailable && selectedPaymentMethod === 'credit-card') {\n setProp('bank-account', 'paymentMethod');\n }\n }\n if (settings.get('getCcInfoSuccess')) {\n paymentOptions.push({value: 'credit-card', name: 'Credit card'});\n // CC only, select it\n if (!ccAvailable && selectedPaymentMethod === 'bank-account') {\n setProp('credit-card', 'paymentMethod');\n }\n }\n return Immutable.fromJS(paymentOptions);\n }", "function fillPromoRegisterFromAdditionalInfo() {\n\t$('#emailIdPromoCode').val($(\"#emailIdAddInfoChkOut\").val());\n\t$('#confrmEmailIdPromoCode').val($(\"#emailIdAddInfoChkOut\").val());\n\t$('#mobileNoPromoCode').val($(\"#mobileNoAddInfoChkOut\").val());\n\t$('#zipCodePromoCode').val($(\"#zipCodeAddInfoChkOut\").val());\n\tif ($('#chkOptInEnhAddInfo').is(\":checked\")) {\n\t\t$(\"#chkOptInEnhCreatProfPromo\").prop('checked', true);\n\t} else {\n\t\t$(\"#chkOptInEnhCreatProfPromo\").prop('checked', false);\n\t}\n\tclearFormField(\"additional_info_box\");\n\t$(\"#additional_info_box\").hide();\n}", "function updateFollowInstitutionsModalFooter(){\n var nextButton = $('#onboarding-follow-institutions__next');\n var numFollows = $(\"#onboarding-follow-institutions-modal\").find('.tagboard__tag.active').length;\n\n var percentage = numFollows*100/5;\n $(\"#onboarding-follow-institutions-modal .meter__bar\").width( percentage + '%');\n\n if(numFollows >= 5) {\n $(nextButton).addClass('active');\n $(nextButton).find(\"span\").text('Pick more providers or move on to the next step');\n } else {\n var followsLeft = 5 - numFollows;\n $(nextButton).removeClass('active');\n if( followsLeft == 1) {\n $(nextButton).find(\"span\").text('One more to go...');\n } else {\n $(nextButton).find(\"span\").text('Pick ' + followsLeft + ' more providers to unlock recommendations');\n }\n }\n }", "function callVerifyFundingSourceAPI() {\n\t$(\"#optionsListContainer\").show();\n\tvar checkoutTotalDueAmount = getFormatedNumber($(\"#amountDueTotal\").text(), false);\n\tvar cashFundingSourcesTotalAmount = getFormatedNumber(calculateCashSummaryTotalAmount(), false);\n\t/* total fund amount is greater than or same as due amount */ \n\tif (cashFundingSourcesTotalAmount >= checkoutTotalDueAmount && $(\"#checkoutApply\").is(\":enabled\")) {\n\t\t$(\"#historyFundingSources\").hide(); /* Hide all history funds */\n\t\t$(\"#editCashSummaryTotal\").show(); /* Show edit icon with total amount */\n\t\t$(\"#cashPaymnetInfoMessage\").show(); /* Show info text message below the total amount area. */\n\t\t$(\"#newSelectOption\").hide();\n\t\t$(\"#optionsListContainer\").hide();\n\t\t/* Create funding sources to call funding sources API. \n\t\t * The false means Promo code section apply button is not clicked to invoke the API call.*/\n\t\thandleBpVerifyFundingSource(false);\n\t} else if(cashFundingSourcesTotalAmount >= checkoutTotalDueAmount && $(\"#checkoutApply\").is(\":disabled\")){\n\t\t$(\"#historyFundingSources\").hide(); /* Hide all history funds */\n\t\t$(\"#editCashSummaryTotal\").show(); /* Show edit icon with total amount */\n\t\t$(\"#cashPaymnetInfoMessage\").show(); /* Show info text message below the total amount area. */\n\t\tif(checkoutTotalDueAmount){\n\t\t\t$(\"#newSelectOption\").hide();\n\t\t\t$(\"#optionsListContainer\").hide();\n\t\t} else {\n\t\t\t$(\"#newSelectOption\").show();\n\t\t\t$(\"#optionsListContainer\").show();\n\t\t}\n\t\t/* Create funding sources to call funding sources API. \n\t\t * The false means Promo code section apply button is not clicked to invoke the API call.*/\n\t\thandleBpVerifyFundingSource(false);\n\t} else {\n\t\t$(\"#editCashSummaryTotal\").hide(); /* Hide edit icon with total amount */\n\t\t$(\"#newSelectOption\").show();\n\t\t$(\"#opsList\").hide();\n\t\tremoveChitErrorBorder();\n\t\tdeActivateCheckoutPayButton();/* Disable submit button. */\n\t\tshowTotalPaymentAndDue(); /* Disable the guest user more info and create account box */\n\t}\n}", "function fillAdditionalInfoFromPromoRegister() {\n\t$('#emailIdAddInfoChkOut').val($(\"#emailIdPromoCode\").val());\n\t$('#mobileNoAddInfoChkOut').val($(\"#mobileNoPromoCode\").val());\n\t$('#zipCodeAddInfoChkOut').val($(\"#zipCodePromoCode\").val());\n\tif ($('#chkOptInEnhCreatProfPromo').is(\":checked\")) {\n\t\t$(\"#chkOptInEnhAddInfo\").prop('checked', true);\n\t} else {\n\t\t$(\"#chkOptInEnhAddInfo\").prop('checked', false);\n\t}\n\t$(\"#additional_info_box\").show();\n\tvalidateAdditionalInfo();\n}", "buildPaymentDetails(cart, shippingOptions, shippingOptionId) {\n // Start with the cart items\n let displayItems = cart.cart.map(item => {\n return {\n label: `${item.quantity}x ${item.title}`,\n amount: {currency: 'USD', value: String(item.total)},\n selected: false\n };\n });\n let total = cart.total;\n\n let displayedShippingOptions = [];\n if (shippingOptions.length > 0) {\n let selectedOption = shippingOptions[shippingOptionId];\n displayedShippingOptions = shippingOptions.map(option => {\n return {\n id: option.id,\n label: option.label,\n amount: {currency: 'USD', value: String(option.price)},\n selected: option === selectedOption\n };\n });\n if (selectedOption) total += selectedOption.price;\n }\n\n let details = {\n displayItems: displayItems,\n total: {\n label: 'Total due',\n amount: {currency: 'USD', value: String(total)}\n },\n shippingOptions: displayedShippingOptions\n };\n\n return details;\n }", "function setupPaymentMethods17() {\n const queryParams = new URLSearchParams(window.location.search);\n if (queryParams.has('message')) {\n showRedirectErrorMessage(queryParams.get('message'));\n }\n\n $('input[name=\"payment-option\"]').on('change', function(event) {\n\n let selectedPaymentForm = $('#pay-with-' + event.target.id + '-form .adyen-payment');\n\n // Adyen payment method\n if (selectedPaymentForm.length > 0) {\n\n // not local payment method\n if (!('localPaymentMethod' in\n selectedPaymentForm.get(0).dataset)) {\n\n resetPrestaShopPlaceOrderButtonVisibility();\n return;\n }\n\n let selectedAdyenPaymentMethodCode = selectedPaymentForm.get(\n 0).dataset.localPaymentMethod;\n\n if (componentButtonPaymentMethods.includes(selectedAdyenPaymentMethodCode)) {\n prestaShopPlaceOrderButton.hide();\n } else {\n prestaShopPlaceOrderButton.show();\n }\n } else {\n // In 1.7 in case the pay button is hidden and the customer selects a non adyen method\n resetPrestaShopPlaceOrderButtonVisibility();\n }\n });\n }", "function CtrlGoToNextCoupon() {\n var nextCouponId , nextCoupon;\n //we get the id of the current coupon. so we can determine the next coupon.\n nextCoupon = UICtrl.getExpandedCoupon().nextElementSibling;\n nextCouponId = nextCoupon.id;\n \n CtrlShrinkCoupon();\n openNextCoupon(nextCouponId);\n updateTotal();\n\n if(jackpotCtrl.hasCoupon(nextCouponId)){\n checkedFields = 4;\n UICtrl.showNextCouponButton();\n UICtrl.showDeleteAllButton(); // we wanna be albe to uncheck all the fields , if there are checked.\n } \n else { checkedFields = 0; UICtrl.fieldsClickable(); }\n }", "function paymentOptions(option) {\r\n const ccDIV = document.getElementById(\"credit-card\");\r\n const ppDIV = document.getElementById(\"paypal\");\r\n const bitcoinDIV =document.getElementById(\"bitcoin\");\r\n if(option == \"credit card\"){\r\n ccDIV.style.display = \"inherit\";\r\n ppDIV.style.display = \"none\";\r\n bitcoinDIV.style.display = \"none\";\r\n } else if (option == \"paypal\"){\r\n ccDIV.style.display = \"none\";\r\n ppDIV.style.display = \"inherit\";\r\n bitcoinDIV.style.display = \"none\";\r\n } else if (option == \"bitcoin\"){\r\n ccDIV.style.display = \"none\";\r\n ppDIV.style.display = \"none\";\r\n bitcoinDIV.style.display = \"inherit\";\r\n }\r\n}", "function showFieldsAccordingToNbPlayers(nb_players, availability, dm){\n\n\n if(nb_players>availability && availability!=null){\n //var msg = \"Attention : Il n'y a pas assez de place disponible (\"+availability+\") par rapport au nombre de participants que vous souhaitez inscrire (\"+nb_players+\")!\";\n //$(\"#form_modal_msg_box\").html(msg).show();\n $(booking_form_nb_select+' option[value=\"' + availability + '\"]').prop('selected', 'selected');\n nb_players = availability;\n }\n\n if(availability!=null){\n var counter = 0;\n $(booking_form_nb_select+\" option\").each(function(){\n counter++;\n if(counter<=(availability)){\n $(this).css('display','block');\n }\n else if(counter>(availability)){\n $(this).css('display','none');\n }\n });\n }\n\n // init form fields\n for(var i = 1; i<= 4; i++){\n\n $(\"#booking_form_member_\"+i+\"_firstname_field\").val(\"\").prop(\"disabled\", false).hide();\n $(\"#booking_form_member_\"+i+\"_lastname_field\").val(\"\").prop(\"disabled\", false).hide();\n $(\"#booking_form_member_\"+i+\"_handicap_field\").val(\"\").prop(\"disabled\", false).hide();\n $(\"#booking_form_member_\"+i+\"_type_select\").attr(\"disabled\", false).hide(); // disable member 4 type\n $(\"#booking_form_member_\"+i+\"_type_select option:first\").prop('selected', 'selected');\n $(\"#booking_form_member_\"+i+\"_total_label\").html(\"\").data(\"cost\", 0).hide();\n $(\"#modal_form_line_\"+i).show();\n }\n\n // display example members\n\n for(var i = 1; i<= (4-availability); i++){\n if(i==1){\n var firstname = dm[\"member1\"].firstname; var lastname = dm[\"member1\"].lastname; var handicap = dm[\"member1\"].handicap; var type = dm[\"member1\"].type;\n }\n else if(i==2){\n var firstname = dm[\"member2\"].firstname; var lastname = dm[\"member2\"].lastname; var handicap = dm[\"member2\"].handicap; var type = dm[\"member2\"].type;\n }\n else if(i==3){\n var firstname = dm[\"member3\"].firstname; var lastname = dm[\"member3\"].lastname; var handicap = dm[\"member3\"].handicap; var type = dm[\"member3\"].type;\n }\n\n $(\"#booking_form_member_\"+i+\"_firstname_field\").val(firstname).prop(\"disabled\", true).show();\n $(\"#booking_form_member_\"+i+\"_lastname_field\").val(lastname).prop(\"disabled\", true).show();\n $(\"#booking_form_member_\"+i+\"_handicap_field\").val(handicap).prop(\"disabled\", true).show();\n $(\"#booking_form_member_\"+i+\"_type_select\").attr(\"disabled\", true).hide();// disable member 4 type\n //$(\"#booking_form_member_\"+i+'_type_select option[value=\"'+type+'\"]').prop('selected','selected');\n $(\"#booking_form_member_\"+i+\"_total_label\").html(\"\").data(\"cost\", 0).hide();\n }\n\n // prefill next field possible with\n if(user_defined==\"member\" && typeof user_connected != \"undefined\"){\n\n var next_place_possible = (4-availability) + 1;\n $(\"#booking_form_member_\"+next_place_possible+\"_type_select\").attr(\"disabled\", false).show(); // disable member 4 type\n\n var cost = $(\"#booking_form_member_\"+next_place_possible+\"_type_select option:selected\").data(\"cost\");\n\n $(\"#booking_form_member_\"+next_place_possible+\"_total_label\").html(cost+\".-\").data(\"cost\", cost).show();\n $(\"#booking_form_member_\"+next_place_possible+\"_type_select option[value='\"+user_member+\"']\").prop('selected','selected');\n var optionValue = $(\"#booking_form_member_\"+next_place_possible+\"_type_select option:selected\").val();\n\n var target = \"#booking_form_member_\"+next_place_possible+\"_type_select option:selected\";\n getRealCost(optionValue, target, \"#booking_form_member_\"+next_place_possible+\"_total_label\");\n }\n\n if(user_defined==\"member\" && typeof user_connected == \"undefined\"){\n\n var next_place_possible = (4-availability) + 1;\n\n var disabledField = true;\n // Si membre hôtel\n if(user_member == 20){\n disabledField = false;\n }\n\n $(\"#booking_form_member_\"+next_place_possible+\"_firstname_field\").val(user_firstname).prop(\"disabled\", disabledField).show();\n $(\"#booking_form_member_\"+next_place_possible+\"_lastname_field\").val(user_lastname).prop(\"disabled\", disabledField).show();\n $(\"#booking_form_member_\"+next_place_possible+\"_handicap_field\").val(user_handicap).prop(\"disabled\", disabledField).show();\n $(\"#booking_form_member_\"+next_place_possible+\"_type_select\").attr(\"disabled\", true).show(); // disable member 4 type\n $(\"#booking_form_member_\"+next_place_possible+\"_type_select option[value='\"+user_member+\"']\").prop('selected','selected');\n\n var cost = $(\"#booking_form_member_\"+next_place_possible+\"_type_select option:selected\").data(\"cost\");\n\n $(\"#booking_form_member_\"+next_place_possible+\"_total_label\").html(cost+\".-\").data(\"cost\", cost).show();\n var optionValue = $(\"#booking_form_member_\"+next_place_possible+\"_type_select option:selected\").val();\n\n var target = \"#booking_form_member_\"+next_place_possible+\"_type_select option:selected\";\n getRealCost(optionValue, target, \"#booking_form_member_\"+next_place_possible+\"_total_label\");\n\n $(\"#p\"+next_place_possible+\"_userid\").val(member_id_connected);\n\n for(var i=1; i<=(nb_players-1);i++){\n next_place_possible += 1;\n $(\"#booking_form_member_\"+next_place_possible+\"_firstname_field\").val(\"\").prop(\"disabled\", false).show();\n $(\"#booking_form_member_\"+next_place_possible+\"_lastname_field\").val(\"\").prop(\"disabled\", false).show();\n $(\"#booking_form_member_\"+next_place_possible+\"_handicap_field\").val(\"\").prop(\"disabled\", false).show();\n $(\"#booking_form_member_\"+next_place_possible+\"_type_select\").attr(\"disabled\", false).show();\n $(\"#booking_form_member_\"+next_place_possible+\"_type_select option:first\").prop('selected','selected');\n\n var optionValue = $(\"#booking_form_member_\"+next_place_possible+\"_type_select option:selected\").val();\n var target = \"#booking_form_member_\"+next_place_possible+\"_type_select option:selected\";\n ////console.log(optionValue);\n getRealCost(optionValue, target, \"#booking_form_member_\"+next_place_possible+\"_total_label\");\n\n $(\"#booking_form_member_\"+next_place_possible+\"_total_label\").html(\"0\").data(\"cost\", 0).show();\n }\n\n if(user_member == 20){\n disabledField = false;\n $(\"#booking_form_member_1_type_select\").prop(\"disabled\", false);\n }\n\n next_place_possible = next_place_possible +1;\n ////console.log(next_place_possible);\n if(next_place_possible<5){\n for(var i=4; i>=next_place_possible;i--){\n $(\"#modal_form_line_\"+i).hide();\n }\n }\n\n\n }\n else if(user_defined==\"member_no_login\"){\n\n var next_place_possible = (4-availability) + 1;\n $(\"#booking_form_member_\"+next_place_possible+\"_firstname_field\").val(\"\").prop(\"disabled\", false).show();\n $(\"#booking_form_member_\"+next_place_possible+\"_lastname_field\").val(\"\").prop(\"disabled\", false).show();\n $(\"#booking_form_member_\"+next_place_possible+\"_handicap_field\").val(\"\").prop(\"disabled\", false).show();\n $(\"#booking_form_member_\"+next_place_possible+\"_type_select\").attr(\"disabled\", false).show();// disable member 4 type\n $(\"#booking_form_member_\"+next_place_possible+\"_type_select option:contains(\\\"\"+user_member+\"\\\")\").prop('selected','selected');\n\n var optionValue = $(\"#booking_form_member_\"+next_place_possible+\"_type_select option:selected\").val();\n var target = \"#booking_form_member_\"+next_place_possible+\"_type_select option:selected\";\n ////console.log(optionValue);\n getRealCost(optionValue, target, \"#booking_form_member_\"+next_place_possible+\"_total_label\");\n\n $(\"#booking_form_member_\"+next_place_possible+\"_total_label\").html(\"\").data(\"cost\", 0).hide();\n }\n else if( typeof user_connected == \"undefined\" ){\n var next_place_possible = (4-availability) + 1;\n $(\"#booking_form_member_\"+next_place_possible+\"_firstname_field\").val(\"\").prop(\"disabled\", false).show();\n $(\"#booking_form_member_\"+next_place_possible+\"_lastname_field\").val(\"\").prop(\"disabled\", false).show();\n $(\"#booking_form_member_\"+next_place_possible+\"_handicap_field\").val(\"\").prop(\"disabled\", false).show();\n $(\"#booking_form_member_\"+next_place_possible+\"_type_select\").attr(\"disabled\", false).show();// disable member 4 type\n $(\"#booking_form_member_\"+next_place_possible+\"_type_select option[value=\\\"4\\\"]\").prop('selected','selected');\n\n var optionValue = $(\"#booking_form_member_\"+next_place_possible+\"_type_select option:selected\").val();\n var target = \"#booking_form_member_\"+next_place_possible+\"_type_select option:selected\";\n ////console.log(optionValue);\n ////console.log(\"recherche prix...\");\n getRealCost(optionValue, target, \"#booking_form_member_\"+next_place_possible+\"_total_label\");\n\n $(\"#booking_form_member_\"+next_place_possible+\"_total_label\").html(\"\").data(\"cost\", 0).hide();\n }\n\n}", "function fillCreateProfileFromPromoRegister() {\n\t$('#emailIdChkOut').val($(\"#emailIdPromoCode\").val());\n\t$('#confrmEmailIdChkOut').val($(\"#confrmEmailIdPromoCode\").val());\n\t$('#passwordChkOut').val($(\"#passwordPromoCode\").val());\n\t$('#mobileNoChkOut').val($(\"#mobileNoPromoCode\").val());\n\t$('#zipCodeChkOut').val($(\"#zipCodePromoCode\").val());\n\t$('#promoCodeDiscount2').val($(\"#promoCodeDiscount1\").val());\n\tif ($('#chkOptInEnhCreatProfPromo').is(\":checked\")) {\n\t\t$(\"#chkOptInEnhCreatProf\").prop('checked', true);\n\t} else {\n\t\t$(\"#chkOptInEnhCreatProf\").prop('checked', false);\n\t}\n\t$(\"#createAccountBoxChkOut\").show();\n\tvalidateCreateProfile();\n}", "buildPaymentRequest(cart) {\n // Supported payment instruments\n const supportedInstruments = [{\n supportedMethods: (PAYMENT_METHODS)\n }];\n\n // Payment options\n const paymentOptions = {\n requestShipping: true,\n requestPayerEmail: true,\n requestPayerPhone: true\n };\n\n let shippingOptions = [];\n let selectedOption = null;\n\n let details = this.buildPaymentDetails(cart, shippingOptions, selectedOption);\n\n // Initialize\n let request = new window.PaymentRequest(supportedInstruments, details, paymentOptions);\n\n // When user selects a shipping address, add shipping options to match\n request.addEventListener('shippingaddresschange', e => {\n e.updateWith(_ => {\n // Get the shipping options and select the least expensive\n shippingOptions = this.optionsForCountry(request.shippingAddress.country);\n selectedOption = shippingOptions[0].id;\n let details = this.buildPaymentDetails(cart, shippingOptions, selectedOption);\n return Promise.resolve(details);\n });\n });\n\n // When user selects a shipping option, update cost, etc. to match\n request.addEventListener('shippingoptionchange', e => {\n e.updateWith(_ => {\n selectedOption = request.shippingOption;\n let details = this.buildPaymentDetails(cart, shippingOptions, selectedOption);\n return Promise.resolve(details);\n });\n });\n\n return request;\n }", "function fillPromoRegisterFromCreateProfile() {\n\t$('#emailIdPromoCode').val($(\"#emailIdChkOut\").val());\n\t$('#confrmEmailIdPromoCode').val($(\"#confrmEmailIdChkOut\").val());\n\t$('#passwordPromoCode').val($(\"#passwordChkOut\").val());\n\t$('#mobileNoPromoCode').val($(\"#mobileNoChkOut\").val());\n\t$('#zipCodePromoCode').val($(\"#zipCodeChkOut\").val());\n\t$('#promoCodeDiscount1').val($(\"#promoCodeDiscount2\").val());\n\tif ($('#chkOptInEnhCreatProf').is(\":checked\")) {\n\t\t$(\"#chkOptInEnhCreatProfPromo\").prop('checked', true);\n\t} else {\n\t\t$(\"#chkOptInEnhCreatProfPromo\").prop('checked', false);\n\t}\n\tclearFormField(\"createAccountBoxChkOut\");\n\t$(\"#createAccountBoxChkOut\").hide();\n\tclearIntervalApp(chkRegisterBtnCount);\n}", "options(params) {\n if(!params) {\n return {\n provider: _currentProvider,\n customProvider: customProvider,\n depth: depth,\n weight: weight,\n spamSeed: spamSeed,\n message: message,\n tag: tag,\n numberOfTransfersInBundle: numberOfTransfersInBundle,\n isLoadBalancing: optionsProxy.isLoadBalancing\n }\n }\n if(params.hasOwnProperty(\"provider\")) {\n _currentProvider = params.provider\n initializeIOTA()\n }\n if(params.hasOwnProperty(\"customProvider\")) {\n customProvider = params.customProvider\n initializeIOTA()\n }\n if(params.hasOwnProperty(\"depth\")) { depth = params.depth }\n if(params.hasOwnProperty(\"weight\")) { weight = params.weight }\n if(params.hasOwnProperty(\"spamSeed\")) { spamSeed = params.spamSeed }\n if(params.hasOwnProperty(\"message\")) { message = params.message }\n if(params.hasOwnProperty(\"tag\")) { tag = params.tag }\n if(params.hasOwnProperty(\"numberOfTransfersInBundle\")) { numberOfTransfersInBundle = params.numberOfTransfersInBundle }\n if(params.hasOwnProperty(\"isLoadBalancing\")) { optionsProxy.isLoadBalancing = params.isLoadBalancing }\n if(params.hasOwnProperty(\"onlySpamHTTPS\")) { onlySpamHTTPS = params.onlySpamHTTPS }\n }", "addGoal(request, response) {\n logger.debug(\"Add a goal\");\n const newGoal = {\n id: uuid(),\n memberid: request.params.memberid,\n date: request.body.date,\n weight: request.body.weight,\n waist: request.body.waist,\n status: \"OPEN\"\n };\n goalStore.addGoal(newGoal);\n if (request.cookies.member != \"\") {\n response.redirect(\"/member-dashboard\");\n } else {\n response.redirect(`/member/${request.params.memberid}`);\n }\n }", "function payBank(sid,mid,mode){//HIK:DONE\n\tvar GatewayMode;\n\tvar BankName;\n\tif(mode === \"NETBANK\"){\n\t\tGatewayMode = document.getElementById('netbankopt').value;\n\t\tbankOptIndex = document.getElementById('netbankopt').selectedIndex;\n\t\tBankName = document.getElementById('netbankopt').options[bankOptIndex].text;\n\t\tif((sid === \"\") || (GatewayMode === \"\") || (BankName === \"\")){\n\t\t\tdocument.getElementById(\"neterror\").className = \"text-danger textcenter bold show\";\n\t\t\treturn false;\n\t\t}\n\t\tdocument.getElementById(\"neterror\").className = \"text-danger textcenter bold hide\";\t\t\n\t}else\n\tif(mode === \"DEBIT\"){\n\t\tGatewayMode = document.getElementById('debitopt').value;\n\t\tbankOptIndex = document.getElementById('debitopt').selectedIndex;\n\t\tBankName = document.getElementById('debitopt').options[bankOptIndex].text;\n\t\tif((sid === \"\") || (GatewayMode === \"\") || (BankName === \"\")){\n\t\t\tdocument.getElementById(\"dberror\").className = \"text-danger textcenter bold show\";\n\t\t\treturn false;\n\t\t}\n\t\tdocument.getElementById(\"dberror\").className = \"text-danger textcenter bold hide\";\t\t\n\t}else\n\tif(mode === \"CREDIT\"){\t\t\n\t\tGatewayMode = document.getElementById('creditopt').value;\n\t\tbankOptIndex = document.getElementById('creditopt').selectedIndex;\n\t\tBankName = document.getElementById('creditopt').options[bankOptIndex].text;\n\t\tif((sid === \"\") || (GatewayMode === \"\") || (BankName === \"\")){\n\t\t\tdocument.getElementById(\"crerror\").className = \"text-danger textcenter bold show\";\n\t\t\treturn false;\n\t\t}\n\t\tdocument.getElementById(\"crerror\").className = \"text-danger textcenter bold hide\";\t\t\n\t}else\n\tif(mode === \"CASH\"){\n\t\tGatewayMode = document.getElementById('cashopt').value;\n\t\tbankOptIndex = document.getElementById('cashopt').selectedIndex;\n\t\tBankName = document.getElementById('cashopt').options[bankOptIndex].text;\n\t\tif((sid === \"\") || (GatewayMode === \"\") || (BankName === \"\")){\n\t\t\tdocument.getElementById(\"casherror\").className = \"text-danger textcenter bold show\";\n\t\t\treturn false;\n\t\t}\n\t\tdocument.getElementById(\"casherror\").className = \"text-danger textcenter bold hide\";\t\t\n\t}else{\n\t\tdocument.getElementById(\"neterror\").className = \"text-danger textcenter bold show\";\n\t\tdocument.getElementById(\"dberror\").className = \"text-danger textcenter bold show\";\n\t\tdocument.getElementById(\"crerror\").className = \"text-danger textcenter bold show\";\n\t\tdocument.getElementById(\"casherror\").className = \"text-danger textcenter bold show\";\n\t\treturn false;\n\t}\n\t\n\t$('<form id=\"deskpay\" action=\"./xcommon/fend/deskpay.php\" method=\"POST\" />')\n\t.append($('<input type=\"hidden\" value=\"'+ sid +'\" name=\"sid\" id=\"sid\">'))\n\t.append($('<input type=\"hidden\" value=\"'+ mode +'\" name=\"PayMode\" id=\"PayMode\" />'))\n\t.append($('<input type=\"hidden\" value=\"'+ GatewayMode +'\" name=\"GatewayMode\" id=\"GatewayMode\" />'))\n\t.append($('<input type=\"hidden\" value=\"'+ BankName +'\" name=\"BankName\" id=\"BankName\" />'))\n\t.appendTo($(document.body))\n\t.submit();\n\treturn false;\n}", "getManualPaymentMethod() {\n const pm = get(this.props.data, 'Collective.host.settings.paymentMethods.manual');\n if (!pm || get(this.state, 'stepDetails.interval')) {\n return null;\n }\n\n return {\n ...pm,\n instructions: this.props.intl.formatMessage(\n {\n id: 'host.paymentMethod.manual.instructions',\n defaultMessage:\n 'Instructions to make the payment of {amount} will be sent to your email address {email}. Your order will be pending until the funds have been received by the host ({host}).',\n },\n {\n amount: formatCurrency(get(this.state, 'stepDetails.totalAmount'), this.getCurrency()),\n email: get(this.props, 'LoggedInUser.email', ''),\n collective: get(this.props, 'loggedInUser.collective.slug', ''),\n host: get(this.props.data, 'Collective.host.name'),\n TierId: get(this.getTier(), 'id'),\n },\n ),\n };\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
send the ajax query
function sendAjaxQuery(url, data) { $.ajax({ url: url, data: data, dataType: 'json', type: 'POST', success: function (dataR) { window.location.href = '/recruiterProfile'; }, error: function (jqXHR, status, err) { alert('Error: ' + err.message); } }); }
[ "function submitCustomQuery(text){\r\n\t\tvar endpoint=\"http://data.uni-muenster.de:8080/openrdf-sesame/repositories/bt\";\r\n\t\t//sent request over jsonp proxy (some endpoints are not cors enabled http://en.wikipedia.org/wiki/Same_origin_policy)\r\n\t\tvar queryUrl = \"http://jsonp.lodum.de/?endpoint=\" + endpoint;\r\n\t\tvar request = { accept : 'application/sparql-results+json' };\r\n\t\t//get sparql query from textarea\r\n\t\trequest.query=text;\r\n\t\tconsole.log('Start Ajax');\r\n\t\t//sent request\r\n\t\t$.ajax({\r\n\t\t\tdataType: \"jsonp\",\r\n\t\t\t//some sparql endpoints do only support \"sparql-results+json\" instead of simply \"json\"\r\n\t\t\tbeforeSend: function(xhrObj){xhrObj.setRequestHeader(\"Accept\",\"application/sparql-results+json\");},\r\n\t\t\tdata: request,\r\n\t\t\turl: queryUrl,\r\n\t\t\tsuccess: callbackFuncResults,\r\n\t\t\terror: function (request, status, error) {\r\n\t\t //alert(request.responseText);\r\n\t\t\t\t\t$('#loadingDiv').hide();\r\n\t\t\t\t\t$('#result_error').slideDown().delay(3000).slideUp();\r\n\t\t\t\t\t$(\"#error\").html(request.responseText);\r\n\t\t }\r\n\t\t});\r\n\t}", "function requestTomTom(query) {\n $.ajax({\n // Rotta response\n 'url': 'http://localhost:8000/search',\n 'dataType': 'json',\n 'headers': {'X-CSRF-TOKEN': $('meta[name=\"csrf-token\"]').attr('content')},\n 'method': 'POST',\n 'data':{\n // le coordinate da mandare al back-end\n 'query_lat': query.lat,\n 'query__long': query.lon,\n 'radius': $('#search_radius').val(),\n\n 'services': checkboxCheck(),\n 'rooms': $('#rooms').val(),\n 'beds': $('#beds').val(),\n 'baths': $('#baths').val(),\n 'mq': $('#mq').val(),\n },\n 'success': function (data) {\n\n // data contiene la ns risposta. gli appartamenti!\n renderApartment_premium(data['premium']);\n renderApartment_free(data['free']);\n },\n 'error':function(){\n console.log('errore!');\n }\n });\n}", "function searchRequest(query_terms)\n{\n $.ajax\n ({\n type: \"GET\",\n url: \"/search/\",\n data: {'q' : query_terms},\n success: paginateResults\n });\n}", "lock_action(link){\n\t\t\t\t\t\t\n\t\t\t\t\t_this=this;\n\t\t\t\t\t$.ajax({\n\t\t\t url: link,\n\t\t\t type:\"POST\",\n\t\t\t dataType:'html',\n\t\t\t //data:(val!=\"\") ? \"filter=\"+val : \"\",\n\t\t\t beforeSend:function(){\n\t\t\t settings.disable_okbutt_mgdialg() ;\n\t\t\t settings.show_message(\"Performing action ...\"); \n\t\t\t },\n\t\t\t success:function(Data) {\n\t\t\t settings.show_message(Data); \n\t\t\t setTimeout(function() {\n\t\t\t\t\t\t\tusers.load_users_data($(\"#search_user_url\").val());\n\t\t\t\t\t\t}, 2000);\t\n\t\t\t },\n\t\t\t error:function(data){\n\t\t\t settings.enable_okbutt_mgdialg();\n\t\t\t settings.show_message(Data.responseText); \n\t\t\t }\n\t\t\t }); \t\t \t\n\t\t\t \t\t\t\n\t\t}", "function doSongsGet(query){\n\t\n\t// sending the HTTP GET request to the Java Servlet with the query data\n\tjQuery.ajax({\n\t\t\"method\": \"GET\",\n\t\t// generate the request url from the query.\n\t\t// escape the query string to avoid errors caused by special characters \n\t\t\"url\": \"api/songs?keywords=\" + escape(query),\n\t\t\"success\": function(resultData) {\n\t\t\t// pass the data, query, and doneCallback function into the success handler\n\t\t\thandleSearchSongsResult(resultData) \n\t\t},\n\t\t\"error\": function(errorData) {\n\t\t\tconsole.log(\"lookup ajax error\")\n\t\t\tconsole.log(errorData)\n\t\t}\n\t})\t\n\t\n}", "function sendFilter(filter) {\n\t\t$.ajax({\n\t\t\turl: SimpleFilterAjaxUrl+'?'+oldGetParams,\n\t\t\ttype: 'POST',\n\t\t\tdata: {_csrf: yii.getCsrfToken(), filter: filter},\n\t\t\tdataType: 'html',\n\t\t\tsuccess: function(data) {\n\t\t\t\tvar wrapper = $('.fltr-data-wrapper');\n\t\t\t\twrapper.children().remove();\n\t\t\t wrapper.html(data);\n\t\t\t replaceUrls(wrapper);\n\t\t\t}\n\t });\n\t}", "function submitQuery() {\n \"use strict\";\n const results = document.getElementById(\"queryResults\");\n const query = getBaseURL() + \"data/?\" + getQueryParamString();\n\n fetch(query).then(function (response) {\n const contentType = response.headers.get(\"content-type\");\n if (contentType && contentType.indexOf(\"application/json\") !== -1) {\n return response.json();\n } else {\n return response.text();\n }\n }).then(function (data) {\n if (typeof data === \"string\") {\n results.textContent = data;\n } else {\n results.textContent = JSON.stringify(data, null, 4);\n }\n });\n}", "function ajaxPostJQ(urlLink, params, callbackfn) {\n\t $.ajax({\n\t\ttype: 'POST',\n\t\turl: urlLink,\n\t\tdata: params,\n\t\tdataType: 'html',\n\t\ttraditional: true,\n\t\tasync: true,\n\t\tsuccess: callbackfn\n\t});\n}", "function lineConnectionQuery(action,resArr,count,delay){\n\tif(count==null || count==\"\" || count == undefined)\n\t\tcount =1;\n\tif(delay == null || delay == undefined || delay == \"\")\n\t\tdelay = 0;\n//\tvar url = \"/cgi-bin/Final/AutoCompletePythonCGI/FastQueryCgi.py\"\n\tif (globalInfoType == \"XML\"){\n\t\tvar query = \"Port1=\"+resArr[0].pDestination+\"^Port2=\"+resArr[0].pSource+\"^Count=\"+count+\"^Delay=\"+delay+\"^ResourceId=\"+window['variable' + dynamicResourceId[pageCanvas] ]+\"^ConfigName=\"+Name;\n\t\tvar url = getURL(\"ConfigEditor\");\n\t} else {\n\t\tvar query = \"{'QUERY':[{'Port1':'\"+resArr[0].pDestination+\"','Port2':'\"+resArr[0].pSource+\"','Count':'\"+count+\"','Delay':'\"+delay+\"','ResourceId':'\";\n\t\tquery += window[\"variable\" + dynamicResourceId[pageCanvas]];\n\t\tquery += \"','ConfigName':'\"+Name+\"'}]}\";\n\t\tvar url = getURL(\"ConfigEditor\",\"JSON\");\n\t}\n//\tvar url = \"https://\"+CURRENT_IP+url;\n\t$.ajax({\n\t\turl: url,\n\t\tdata:{\n\t\t\t\"action\":action,\n\t\t\t\"query\":query,\n\t\t},\n\t\tdataType: 'html',\n\t\tmethod: 'POST',\n\t\tproccessData: false,\n\t\tasync:false,\n\t\tsuccess: function(data) {\n\t\t\tdata = $.trim(data);\n\t\t\tif (globalInfoType == \"XML\"){\n\t\t\t\tif (data==\"1\"){\n\t\t\t\t\tif (globalDeviceType == 'Mobile'){\n\t\t\t\t\t\terror(action+\" Successful\",action);\n\t\t\t\t\t} else {\n\t\t\t\t\t\talerts(action+\" Successful\");\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tif (globalDeviceType == 'Mobile'){\n\t\t\t\t\t\terror(\"Failed to \"+action,action);\n\t\t\t\t\t} else {\n\t\t\t\t\t\talerts(\"Failed to \"+action);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdata = data.replace(/'/g,'\"');\n\t\t\t\tvar jsonData = jQuery.parseJSON(data);\t\n\t\t\t\tvar row = jsonData.RESULT[0];\n\t\t\t\tif (row==\"1\"){\n\t\t\t\t\tif (globalDeviceType == 'Mobile'){\n\t\t\t\t\t\terror(action+\" Successful\",action);\n\t\t\t\t\t} else {\n\t\t\t\t\t\talerts(action+\" Successful\");\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tif (globalDeviceType == 'Mobile'){\n\t\t\t\t\t\terror(\"Failed to \"+action,action);\n\t\t\t\t\t} else {\n\t\t\t\t\t\talerts(\"Failed to \"+action);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tsetTimeout(function(){\n\t\t\t\tif (globalDeviceType == 'Mobile'){\n\t\t\t\t\t$.mobile.changePage($('#configEditorPage'),{\n\t\t\t\t\t\ttransition: \"pop\"\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\t$('#configPopUp').dialog('destroy');\n\t\t\t\t}\n\t\t\t},1000);\n\n\t\t}\n\t});\t\t\n}", "function IAjaxBatchRequest() {}", "function callAjaxSearch() {\n\n searchTerm = $(settings.input).val();\n\n //No term - clear results\n if (searchTerm == \"\") {\n\n clear();\n resetPage();\n updateUI();\n\n\n }\n //Different term than last time - clear everything and start search\n else if (searchTerm != lastTerm) {\n\n clear();\n resetPage();\n search();\n\n }\n //Same term but different page - append content (if infinite scroll is active)\n else if (currentPage != lastPage) {\n\n if (!settings.infiniteScroll) {\n\n clear();\n }\n\n search();\n\n }\n\n\n timer = setTimeout(function(){callAjaxSearch()}, settings.delay);\n }", "function ajax(params) {\n delete params['token_auth'];\n return $.ajax({\n url: 'index.php?' + $.param(params),\n dataType: 'json',\n data: { token_auth: tokenAuth },\n type: 'POST'\n });\n }", "function ajax_voleiball_unirse(){\r\n\t\r\n\t\r\n\t$('#form_unirse_volei').submit(function(){\r\n\t\tteam_name = $('#unirse_equipo_voleiball').val();\r\n\t\t\r\n\t\t\t\t\r\n\t\t$.ajax({\r\n\t\t type: \"POST\",\r\n\t\t url: \"/unirse_equipo_voleiball\",\r\n\t\t data: JSON.stringify({myDict: {'equipo_voleiball': team_name}}),\r\n\t\t contentType: \"application/json; charset=utf-8\"\r\n\t\t }).done(function(result) {\r\n\t\t \t\r\n\t\t\t \tif (result == \"Ya tiene equipo\")\r\n\t\t\t \t\t$('#error_unirse_equipo_voleiball').css('display','block').html(\"<strong>Ya tiene equipo</strong>\").fadeOut(5000);\r\n\t\t\t \telse if (result == \"El equipo no existe\")\r\n\t\t\t \t\t$('#error_unirse_equipo_voleiball').css('display','block').html(\"<strong>El equipo no existe</strong>\").fadeOut(5000);\r\n\t\t\t \telse if (result == \"Inscrito al equipo\")\r\n\t\t\t \t\t$('#ok_unirse_equipo_voleiball').css('display','block').html(\"<strong>Inscrito al equipo</strong>\").fadeOut(5000);\r\n\t\t\t \telse if (result == \"Introduzca nombre de equipo\")\r\n\t\t\t \t\t$('#warning_unirse_equipo_voleiball').css('display','block').html(\"<strong>Introduzca nombre de equipo</strong>\").fadeOut(5000);\r\n\t\t\t});\r\n\t\t\treturn false;\r\n\t\t});\r\n}", "function genericAjax() {\n $.ajax({\n url: document.URL,\n data: JSON.stringify({\n newKeywords: document.getElementById('results-keyword').value,\n newPostcode: document.getElementById('results-postcode').value,\n slider: document.getElementById('distRange').value,\n sortBy: document.getElementById('selectMe').value\n }),\n contentType: 'application/json',\n type: 'POST',\n dataType: \"json\",\n success: function (data) {\n console.log(data);\n // Code to change the page goes here\n document.getElementById('results-keyword').value = data.prevQuery.keyword;\n document.getElementById('results-postcode').value = data.prevQuery.postcode;\n document.getElementById('distRange').value = data.prevQuery.slider;\n document.getElementById('selectMe').value = data.prevQuery.sortBy;\n\n showAjaxSearchResults(data.html, data.results, data.prevQuery.lat, data.prevQuery.lng);\n },\n error: function (xhr, status, error) {\n console.log(\"err\");\n }\n });\n}", "function sendAndUpdate(xhr, json) {\n xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');\n xhr.send(json);\n xhr.onreadystatechange = function () {\n if(xhr.readyState == 4){\n if(xhr.status == 200){\n document.getElementById('input_box').innerHTML = \"\";\n document.getElementById('data').innerHTML = \"\";\n if(checkTimeTable == true && checkStaff == false){\n getTimeTable(dataTable, true);\n } else {\n getStaff(dataTable,true);\n }\n }\n }\n }\n}", "function sendDataToServer(survey) {\n //var resultAsString = JSON.stringify(survey.data);\n //alert(resultAsString); //send Ajax request to your web server.\n let dataReq = new RequestObj(1, \"/survey\", \"/save/projects/?/context/?\", [projectName, context], [], survey.data);\n userEmail = survey.data.EMAIL1;\n serverSide(dataReq, \"POST\", function () {\n //log.warn(a);\n let asciiMail = \"\";\n for (let i = 0; i < userEmail.length; i++) {\n asciiMail += userEmail[i].charCodeAt(0) + \"-\";\n }\n asciiMail = asciiMail.substring(0, asciiMail.length - 1);\n location.href = window.location.href + \"&userEmail=\" + asciiMail;\n })\n}", "function recent_activity_ajax(category_id,from_date,to_date,request) {\n jQuery(\".loading\").show();\n jQuery.ajax({\n type: \"GET\",\n url: \"/dashboard\",\n data: {\n category_id: category_id,\n from_date: from_date,\n to_date: to_date,\n request: request,\n status: \"tab_ajax\"\n },\n success: function() {\n jQuery(\".loading\").hide();\n\n }\n });\n return false;\n}", "function submitkommentar(){\n\n $(\"#progress\").css(\"display\", \"table-row\");\n\n $.ajax({url: \"/api/lagreKommentar.php\",\n data: {kommentar: $(\"#tekstfelt\").val(),\n dato: new Date().toLocaleDateString(),\n album: albumId,\n bilde: bilde,\n navn: bruker},\n type: \"POST\",\n dataType: \"html\",\n success: function(data){\n $(\"#progress\").css(\"display\", \"none\");\n var commentNode = $.parseHTML(data);\n $(commentNode).find(\".slettkommentar\").click(slettKommentar);\n $(\"#progress\").before(commentNode);\n },\n error: function(a, b){\n $(\"#progress\").css(\"display\", \"none\");\n alert(\"Noe gikk galt, kommentaren ble ikke lagret\");\n }\n });\n }", "function sendEquation() {\n $.ajax({\n type: 'POST',\n url: '/math',\n data: equation,\n success: function() {\n console.log(\"Data sent!\");\n router();\n }\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Highlight download button for user's platform
function highlightOSButton() { var ua = navigator.userAgent; var link; if (ua.indexOf('Win') !== -1) { link = windowsDownloadLink; } else if (ua.indexOf('Mac') !== -1) { link = macDownloadLink; } else if (ua.indexOf('Linux') !== -1) { link = linuxDownloadLink; } if (link) { link.classList.remove('alt'); link.classList.add('strong'); } }
[ "function setupDownloadButton (downloadButton) {\n var buttonData = getButtonData()\n downloadButton.href = buttonData.url\n downloadButton.getElementsByClassName('download-text')[0].textContent = buttonData.text\n for (var i = 0; i < buttonData.icon.length; i++) {\n downloadButton.getElementsByClassName('download-os-icon')[0].classList.add(buttonData.icon[i])\n };\n }", "function updateDownloadButtonState() {\n const menuDownloadPdf = document.getElementById('menu-download-pdf');\n const menuDownloadPng = document.getElementById('menu-download-png');\n\n if (navigator.onLine) {\n if (menuDownloadPdf) menuDownloadPdf.disabled = false;\n if (menuDownloadPng) menuDownloadPng.disabled = false;\n } else {\n if (menuDownloadPdf) menuDownloadPdf.disabled = true;\n if (menuDownloadPng) menuDownloadPng.disabled = true;\n }\n}", "function setDownloadingButtonState($el, contentType) {\r\n if (contentType == liveBackgroundType || contentType == flixelBackgroundType || contentType == liveThemesType) clearInstallContentButtons(contentType);\r\n setInstallButtonClass($el, \"btn-info\");\r\n $(\".av-content-install\").attr(\"data-content-downloading\", false);\r\n $el.attr(\"data-content-downloading\", true);\r\n if (contentType == flixelBackgroundType) $el.text(translate(\"options_tabs_item_buttons_download_flixel\") + \"...\");\r\n else $el.text(translate(\"options_tabs_item_buttons_download\") + \"...\");\r\n}", "setupDownloadingUI() {\n this.downloadStatus = document.getElementById(\"downloadStatus\");\n this.downloadStatus.textContent = DownloadUtils.getTransferTotal(\n 0,\n this.update.selectedPatch.size\n );\n this.selectPanel(\"downloading\");\n this.aus.addDownloadListener(this);\n }", "function hide_download_icons_android(){\r\n if(IsAndroid() === true){\r\n CSSLoad(\"style_hide_download_section.css?v0221\");\r\n CSSLoad(\"style_hide_window_control_section.css?v023\");\r\n\r\n //and hide buttons on mobile devices PDF and XLS save documents\r\n element_id_hide(\"btn_export_pdf_profile\");\r\n element_id_hide(\"btn_export_xls\");\r\n element_id_hide(\"btn_tbl_pdf\");\r\n element_id_hide(\"btn_export_pdf_pp\");\r\n }\r\n}", "function createDownloadButton(memeId) {\n //Create an img element for the picture for the button\n var imgLayer = document.createElement(\"img\");\n\n //Add the download image to the img element\n imgLayer.src = \"download.png\";\n\n //Give a class name to the all the download buttons to style all the download buttons\n imgLayer.className = \"download_button\";\n\n //Create an a element that will allow the user to download the image\n var downloadButton = document.createElement(\"a\");\n\n //Get the children of the li element for this meme\n var childNodes = document.getElementById(memeId).children;\n\n //Set the name of the file that will show when the user downloads the meme\n downloadButton.download = childNodes[1].innerHTML;\n\n //Set the link of the button to the meme\n downloadButton.href = childNodes[0].src;\n\n //Add the button image to the a element and add the download button to the li element\n downloadButton.appendChild(imgLayer);\n document.getElementById(memeId).appendChild(downloadButton);\n}", "function disableDownloadButtons() {\n\t$('.dwnld').prop('disabled', true);\n}", "function saveJsonButton(fileSpec, selector) {\n let parent = document.querySelector(selector);\n let a = document.createElement(\"a\");\n let b = document.createElement(\"button\");\n let uc = encodeURIComponent(fileSpec.data);\n let hr = `data:application/json;charset=utf-8,${uc}`;\n a.setAttribute(\"href\", hr);\n a.setAttribute(\"download\", fileSpec.name);\n a.style.visibility = \"hidden\";\n b.innerHTML = `Download file: ${fileSpec.name}`;\n b.onclick = _ => a.click();\n parent.append(a);\n parent.append(b);\n return;\n}", "function checkArchive ( )\n {\n\tvar title = getElementValue(\"arc_title\");\n\tvar btn = myGetElement(\"btn_download\");\n\t\n\tif ( title && visible.o2 )\n\t{\n\t btn.textContent = \"Create Archive\";\n\t btn.onclick = archiveMainURL;\n\t}\n\t\n\telse\n\t{\n\t btn.textContent = \"Download\";\n\t btn.onclick = downloadMainURL;\n\t}\n }", "function fixDownloadButton() {\n\t\tlet dlBtn = document.getElementsByClassName('dev-page-download');\n\n\t\tfor(let i = 0; i < dlBtn.length; i++) {\n\t\t\tcleanupLink(dlBtn[i]);\n\n\t\t\tif(debug)\n\t\t\t\tconsole.info(scriptName + ': Removed junk from Download-Button');\n\t\t}\n\t}", "function drawDownloadLink (upload) {\n container.innerHTML = `\n <div class=\"heading\">The upload is complete!</div>\n\n <a href=\"${upload.url}\" target=\"_blank\" class=\"button button-primary\">\n Download ${upload.file.name} (${formatBytes(upload.file.size)})\n </a>\n <br />\n or\n <a href=\"#\" id=\"js-reset-demo\">Upload another file</a>\n `\n\n const resetButton = container.querySelector('#js-reset-demo')\n resetButton.addEventListener('click', (event) => {\n event.preventDefault()\n drawFileInput()\n })\n}", "function refreshButtonStyle(button) {\r\r\n $(button).removeClass();\r\r\n\r\r\n var addon = JSON.parse(unescape($(button).data('key')));\r\r\n\r\r\n $(button).addClass(getButtonStyle(addon));\r\t\r // $(button).attr('disabled',true);\r\t\r\n if($(button).attr('class')=='success'){\r\t\r\t$(button).prop('disabled',true); \r\t\r\t}\r\n if (studio.extension.storage.getItem('ERROR') === 'ok') {\r\r\n /// SUCCESS\r\r\n //$(button).text(studio.extension.storage.getItem(addon.name));\r\r\n\r\r\n $(button).off('click');\r\r\n } else {\r\r\n /// ERROR\r\r\n $(button).addClass('error');\r\r\n console.error(studio.extension.storage.getItem('ERROR'));\r\r\n }\r\r\n}", "function showDownloadPageText() {\n\t\treturn \t\"<div style='width: 100%; height: 100%; color: white; background-color: black'>\" +\n\t\t\t\"<div align='center'>\" +\n\t\t\t\"<h2>Widevine Video Optimizer is not installed</h2>\" +\n\t\t\t\"<input type='button' value='Get Video Optimizer' OnClick='javascript: window.open(\\\"http://tools.google.com/dlpage/widevine\\\");'>\" +\n\t\t\t\"</div>\" +\n\t\t\t\"</div>\"\n\t}", "function refresh_icon(){\n var logging_button = jQuery('#crowdlogger-logging-button');\n // Logging is enabled.\n if( CROWDLOGGER.preferences.get_bool_pref('logging_enabled', false ) ){\n logging_button.addClass('crowdlogger-logging-on-button').\n removeClass('crowdlogger-logging-off-button');\n logging_button.html(\n CROWDLOGGER.gui.buttons.current.menu_label_logging_on);\n logging_button.attr('title', \n CROWDLOGGER.gui.buttons.current.logging_on_hover_text);\n // Logging is disabled.\n } else {\n logging_button.removeClass('crowdlogger-logging-on-button').\n addClass('crowdlogger-logging-off-button'); \n logging_button.html(\n CROWDLOGGER.gui.buttons.current.menu_label_logging_off);\n logging_button.attr('title', \n CROWDLOGGER.gui.buttons.current.logging_off_hover_text); \n }\n}", "function addHighlightToButton(id) {\n const element = document.getElementById(id)\n element.classList.add('w3-white')\n}", "function dublincoreChangeState() {\n\tvar tbutton = document.getElementById(\"dublincore-toolbarbutton\");\n\tvar sbutton = document.getElementById(\"dublincore-statusbarbutton\");\n\tif (tbutton) tbutton.disabled = true;\n\tsbutton.disabled = true;\n\t\n\t// quick check of metas\n\tvar metas = window.content.document.getElementsByTagName(\"meta\");\n\tvar links = window.content.document.getElementsByTagName(\"link\");\n\n\tif ((dc_crawler(metas,'name','content',dcElements,'dc.')) ||\n\t\t(dc_crawler(metas,'name','content',dcElementTerms,'dcterms.')) ||\n\t\t(dc_crawler(links,'rel','href',dcElements,'dc.')) ||\n\t\t(dc_crawler(links,'rel','href',dcElementTerms,'dcterms.'))) {\n\n\t\tif (tbutton) tbutton.disabled = false;\n\t\tsbutton.disabled = false;\n\n\t}\n}", "static set toolbarButton(value) {}", "function updateBrowserAction() {\n var buttonTitle = \"Disable Accenture SignOn\";\n var buttonIcon = \"images/icon-48.png\";\n if( getIsACNUserAgentEnabled() == \"false\" ) {\n buttonTitle = \"Enable Accenture SignOn\";\n buttonIcon = \"images/gray-icon-48.png\";\n }\n chrome.browserAction.setTitle({\n title: buttonTitle \n });\n chrome.browserAction.setIcon({\n path: buttonIcon\n });\n}", "function show_wysiwyg_button(cell) {\n cell.element.find(\".wysiwyg-toggle\").show();\n cell.element.find(\".wysiwyg-done\").show();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get All Form Leads
async getLeadAll() { this.props.navigation.navigate('AllLeads', { title: 'All Leads', type: 'multiple', formData: false, selectFromFB: true }) }
[ "function getListFormUrl(l, f) {\n\n\t\tvar thisForm, u;\n\n\t\t$().SPServices({\n\t\t\toperation: \"GetFormCollection\",\n\t\t\tasync: false,\n\t\t\tlistName: l,\n\t\t\tcompletefunc: function (xData, Status) {\n\t\t\t\tu = $(xData.responseXML).find(\"Form[Type='\" + f + \"']\").attr(\"Url\");;\n\t\t\t}\n\t\t});\n\t\treturn u;\n\n\t} // End of function getListFormUrl", "async getAllLessons() {\n const lessonCollection = await lessons();\n const lessonList = await lessonCollection.find({}).toArray();\n return lessonList;\n }", "function save_potential_leads(){\n //Setup Vars\n var potential_leads = [];\n // Access Dom and Pull List of Potential Leads\n let initial_data = document.getElementById('results-list').getElementsByClassName(\"result\");\n\n for (elt of initial_data){\n //Scrape Variables off Page\n name = rid_of_amp(elt.getElementsByClassName(\"name-link\")[0].innerHTML);\n position = rid_of_amp(elt.getElementsByClassName(\"info\")[0].getElementsByTagName('p')[0].innerHTML);\n url = elt.getElementsByClassName(\"image-wrapper\")[0].href;\n\n info = {\n name: name,\n position: position,\n url: url,\n cool: 0\n };\n\n potential_leads.push(info);\n }\n return potential_leads;\n}", "leadList(req, res) {\n\n con.query(\"SELECT * FROM `object_query_22` where ActiveStatus=1\", function(err, result) {\n if (err)\n throw err;\n else {\n\n return res.status(200).json({\n leads: result\n })\n }\n })\n }", "static listByFormId(form_id) {\n return this.queryByFormId(form_id).then((rows) => rows.map((row) => new this(row, false)));\n }", "function getAdGroups(){ \n var adGroups=[];\n var campaignIt = AdWordsApp.campaigns()\n .withCondition(\"Status = ENABLED \")\n .get();\n while(campaignIt.hasNext()){\n var campaign = campaignIt.next();\n var name = campaign.getName();\n if(campaigns[name]){ \n var adGroupIt = campaign.adGroups()\n .withCondition(\"Status = ENABLED\")\n .get();\n while(adGroupIt.hasNext()){\n var adGroup = adGroupIt.next();\n adGroups.push(adGroup); \n }\n }\n }\n return adGroups;\n}", "async function getAdvisoryList(req, res) {\n try {\n const advisoryListResult = await axios(\n \"https://www.travel-advisory.info/api\"\n );\n res.send(advisoryListResult.data.data);\n } catch (err) {\n res.status(500).json({ message: err.message });\n }\n}", "function GetSelectedFields(){\n for (var i = 0; i < fields.selected.length; i++) {\n\n ShowSelectedFieldInputForm(fields.selected., type, id);\n }\n}", "function getDomains() {\n var domains = new Array();\n $(\"#edit-field-domain-access :checked\").each(function(index, obj) {\n domains.push(obj.value);\n });\n setOptions(domains);\n }", "static get flightList() {\n return FlightList;\n }", "static list() {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const contactWebsite = (yield db_1.db.read.columns('*').tables('ContactWebsites').get()).rows;\n return contactWebsite;\n }\n catch (err) {\n throw new Error(err);\n }\n });\n }", "function formToFieldList(formID) {\n let form = document.getElementById(formID).elements;\n let formValues = [];\n\n for (let i = 0; i < form.length; i++) {\n if (form[i].type === 'text') {\n formValues.push(form[i].value)\n }\n if (form[i].type === 'checkbox') {\n formValues.push(form[i].checked)\n }\n }\n return formValues;\n}", "function getFormElementTargets(el) {\n\tvar targets = [el];\n\tif (!el.id.length) return targets;\n\treturn targets.concat(toArr(document.querySelectorAll('label[for=\"' + el.id + '\"]')));\n}", "function addAgenciesToBrowseAll() {\n\t\n\tvar list = document.getElementById(\"agencyList\");\n\tif(!list) {\n\t\treturn;\n\t}\n\t\n\tvar i;\n\tfor(i in agencies) {\n\t\t\n\t\tvar agency = agencies[i];\n\t\tvar a = document.createElement(\"a\");\n\t\ta.href = \"Homepage.php?what=agency&id=\"+i;\n\t\tvar t = document.createTextNode(agency.name);\n\t\ta.appendChild(t);\n\t\tvar li = document.createElement(\"li\");\n\t\tli.appendChild(a);\n\t\tlist.appendChild(li);\n\t}\n}", "static loadFormPages($, ownerDocument, firstFormHTML, progressBar, progressSpan) {\n const requests = [];\n for(let a = 0; a < firstFormHTML.length; a++) {\n const data = firstFormHTML[a];\n // load data from pages for other forms\n const formLinks = $(data, ownerDocument).find('.formeregistration a');\n if(formLinks.length) {\n progressBar['max'] = progressBar['max'] + formLinks.length;\n for(let i = 0; i < formLinks.length; i++) {\n const link = formLinks.eq(i).attr('href');\n const r = DexUtilities.getPokemonDexPage($, link.substring('/dex/'.length))\n .then((formHTML) => {\n progressBar.value = progressBar['value'] + 1;\n progressSpan.textContent = `Loaded ${progressBar['value']} of ${progressBar['max']} Pokemon`;\n return formHTML;\n }, (error) => {\n console.log(error);\n });\n requests.push(r);\n }\n }\n } // for\n\n return Promise.all(requests);\n }", "ListAllConsentCampaignAvailable() {\n let url = `/me/consent`;\n return this.client.request('GET', url);\n }", "function getFormFields(form) {\n const fields = [];\n // Iterate over the form controls\n for (i = 0; i < form.elements.length; i++) {\n const el = form.elements[i];\n if (el.nodeName === 'INPUT' ||\n el.nodeName === 'SELECT' ||\n el.nodeName === 'TEXTAREA') {\n fields.push(el);\n }\n }\n return fields;\n }", "function getKeywords(){ \n var keywords={};\n var campaignIt = AdWordsApp.campaigns()\n .withCondition(\"Status = ENABLED \")\n .get();\n while(campaignIt.hasNext()){\n var campaign = campaignIt.next();\n var name = campaign.getName();\n if(campaigns[name]){\n var keywordIt = campaign.keywords()\n .get();\n \n while(keywordIt.hasNext()){\n var keyword = keywordIt.next();\n var id=keyword.getId().toString();\n keywords[id]=keyword; \n }\n }\n }\n return keywords;\n}", "findAll() {\n return new Promise((resolve, reject) => {\n let results = []\n\n base('Recipients')\n .select()\n .eachPage(\n (records, fetchNextPage) => {\n results = [...results, ...records]\n fetchNextPage()\n },\n async (err) => {\n if (err) return reject(err)\n resolve(results)\n }\n )\n })\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GLOBAL SCOPE // AJAX REQUEST TO TURN THE MARKERS ON AND OFF FOR EACG SET checks to see of the film title is in the turned on array if it is off, adds a marker to say that this film is turned on, calls ajax to get the data. success function calls the setpoints function in the map and sends the map point, the icon, the array index for remove markers, and the object from SQL if if is off it calls the remove markers function to take off the markers, and splices the films from the off or on index
function ajax_request_to_turn_markers_on_and_off(film,trigger) { if (filmsTurnedOn.indexOf(film) == -1) { // Asks if the film is not in the on/off array trigger.style.color = "rgb(231,174,24)"; // Takes the trigger link and changes the color to gold filmsTurnedOn.push(film); // pushes the film to the on array arrayIndex = filmsTurnedOn.indexOf(film); // Takes the index for the remove array $.ajax({ type:"POST", url: "ajax_call_for_all_locations_of_film.php", data: {'film':film}, success: function(result){ result = JSON.parse(result); for (i = 0; i < result.length; i++) { var point = new google.maps.LatLng(result[i].setting_lat, result[i].setting_lng); setPoints(point,'img/mapicon.png', arrayIndex, result[i]); // Calls the set points function } }}); } else if (filmsTurnedOn.indexOf(film) != -1) { // Asks if the film is not in the on/off array trigger.style.color = "rgb(70,75,71)"; // Takes the trigger link and changes the color to black arrayIndex = filmsTurnedOn.indexOf(film); // Takes the index for the remove array removeMarkers(removeArrays[arrayIndex]); // Calls the remove markers function filmsTurnedOn[arrayIndex] = null; // Turns the film index to null } }
[ "function waldoCarmen(){\n var request = xmlReq();\n request.open(\"GET\",\n \"http://messagehub.herokuapp.com/a3.json\",\n true);\n request.send();\n request.onreadystatechange = function(){\n if(request.readyState === 4 && request.status === 200){\n var locs = JSON.parse(request.responseText);\n for(var i = 0; i < 2; i++){\n if(typeof locs[i] != 'undefined'){\n var name = locs[i][\"name\"];\n WCpos[name] = new google.maps.LatLng(\n locs[i][\"loc\"][\"latitude\"],locs[i][\"loc\"][\"longitude\"]);\n var marker = new google.maps.Marker({\n position:WCpos[name],\n map:map});\n marker.setIcon(\"carmen.png\");\n marker.setTitle(name);\n if(name == \"Waldo\"){\n marker.setIcon(\"waldo.png\");\n }\n marker.setVisible(true);\n createWindow(marker,name);\n windows[name].setContent(locs[i][\"loc\"][\"note\"]);\n }\n }\n }\n }\n}", "function updateMap() {\n\tif (myKeyWords == \"\") {\n\t\tfor (var i = 0; i < MAX_K; i++){\n\t\t\tkNearMarkers[i].setVisible(false);\n\t\t}\n\t\treturn ;\n\t}\n\t$.post(\"/search/\", {\n\t\tuserPos:myMarker.getPosition().toUrlValue(),\n\t\tkeyWords:myKeyWords,\n\t}, function(data, status){\n\t\t/* Cancel all the old k-near-markers */\n\t\tfor (var i = 0; i < MAX_K; i++){\n\t\t\tkNearMarkers[i].setVisible(false);\n\t\t}\n\t\t\n\t\t/* Return result from django backend */\n\t\tvar dataJSON = $.parseJSON(data);\n\t\t\n\t\t$(\"#BestMap\").attr(\"src\", dataJSON.BestMap);\n\t\t\n\t\t/* Display the new k-near-markers*/\n\t\t$.each(dataJSON.Pos, function(i, item){\n\t\t\tif (i < MAX_K){\n\t\t\t\t//alert(item.Lat + ';' + item.Lng);\n\t\t\t\tkNearMarkers[i].setPosition({lat:item.Lat, lng:item.Lng});\n\t\t\t\tkNearMarkers[i].setVisible(true);\n\t\t\t\tkNearMarkers[i].setTitle(item.Name + \"\\nAddr: \" + item.Addr \n\t\t\t\t+ \".\\nPCode: \" + item.Pcode);\n\t\t\t\t\n\t\t\t\tif (i < MAX_PANEL) {\n\t\t\t\t\t$(\"#name\"+i).text(item.Name);\n\t\t\t\t\t$(\"#info\"+i).text(\"Address: \" + item.Addr + \". PCode: \" + item.Pcode);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t//$( \"#rtnMsg\" ).text( data );\n\t});\n\t//$( \"#test_input\" ).text( this.value );\n}", "function openMarkers(){\n infoWindow.setContent(info);\n animation();\n infoWindow.open(map,marker)\n }", "function refreshMarkers(data) {\n\n // remove all currently visible markers\n clearMarker(markersArray);\n\n // parse the AIS data to extract the vessels\n var vessels = parseXml(data);\n\n // create and return GoogleMaps markers for each of the extracted vessels\n jQuery.extend(true, markersArray, convertToGoogleMarkers(map,vessels));\n\n}", "function markMap()\n\t{\n\t\tstrResult=req.responseText;\n\n\t\tfltLongitude=getValue(\"<Longitude>\",\"</Longitude>\",11);\n\t\tfltLatitude=getValue(\"<Latitude>\",\"</Latitude>\",10);\n\t\tif( fltLongitude==\"\" || fltLatitude==\"\")\n\t\t{\n\t\t\tshowSearchResultsError('No information found',\"WARNING\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// First Clear any Previous Error Messages \t\n\t\t\tdocument.getElementById(\"divMapErrorBox\").innerHTML=\"\";\n\t\t\tdocument.getElementById(\"divMapErrorBox\").style.visibility=\"visible\";\n\t\t\t\n\t\t\t// Create Html \n\t\t\tstrHtml=\"<table cellspacing=0 cellpadding=0 border=0>\";\n\t\t\tstrHtml=strHtml+\"<tr><td align=right><b>Longitude:</b></td><td width=5></td><td>\"+fltLongitude+\"</td>\";\n\t\t\tstrHtml=strHtml+\"<tr><td align=right><b>Latitude:</b></td><td width=5></td><td>\"+fltLatitude+\"</td>\";\n\t\t\tstrHtml=strHtml+\"</table>\";\n\t\t\t\n\t\t\t// Save Location in Global Variables \n\t\t\t//G_CURRENT_POINT=new YGeoPoint(fltLatitude,fltLongitude);\n\t\t\t\n\t\t\t//Show Marker \n\t \t showMarker(fltLatitude, fltLongitude,13,\"\",strHtml);\n\t \t \n\t \t //document.getElementById('mapContainer').innerHTML=\"Problems ..........\";\n\t\t} \n\t}", "function setMarkers(location) {\n\n for (i = 0; i < location.length; i++) {\n location[i].holdMarker = new google.maps.Marker({\n position: new google.maps.LatLng(location[i].lat, location[i].lng),\n map: map,\n title: location[i].title,\n icon: {\n url: 'img/marker.png',\n size: new google.maps.Size(25, 40),\n origin: new google.maps.Point(0, 0),\n anchor: new google.maps.Point(12.5, 40)\n },\n shape: {\n coords: [1, 25, -40, -25, 1],\n type: 'poly'\n }\n });\n\n //function to place google street view images within info windows\n //determineImage();\n getFlickrImages(location[i]);\n //Binds infoWindow content to each marker\n //Commented for testing\n // location.contentString = '<img src=\"' + streetViewImage +\n // '\" alt=\"Street View Image of ' + location.title + '\"><br><hr style=\"margin-bottom: 5px\"><strong>' +\n // location.title + '</strong><br><p>' +\n // location.cityAddress + '<br></p><a class=\"web-links\" href=\"http://' + location.url +\n // '\" target=\"_blank\">' + location.url + '</a>';\n\n //Testing flickr out (not yet)\n\n\n var infowindow = new google.maps.InfoWindow({\n content: arrayMarkers[i].contentString\n });\n\n //Click marker to view infoWindow\n //zoom in and center location on click\n new google.maps.event.addListener(location[i].holdMarker, 'click', (function(marker, i) {\n return function() {\n numb = i;\n infowindow.setContent(location[i].contentString);\n infowindow.open(map, this);\n var windowWidth = $(window).width();\n if (windowWidth <= 1080) {\n map.setZoom(14);\n } else if (windowWidth > 1080) {\n map.setZoom(16);\n }\n map.setCenter(marker.getPosition());\n location[i].picBoolTest = true;\n };\n })(location[i].holdMarker, i));\n\n //Click nav element to view infoWindow\n //zoom in and center location on click\n var searchNav = $('#nav' + i);\n searchNav.click((function(marker, i) {\n return function() {\n infowindow.setContent(location[i].contentString);\n infowindow.open(map, marker);\n map.setZoom(16);\n map.setCenter(marker.getPosition());\n location[i].picBoolTest = true;\n };\n })(location[i].holdMarker, i));\n }\n}", "changeMarker() {\n\t\t_.forEach(this.markers, (a) => a.style.display = this.saved ? 'inline' : '');\n\t}", "function addPlane(data) {\n //create latitude and longitude\n var lls = new google.maps.LatLng(parseFloat(data[\"latitude\"]), parseFloat(data[\"longitude\"]));\n\n //var image = \"http://wz5.resources.weatherzone.com.au/images/widgets/nav_trend_steady.gif\";\n\n var image = imgs[(Math.round(data[\"heading\"] / 10) % 36).toString()]; //\"http://abid.a2hosted.com/plane\" + Math.round(data[\"heading\"] / 10) % 36 + \".gif\";\n //create the marker, attach to map\n var m = new google.maps.Marker({\n position: lls,\n map: map,\n icon: image\n });\n\n m.addListener('click', function() {\n //if clicked then show info\n hideHoverWindow();\n selected_plane = data[\"id\"];\n showSelectedInfo();\n });\n\n\n m.addListener('mouseover', function() {\n //only if no airport is clicked upon, then show the hover for this\n showHoverWindow(prettifyPlaneData(data));\n\n //Get origin and destination locations\n for (var j = 0; j < latest_json[0].length; j++) {\n if (latest_json[0][j][\"id\"] === data[\"depairport_id\"]) {\n d_coord = {lat: latest_json[0][j][\"latitude\"], lng: latest_json[0][j][\"longitude\"]};\n }\n if (latest_json[0][j][\"id\"] === data[\"arrairport_id\"]) {\n a_coord = {lat: latest_json[0][j][\"latitude\"], lng: latest_json[0][j][\"longitude\"]};\n }\n }\n //Current plane position\n var plane_coord = {\n lat: parseFloat(data[\"latitude\"]),\n lng: parseFloat(data[\"longitude\"])\n };\n var flightPlanCoordinates = [d_coord];\n\n for (var j = 0; j < data[\"detailedroute\"].length; j++) {\n var tmppush = {\n lat: parseFloat(data[\"detailedroute\"][j][1]),\n lng: parseFloat(data[\"detailedroute\"][j][2])\n };\n\n var added_plane = false;\n //See if plane is in a box from prev location to curr location\n //if so, a line to it should be drawn\n var prev_point_lat = flightPlanCoordinates[flightPlanCoordinates.length - 1]['lat'];\n var prev_point_lng = flightPlanCoordinates[flightPlanCoordinates.length - 1]['lng'];\n var curr_point_lat = tmppush['lat'];\n var curr_point_lng = tmppush['lng'];\n\n //Define Bounding Box, we will check if plane is within this box!\n var latLogBox = {\n ix : (Math.min(prev_point_lng, curr_point_lng)) - 0,\n iy : (Math.max(prev_point_lat, curr_point_lat)) + 0,\n ax : (Math.max(prev_point_lng, curr_point_lng)) + 0,\n ay : (Math.min(prev_point_lat, curr_point_lat)) - 0\n };\n\n if ((plane_coord.lat <= latLogBox.iy && plane_coord.lat >= latLogBox.ay) && (latLogBox.ix <= plane_coord.lng && plane_coord.lng <= latLogBox.ax) && added_plane === false) {\n //Plane is within bounds, let try pushing it\n added_plane = true;\n flightPlanCoordinates.push(plane_coord);\n }\n flightPlanCoordinates.push(tmppush);\n }\n\n //add arrival airport coordinates\n flightPlanCoordinates.push(a_coord);\n\n\n flightPath = new google.maps.Polyline({\n path: flightPlanCoordinates,\n geodesic: false,\n strokeColor: '#0000FF',\n strokeOpacity: 1.0,\n strokeWeight: 2,\n map: map\n });\n });\n\n m.addListener('mouseout', function() {\n //if nothing has been clicked on, then hide the info window (ALSO SEE CONFIGURE FUNCTION FOR CLICK EVENT LISTERNERS!)\n flightPath.setMap(null);\n $(\".hoverwindow\").css(\"display\", \"none\");\n });\n //add current marker to airports array\n planes.push(m);\n\n //Update online table\n $(\"#tablefilterpilot tbody\").append(\"<tr><td class='hidden'>\" + data['id'] + \"</td><td class='hidden'>\" + data['airline_name'] + \"</td><td><a href=\\\"#\\\" onclick=\\\"centerMap(\"+data['id']+\", 2)\\\">\"+data['callsign']+\"</a></td><td>\"+data['real_name']+\"</td><td>\"+data['depairport']+\"</td><td>\"+data['arrairport']+\"</td></tr>\");\n}", "function load_map() {\n\tmap = new L.Map('map', {zoomControl: true});\n\n\t// from osmUrl we can change the looks of the map (make sure that any reference comes from open source data)\n\tvar osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',\n\t// var osmUrl = 'https://tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png',\n\t\tosmAttribution = 'Map data &copy; 2012 <a href=\"http://openstreetmap.org\">OpenStreetMap</a> contributors',\n\t\tosm = new L.TileLayer(osmUrl, {maxZoom: 18, attribution: osmAttribution});\n\n\n\t// define the center and zoom level when loading the page (zoom level 3 allows for a global view)\n\tmap.setView(new L.LatLng(20, 10), 3).addLayer(osm);\n\n\n\t$.ajax({\n\t\turl: 'js/doe.csv',\n\t\tdataType: 'text/plain',\n\t}).done(successFunction);\n\n\tfunction successFunction(data) {\n\t\tvar planes = data.split('/\\r?\\n|\\r/');\n\t\tconsole.log(planes);\n\n\t\t// for (var i = 0; i < planes.length; i++) {\n\t\t// \tvar markersplit = planes[i].split(',');\n\t\t// \tmarker = new L.marker([markersplit[3],markersplit[4]]).bindPopup(markersplit[0]).addTo(map);\n\t\t// }\n\n\t}\n\n\n\t// variable to allow to read the points from above and pass that to the marker rendering function\n\n\n\n\t// create layer with all the markers to turn on and off (maybe no need for this)\n\t// var overlayMaps = {\n\t// \t\"Cities\" : marker\n\t// }\n\t// L.control.layers(overlayMaps).addTo(map);\n\n\n}", "function searchMarkers() {\n var manufacturer = document.getElementById(\"manufacturerSelect\").value;\n var model = document.getElementById(\"modelSelect\").value;\n\n // if model is set to all, all vehicle models will be displayed\n // for the chosen manufacturer\n if (model === \"All\") {\n $.ajax({\n url:\"/objectmapper/public/searcManufacturerhMarkers/\"+manufacturer,\n type:\"GET\",\n success:function(data){\n $(\"#clearButton\").remove(); \n $('#search_vehicles_list').empty();\n hideMarkers(markersArray);\n $('#searchDiv').append(\"<button id='clearButton' class='btn btn-sm btn-warning' onclick='displayMarkers(); resetFilters()'>Clear search</button>\");\n //Handle Data\n console.log(data);\n var data = JSON.parse(data);\n\n $.each(data , function(key,value){\n\n if (value.manufacturer === \"Audi\") {\n var marker = new google.maps.Marker({\n //position: parseFloat(value.lat)+parseFloat(value.lng),\n position: {lat: value.lat, lng: value.lng},\n map:map,\n draggable: true,\n icon: yellow_MarkerA,\n title: value.manufacturer + \" \" + value.model + '\\n' + value.registration,\n });\n }\n\n if (value.manufacturer === \"Mercedes-Benz\") {\n var marker = new google.maps.Marker({\n //position: parseFloat(value.lat)+parseFloat(value.lng),\n position: {lat: value.lat, lng: value.lng},\n map:map,\n draggable: true,\n icon: pink_MarkerM,\n title: value.manufacturer + \" \" + value.model + '\\n' + value.registration,\n });\n }\n\n if (value.manufacturer === \"Skoda\") {\n var marker = new google.maps.Marker({\n //position: parseFloat(value.lat)+parseFloat(value.lng),\n position: {lat: value.lat, lng: value.lng},\n map:map,\n draggable: true,\n icon: darkgreen_MarkerS,\n title: value.manufacturer + \" \" + value.model + '\\n' + value.registration,\n });\n }\n\n if (value.manufacturer === \"Volkswagen\") {\n var marker = new google.maps.Marker({\n //position: parseFloat(value.lat)+parseFloat(value.lng),\n position: {lat: value.lat, lng: value.lng},\n map:map,\n draggable: true,\n icon: blue_MarkerV,\n title: value.manufacturer + \" \" + value.model + '\\n' + value.registration,\n });\n }\n\n\n var infoWindow = new google.maps.InfoWindow({\n content: '<div id=\"windowContent\" class=\"windowContent\"><div id=\"infoDiv\" class=\"infoDiv\"><h4 class=\"id\" hidden>'+ value.id +'</h4>'\n +'<h4 class=\"manufacturer\">' + value.manufacturer + '</h4>' \n + '<h4 class=\"model\">' + value.model + '</h4>' \n + '<h4 class=\"year\">' + value.year + '</h4>' \n + '<h4 class=\"price\">' + value.price + '</h4>' \n +'<h4 class=\"registration\">' + value.registration + '</h4>'\n + \"<h4 class='lat' hidden>\" + value.lat + \"</h4>\" \n + \"<h4 class='lng' hidden>\" + value.lng + \"</h4>\"\n + '<form id=\"deleteForm\" class=\"deleteForm\" action=\"/objectmapper/public/destroy/'+value.id\n +'\" method=\"DELETE\">' \n + '<input type=\"submit\" value=\"Delete\"</input>' \n + '</form>' +'</h4></div>'\n + '<input type=\"button\" id=\"toggleEditButton\" value=\"Toggle Edit\" onclick=\"toggleEdit()\"</input>'\n + '</div>'\n + '</div>'\n + '<div id=\"testEditForm\" class=\"testEditForm\" style=\"display: none\">'\n + '<form id=\"editForm\" action=\"/objectmapper/public/update/'+value.id+'\" method=\"POST\">'\n + '<table class=\"table-responsive\">'\n + '<h4 class=\"editId\" hidden>'+ value.id +'</h4>'\n + '<tr><td><input name=\"editManufacturer\" class=\"editManufacturer\" value=\"' + value.manufacturer + '\"></input></td></tr>'\n + '<tr><td><input name=\"editModel\" class=\"editModel\" value=\"' + value.model + '\"></input></td></tr>'\n + '<tr><td><input name=\"editYear\" class=\"editYear\" value=\"' + value.year + '\"></input></td></tr>'\n + '<tr><td><input name=\"editPrice\" class=\"editPrice\" value=\"' + value.price + '\"></input></td></tr>'\n + '<tr><td><input name=\"editRegistration\" class=\"editRegistration\" value=\"' + value.registration + '\"></input></td></tr>'\n + '<tr><td><textarea type=\"text\" class=\"editDescription\" name=\"editDescription\">\"' + value.description +'\"></textarea></td></tr>'\n + '<tr><td><input name=\"editLat\" class=\"editLat\" value=\"' + value.lat + '\"></input></td></tr>'\n + '<tr><td><input name=\"editLng\" class=\"editLng\" value=\"' + value.lng + '\"></input></td></tr>'\n + '<tr><td><input type=\"button\" id=\"toggleEditButton\" value=\"Toggle Edit\" onclick=\"toggleEdit()\"</input></td></tr>' \n + '<tr><td><input type=\"submit\" id=\"updateButton\" value=\"Update\"</input></td></tr>' \n + '</table>'\n + '<input type=\"hidden\" name=\"_token\" value=\"'+csrf_token.value+'\"></input>'\n + '</form>' \n + '</div>'\n\n }); \n\n google.maps.event.addListener(marker, 'click', function() {\n infoWindow.open(map, marker);\n }) \n\n // close info window if map is clicked\n google.maps.event.addListener(map, 'click', function() {\n infoWindow.close(map, marker);\n })\n // part of search \n markersArray.push(marker);\n\n\n // vehicles list is filtered based on the search paramaters from the dropdowns \n $('#vehicles_list').hide();\n\n $('#search_vehicles_list').append(\"<p hidden>\" + value.id + \"</p>\" \n + \"<button id='markerLink' class='linkButton' onclick='linkMarkers(this.value); displayClearButton();' value='\"+ value.id +\"'>\" + value.manufacturer \n + \"</button>\" + \" \" + value.model \n + \"<div class='col-md-13'>Price: \" + value.price + \"</div>\" \n + \"<div class='col-md-13'> Registration: \" + value.registration + \"</div>\"\n + \"<div class='col-md-13'> Last updated: \" + value.updated_at + \"</div>\"\n + \"<div id='item' class='item'><button class='linkButton toggleDiv' id='atest'>Description</button>\"\n + \"<div id='description_collapse' class='description'>\" + value.description + \"</div></div>\" + \"<br>\").show();\n\n });\n\n // handles hide toggle for list descriptions \n $('.item div').hide();\n $('.item button').click(function(){\n\n // hide all span\n var $this = $(this).parent().find('div.description');\n // var $this = $(this).next('div.description');\n $(\".item div.description\").not($this).hide();\n\n $this.slideToggle(\"slow\").complete();\n });\n\n // $('#search_vehicles_list').hide();\n // $('#vehicles_list').\n },\n error:function(data){\n alert('Failed: Check search paramaters');\n }\n });\n}\n // else if model is not set to \"All\", the chosen model will be displayed on the map \n else{ \n $.ajax({\n url:\"/objectmapper/public/searchMarkers/\"+manufacturer+\"/\"+model,\n type:\"GET\",\n success:function(data){\n $(\"#clearButton\").remove(); \n $('#search_vehicles_list').empty();\n $('#vehicles_list').show();\n hideMarkers(markersArray);\n $('#searchDiv').append(\"<button id='clearButton' class='btn btn-sm btn-warning' onclick='displayMarkers(); resetFilters()'>Clear search</button>\");\n //Handle Data\n console.log(data);\n var data = JSON.parse(data);\n if (data <= 0) {\n alert(\"Vehicle does not exist.\");\n displayMarkers();\n $('#search_vehicles_list').hide();\n }\n $.each(data , function(key,value){\n\n if (value.manufacturer === \"Audi\") {\n var marker = new google.maps.Marker({\n //position: parseFloat(value.lat)+parseFloat(value.lng),\n position: {lat: value.lat, lng: value.lng},\n map:map,\n draggable: true,\n icon: yellow_MarkerA,\n title: value.manufacturer + \" \" + value.model + \" \" + value.registration,\n });\n }\n\n if (value.manufacturer === \"Mercedes-Benz\") {\n var marker = new google.maps.Marker({\n //position: parseFloat(value.lat)+parseFloat(value.lng),\n position: {lat: value.lat, lng: value.lng},\n map:map,\n draggable: true,\n icon: pink_MarkerM,\n title: value.manufacturer + \" \" + value.model + \" \" + value.registration,\n });\n }\n\n if (value.manufacturer === \"Skoda\") {\n var marker = new google.maps.Marker({\n //position: parseFloat(value.lat)+parseFloat(value.lng),\n position: {lat: value.lat, lng: value.lng},\n map:map,\n draggable: true,\n icon: darkgreen_MarkerS,\n title: value.manufacturer + \" \" + value.model + \" \" + value.registration,\n });\n }\n\n if (value.manufacturer === \"Volkswagen\") {\n var marker = new google.maps.Marker({\n //position: parseFloat(value.lat)+parseFloat(value.lng),\n position: {lat: value.lat, lng: value.lng},\n map:map,\n draggable: true,\n icon: blue_MarkerV,\n title: value.manufacturer + \" \" + value.model + \" \" + value.registration,\n });\n }\n\n\n\n var infoWindow = new google.maps.InfoWindow({\n content: '<div id=\"windowContent\" class=\"windowContent\"><div id=\"infoDiv\" class=\"infoDiv\"><h4 class=\"id\" hidden>'+ value.id +'</h4>'\n +'<h4 class=\"manufacturer\">' + value.manufacturer + '</h4>' \n + '<h4 class=\"model\">' + value.model + '</h4>' \n + '<h4 class=\"year\">' + value.year + '</h4>' \n + '<h4 class=\"price\">' + value.price + '</h4>' \n +'<h4 class=\"registration\">' + value.registration + '</h4>'\n + \"<h4 class='lat' hidden>\" + value.lat + \"</h4>\" \n + \"<h4 class='lng' hidden>\" + value.lng + \"</h4>\"\n + '<form id=\"deleteForm\" class=\"deleteForm\" action=\"/objectmapper/public/destroy/'+value.id\n +'\" method=\"DELETE\">' \n + '<input type=\"submit\" value=\"Delete\"</input>' \n + '</form>' +'</h4></div>'\n + '<input type=\"button\" id=\"toggleEditButton\" value=\"Toggle Edit\" onclick=\"toggleEdit()\"</input>'\n + '</div>'\n + '</div>'\n + '<div id=\"testEditForm\" class=\"testEditForm\" style=\"display: none\">'\n + '<form id=\"editForm\" action=\"/objectmapper/public/update/'+value.id+'\" method=\"POST\">'\n + '<table class=\"table-responsive\">'\n + '<h4 class=\"editId\" hidden>'+ value.id +'</h4>'\n + '<tr><td><input name=\"editManufacturer\" class=\"editManufacturer\" value=\"' + value.manufacturer + '\"></input></td></tr>'\n + '<tr><td><input name=\"editModel\" class=\"editModel\" value=\"' + value.model + '\"></input></td></tr>'\n + '<tr><td><input name=\"editYear\" class=\"editYear\" value=\"' + value.year + '\"></input></td></tr>'\n + '<tr><td><input name=\"editPrice\" class=\"editPrice\" value=\"' + value.price + '\"></input></td></tr>'\n + '<tr><td><input name=\"editRegistration\" class=\"editRegistration\" value=\"' + value.registration + '\"></input></td></tr>'\n + '<tr><td><textarea type=\"text\" class=\"editDescription\" name=\"editDescription\">\"' + value.description +'\"></textarea></td></tr>'\n + '<tr><td><input name=\"editLat\" class=\"editLat\" value=\"' + value.lat + '\"></input></td></tr>'\n + '<tr><td><input name=\"editLng\" class=\"editLng\" value=\"' + value.lng + '\"></input></td></tr>'\n + '<tr><td><input type=\"button\" id=\"toggleEditButton\" value=\"Toggle Edit\" onclick=\"toggleEdit()\"</input></td></tr>' \n + '<tr><td><input type=\"submit\" id=\"updateButton\" value=\"Update\"</input></td></tr>' \n + '</table>'\n + '<input type=\"hidden\" name=\"_token\" value=\"'+csrf_token.value+'\"></input>'\n + '</form>' \n + '</div>'\n\n }); \n\n google.maps.event.addListener(marker, 'click', function() {\n infoWindow.open(map, marker);\n }) \n\n // close info window if map is clicked\n google.maps.event.addListener(map, 'click', function() {\n infoWindow.close(map, marker);\n })\n // part of search \n markersArray.push(marker);\n\n\n // vehicles list is filtered based on the search paramaters from the dropdowns \n $('#vehicles_list').hide();\n\n $('#search_vehicles_list').append(\"<p hidden>\" + value.id + \"</p>\" \n + \"<button id='markerLink' class='linkButton' onclick='linkMarkers(this.value); displayClearButton();' value='\"+ value.id +\"'>\" + value.manufacturer \n + \"</button>\" + \" \" + value.model \n + \"<div class='col-md-13'>Price: \" + value.price + \"</div>\" \n + \"<div class='col-md-13'> Registration: \" + value.registration + \"</div>\"\n + \"<div class='col-md-13'> Last updated: \" + value.updated_at + \"</div>\"\n + \"<div id='item' class='item'><button class='linkButton toggleDiv' id='atest'>Description</button>\"\n + \"<div id='description_collapse' class='description'>\" + value.description + \"</div></div>\" + \"<br>\").show();\n\n });\n\n // handles hide toggle for list descriptions \n $('.item div').hide();\n $('.item button').click(function(){\n\n // hide all span\n var $this = $(this).parent().find('div.description');\n // var $this = $(this).next('div.description');\n $(\".item div.description\").not($this).hide();\n\n $this.slideToggle(\"slow\").complete();\n });\n\n // $('#search_vehicles_list').hide();\n // $('#vehicles_list').\n },\n error:function(data){\n alert('Failed: Check search paramaters');\n }\n });\n}\n}", "function toggleScrapingMarkers() {\n if (scrapingMarkersVisible) {\n scrapingMarkersGroup.remove();\n $('#scrapingLegendLabel').css('text-decoration', 'line-through');\n scrapingMarkersVisible = false;\n } else {\n scrapingMarkersGroup.addTo(mymap);\n $('#scrapingLegendLabel').css('text-decoration', 'none');\n scrapingMarkersVisible = true;\n }\n}", "function placeMarkers() {\n\n //custom image for the marker\n var image = {\n url: 'place_marker.png',\n // This marker is 24 pixels wide by 24 pixels high.\n scaledSize: new google.maps.Size(24, 24),\n // The origin for this image is (0, 0).\n origin: new google.maps.Point(0, 0)\n };\n //Defines the clickable region of the icon (ie not the transparent outer part)\n var shape = {\n coords: [1, 1, 1, 20, 20, 20, 20, 1],\n type: 'poly'\n };\n\n //for each station create the marker on the map and add a listener\n for (var key in Stations) {\n marker = new google.maps.Marker({\n position: Stations[key].position,\n map: map,\n icon: image,\n shape: shape,\n title: Stations[key].name\n });\n marker.addListener('click', function() {\n displaySubwayStation(this);\n });\n\n };\n\n}", "function addRouteMarkers() {\n\n // Add start location\n map.addMarker({\n lat: startLocation[0],\n lng: startLocation[1],\n title: \"Start Location: \" + startLocation[2],\n icon: \"images/start.png\"\n });\n\n // Add end location\n if (endLocation != startLocation) {\n map.addMarker({\n lat: endLocation[0],\n lng: endLocation[1],\n title: \"End Location: \" + endLocation[2],\n icon: \"images/end.png\"\n });\n }\n\n // Add all path markers\n for (var i = 0; i < path.length; i++) {\n map.addMarker({\n lat: path[i][0],\n lng: path[i][1],\n title: path[i][2],\n icon: markers[i],\n infoWindow: {\n content: \"<p>\" + path[i][2] + \"</p><p><input onclick='search([\" + path[i][0] + \",\" + path[i][1] + \"], \\\"\\\")'\" + \" type='button' value='Search Nearby'></p>\" + \n \"<span id='marker' class='delete' onclick='cancelStopMarker(\\\"\" + path[i][2] + \"\\\")'><img src='images/cancel.png' alt='cancel' /></span>\"\n }\n });\n }\n\n fitMap();\n}", "async function updateMarkers() {\n if (markerListCache.length > 0) {\n markerListCache.forEach((item) => {\n if (jQuery(`#events ul #${item.id}`).length === 0) {\n jQuery(\n `<li id=${item.id\n }><b><a href=\"#\" class=\"time-marker\">${item.time_marker\n }</a></b>${item.name\n }</li>`,\n ).appendTo('#events ul');\n }\n });\n } else {\n $.ajax({\n type: 'GET',\n url: `${baseRemoteURL}markers`,\n dataType: 'json',\n async: true,\n cache: true,\n success(data) {\n markerListCache = data;\n data.forEach((item) => {\n if (jQuery(`#events ul #${item.id}`).length === 0) {\n jQuery(\n `<li id=${item.id\n }><b><a href=\"#\" class=\"time-marker\">${item.time_marker\n }</a></b>${item.name\n }</li>`,\n ).appendTo('#events ul');\n }\n });\n },\n });\n }\n jQuery('.time-marker').on('click', function () {\n jumpToTime(this.text);\n johng.updateClock();\n johng.play();\n });\n}", "function loadMap( a,z ) {\n\t\n\tgo();\n\t\n\n\tfunction ready() {\n\t\tsetTimeout( function() {\n\t\t\tvar only = ! vote.info || ! vote.info.latlng;\n\t\t\tif( home.info && home.info.latlng )\n\t\t\t\tsetMarker({\n\t\t\t\t\tplace: home,\n\t\t\t\t\timage: 'marker-green.png',\n\t\t\t\t\topen: only,\n\t\t\t\t\thtml: ! only ? formatHome(true) : vote.htmlInfowindow || formatHome(true)\n\t\t\t\t});\n\t\t\tif( vote.info && vote.info.latlng )\n\t\t\t\tmap.setCenter( vote.info.latlng );\n\t\t\t\tsetMarker({\n\t\t\t\t\tplace: vote,\n\t\t\t\t\thtml: vote.htmlInfowindow,\n\t\t\t\t\topen: true,\n\t\t\t\t\tzIndex: 1\n\t\t\t\t});\n\t\t}, 500 );\n\t\t\n\t}\n\t\n\tfunction setMarker( a ) {\n\t\tif(a != null && a.place != null && a.place.info != null && a.place.info.latlng){\n\t\t\tvar mo = {\n\t\t\t\tposition: a.place.info.latlng\n\t\t\t};\n\t\t}\n\t\tif( a.image ) mo.icon = imgUrl( a.image );\n\t\tvar marker = a.place.marker = new gm.Marker( mo );\n\t\taddOverlay( marker );\n\t\tgme.addListener( marker, 'click', function() {\n\t\t\tif( balloon ) openBalloon();\n\t\t\telse selectTab( '#detailsbox' );\n\t\t});\n\t\tif( balloon ) openBalloon();\n\t\t\n\t\tfunction openBalloon() {\n\t\t\tvar iw = new gm.InfoWindow({\n\t\t\t\tcontent: $(a.html)[0],\n\t\t\t\tmaxWidth: Math.min( $map.width() - 100, 350 ),\n\t\t\t\tzIndex: a.zIndex || 0\n\t\t\t});\n\t\t\tiw.open( map, marker );\n\t\t}\n\t}\n\t\n\tfunction go() {\n\t\t\n\t\n\t\tsetVoteHtml();\n\t\t\n\t\tvar homeLatLng = home && home.info && home.info.latlng;\n\t\tvar voteLatLng = vote && vote.info && vote.info.latlng;\n\t\t\n\t\t$tabs.html( tabLinks( initialMap() ? '#mapbox' : '#detailsbox' ) );\n\t\tif( ! sidebar ) $map.css({ visibility:'hidden' });\n\t\tsetLayout();\n\t\tif( initialMap() ) {\n\t\t\t$map.show().css({ visibility:'visible' });\n\t\t\tif( ! sidebar ) $detailsbox.hide();\n\t\t}\n\t\telse {\n\t\t\tif( ! sidebar ) $map.hide();\n\t\t\t$detailsbox.show();\n\t\t}\n\t\t\n\t\tif( homeLatLng && voteLatLng ) {\n\t\t\tnew gm.DirectionsService().route({\n\t\t\t\torigin: homeLatLng,\n\t\t\t\tdestination: voteLatLng,\n\t\t\t\ttravelMode: gm.TravelMode.DRIVING\n\t\t\t}, function( result, status ) {\n\t\t\t\tif( status != 'OK' ) return;\n\t\t\t\tvar route = result.routes[0];\n\t\t\t\tmap.fitBounds( route.bounds );\n\t\t\t\tvar polyline = new gm.Polyline({\n\t\t\t\t\tpath: route.overview_path,\n\t\t\t\t\tstrokeColor: '#0000FF',\n\t\t\t\t\tstrokeOpacity: .5,\n\t\t\t\t\tstrokeWeight: 5\n\t\t\t\t});\n\t\t\t\taddOverlay( polyline );\n\t\t\t});\n\t\t}\n\t\telse if( voteLatLng ) {\n\t\t\t//x\t\t\t\n\t\t\t//if (!z) map.setZoom( 15 );\n\t\t\t//else map.setZoom( z );\n\t\t}\n\t\t\n\t\tready();\n\t\tspin( false );\n\t}\n}", "function createMarker(i) {\n\n // Create a marker for the current station with a custom icon\n var stationMarker = new google.maps.Marker({\n position: stations[i].position,\n icon: 'tsymbol.png',\n map: map\n });\n\n // Extract stop id for JSON retrieval and name of station for the infowindow\n var curr_stop_id = stations[i].stop_id;\n var stationName = stations[i].name;\n\n // Anytime the station marker is clicked...\n google.maps.event.addListener(stationMarker, 'click', (function(curr_stop_id, stationName) {\n return function() {\n\n // Make instance of XHR object to make HTTP request after page is loaded\n request = new XMLHttpRequest();\n \n // Open the JSON file at remote location\n request.open(\"GET\", \"https://chicken-of-the-sea.herokuapp.com/redline/schedule.json?stop_id=\" + curr_stop_id, true);\n\n // Set up callback for when HTTP response is returned\n request.onreadystatechange = (function(stationName) {\n return function() {\n\n // Create empty strings for infowindow data\n var arrivalTime = \" \";\n var direction = \" \";\n\n if (request.readyState == 4 && request.status == 200) {\n // When we get JSON data back, parse it\n theData = request.responseText;\n stationInfo = JSON.parse(theData);\n returnHTML = \"This stop is: \";\n \n // If there is data for this station...\n if (stationInfo[\"data\"].length != 0) {\n // Go through JSON object and extract arrival times and direction to place inside infowindow\n for (var i = 0; i < stationInfo[\"data\"].length; i++) {\n if (stationInfo[\"data\"][i][\"attributes\"][\"arrival_time\"] != null) {\n arrivalTime += stationInfo[\"data\"][i][\"attributes\"][\"arrival_time\"].slice(11,16) + \"<br/>\";\n\n if (stationInfo[\"data\"][i][\"attributes\"][\"direction_id\"] == 0) {\n direction += \"Southbound\" + \"<br/>\";\n } else {\n direction += \"Northbound\" + \"<br/>\";\n }\n } else {\n arrivalTime += \"TBD\" + \"<br/>\";\n direction += \"TBD\" + \"<br/>\"\n }\n }\n\n returnHTML = returnHTML + stationName + \"<p>Here is the upcoming schedule: </p>\" + \"<p class='left'>\" + \"<u>Time of Arrival</u>\" + \"<br/>\" + arrivalTime + \"</p>\"+ \"<p class='right'>\" + \"<u>Direction</u>\" + \"<br/>\" + direction + \"</p>\";\n } else {\n returnHTML = \"Arrival times for this station are currently unavailable.\";\n }\n infoWindow.setContent(returnHTML);\n infoWindow.open(map, stationMarker);\n }\n }\n })(stationName);\n \n // Send the request\n request.send();\n }\n })(curr_stop_id, stationName));\n}", "function populateSitesOnMap() {\n\tclearMap();\n $.when(loadSites()).done(function(results) {\n for (var s in sites) {\n var marker = new google.maps.Marker({\n position: new google.maps.LatLng(sites[s].location.x, sites[s].location.y),\n map: map,\n // label: \"A\",\n icon: {url: 'http://maps.gstatic.com/mapfiles/markers2/marker.png'},\n //animation: google.maps.Animation.DROP,\n title: sites[s].name\n });\n\n markers.push(marker);\n marker.setMap(map);\n bindInfoWindow(marker, map, infowindow, sites[s]);\n }\n });\n}", "function displayKml(doc){ var numberOfPolys = doc[0].gpolygons.length; var numberOfPolys1= doc[1].gpolygons.length; var numberOfPolys2= doc[2].gpolygons.length; for(var i = 0; i < numberOfPolys; i++) { doc[0].gpolygons[i].setMap(null); } for(var i = 0; i < numberOfPolys1; i++) { doc[1].gpolygons[i].setMap(null); } for(var i = 0; i < numberOfPolys2; i++) { doc[2].gpolygons[i].setMap(null); } $(\"#tsunami\").click(function(){\r\n\t\tfor(var i = 0; i < numberOfPolys; i++) { doc[0].gpolygons[i].setMap(map); } for(var i = 0; i < numberOfPolys1; i++) { doc[1].gpolygons[i].setMap(null); } for(var i = 0; i < numberOfPolys2; i++) { doc[2].gpolygons[i].setMap(null); } \r }); $(\"#lavaflow\").click(function(){\r\n\t\t for(var i = 0; i < numberOfPolys; i++) { doc[0].gpolygons[i].setMap(null); } for(var i = 0; i < numberOfPolys1; i++) { doc[1].gpolygons[i].setMap(map); } for(var i = 0; i < numberOfPolys2; i++) { doc[2].gpolygons[i].setMap(null); } \r }); $(\"#hurricane\").click(function(){\r\n\t\t for(var i = 0; i < numberOfPolys1; i++) { doc[1].gpolygons[i].setMap(null); } for(var i = 0; i < numberOfPolys; i++) { doc[0].gpolygons[i].setMap(null); } for(var i = 0; i < numberOfPolys2; i++) { doc[2].gpolygons[i].setMap(map); } \r }); }", "function loadMap(data, title, infoFunc) {\n $('#map-name').text(title); \n $.mobile.changePage($('#map'));\n $('#map-content').css('padding','0');\n $('#map-content').height($('#map').height() - $('#map div:first').height() - 2);\n if (!map) {\n var latlng = new google.maps.LatLng(43.6547, -79.3739);\n var myOptions = { \n center: latlng,\n zoom: 12,\n mapTypeId: google.maps.MapTypeId.ROADMAP\n };\n map = new google.maps.Map(document.getElementById('map-content'),\n myOptions); \n }\n $.each(markers, function(index, point) {\n point.setMap(null);\n });\n markers = []; \n var bounds = new google.maps.LatLngBounds();\n $.each(data, function(index, stop) {\n var location = new google.maps.LatLng(stop.location[1], \n stop.location[0]);\n var point = new google.maps.Marker({\nposition: location,\nmap: map \n}); \n var infoWindow = new google.maps.InfoWindow({\ncontent: infoFunc(stop)\n});\n google.maps.event.addListener(point, 'click', function() {\n infoWindow.open(map, point);\n }); \n bounds.extend(location);\n markers.push(point); \n });\nmap.fitBounds(bounds);\ngoogle.maps.event.addListener(map, 'tilesloaded', function() {\n $.mobile.hidePageLoadingMsg();\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a transaction instruction that creates a new account at an address generated with `from`, a seed, and programId
static createAccountWithSeed(params) { const type = SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed; const data = encodeData(type, { base: toBuffer(params.basePubkey.toBuffer()), seed: params.seed, lamports: params.lamports, space: params.space, programId: toBuffer(params.programId.toBuffer()) }); let keys = [{ pubkey: params.fromPubkey, isSigner: true, isWritable: true }, { pubkey: params.newAccountPubkey, isSigner: false, isWritable: true }]; if (params.basePubkey != params.fromPubkey) { keys.push({ pubkey: params.basePubkey, isSigner: true, isWritable: false }); } return new TransactionInstruction({ keys, programId: this.programId, data }); }
[ "function generateNewAddress(){\n \n server.accounts()\n .accountId(source.publicKey())\n .call()\n .then(({ sequence }) => {\n const account = new StellarSdk.Account(source.publicKey(), sequence)\n const transaction = new StellarSdk.TransactionBuilder(account, {\n fee: StellarSdk.BASE_FEE\n })\n .addOperation(StellarSdk.Operation.createAccount({\n destination: destination.publicKey(),\n startingBalance: '2'\n }))\n .setTimeout(30)\n .build()\n transaction.sign(StellarSdk.Keypair.fromSecret(source.secret()))\n return server.submitTransaction(transaction)\n })\n .then(results => {\n console.log('Transaction', results._links.transaction.href)\n console.log('New Keypair', destination.publicKey(), destination.secret())\n })\n\n }", "static async createProgramAddress(seeds, programId) {\n let buffer = Buffer.alloc(0);\n seeds.forEach(function (seed) {\n if (seed.length > MAX_SEED_LENGTH) {\n throw new TypeError(`Max seed length exceeded`);\n }\n\n buffer = Buffer.concat([buffer, toBuffer(seed)]);\n });\n buffer = Buffer.concat([buffer, programId.toBuffer(), Buffer.from('ProgramDerivedAddress')]);\n let hash = await sha256$1(new Uint8Array(buffer));\n let publicKeyBytes = new bn$1(hash, 16).toArray(undefined, 32);\n\n if (is_on_curve(publicKeyBytes)) {\n throw new Error(`Invalid seeds, address must fall off the curve`);\n }\n\n return new PublicKey(publicKeyBytes);\n }", "static allocate(params) {\n let data;\n let keys;\n\n if ('basePubkey' in params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed;\n data = encodeData(type, {\n base: toBuffer(params.basePubkey.toBuffer()),\n seed: params.seed,\n space: params.space,\n programId: toBuffer(params.programId.toBuffer())\n });\n keys = [{\n pubkey: params.accountPubkey,\n isSigner: false,\n isWritable: true\n }, {\n pubkey: params.basePubkey,\n isSigner: true,\n isWritable: false\n }];\n } else {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.Allocate;\n data = encodeData(type, {\n space: params.space\n });\n keys = [{\n pubkey: params.accountPubkey,\n isSigner: true,\n isWritable: true\n }];\n }\n\n return new TransactionInstruction({\n keys,\n programId: this.programId,\n data\n });\n }", "static async createWithSeed(fromPublicKey, seed, programId) {\n const buffer = Buffer.concat([fromPublicKey.toBuffer(), Buffer.from(seed), programId.toBuffer()]);\n const hash = await sha256$1(new Uint8Array(buffer));\n return new PublicKey(Buffer.from(hash, 'hex'));\n }", "async function main(to, from) {\n\n const list = await listunspent();\n\n const addresses = new Set();\n const utxosSortedByAddress = list.reduce( (accumulator, utxo) => {\n const address = utxo.address;\n addresses.add(address);\n if (!accumulator[address]) {\n accumulator[address] = [];\n }\n accumulator[address].push(utxo);\n return accumulator;\n }, {});\n\n const addressArray = Array.from(addresses);\n\n if (addressArray.length === 0) {\n console.log('No UTXOs found with 10 or more confirmations.');\n process.exit(0);\n }\n\n let sendFrom = from ? from : '';\n if (!from || !to) {\n const response = await inquirer.prompt([\n {\n type: 'list',\n name: 'sendFrom',\n message: `Select an address to migrate:`,\n choices: addressArray,\n default: addressArray[0]\n },\n ]);\n sendFrom = response.sendFrom;\n }\n const utxoArray = utxosSortedByAddress[sendFrom];\n\n let sendTo = to ? to : '';\n if (!from || !to) {\n const response = await inquirer.prompt([\n {\n name: 'sendTo',\n message: `Enter address to send to:`\n },\n ]);\n sendTo = response.sendTo;\n if (!sendTo) {\n console.log('Send To address cannot be blank.');\n process.exit(0);\n }\n }\n\n if (!from || !to) {\n const { confirm } = await inquirer.prompt([\n {\n type: 'list',\n name: 'confirm',\n message: `Migrate ${utxoArray.length} UTXOs from ${sendFrom} to ${sendTo}?`,\n choices: ['Continue', 'Cancel']\n },\n ]);\n if (confirm === 'Cancel') {\n console.log('Aborted by user.');\n process.exit(0);\n }\n }\n\n utxoArray.forEach( async (utxo) => {\n const amount = Math.round(utxo.amount * 100000000);\n const minUtxoSize = argv.minUtxoSize ? argv.minUtxoSize : 100000000;\n if (amount > minUtxoSize) {\n const fee = 10000;\n const sendAmount = (amount - fee) / 100000000;\n const send = {};\n send[sendTo] = sendAmount;\n console.log(`Creating txn to send ${sendAmount} from ${sendFrom} to ${sendTo}`);\n let rawTxn = await createrawtransaction([utxo], send).catch((err) => {\n console.log('createrawtransaction Error.', err);\n console.log('Error creating raw transaction with utxo:', utxo);\n process.exit(0);\n });\n const signedTxn = await signrawtransaction(rawTxn).catch((err) => {\n console.log('signrawtransaction',err);\n console.log('Error signing raw transaction:', rawTxn);\n process.exit(0);\n });\n const txid = await sendrawtransaction(signedTxn.hex).catch((err) => {\n console.log('sendrawtransaction', err);\n console.log('Error sending signed transaction hex:', signedTxn);\n process.exit(0);\n });\n console.log(`Sent ${utxo.amount} to ${sendTo}. txid: ${txid}`);\n }\n });\n\n}", "function createNewAddress() { return { type: types.CREATE_NEW_ADDRESS }; }", "function createOrderAddress(productId, quantity){\n var inqPromise = inquirerCreateAddress();\n inqPromise.then(function(inqRes){\n var addressObj = {\n address : inqRes.addressLine,\n city : inqRes.myCity,\n state : inqRes.myState,\n zip : inqRes.myZip,\n }\n custQueryHelper.createOrderAndAddressTransaction(connection,productId, quantity, addressObj, currentCustomer);\n });\n}", "async createTokenTx (addr, qty, path) {\n try {\n // console.log(`path: ${path}`)\n if (path !== 145 && path !== 245) {\n throw new Error('path must have a value of 145 or 245')\n }\n\n if (isNaN(Number(qty)) || Number(qty) <= 0) {\n throw new Error('qty must be a positive number.')\n }\n\n // Open the wallet controlling the tokens\n // const walletInfo = this.tlUtils.openWallet()\n // const mnemonic = walletInfo.mnemonic\n const mnemonic = this.config.mnemonic\n\n // root seed buffer\n const rootSeed = await this.bchjs.Mnemonic.toSeed(mnemonic)\n\n // master HDNode\n const masterHDNode = this.bchjs.HDNode.fromSeed(rootSeed)\n\n // BEGIN - Get BCH to UTXO to pay transaction\n\n // Account path 145 to pay for bch miner fees\n const accountBCH = this.bchjs.HDNode.derivePath(\n masterHDNode,\n \"m/44'/145'/0'\"\n )\n\n const changeBCH = this.bchjs.HDNode.derivePath(accountBCH, '0/0')\n\n // Generate an EC key pair for signing the transaction.\n const keyPairBCH = this.bchjs.HDNode.toKeyPair(changeBCH)\n\n const cashAddressBCH = this.bchjs.HDNode.toCashAddress(changeBCH)\n // console.log(\n // `145 cashAddressBCH: ${JSON.stringify(cashAddressBCH, null, 2)}`\n // )\n\n // Utxos from address derivation 145\n // const utxosBCH = await this.bchjs.Blockbook.utxo(cashAddressBCH)\n const fulcrumResult = await this.bchjs.Electrumx.utxo(cashAddressBCH)\n const utxosBCH = fulcrumResult.utxos\n // console.log(`utxosBCH: ${JSON.stringify(utxosBCH, null, 2)}`)\n\n if (utxosBCH.length === 0) {\n throw new Error(\n `Address ${cashAddressBCH} does not have a BCH UTXO to pay miner fees.`\n )\n }\n\n // Choose a BCH UTXO to pay for the transaction.\n const bchUtxo = await this.bchjs.Utxo.findBiggestUtxo(utxosBCH)\n // console.log(`bchUtxo: ${JSON.stringify(bchUtxo, null, 2)}`);\n\n // Add satoshis property.\n bchUtxo.satoshis = Number(bchUtxo.value)\n\n // END - Get BCH to UTXO to pay transaction\n\n // BEGIN - Get token UTXOs for SLP transaction\n\n // HDNode of BIP44 account\n const account = this.bchjs.HDNode.derivePath(\n masterHDNode,\n `m/44'/${path}'/0'`\n )\n\n const change = this.bchjs.HDNode.derivePath(account, '0/0')\n\n // Generate an EC key pair for signing the transaction.\n const keyPair = this.bchjs.HDNode.toKeyPair(change)\n\n // get the cash address\n const cashAddress = this.bchjs.HDNode.toCashAddress(change)\n const slpAddress = this.bchjs.HDNode.toSLPAddress(change)\n // console.log(\n // `${path} cashAddress: ${JSON.stringify(cashAddress, null, 2)}`\n // )\n\n const addrData = await this.bchjs.PsfSlpIndexer.balance(cashAddress)\n const addrUtxos = addrData.balance.utxos\n // console.log(`addrUtxos: ${JSON.stringify(addrUtxos, null, 2)}`);\n\n if (addrUtxos.length === 0) {\n throw new Error('No token UTXOs to spend! Exiting.')\n }\n\n let tokenUtxos = addrUtxos.filter(\n (x) => x.tokenId === this.config.SLP_TOKEN_ID\n )\n // console.log(\n // `tokenUtxos (filter 1): ${JSON.stringify(tokenUtxos, null, 2)}`\n // );\n\n // Bail out if no token UTXOs are found.\n if (tokenUtxos.length === 0) {\n throw new Error('No token UTXOs are available!')\n }\n\n // Add missing properties to the UTXOs.\n tokenUtxos = tokenUtxos.map((x) => {\n x.tx_hash = x.txid\n x.tx_pos = x.vout\n x.decimals = TOKEN_DECIMALS\n x.tokenQty = new BigNumber(x.qty).dividedBy(10 ** TOKEN_DECIMALS)\n x.tokenQty = x.tokenQty.toString()\n x.value = this.bchjs.BitcoinCash.toSatoshi(x.value)\n\n return x\n })\n // console.log(`tokenUtxos (2): ${JSON.stringify(tokenUtxos, null, 2)}`);\n\n const { script, outputs } =\n this.bchjs.SLP.TokenType1.generateSendOpReturn(tokenUtxos, Number(qty))\n\n // END - Get token UTXOs for SLP transaction\n\n // BEGIN transaction construction.\n\n // console.log(`config.NETWORK: ${config.NETWORK}`)\n // console.log(`bchUtxo: ${JSON.stringify(bchUtxo, null, 2)}`)\n // console.log(`tokenUtxos: ${JSON.stringify(tokenUtxos, null, 2)}`)\n\n // instance of transaction builder\n let transactionBuilder\n if (this.config.NETWORK === 'mainnet') {\n transactionBuilder = new this.bchjs.TransactionBuilder()\n } else transactionBuilder = new this.bchjs.TransactionBuilder('testnet')\n\n // Add the BCH UTXO as input to pay for the transaction.\n const originalAmount = Number(bchUtxo.value)\n transactionBuilder.addInput(bchUtxo.tx_hash, bchUtxo.tx_pos)\n\n // add each token UTXO as an input.\n for (let i = 0; i < tokenUtxos.length; i++) {\n transactionBuilder.addInput(\n tokenUtxos[i].tx_hash,\n tokenUtxos[i].tx_pos\n )\n }\n\n // TODO: Create fee calculator like slpjs\n // get byte count to calculate fee. paying 1 sat\n // Note: This may not be totally accurate. Just guessing on the byteCount size.\n // const byteCount = this.BITBOX.BitcoinCash.getByteCount(\n // { P2PKH: 3 },\n // { P2PKH: 5 }\n // )\n // //console.log(`byteCount: ${byteCount}`)\n // const satoshisPerByte = 1.1\n // const txFee = Math.floor(satoshisPerByte * byteCount)\n // console.log(`txFee: ${txFee} satoshis\\n`)\n const txFee = 500\n\n // amount to send back to the sending address.\n // It's the original amount - 1 sat/byte for tx size\n const remainder = originalAmount - txFee - 546 * 2\n\n // console.log(`originalAmount: ${originalAmount}`)\n // console.log(`remainder: ${remainder}`)\n\n if (remainder < 546) {\n throw new Error('Selected UTXO does not have enough satoshis')\n }\n // console.log(`remainder: ${remainder}`)\n\n // Add OP_RETURN as first output.\n transactionBuilder.addOutput(script, 0)\n\n // Send dust transaction representing tokens being sent.\n transactionBuilder.addOutput(\n this.bchjs.SLP.Address.toLegacyAddress(addr),\n 546\n )\n\n // Return token change back to the token-liquidity app.\n if (outputs > 1) {\n transactionBuilder.addOutput(\n this.bchjs.SLP.Address.toLegacyAddress(slpAddress),\n 546\n )\n }\n\n // Last output: send the BCH change back to the wallet.\n transactionBuilder.addOutput(\n this.bchjs.Address.toLegacyAddress(cashAddressBCH),\n remainder\n )\n\n // Sign the transaction with the private key for the BCH UTXO paying the fees.\n let redeemScript\n transactionBuilder.sign(\n 0,\n keyPairBCH,\n redeemScript,\n transactionBuilder.hashTypes.SIGHASH_ALL,\n originalAmount\n )\n\n // Sign each token UTXO being consumed.\n for (let i = 0; i < tokenUtxos.length; i++) {\n const thisUtxo = tokenUtxos[i]\n\n transactionBuilder.sign(\n 1 + i,\n keyPair,\n redeemScript,\n transactionBuilder.hashTypes.SIGHASH_ALL,\n Number(thisUtxo.value)\n )\n }\n\n // build tx\n const tx = transactionBuilder.build()\n\n // output rawhex\n const hex = tx.toHex()\n // console.log(`Transaction raw hex: `, hex)\n\n // END transaction construction.\n\n return hex\n } catch (err) {\n wlogger.debug(`Error in createTokenTx: ${err.message}`, err)\n // console.error(\"Error in createTokenTx(): \", err);\n\n // if (err.message) throw new Error(err.message)\n // else throw new Error('Error in createTokenTx()')\n throw err\n }\n }", "function makeInviteCode() {\n const random = crypto.randomBytes(5).toString('hex');\n return base32.encode(random);\n}", "async function makeSimpleTx() {\n await t.wait(erc20.transfer(userAFunnel, userAAmount, overrides),\n 'erc20 transfer');\n\n // User A Deposit Token.\n const userADepositToken = new Deposit({\n token: 1,\n owner: userA,\n blockNumber: utils.bigNumberify(await t.getBlockNumber()).add(1),\n value: userAAmount,\n });\n const userADepositTokenTx = await t.wait(contract.deposit(userA, erc20.address, overrides),\n 'token deposit', Fuel.errors);\n\n // Set fee stipulations.\n let feeToken = 1;\n let fee = opts.signatureFee || utils.parseEther('.000012');\n let noFee = utils.bigNumberify(fee).lte(0);\n\n // Build the transaction in question.\n return await tx.Transaction({\n override: true,\n chainId: 0,\n witnesses: [\n userAWallet,\n ],\n metadata: [\n tx.MetadataDeposit({\n blockNumber: userADepositToken.properties.blockNumber().get(),\n token: userADepositToken.properties.token().get(),\n }),\n ],\n data: [\n userADepositToken.keccak256(),\n ],\n inputs: [\n tx.InputDeposit({\n owner: userADepositToken.properties\n .owner().get(),\n }),\n ],\n signatureFeeToken: feeToken,\n signatureFee: fee,\n signatureFeeOutputIndex: noFee ? null : 0,\n outputs: [\n tx.OutputTransfer({\n noshift: true,\n token: '0x01',\n owner: producer,\n amount: utils.parseEther('1000.00'),\n }),\n ],\n contract,\n });\n }", "createAccount()\n {\n account = this.web3.eth.accounts.create();\n\n vaultData.account_list.push(account)\n\n this.selectAccount( account.address )\n\n this.saveVaultData( vaultData )\n\n }", "static generateWallet() {\n const wallet = EthereumJsWallet.generate();\n\n AnalyticsUtils.trackEvent('Generate wallet', {\n walletAddress: wallet.getAddressString(),\n });\n\n return this.storeWallet(wallet);\n }", "walletSetup(seed) {\n\n const root = Hdkey.fromMasterSeed(seed);\n const masterPrivateKey = root.privateKey.toString('hex');\n\n const addrNode = root.derive(\"m/44'/60'/0'/0/0\"); //line 1\n const pubKey = EthUtil.privateToPublic(addrNode._privateKey);\n const addr = EthUtil.publicToAddress(pubKey).toString('hex');\n const address = EthUtil.toChecksumAddress(addr);\n const key = {\n 'root': root,\n 'masterPrivateKey': masterPrivateKey,\n 'addrNode': addrNode,\n 'pubKey': pubKey,\n 'addr': addr,\n 'address': address\n };\n const hexPrivateKey = EthUtil.bufferToHex(addrNode._privateKey)\n this.props.setKeys(masterPrivateKey, address, hexPrivateKey);\n\n this.props.navigation.navigate('HomeScreen');\n /*\n If using ethereumjs-wallet instead do after line 1:\n const address = addrNode.getWallet().getChecksumAddressString();\n */\n }", "function createHello(hello) {\n contract.methods.CreateHello(hello).send({ from: address })\n }", "function constructTx(params) {\n return __awaiter(this, void 0, void 0, function () {\n var signedTx, _a, serializedSignedTx, txHash, numOfKB;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0: return [4 /*yield*/, makeSignedTx(params)];\n case 1:\n signedTx = (_b.sent()).signedTx;\n xmr_str_utils_1.JSONPrettyPrint(\"constructTx\", { signedTx: signedTx }, \"signedTx\");\n _a = getSerializedTxAndHash(signedTx), serializedSignedTx = _a.serializedSignedTx, txHash = _a.txHash;\n xmr_str_utils_1.JSONPrettyPrint(\"constructTx\", { serializedSignedTx: serializedSignedTx, txHash: txHash }, \"serializedTxAndHash\");\n numOfKB = getTxSize(serializedSignedTx, params.networkFee).numOfKB;\n xmr_str_utils_1.JSONPrettyPrint(\"constructTx\", { numOfKB: numOfKB }, \"numOfKb\");\n return [2 /*return*/, { numOfKB: numOfKB, txHash: txHash, serializedSignedTx: serializedSignedTx }];\n }\n });\n });\n}", "function makeTuid() {\n return crypto.randomBytes(16).toString('hex')\n}", "async function createMondayAccount(account) {\n console.log('Creting new Monday account:', account.Name)\n await monday.createItem(boardId, account.Id, {\n Name: () => account.Name,\n Phone: () => account.Phone,\n })\n }", "async function genSegWitAddr() {\n\n\tconst mnemonics = mnemonic.generateMnemonic(); //generates string\n const seed = await bip39.mnemonicToSeed(mnemonics);\n const root = hdkey.fromMasterSeed(seed);\n\n\tconst masterPrivateKey = root.privateKey.toString('hex');\n\tconst masterPublicKey = root.publicKey.toString('hex');\n\n\tconst addrnode = root.derive(\"m/44'/0'/0'/0/0\");\n\tconsole.log(addrnode._publicKey);\n\n\tconst step1 = addrnode._publicKey;//Get your public key\n\tconst step2 = createHash('sha256').update(step1).digest(); //Perform SHA-256 hashing on the public key\n\tconst step3 = createHash('rmd160').update(step2).digest(); //Perform RIPEMD-160 hashing on the result of SHA-256\n\n\tvar step4 = Buffer.allocUnsafe(21);//Add version byte in front of RIPEMD-160 hash (0x00 for mainnet, 0x6f for testnet)\n\tstep4.writeUInt8(0x00, 0);\n\tstep3.copy(step4, 1); //step4 now holds the extended RIPMD-160 result\n\n\tconst step9 = bs58check.encode(step4);\n\tconsole.log('Base58Check: ' + step9);\n\treturn step9;\n\t\n}", "function createShipTo(custCode,so,callback){\n\t// Create shipToCode\n\tvar genCode=new Request(\"DECLARE @docCode NVARCHAR(30);EXEC [dbo].GenerateDocumentCode @Transaction='CustomerShipTo', @DocumentCode=@docCode output;SELECT @docCode;\",function(err,rowCount,docRows){\n\t\tvar shipToCode=docRows[0][0].value;\n\t\t\n\t\t// Generate template\n\t\tvar soTmp=templates.customerShipTo(shipToCode,custCode,so);\n\t\t\n\t\tresolveAddress(soTmp.PostalCode,function(addr){\n\t\t\tsoTmp.State=addr.StateCode.value;\n\t\t\tsoTmp.County=addr.County.value;\n\t\t\tsoTmp.Country=addr.CountryCode.value;\n\t\t\tsoTmp.City=addr.City.value;\n\t\t\t\n\t\t\t// Finalize SQL\n\t\t\tvar sql=templates.generateSQLByTemplate(\"INSERT\",\"CustomerShipTo\",soTmp);\n\t\t\t\n\t\t\tvar createCustomerShipTo=new Request(sql,function(err,rowCount,custRows){\n\t\t\t\tif (err){\n\t\t\t\t\tlog.doLog('error','createShipTo','Failed to create shipTo: '+err);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tlog.doLog('info','createShipTo','Did create shipTo: '+custCode+' - '+shipToCode);\n\t\t\t\tvar fixCustShipTo=new Request(\"UPDATE Customer SET DefaultShipToCode='\"+shipToCode+\"' WHERE CustomerCode='\"+custCode+\"'\",function(err,rowCount,rows){\n\t\t\t\t\tif (err){\n\t\t\t\t\t\tlog.doLog('error','createShipTo','Failed to update customer with shipTo: '+err);\n\t\t\t\t\t}else{\n\t\t\t\t\t\t// Generate account codes and callback when done\n\t\t\t\t\t\tlog.doLog('info','createShipTo','Did link shipTo: '+custCode+' - '+shipToCode);\n\t\t\t\t\t\tcreateAcctCodes(custCode,shipToCode,function(){\n\t\t\t\t\t\t\tcallback(shipToCode);\n\t\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\tconnection.execSqlBatch(fixCustShipTo);\n\t\t\t});\n\t\t\t\n\t\t\tconnection.execSqlBatch(createCustomerShipTo);\n\t\t});\n\t\t\n\t});\n\t\n\tconnection.execSqlBatch(genCode);\n}", "function createAccount (account) {\r\n accounts.push(account);\r\n return account;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assert that the given number of resources of the given type exist in the template.
resourceCountIs(type, count) { const counted = (0, resources_1.countResources)(this.template, type); if (counted !== count) { throw new Error(`Expected ${count} resources of type ${type} but found ${counted}`); } }
[ "hasResource(type, props) {\n const matchError = (0, resources_1.hasResource)(this.template, type, props);\n if (matchError) {\n throw new Error(matchError);\n }\n }", "resourcePropertiesCountIs(type, props, count) {\n const counted = (0, resources_1.countResourcesProperties)(this.template, type, props);\n if (counted !== count) {\n throw new Error(`Expected ${count} resources of type ${type} but found ${counted}`);\n }\n }", "hasResourceProperties(type, props) {\n const matchError = (0, resources_1.hasResourceProperties)(this.template, type, props);\n if (matchError) {\n throw new Error(matchError);\n }\n }", "allResources(type, props) {\n const matchError = (0, resources_1.allResources)(this.template, type, props);\n if (matchError) {\n throw new Error(matchError);\n }\n }", "async function validateTemplate() {\n // Get item sub type\n const itemSubType = getItemSubType();\n core.info(`validateTemplate: itemSubType: ${itemSubType}`);\n\n // Compose message\n const message = composeMessage({ requireTemplate: true });\n\n // If issue type could not be determined\n if (itemSubType === undefined) {\n // Post error comment\n await postComment(message);\n return false;\n }\n\n // Ensure required headlines\n const patterns = template[itemSubType].headlines.map(h => {\n return { regex: h };\n });\n\n // If validation failed\n if (validatePatterns(patterns, itemBody).filter(v => !v.ok).length > 0) {\n core.info('Required headlines are missing.');\n\n // Post error comment\n await postComment(message);\n return false;\n }\n\n core.info('Required headlines were found.');\n return true;\n}", "allResourcesProperties(type, props) {\n const matchError = (0, resources_1.allResourcesProperties)(this.template, type, props);\n if (matchError) {\n throw new Error(matchError);\n }\n }", "findResources(type, props = {}) {\n return (0, resources_1.findResources)(this.template, type, props);\n }", "verifyNumberOfProducts(noOfProduct){\n cy.get(this.numberOfCartItems).should('have.length',noOfProduct)\n }", "templateMatches(expected) {\n const matcher = matcher_1.Matcher.isMatcher(expected) ? expected : match_1.Match.objectLike(expected);\n const result = matcher.test(this.template);\n if (result.hasFailed()) {\n throw new Error([\n 'Template did not match as expected. The following mismatches were found:',\n ...result.toHumanStrings().map(s => `\\t${s}`),\n ].join('\\n'));\n }\n }", "function validReferences(){\n\n let count = 3;\n for(let i = 1; i < 4; i++){\n let holder = validText(\"labelRefFirstName\"+i, \"refFirstName\"+i);\n let holder1 = validText(\"labelRefLastName\"+i, \"refLastName\"+i);\n let holder2 = validText(\"labelRefRelationship\"+i,\"refRelationship\"+i);\n let holder3 = validatePhoneNum(\"labelRefPhone\"+i,\"refPhone\"+i);\n let holder4 = validMail(\"labelRefEmail\"+i,\"refEmail\"+i);\n if(holder === false || holder1 === false || holder2 === false || holder3 === false || holder4 === false){\n count--;\n }\n }\n $(\"#errReferences\").hide();\n\n if(count !== 3){\n $(\"#errReferences\").show();\n document.getElementById(\"errReferences\").innerHTML = \"*Requires 3 References: \"+count+\"/3\";\n }\n\n}", "function _need_validate(template, response){\n var newslist = response.newslist;\n for (var i=0; i < template.blocks.length; i++){\n if (!template.blocks[i].new || template.blocks[i].validated){\n continue;\n }\n var bid = template.blocks[i].id;\n if (bid in newslist){\n return true;\n }\n }\n return false;\n}", "testAssertResultLength() {\n \n }", "function check_total_attachment_size(count, expectedSize, exact) {\n let list = mc.e(\"attachmentList\");\n let nodes = list.querySelectorAll(\"richlistitem.attachmentItem\");\n let sizeNode = mc.e(\"attachmentSize\");\n\n Assert.equal(\n nodes.length,\n count,\n \"Should have the expected number of attachments\"\n );\n\n let lastPartID;\n let size = 0;\n for (let i = 0; i < nodes.length; i++) {\n let attachment = nodes[i].attachment;\n if (!lastPartID || attachment.partID.indexOf(lastPartID) != 0) {\n lastPartID = attachment.partID;\n let currSize = attachment.size;\n if (currSize > 0 && !isNaN(currSize)) {\n size += Number(currSize);\n }\n }\n }\n\n Assert.ok(\n Math.abs(size - expectedSize) <= epsilon * count,\n `Total attachments size should be within ${epsilon * count} ` +\n `of ${expectedSize} (actual: ${size})`\n );\n\n // Next, make sure that the formatted size in the label is correct\n let formattedSize = sizeNode.getAttribute(\"value\");\n let expectedFormattedSize = messenger.formatFileSize(size);\n let messengerBundle = mc.window.document.getElementById(\"bundle_messenger\");\n\n if (!exact) {\n if (size == 0) {\n expectedFormattedSize = messengerBundle.getString(\n \"attachmentSizeUnknown\"\n );\n } else {\n expectedFormattedSize = messengerBundle.getFormattedString(\n \"attachmentSizeAtLeast\",\n [expectedFormattedSize]\n );\n }\n }\n Assert.equal(\n formattedSize,\n expectedFormattedSize,\n \"Displayed attachments total size should match\"\n );\n}", "function loadspriteCount() {\n\treturn $(i18n.loadspriteElement).get().length;\n}", "function loadTemplates(){\n for(let name of templates.toLoad) loadTemplate(name);\n}", "validateGamesQuantity(){\n\n const list = this.getGamesList().childNodes;\n\n if(list.length > 3){\n\n this.disableElement(this[createInputElement]);\n this.disableElement(this[sliderMenuElement]);\n this.showMessage('You have exceeded allowed number of active games. Complete your active games.');\n }\n }", "function validateTemplate(template, schema){\n console.log(\"Validating template \" + templateFileName + \" against schema \" + schemaFileName + \" . . .\");\n //var validation = validate(templateFile, schema);\n var validator = new validate.Validator(schema);\n var check = validator.check(template);\n console.log(\"Validation: \" + check);\n}", "function lengthCheck(r){\n\t\t// If JSON object is empty, no restaurants were found\n\t\tif (r.length == 0) {\n\t\t\tMaterialize.toast(\"No Restaurants by that name were found in that area!\", 4000);\n\t\t}\n\t\t// If JSON object is not empty, find out how many unique restaurants are in the response.\n\t\telse{\n var licenseArray = [];\n var multiRestaurantArray = [];\n\t\t\tfor (var i = 0; i < r.length; i++){\n\t\t\t\tif (!licenseArray.includes(r[i].license_)) {\n licenseArray.push(r[i].license_);\n multiRestaurantArray.push(\n {\n license: r[i].license_,\n address: r[i].address,\n name: r[i].dba_name,\n latitude: r[i].latitude,\n longitude: r[i].longitude,\n zip: r[i].zip\n }\n );\n };\n };\n if (licenseArray.length == 1) {\n addResultsToPage(r);\n }\n else if (licenseArray.length > 1){\n $(\"#multipleLocationsModal\").html(\"\");\n userPickRestaurant(multiRestaurantArray, r);\n };\n\t\t};\n\t}", "function hasPageTemplate (theme, name) {\n\treturn test('-f', THEME_DIR+theme+'/'+name+'.swig');\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register a component resource.
registerComponent(component) { this.requireValidComponent(component); if (component.term.termType !== 'NamedNode') { this.logger.warn(`Registered a component that is identified by a ${component.term.termType} (${component.value}) instead of an IRI identifier.`); } this.componentResources[component.value] = component; }
[ "registerModuleResource(moduleResource) {\n if (moduleResource.property.components) {\n for (const component of moduleResource.properties.components) {\n component.property.module = moduleResource;\n this.registerComponent(component);\n }\n }\n else {\n this.logger.warn(`Registered a module ${moduleResource.value} without components.`);\n }\n }", "function registerResource(res, parent, t, name, custom, remote, newDependency, props, opts, sourcePosition) {\n const label = `resource:${name}[${t}]`;\n log.debug(`Registering resource: t=${t}, name=${name}, custom=${custom}, remote=${remote}`);\n const monitor = settings_2.getMonitor();\n const resopAsync = prepareResource(label, res, parent, custom, remote, props, opts, t, name);\n // In order to present a useful stack trace if an error does occur, we preallocate potential\n // errors here. V8 captures a stack trace at the moment an Error is created and this stack\n // trace will lead directly to user code. Throwing in `runAsyncResourceOp` results in an Error\n // with a non-useful stack trace.\n const preallocError = new Error();\n debuggable_1.debuggablePromise(resopAsync.then((resop) => __awaiter(this, void 0, void 0, function* () {\n log.debug(`RegisterResource RPC prepared: t=${t}, name=${name}` +\n (settings_2.excessiveDebugOutput ? `, obj=${JSON.stringify(resop.serializedProps)}` : ``));\n const req = new resproto.RegisterResourceRequest();\n req.setType(t);\n req.setName(name);\n req.setParent(resop.parentURN);\n req.setCustom(custom);\n req.setObject(gstruct.Struct.fromJavaScript(resop.serializedProps));\n req.setProtect(opts.protect);\n req.setProvider(resop.providerRef);\n req.setDependenciesList(Array.from(resop.allDirectDependencyURNs));\n req.setDeletebeforereplace(opts.deleteBeforeReplace || false);\n req.setDeletebeforereplacedefined(opts.deleteBeforeReplace !== undefined);\n req.setIgnorechangesList(opts.ignoreChanges || []);\n req.setVersion(opts.version || \"\");\n req.setAcceptsecrets(true);\n req.setAcceptresources(!utils.disableResourceReferences);\n req.setAdditionalsecretoutputsList(opts.additionalSecretOutputs || []);\n if (resop.monitorSupportsStructuredAliases) {\n const aliasesList = yield mapAliasesForRequest(resop.aliases, resop.parentURN);\n req.setAliasesList(aliasesList);\n }\n else {\n req.setAliasurnsList(resop.aliases);\n }\n req.setImportid(resop.import || \"\");\n req.setSupportspartialvalues(true);\n req.setRemote(remote);\n req.setReplaceonchangesList(opts.replaceOnChanges || []);\n req.setPlugindownloadurl(opts.pluginDownloadURL || \"\");\n req.setRetainondelete(opts.retainOnDelete || false);\n req.setDeletedwith(resop.deletedWithURN || \"\");\n req.setAliasspecs(true);\n req.setSourceposition(marshalSourcePosition(sourcePosition));\n if (resop.deletedWithURN && !(yield settings_1.monitorSupportsDeletedWith())) {\n throw new Error(\"The Pulumi CLI does not support the DeletedWith option. Please update the Pulumi CLI.\");\n }\n const customTimeouts = new resproto.RegisterResourceRequest.CustomTimeouts();\n if (opts.customTimeouts != null) {\n customTimeouts.setCreate(opts.customTimeouts.create);\n customTimeouts.setUpdate(opts.customTimeouts.update);\n customTimeouts.setDelete(opts.customTimeouts.delete);\n }\n req.setCustomtimeouts(customTimeouts);\n const propertyDependencies = req.getPropertydependenciesMap();\n for (const [key, resourceURNs] of resop.propertyToDirectDependencyURNs) {\n const deps = new resproto.RegisterResourceRequest.PropertyDependencies();\n deps.setUrnsList(Array.from(resourceURNs));\n propertyDependencies.set(key, deps);\n }\n const providerRefs = req.getProvidersMap();\n for (const [key, ref] of resop.providerRefs) {\n providerRefs.set(key, ref);\n }\n // Now run the operation, serializing the invocation if necessary.\n const opLabel = `monitor.registerResource(${label})`;\n runAsyncResourceOp(opLabel, () => __awaiter(this, void 0, void 0, function* () {\n let resp = {};\n let err;\n try {\n if (monitor) {\n // If we're running with an attachment to the engine, perform the operation.\n resp = yield debuggable_1.debuggablePromise(new Promise((resolve, reject) => monitor.registerResource(req, (rpcErr, innerResponse) => {\n if (rpcErr) {\n err = rpcErr;\n // If the monitor is unavailable, it is in the process of shutting down or has already\n // shut down. Don't emit an error and don't do any more RPCs, just exit.\n if (rpcErr.code === grpc.status.UNAVAILABLE ||\n rpcErr.code === grpc.status.CANCELLED) {\n // Re-emit the message\n settings_2.terminateRpcs();\n rpcErr.message = \"Resource monitor is terminating\";\n preallocError.code = rpcErr.code;\n }\n // Node lets us hack the message as long as we do it before accessing the `stack` property.\n log.debug(`RegisterResource RPC finished: ${label}; err: ${rpcErr}, resp: ${innerResponse}`);\n preallocError.message = `failed to register new resource ${name} [${t}]: ${rpcErr.message}`;\n reject(preallocError);\n }\n else {\n log.debug(`RegisterResource RPC finished: ${label}; err: ${rpcErr}, resp: ${innerResponse}`);\n resolve(innerResponse);\n }\n })), opLabel);\n }\n else {\n // If we aren't attached to the engine, in test mode, mock up a fake response for testing purposes.\n const mockurn = yield resource_1.createUrn(req.getName(), req.getType(), req.getParent()).promise();\n resp = {\n getUrn: () => mockurn,\n getId: () => undefined,\n getObject: () => req.getObject(),\n getPropertydependenciesMap: () => undefined,\n };\n }\n }\n catch (e) {\n err = e;\n resp = {\n getUrn: () => \"\",\n getId: () => undefined,\n getObject: () => req.getObject(),\n getPropertydependenciesMap: () => undefined,\n };\n }\n resop.resolveURN(resp.getUrn(), err);\n // Note: 'id || undefined' is intentional. We intentionally collapse falsy values to\n // undefined so that later parts of our system don't have to deal with values like 'null'.\n if (resop.resolveID) {\n const id = resp.getId() || undefined;\n resop.resolveID(id, id !== undefined, err);\n }\n const deps = {};\n const rpcDeps = resp.getPropertydependenciesMap();\n if (rpcDeps) {\n for (const [k, propertyDeps] of resp.getPropertydependenciesMap().entries()) {\n const urns = propertyDeps.getUrnsList();\n deps[k] = urns.map((urn) => newDependency(urn));\n }\n }\n // Now resolve the output properties.\n yield resolveOutputs(res, t, name, props, resp.getObject(), deps, resop.resolvers, err);\n }));\n })), label);\n}", "registerComponent(component) {\n if (this.vues[component.name] === undefined) {\n this.vues[component.name] = component;\n } else {\n this.vues[component.name].apps.push(...component.apps);\n }\n }", "constructor(type, name, args = {}, opts = {}, remote = false) {\n // Explicitly ignore the props passed in. We allow them for back compat reasons. However,\n // we explicitly do not want to pass them along to the engine. The ComponentResource acts\n // only as a container for other resources. Another way to think about this is that a normal\n // 'custom resource' corresponds to real piece of cloud infrastructure. So, when it changes\n // in some way, the cloud resource needs to be updated (and vice versa). That is not true\n // for a component resource. The component is just used for organizational purposes and does\n // not correspond to a real piece of cloud infrastructure. As such, changes to it *itself*\n // do not have any effect on the cloud side of things at all.\n super(type, name, /*custom:*/ false, /*props:*/ remote || (opts === null || opts === void 0 ? void 0 : opts.urn) ? args : {}, opts, remote);\n /**\n * A private field to help with RTTI that works in SxS scenarios.\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention,no-underscore-dangle,id-blacklist,id-match\n this.__pulumiComponentResource = true;\n /** @internal */\n // eslint-disable-next-line @typescript-eslint/naming-convention,no-underscore-dangle,id-blacklist,id-match\n this.__registered = false;\n this.__remote = remote;\n this.__registered = remote || !!(opts === null || opts === void 0 ? void 0 : opts.urn);\n this.__data = remote || (opts === null || opts === void 0 ? void 0 : opts.urn) ? Promise.resolve({}) : this.initializeAndRegisterOutputs(args);\n }", "function registerForLocalization(component) {\n component.contextType = __WEBPACK_IMPORTED_MODULE_2__globalization_GlobalizationContext__[\"a\" /* GlobalizationContext */];\n}", "register() {\n this._container.instance('expressApp', require('express')())\n\n //TODO: add Socket.io here @url https://trello.com/c/KFCXzYom/71-socketio-adapter\n\n this._container.register('httpServing', require(FRAMEWORK_PATH + '/lib/HTTPServing'))\n .dependencies('config', 'expressApp')\n .singleton()\n\n this._container.instance('expressRouterFactory', () => {\n return require('express').Router()\n })\n\n this._container.register('RoutesResolver', require(FRAMEWORK_PATH + '/lib/RoutesResolver'))\n .dependencies('logger', 'app', 'expressRouterFactory')\n\n this._container.register('httpErrorHandler', require(FRAMEWORK_PATH + '/lib/HTTPErrorHandler'))\n .dependencies('logger')\n .singleton()\n\n //TODO: add WS the serving @url https://trello.com/c/KFCXzYom/71-socketio-adapter\n }", "function _createResource({domain, path, contentType, token, args}) {\n //Remove the path if we are running in function mode, so paths in original action work\n return post.func(args)({\n domain,\n token,\n path: '/resources',\n headers: {\n 'Content-Type': contentType\n },\n data: {}\n }).then(({response}) => {\n var id = response.headers.location.split('/')\n id = id[id.length-1]\n\n return put.func(args)({\n domain,\n path,\n token,\n headers: {\n 'Content-Type': contentType\n },\n data: {\n _id:'resources/'+id,\n _rev: '0-0'\n }\n });\n });\n}", "_addResources(resources, forceUpdate = false) {\n for (const id in resources) {\n this.layerManager.resourceManager.add({\n resourceId: id,\n data: resources[id],\n forceUpdate\n });\n }\n }", "function loadComponent(model, resource, jsonld) {\n var component = getComponent(model, resource['@id']);\n component.status = jsonld.getReference(resource,\n 'http://etl.linkedpipes.com/ontology/status');\n component.order = jsonld.getInteger(resource,\n 'http://linkedpipes.com/ontology/executionOrder');\n component.dataUnits = jsonld.getReferenceAll(resource,\n 'http://etl.linkedpipes.com/ontology/dataUnit');\n // Check status for mapping.\n switch (component.status) {\n case 'http://etl.linkedpipes.com/resources/status/finished':\n case 'http://etl.linkedpipes.com/resources/status/mapped':\n component.mapping = MappingStatus.FINISHED_MAPPED;\n break;\n case 'http://etl.linkedpipes.com/resources/status/failed':\n component.mapping = MappingStatus.FAILED;\n break;\n default:\n component.mapping = MappingStatus.UNFINISHED;\n break;\n }\n }", "requireValidComponent(componentResource, referencingComponent) {\n if (!this.isValidComponent(componentResource)) {\n throw new Error(`Resource ${componentResource.value} is not a valid component, either it is not defined, has no type, or is incorrectly referenced${referencingComponent ? ` by ${referencingComponent.value}` : ''}.`);\n }\n }", "function Resource(uri) {\n this._init(uri);\n}", "function CustomResource(props) {\n return __assign({ Type: 'AWS::CloudFormation::CustomResource' }, props);\n }", "constructor() {\n\t\tthis.register = this.register.bind(this);\n\t}", "function startResourceUpdate(resource) {\n return { type: START_RESOURCE_UPDATE,\n resource: resource};\n}", "function Resource(props) {\n return __assign({ Type: 'AWS::ApiGateway::Resource' }, props);\n }", "InstallComponent(string, string, string, string) {\n\n }", "static registerDefaultComponent(component) {\n BeastController.basicComponents.push(component);\n }", "constructor(t, name, custom, props = {}, opts = {}, remote = false, dependency = false) {\n /**\n * A private field to help with RTTI that works in SxS scenarios.\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention,no-underscore-dangle,id-blacklist,id-match\n this.__pulumiResource = true;\n this.__pulumiType = t;\n if (dependency) {\n this.__protect = false;\n this.__providers = {};\n return;\n }\n if (opts.parent && !Resource.isInstance(opts.parent)) {\n throw new Error(`Resource parent is not a valid Resource: ${opts.parent}`);\n }\n if (!t) {\n throw new errors_1.ResourceError(\"Missing resource type argument\", opts.parent);\n }\n if (!name) {\n throw new errors_1.ResourceError(\"Missing resource name argument (for URN creation)\", opts.parent);\n }\n // Before anything else - if there are transformations registered, invoke them in order to transform the properties and\n // options assigned to this resource.\n const parent = opts.parent || state_1.getStackResource();\n this.__transformations = [...(opts.transformations || []), ...((parent === null || parent === void 0 ? void 0 : parent.__transformations) || [])];\n for (const transformation of this.__transformations) {\n const tres = transformation({ resource: this, type: t, name, props, opts });\n if (tres) {\n if (tres.opts.parent !== opts.parent) {\n // This is currently not allowed because the parent tree is needed to establish what\n // transformation to apply in the first place, and to compute inheritance of other\n // resource options in the Resource constructor before transformations are run (so\n // modifying it here would only even partially take affect). It's theoretically\n // possible this restriction could be lifted in the future, but for now just\n // disallow re-parenting resources in transformations to be safe.\n throw new Error(\"Transformations cannot currently be used to change the `parent` of a resource.\");\n }\n props = tres.props;\n opts = tres.opts;\n }\n }\n this.__name = name;\n // Make a shallow clone of opts to ensure we don't modify the value passed in.\n opts = Object.assign({}, opts);\n // Check the parent type if one exists and fill in any default options.\n this.__providers = {};\n if (parent) {\n this.__parentResource = parent;\n this.__parentResource.__childResources = this.__parentResource.__childResources || new Set();\n this.__parentResource.__childResources.add(this);\n if (opts.protect === undefined) {\n opts.protect = parent.__protect;\n }\n this.__providers = parent.__providers;\n }\n // providers is found by combining (in ascending order of priority)\n // 1. provider\n // 2. self_providers\n // 3. opts.providers\n this.__providers = Object.assign(Object.assign(Object.assign({}, this.__providers), convertToProvidersMap(opts.providers)), convertToProvidersMap(opts.provider ? [opts.provider] : {}));\n // provider is the first option that does not return none\n // 1. opts.provider\n // 2. a matching provider in opts.providers\n // 3. a matching provider inherited from opts.parent\n if ((custom || remote) && opts.provider === undefined) {\n const pkg = resource_1.pkgFromType(t);\n const parentProvider = parent === null || parent === void 0 ? void 0 : parent.getProvider(t);\n if (pkg && pkg in this.__providers) {\n opts.provider = this.__providers[pkg];\n }\n else if (parentProvider) {\n opts.provider = parentProvider;\n }\n }\n this.__protect = !!opts.protect;\n this.__prov = custom || remote ? opts.provider : undefined;\n this.__version = opts.version;\n this.__pluginDownloadURL = opts.pluginDownloadURL;\n // Collapse any `Alias`es down to URNs. We have to wait until this point to do so because we do not know the\n // default `name` and `type` to apply until we are inside the resource constructor.\n this.__aliases = [];\n if (opts.aliases) {\n for (const alias of opts.aliases) {\n this.__aliases.push(collapseAliasToUrn(alias, name, t, parent));\n }\n }\n const sourcePosition = Resource.sourcePosition();\n if (opts.urn) {\n // This is a resource that already exists. Read its state from the engine.\n resource_1.getResource(this, parent, props, custom, opts.urn);\n }\n else if (opts.id) {\n // If this is a custom resource that already exists, read its state from the provider.\n if (!custom) {\n throw new errors_1.ResourceError(\"Cannot read an existing resource unless it has a custom provider\", opts.parent);\n }\n resource_1.readResource(this, parent, t, name, props, opts, sourcePosition);\n }\n else {\n // Kick off the resource registration. If we are actually performing a deployment, this\n // resource's properties will be resolved asynchronously after the operation completes, so\n // that dependent computations resolve normally. If we are just planning, on the other\n // hand, values will never resolve.\n resource_1.registerResource(this, parent, t, name, custom, remote, (urn) => new DependencyResource(urn), props, opts, sourcePosition);\n }\n }", "function registerResourceOutputs(res, outputs) {\n // Now run the operation. Note that we explicitly do not serialize output registration with\n // respect to other resource operations, as outputs may depend on properties of other resources\n // that will not resolve until later turns. This would create a circular promise chain that can\n // never resolve.\n const opLabel = `monitor.registerResourceOutputs(...)`;\n runAsyncResourceOp(opLabel, () => __awaiter(this, void 0, void 0, function* () {\n // The registration could very well still be taking place, so we will need to wait for its URN.\n // Additionally, the output properties might have come from other resources, so we must await those too.\n const urn = yield res.urn.promise();\n const resolved = yield rpc_1.serializeProperties(opLabel, { outputs });\n const outputsObj = gstruct.Struct.fromJavaScript(resolved.outputs);\n log.debug(`RegisterResourceOutputs RPC prepared: urn=${urn}` +\n (settings_2.excessiveDebugOutput ? `, outputs=${JSON.stringify(outputsObj)}` : ``));\n // Fetch the monitor and make an RPC request.\n const monitor = settings_2.getMonitor();\n if (monitor) {\n const req = new resproto.RegisterResourceOutputsRequest();\n req.setUrn(urn);\n req.setOutputs(outputsObj);\n const label = `monitor.registerResourceOutputs(${urn}, ...)`;\n yield debuggable_1.debuggablePromise(new Promise((resolve, reject) => monitor.registerResourceOutputs(req, (err, innerResponse) => {\n log.debug(`RegisterResourceOutputs RPC finished: urn=${urn}; ` +\n `err: ${err}, resp: ${innerResponse}`);\n if (err) {\n // If the monitor is unavailable, it is in the process of shutting down or has already\n // shut down. Don't emit an error and don't do any more RPCs, just exit.\n if (err.code === grpc.status.UNAVAILABLE || err.code === grpc.status.CANCELLED) {\n settings_2.terminateRpcs();\n err.message = \"Resource monitor is terminating\";\n }\n reject(err);\n }\n else {\n log.debug(`RegisterResourceOutputs RPC finished: urn=${urn}; ` +\n `err: ${err}, resp: ${innerResponse}`);\n resolve();\n }\n })), label);\n }\n }), false);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If the cart items availibility is loaded, returns whether all the items are availible
cartHasUnAvailibleItems() { const itemAvailibility = Object.keys(this.state.itemsAvailible).map( itemId => this.state.itemsAvailible[itemId], ); return !itemAvailibility.every(itemAvailible => itemAvailible === true); }
[ "isItemAvailableOnFavoriteStore (skuId, quantity) {\n this.store.dispatch(getSetSuggestedStoresActn(EMPTY_ARRAY)); // clear previous search results\n let storeState = this.store.getState();\n let preferredStore = storesStoreView.getDefaultStore(storeState);\n let {coordinates} = preferredStore.basicInfo;\n let currentCountry = sitesAndCountriesStoreView.getCurrentCountry(storeState);\n\n return this.tcpStoresAbstractor.getStoresPlusInventorybyLatLng(skuId, quantity, 25, coordinates.lat, coordinates.long, currentCountry).then((searchResults) => {\n let store = searchResults.find((storeDetails) => storeDetails.basicInfo.id === preferredStore.basicInfo.id);\n return store && store.productAvailability.status !== BOPIS_ITEM_AVAILABILITY.UNAVAILABLE;\n }).catch(() => {\n // assume not available\n return false;\n });\n }", "function CheckExpenseItems(itemCount)\n{\n if (itemCount > 0)\n {\n return true;\n }\n else\n {\n return false;\n }\n}", "isInUse() {\n const { items, filters = {} } = this.props;\n let inUse = false;\n items.forEach(item => {\n if (item.key in filters && Array.isArray(filters[item.key]) && filters[item.key].length) {\n inUse = true;\n this.hasBeenUsed = true;\n }\n });\n return inUse;\n }", "function checkBsktForLeft() {\n for (let good in bestOffer.left) {\n if (basket.hasOwnProperty(bestOffer.left[good])) {\n return true;\n }\n }\n}", "function checkAllBidsResponseReceived(){\n\t\tvar available = true;\n\n\t\tutils._each(bidResponseReceivedCount, function(count, bidderCode){\n\t\t\tvar expectedCount = getExpectedBidsCount(bidderCode);\n\n\t\t\t// expectedCount should be set in the adapter, or it will be set\n\t\t\t// after we call adapter.callBids()\n\t\t\tif ((typeof expectedCount === objectType_undefined) || (count < expectedCount)) {\n\t\t\t\tavailable = false;\n\t\t\t}\n\t\t});\n\n\t\treturn available;\n\t}", "function isDollarStore(inventory) {\n for (var item of Object.keys(inventory)) {\n if (inventory[item].price > 1) {\n return false;\n }\n }\n return true;\n}", "get checkedItems() {\n return this.composer.queryItems((item) => {\n return this.isItemChecked(item) && (!this.manageRelationships || !this.getItemChildren(item).length);\n }, Infinity);\n }", "areComponentsLoaded() {\n return this.vues.filter((component) => !component.isLoaded).length === 0;\n }", "checkValidityProblems() {\n\t\t//Check whether there are any unnamed items or items without prices\n\t\tlet problems = false;\n\t\tif(this.state.albumName === \"\") {\n\t\t\tproblems = true;\n\t\t}\n\t\tfor (let item of this.state.items) {\n\t\t\tif(item.itemName === \"\" || (this.state.isISO && item.description === \"\") || (!this.state.isISO && (item.price === \"\" || item.pic === null)) ) {\n\t\t\t\tproblems = true;\n\t\t\t}\n\t\t}\n\t\tif (problems) {\n\t\t\tlet items = this.state.items;\n\t\t\tfor (let i = 0; i < items.length; i++) {\n\t\t\t\titems[i].highlighted = true;\n\t\t\t}\n\t\t\tthis.setState({\n\t\t\t\tshowMissingFieldsPopup: true,\n\t\t\t\thighlighted: true,\n\t\t\t\titems: items\n\t\t\t})\n\t\t}\n\t\treturn(problems);\n\t}", "ifConversionRatesAvailable() {\n return !!(\n this.initialCurrencyConversionData?.rates &&\n Object.keys(this.initialCurrencyConversionData.rates).length !== 0\n );\n }", "function isEnoughCoinsForGraf() {\n if (state.activeCoins.length === 0) {\n return false;\n }\n return true;\n }", "function anyItemSelected(){\n\tvar result = false;\n\t$(\".filleditem\").each(function() {\n\t\tif ($(this).hasClass(\"selected\")) {\n\t\t\tconsole.log(\"An item is selected\");\n\t\t\tresult = true;\n\t\t}\n\t});\n\treturn result;\n}", "infoResponseIsInStore() {\n const responses = this.currentInfoResponses();\n if (responses.length === this.imageServiceIds().length) {\n return true;\n }\n return false;\n }", "function pollingFn() {\n return (\n $('#thisCollection .product-grid-component .row .product-element').length\n > 0 && utag_data.product_attribute.search('bedroom') > -1\n );\n}", "isSatisfied(item) {\n return this.specs.every(x => x.isSatisfied(item));\n }", "function waitReady() {\n ready = getStore().getState().blocksSaveDataGet.contextListReady.hasAll();\n if (!ready) {\n window.setTimeout(waitReady, 50);\n return false;\n }\n resolve(true);\n return true;\n }", "function areChildrenVisible(item) {\n // we do not want to populate item with \n if (typeof item.ChildrenVisible != \"undefined\") {\n return item.ChildrenVisible;\n } else {\n return true;\n }\n }", "function achievements_check_in_inventory(id){\n\n\tvar ac = this.achievements_get(id);\n\t\n\tif (!ac || !num_keys(ac.conditions)) return false;\n\t\n\tfor (var condition in ac.conditions){\n\t\tvar data = ac.conditions[condition];\n\t\t\n\t\tif (data.type === null){\n\t\t\treturn false;\n\t\t}\n\t\telse if (data.type == 'counter' && data.group == 'in_inventory'){\n\t\t\tif (this.countItemClass(data.label) < intval(data.value)){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tlog.error('Undefined achievement condition for '+id+' in achievements_check_in_inventory(): '+data.type+' - '+data.group);\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\treturn true;\n}", "function checkForRefillProducts() {\n var countSor = 0,\n basket = BasketMgr.getCurrentBasket();\n\n if (basket) {\n var customer = basket.getCustomer();\n if (customer && !checkforExclusivelyGroup(customer)) {\n var productLineItems = basket.allProductLineItems;\n\n for each (var lineItem in productLineItems) {\n if ('hasSmartOrderRefill' in lineItem.custom\n && lineItem.custom.hasSmartOrderRefill\n && (lineItem.custom.SorMonthInterval > 0 || lineItem.custom.SorWeekInterval > 0)) {\n countSor++;\n }\n }\n }\n }\n\n session.custom.hasSORProducts = (countSor > 0);\n return (countSor > 0) ? true : false;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
initNums() takes no inputs and makes ajax request to retrieve 4 numbers to display screen
function initNums() { xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { //set fourNum equal to string list of integers retrieved by init.php fourNum = this.responseText; main(); } console.log("initiating nums"); } xhttp.open("GET", "InitialNum.php?q=", true); xhttp.send(); }
[ "function updateNums() {\n xhttp = new XMLHttpRequest();\n xhttp.onreadystatechange = function() {\n if (this.readyState == 4 && this.status == 200) {\n //set fourNum equal to string list of integers retrieved by init.php\n\n fourNum = this.responseText;\n console.log(fourNum);\n main();\n\n }\n\nconsole.log(\"changing nums\");\n }\n xhttp.open(\"GET\", \"NextNum.php?q=\", true);\n xhttp.send();\n\n}", "constructor () {\n this.numbers = this._buildNumbers();\n }", "function numbersReq(req, res, next) {\n console.log(++numberReq);\n next();\n}", "function logNumber(){\n $('.num').on(\"click\",function(){\n numFirst = 0;\n numFirst = ($(this).text());\n inputArray.push(numFirst);\n clearScreen();\n return inputArray;\n });\n }", "function addNumtoScreen(){\n $('.num').on(\"click\", function(){\n switch(numFirst){\n case '.':\n $('.screenp').append('.');\n $('.op').empty();\n break;\n case '0':\n $('.screenp').append('0');\n $('.op').empty();\n break;\n case '1':\n $('.screenp').append('1');\n $('.op').empty();\n break;\n case '2':\n $('.screenp').append('2');\n $('.op').empty();\n break;\n case '3':\n $('.screenp').append('3');\n $('.op').empty();\n break;\n case '4':\n $('.screenp').append('4');\n $('.op').empty();\n break;\n case '5':\n $('.screenp').append('5');\n $('.op').empty();\n break;\n case '6':\n $('.screenp').append('6');\n $('.op').empty();\n break;\n case '7':\n $('.screenp').append('7');\n $('.op').empty();\n break;\n case '8':\n $('.screenp').append('8');\n $('.op').empty();\n break;\n case '9':\n $('.screenp').append('9');\n $('.op').empty();\n break;\n }\n });\n }", "function numbers() {\n\t$('#liveupdate').load('newliveupdate.php');\n}", "function loadNumericSlider()\n {\n logDebug(\"loadNumericSlider: \");\n return partial(initNumericSlider) ;\n }", "function getNumberOfQuestions(){\n\t$.ajax({\n\t\ttype: \"GET\",\n\t\turl: \"http://127.0.0.1:8888/public/getQuestionsCount\",\n\t\tdatatype: 'jsonp',\n\t\tsuccess: function(response){\n\t\t\tvar questionCount = parseInt(response);\n\t\t\t$(\".numOfQuestions\").find(\"p\").html(\" av \" + questionCount);\n\t\t}\n\t});\n}", "function getImageNumbering(callback){\n var num = '0';\n if (opts.imageArray.length === 0 && opts.imagesInfo.length === 4) {\n (function intern(){\n var path = [opts.imagePath, opts.imagesInfo[0], num, '1.', opts.imagesInfo[1]].join('');\n var $img = $('<img>', {\n src: path,\n load: function(){\n priv.numbering = num;\n populateArray(true);\n },\n error: function(){\n num += '0';\n setTimeout(intern, 10);\n }\n });\n })();\n }\n else {\n populateArray(false);\n }\n }", "function top_performing_page_init() {\n //console.log('top performing page loaded');\n var xmlhttp = new XMLHttpRequest();\n var url = $('#ad-get-top-performing-pages-input').val();\n xmlhttp.onreadystatechange = function () {\n if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {\n try {\n var myArr = JSON.parse(xmlhttp.responseText);\n top_performing_page_run(myArr)\n } catch (e) {\n }\n }\n };\n xmlhttp.open(\"GET\", url, true);\n xmlhttp.send();\n }", "function request_credit_score() {\n\n $.ajax({\n url: credit_amount_url\n }).done(function (data) {\n $('#credit-num').text(data.credit_amount);\n setTimeout(function(){\n request_credit_score();\n }, 5000);\n });\n\n }", "function getCalculations() {\n $.ajax({\n type: 'GET',\n url: '/inputs',\n }).then(function (response) {\n console.log('Successful GET');\n // after we has them, append everything to DOM\n appendToDom(response);\n });\n}", "function start() {\n targetNumber = Math.floor(Math.random() * 102) + 19;\n console.log(targetNumber);\n applyValues();\n console.log(toppings);\n updateHtml();\n }", "function get_run_data(on_fetch) {\n var run_id = $(\"#result_selection\").val();\n var k = parseInt($(\"#run_selection\").val());\n var gen = parseInt($(\"#gen_number\").val());\n\n $.ajax({\n url: '/run-data',\n type: 'post',\n data: {\n run_id: run_id,\n k: k,\n generation: gen\n },\n success: on_fetch\n });\n}", "function yourLottoNbrs()\n {\n var nbr1, nbr2, nbr3, nbr4, nbr5, nbr6; //variables for 6 numbers\n {\n nbr1 = Math.floor(9 * Math.random());//random #1\n nbr2 = Math.floor(9 * Math.random());//random #2\n nbr3 = Math.floor(9 * Math.random());//random #3\n nbr4 = Math.floor(9 * Math.random());//random #4\n nbr5 = Math.floor(9 * Math.random());//random #5\n nbr6 = Math.floor(9 * Math.random());//random #6\n console.log(\"Your Lotto numbers for today are: \" + nbr1 + \" \" + nbr2 + \" \" + nbr3 + \" \" +\n nbr4 + \" \" + nbr5 + \" \" + nbr6 + \" .\");\n\n }\n }", "function CtrlChooseRandomNum(){\n var clickedElementId, counterStr, counter ,targetCoupon , allCoupons;\n clickedElementId = event.target.id;\n allCoupons = selectedElementIs.allCoupons;\n\n // check whether we clicked on fillAllCouponsButton or on one of the other FillrandomButton\n if(clickedElementId === selectedElementIs.fillAllCouponsButton.id) { counter = allCoupons.length; }\n else if(clickedElementId.includes('Fields')) {\n counterStr = clickedElementId[0]; // extract from the id, how many coupons we wanna fill.\n counter = parseInt(counterStr); // we make the extracted number and Interger.\n }\n\n //this is the main-part . go through with the function ONLY IF the counter is defined\n if(typeof counter !== \"undefined\") {\n for(var i = 0 ; i < allCoupons.length ; i++) { // we loop through all coupons from first to the nineth coupon.\n if(jackpotCtrl.hasCoupon(allCoupons[i].id) === 0) { // if the coupon is NOT saved yet. then fill it randomly.\n targetCoupon = allCoupons[i];\n UICtrl.fillRandomly(targetCoupon);\n\n // show it , by hidin the number of coupon, and showing the lil fields\n UICtrl.hideNumOfCoupon(targetCoupon); // it hides the numbers up until the last filled coupon.\n UICtrl.showFieldsOfOneCoupon(targetCoupon);\n\n //we add the new coupon to the data structure\n CtrlAddNewCoupon(targetCoupon); \n\n counter--; // keeping track of how many coupons to fill randomly.\n }\n if(counter === 0) { break;} // we get out of the loop once the chosen number coupons to fill , is reached.\n }\n\n CtrlClosePopup();\n updateTotal();\n UICtrl.showDeleteAllButton();\n UICtrl.exposeNextCoupon(jackpotCtrl.getAllCoupons());\n UICtrl.activateDoneFillingBtn();\n }\n }", "function addNumbers() {\n questionNumber++;\n}", "function getNumberOfHosts(){ \n\tvar client;\n\tclient = configureBrowserRequest(client);\t\n\tclient.open(\"POST\", \"?n-hosts\", true);\n\tclient.send();\n\t\n\tclient.onreadystatechange = function() {\n\t\tif(client.readyState == 4 && client.status == 200){\n\n\t\t\tif(parseInt(client.responseText) != currUsers){\n\t\t\t\tcurrUsers = parseInt(client.responseText);\n\t\t\t\tif(page == 2)\n\t\t\t\t\trequestAndPutHTML(\"?list-users\", \"users-list-body\");\n\t\t\t}\t\t\t\t\n\t\t\tif(parseInt(client.responseText) <= 2) {\n\t\t\t\tdocument.getElementById(\"n-hosts\").style.color = \"#f00\";\n\t\t\t\tdocument.getElementById(\"n-hosts\").innerHTML = \"<strong>\" + client.responseText + \"</strong>\";\n\t\t\t} else {\n\t\t\t\tdocument.getElementById(\"n-hosts\").style.color = \"#fff\";\n\t\t\t\tdocument.getElementById(\"n-hosts\").innerHTML = client.responseText;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tclient.open(\"POST\", \"?n-hosts\", true);\n\tclient.send();\n}", "function initComputation() {\n\n\tvar matriceRequest = new XMLHttpRequest();\n\tvar matriceWcag;\n method = \"GET\",\n\tmatriceVallydette = 'json/wcag-' + globalLang+ '.json';\n\n\tmatriceRequest.open(method, matriceVallydette, true);\n\tmatriceRequest.onreadystatechange = function () {\n\t if(matriceRequest.readyState === 4 && matriceRequest.status === 200) {\n\t\t\tdataWCAG = JSON.parse(matriceRequest.responseText);\n\t\t\t\n\t\t\tdataWCAG.items.forEach(initRulesAndTests);\n\n var btnShowResult = document.getElementById(\"btnShowResult\");\n btnShowResult.addEventListener('click', function () {\n\t\t\t\trunComputation();\n\t\t\t\tutils.setPageTitle(langVallydette.auditResult);\n\t\t\t\tutils.resetActive(document.getElementById(\"pageManager\"));\n\t\t\t\tutils.putTheFocus(document.getElementById(\"pageName\"));\n }, false);\n\t\t\n\t runTestListMarkup(dataVallydette.checklist.page[currentPage].items);\n\t\tif(window.location.hash !== \"\"){\n\t\t\tdocument.getElementById(window.location.hash.substring(1)).scrollIntoView();\n\t\t}\n\t\t\n\n\t }\n\t};\n\tmatriceRequest.send();\n\t\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Used to mark an email as read
function mark_read(email_id) { fetch('/emails/'+email_id, { method: 'PUT', body: JSON.stringify({ read: true, }) }) console.log("Email marked as Read") }
[ "function markAsRead(emailID) {\n let newRead = readEmails;\n if (!newRead.includes(emailID)) {\n newRead.push(emailID);\n }\n setReadEmails(newRead);\n }", "_onChangeMarkAllAsRead() {\n if (\n !this.isMarkAllAsReadRequested ||\n !this.thread ||\n !this.thread.mainCache ||\n !this.isLoaded ||\n this.isLoading\n ) {\n // wait for change of state before deciding what to do\n return;\n }\n this.update({ isMarkAllAsReadRequested: false });\n if (\n this.thread.isTemporary ||\n this.thread.model === 'mail.box' ||\n this.thread.mainCache !== this ||\n this.threadViews.length === 0\n ) {\n // ignore the request\n return;\n }\n this.env.models['mail.message'].markAllAsRead([\n ['model', '=', this.thread.model],\n ['res_id', '=', this.thread.id],\n ]);\n }", "function sendReadReceipt(recipientId,senderId){console.log(\"Sending a read receipt to mark message as seen\");var messageData={recipient:{id:recipientId},sender_action:\"mark_seen\"};return callSendAPI(messageData,senderId);}", "function markSelectedAsRead() {\n let newRead = [...readEmails]\n for (let i = 0; i < selectedEmails.length; i++) {\n if (!newRead.includes(selectedEmails[i])) {\n newRead.push(selectedEmails[i]);\n }\n } \n setReadEmails(newRead);\n }", "function markSelectedAsUnread() {\n let newRead = [...readEmails]\n newRead = newRead.filter((id) => !selectedEmails.includes(id));\n setReadEmails(newRead);\n }", "function markAsRead(id) {\n var alert = $(`#alert${id}`);\n if (!alert.hasClass('alertRead')) {\n alert.addClass('alertRead');\n res.alertcount = res.alertcount - 1;\n updateAlertCount();\n }\n $.ajax(`/api/User/Alert/${id}/Read`,\n {\n type: 'PUT',\n dataType: 'json'\n })\n .done(() => { /*ok*/ })\n .fail(() => alert('Cannot change alert.'));\n}", "onRetrievingUnreadEmails() {\r\n this._update('Retrieving emails...');\r\n }", "function reportMsgRead({ isNewRead = false, key = null }) {\n if (isNewRead) {\n gSecureMsgProbe.isNewRead = true;\n }\n if (key) {\n gSecureMsgProbe.key = key;\n }\n if (gSecureMsgProbe.key && gSecureMsgProbe.isNewRead) {\n Services.telemetry.keyedScalarAdd(\n \"tb.mails.read_secure\",\n gSecureMsgProbe.key,\n 1\n );\n }\n}", "function mark_archive(email_id) {\n fetch('/emails/'+email_id, {\n method: 'PUT',\n body: JSON.stringify({\n archived: true,\n })\n })\n load_mailbox('archive')\n console.log(\"Email Archived\")\n}", "async function asyncSetRead(aIds, flagRead) {\n console.log('Model::asyncSetRead()');\n const body = {\n messageIds: aIds,\n command: 'read',\n read: flagRead,\n };\n const response = await fetch('http://localhost:8082/api/messages', {\n method: 'PATCH',\n body: JSON.stringify(body),\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n },\n });\n const json = await response.json();\n return json;\n}", "async function asyncMarkAsUnread(aIds) {\n console.log(`Model::asyncMarkAsUnread(${aIds}`);\n return asyncSetRead(aIds, false);\n}", "shouldMarkMessagesReadOnLeavingFolder(aMsgFolder) {\n return Services.prefs.getBoolPref(\n \"mailnews.mark_message_read.\" + aMsgFolder.server.type\n );\n }", "async toggleStar() {\n await this.async(() => this.env.services.rpc({\n model: 'mail.message',\n method: 'toggle_message_starred',\n args: [[this.id]]\n }));\n }", "function startUnreadAlarm(){\n\n\tconsole.log(\"[UNREAD UPDATE] Creating alarm\");\n\tvar alarm = chrome.alarms.create(\"unreadAlarm\", {\n\t\twhen:0,\n\t\tperiodInMinutes: 5\n\t});\n\n\tconsole.log(\"[ALARMS] Adding event to alarm\");\n\tchrome.alarms.onAlarm.addListener(function(alarm) {\n\t\tif(alarm.name == \"unreadAlarm\"){\n\t\t\tcheckUnread();\n\t\t}\n\n\t\tif(alarm.name == \"updateAlarm\"){\n\t\t\tupdateFeeds();\n\t\t}\n\t});\n\tlistAlarms();\n}", "async function asyncMarkAsRead(aIds) {\n console.log(`Model::asyncMarkAsRead(${aIds}`);\n return asyncSetRead(aIds, true);\n}", "async messagingThreadSetAdminReadDate (socket, data, reply) {\n\n\t\t// Make sure the client passed in safe values.\n\t\tconst itemId = String(data.itemId);\n\n\t\tconst recUser = await this.database.get(`User`, { _id: itemId });\n\t\tconst lastRead = Math.max(recUser.conversation.lastMessageReceivedAt, recUser.conversation.lastMessageSentAt);\n\n\t\tawait this.database.update(`User`, itemId, {\n\t\t\t'appData.adminLastReadMessages': lastRead,\n\t\t});\n\n\t\treturn reply({ success: true });\n\n\t}", "static changeReadStatus(target) {\n if (target.classList.contains('read-btn')) {\n target.textContent === 'yes'\n ? (target.textContent = 'no')\n : (target.textContent = 'yes');\n // Success message\n UI.alertMessage('Read status changed', 'success');\n } else {\n return;\n }\n }", "async shareDocumentToEmail(id, email, accessType = 'read') {\n\n const User = this.database.models().user\n\n const user = User.findOne({ email: _.toLower(email) })\n if (user) {\n return this.shareDocumentToUser(id, user._id, accessType)\n } else {\n //@todo create an invitation and we do need notify to client to create an account and access the document\n return 'Need implement'\n }\n\n }", "waitMail(addr) {\n return imap_listener.waitMail(addr);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Refresh product total price
function refreshProductTotal() { var total = 0, isPound = false; $('#productsPanel .product-total').each(function() { var productTotal = $(this).text(); if ( productTotal.charAt(0) === '&' ) { productTotal = productTotal.replace('&pound;',''); isPound = true; } else { productTotal = productTotal.replace('€',''); } productTotal = productTotal.replace('.',''); productTotal = parseFloat(productTotal.replace(',', '.')); productTotal = parseFloat(productTotal.toFixed(2)); total = parseFloat(total + productTotal); }) total = total.toFixed(2); total = total.toString(); total = total.replace('.',','); if ( isPound == true ) { $('#productsStepTotal').html('&pound;'+total); } else { $('#productsStepTotal').html(total+'€'); } refreshCheckoutTotal(); }
[ "function getTotalPrice() {\n var totalPrice = 0;\n _.each(createSaleCtrl.saleProducts, function(product) {\n totalPrice += product.price*createSaleCtrl.bought[product.barCode];\n });\n createSaleCtrl.totalPrice = totalPrice;\n }", "@api\n addTotalPrice(price) {\n this.totalPrice += price;\n }", "async price_update() {}", "function setPrice(){\n var basePrice = 10;\n var totalPrice = 0;\n totalPrice = basePrice + getPriceValue();\n console.log(totalPrice);\n\n // display total price in the panel price\n var total = $('.panel.price').find('strong');\n console.log(total);\n $(total).html('$' + totalPrice);\n}", "function updateCartPrice() {\n var currentCartArray = JSON.parse(localStorage.getItem(\"cart\"));\n var subtotal = 0;\n var tax = 0;\n var total = 0;\n for (var i = 0; i < currentCartArray.length; i++) {\n if (currentCartArray[i] === null) {continue;}\n subtotal += Number(currentCartArray[i].price);\n }\n tax = subtotal * 0.07;\n total = Number(subtotal) + Number(tax);\n\n var currentSubtotalNum = document.getElementById(\"subtotal-num\");\n var currentTaxNum = document.getElementById(\"tax-num\");\n var currentTotalNum = document.getElementById(\"total-num\");\n\n currentSubtotalNum.innerText = \"$\" + Number(subtotal).toFixed(2);\n currentTaxNum.innerText = \"$\" + Number(tax).toFixed(2);\n currentTotalNum.innerText = \"$\" + Number(total).toFixed(2);\n}", "function changePrice(finish) {\n\t\t\tvar productID \t= $('body').attr('data-product-id'),\n\t\t\t\tfinishID \t= $('#finishesList input[type=\"radio\"]:checked').attr('data-finish');\n\t\t\t\tquantity \t= 1;\n\n\t\t\tcommon.blockUI();\n\t\t\t$.ajax({\n\t\t\t\turl: '/includes/web/plugin_precio_detalle.asp?id_producto=' + productID + '&cantidad=' + quantity + '&id_color=' + finishID,\n\t\t\t\tsuccess: function (data) {\n\t\t\t\t\tcommon.unblockUI();\n\t\t\t\t\tvar info = data.split('|');\n\t\t\t\t\t// refresh new price per unit in unit price\n\t\t\t\t\t$('#unitsPrice').html(info[1]);\n\t\t\t\t\t// refresh new values to main price section\n\t\t\t\t\t$('#priceContainer').find('#oldPrice').html(info[0]);\n\t\t\t\t\t$('#priceContainer').find('#productPrice').html(info[1]);\n\t\t\t\t\t$('#priceContainer').find('#discount').html(info[2]);\n\t\t\t\t}\n\t\t\t});\n\t\t}", "function updateProductQuantity() {\n var $this = $(this);\n $('.shop-analytics-single-product-details').data('quantity', $this.val());\n }", "function updateCartItems(){\n\tvar totalItems = 0;\n\tvar productTotal = 0;\n\t$('.numbers :input').each(function(){\n\t\tproductTotal += getPrice($(this).attr('id'),parseInt($(this).val(), 10));\n\t\ttotalItems += parseInt($(this).val(), 10);\n\t});\n\t$('#total').html('$' + productTotal.toFixed(2));\n\t$('#cart').html('<img src=\"images/cart.svg\" alt=\"cart\" />' + totalItems);\n\t$('#sidecart').html('<img src=\"images/cart.svg\" alt=\"cart\" />' + totalItems);\n}", "function getProductPrices()\n {\n $.getJSON(productPricesEndpoint, function (data) {\n prices = data;\n\n updateProductPrices();\n });\n }", "function refreshProductList() {\n loadProducts()\n .then(function (results) {\n vm.products = results;\n });\n }", "function updateTotalTable() {\r\n let price = 0;\r\n let discount = 0;\r\n for (let i = 0; i < this.itemsInCart.length; i++) {\r\n price += this.itemsInCart[i].price.display * this.itemsInCart[i].qty;\r\n discount += this.itemsInCart[i].discount;\r\n }\r\n const totalPriceAfterDiscount = ((discount / 100) * price);\r\n const totalCost = (price - totalPriceAfterDiscount);\r\n console.log(totalCost);\r\n document.getElementById('totalItemPrice').innerHTML = '$' + price;\r\n document.getElementById('totalDiscount').innerHTML = '-' + discount + '%';\r\n\r\n document.getElementById('totalPrice').innerHTML = '$' + totalCost;\r\n\r\n}", "function updateCartQuantity() {\n let sum = null;\n for (let i = 0; i < order.length; i++) {\n sum += order[i].quantity;\n }\n cartCount = sum;\n $('#cartCount')\n .text(cartCount);\n orderSubTotal();\n }", "get price() {\n return this._price\n }", "function totalPrice(){\n\t\t\t\tvar totalPrice = 0;\n\t\t\t\tfor (var i in cart){\n\t\t\t\t\ttotalPrice += cart[i].price;\n\t\t\t\t}\n\t\t\t\treturn totalPrice;\n\t\t\t}", "function updateItemTotal(){\n let quantity = $(this).val(); // Get the item quantity\n let item = $(this).attr(\"id\"); // Get the item selected\n let total;\n \n // Find which item was updated\n if(item == \"item1\"){\n total = quantity * 24.99;\n total = total.toFixed(2);\n $(\"#total1\").html(`${total}`);\n } \n else if(item == \"item2\"){\n total = quantity * 10.00;\n total = total.toFixed(2);\n $(\"#total2\").html(`${total}`);\n } \n else if(item == \"item3\"){\n total = quantity * 24.99;\n total = total.toFixed(2);\n $(\"#total3\").html(`${total}`);\n }\n \n updateSubtotal();\n updateTax();\n updateFinalTotal();\n }", "priceCalc(){\n var that = this;\n var equipmetCost = 0;\n var tempPrice = this.phoneStorage.filter(function(el){\n if(el.storage == that.selectedStorage ){\n return el;\n }\n });\n this.selectedEquipment.forEach(function(el){\n equipmetCost += Number(el);\n });\n this.total = equipmetCost + tempPrice[0].price - this.selectedRate;\n\n }", "total() {\n return Menu.getSodaPrice();\n }", "function updateCartTotal() {\n var cartItemContainer = $('.cart-items')[0];\n var cartRows = cartItemContainer.getElementsByClassName('cart-row');\n var total = 0;\n for (var i = 0; i < cartRows.length; i++) {\n var cartRow = cartRows[i];\n var priceElement = cartRow.getElementsByClassName('cart-price')[0];\n var quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0];\n var price = parseFloat(priceElement.innerText.replace('R.', ''));\n var quantity = quantityElement.value;\n total = total + (price * quantity);\n }\n var amt = 60\n $('input[name=\"drone\"]').change(function () {\n if ($(this).attr(\"id\") == \"Post\") {\n amt = 60;\n } else {\n amt = 100;\n }\n $('.cart-total-price').text(\"R \" + (total + amt).toFixed(2))\n })\n $('.btn-coupon').click(function () {\n if ($('#Coupon').val() == \"BOH232\") {\n var code = -100;\n $('.cart-total-price').text(\"R \" + (total + code + amt).toFixed(2))\n } else {\n var code = 0;\n $('.cart-total-price').text(\"R \" + (total + code + amt).toFixed(2))\n }\n\n })\n}", "function changeValue() {\n\t\t\t\tif($(\"#basket-replace\").length != 0){\n\t\t\t\t\tvar cartTotal = 0;\n\n\t\t\t\t\t//first part\n\t\t\t\t\t$('.cart-item').each(function(){\n\t\t\t\t\t\tvar quant = $(this).find('input[name=quantity]').val();\n\t\t\t\t\t\tcartTotal += quant * $(this).attr('data-current-box-price');\n\t\t\t\t\t});\n\t\t\t\t\t\n\t\t\t\t\t//second part\n\t\t\t\t\tif(cartTotal <= 20000){\n\t\t\t\t\t\tprice_type = 'Белая';\n\t\t\t\t\t\tpercent = 1;\n\t\t\t\t\t}else if(cartTotal <= 80000){\n\t\t\t\t\t\tprice_type = 'Зелёная';\n\t\t\t\t\t\tpercent = 0.95;\n\n\t\t\t\t\t}else if(cartTotal <= 200000){\n\t\t\t\t\t\tprice_type = 'Синяя';\n\t\t\t\t\t\tpercent = 0.93;\n\t\t\t\t\t}else if (cartTotal >= 200000){\n\t\t\t\t\t\tprice_type = 'Красная';\n\t\t\t\t\t\tpercent = 0.9;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t$(\".cart-item\").each(function(key, e){\n\t\t\t\t\t\tvar productSumItem = $(e).find('.multiply-price');\n\t\t\t\t\t\tvar quant = $(e).find('input[name=quantity]').val();\n\t\t\t\t\t\t//without discount price\n\t\t\t\t\t\tvar price = $(e).attr('data-current-price');\n\t\t\t\t\t\tvar boxPrice = $(e).attr('data-current-box-price');\n\n\t\t\t\t\t\t$(e).find('.box-price').find('.price__value').text(parseInt(boxPrice * percent));\n\t\t\t\t\t\t$(e).find('.current-price').find('.price__value').text(parseInt(price * percent));\n\t\t\t\t\t\t$(e).find('.product-sum').find('.price__value').text(parseInt(boxPrice * percent * quant));\n\t\t\t\t\t\tvar economy = boxPrice * quant - boxPrice * quant * percent;\n\t\t\t\t\t\t$(e).find('.prod-economy span').text(parseInt(economy)).show();\n\t\t\t\t\t\tif(percent != 1){\n\t\t\t\t\t\t\t$(e).find('.box-price-old').find('.price__value').text(boxPrice);\n\t\t\t\t\t\t\t$(e).find('.old-price').find('.price__value').text(price);\n\t\t\t\t\t\t\t$(e).find('.product-sum-old').find('.price__value').text(boxPrice * quant);\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t$('.price_old').find('.price__value').text('');\n\t\t\t\t\t\t\t$(e).find('.prod-economy').hide();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\t$('.all-orders-prices-sum, .bulk-total').text(cartTotal * percent);\n\t\t\t\t\t$('.cart-total').text(cartTotal);\n\t\t\t\t\t$('.economy-value').text(cartTotal - cartTotal * percent);\n\t\t\t\t\t\n\t\t\t\t\t$('.price-type').text(price_type);\n\t\t\t\t}\n\t\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hides the "Hide maps with no year listed" checkbox if not sorting by year Parameters:selectedSort alllowercase string representation of the selected sort value controlsNode the node that contains the sorting/hide controls
function hideYearControl(selectedSort, controlsNode) { var hideNoYearLabel = controlsNode.children[3]; if (selectedSort == "year") { hideNoYearLabel.style.display = "inline-block"; } else { hideNoYearLabel.style.display = "none"; } }
[ "function hideNoYear() {\n\tvar controlsNode = this.parentNode.parentNode;\n\tvar maps = $(controlsNode).parent().parent().find('.map');\n\tvar mapsNode = $(controlsNode.parentNode.parentNode).find('.maps')[0];\n\tvar mapsToOutput = [];\n\tif (this.checked) { // Hide maps\n\t\tfor (var i = 0; i < maps.length; i++) {\n\t\t\tvar year = maps[i].firstElementChild.children[3].textContent;\n\t\t\tif (year != \"No year listed\") {\n\t\t\t\tmapsToOutput.push(maps[i]);\n\t\t\t} else {\n\t\t\t\tnoYearMaps.push(maps[i]);\n\t\t\t}\n\t\t}\n\t} else { // Unhide maps\n\t\tif (controlsNode.children[2].firstElementChild.checked) { // If in descending order\n\t\t\tfor (var i = 0; i < noYearMaps.length; i++) {\n\t\t\t\tmapsToOutput.push(noYearMaps[i]);\n\t\t\t}\n\t\t\tfor (var i = 0; i < maps.length; i++) {\n\t\t\t\tmapsToOutput.push(maps[i]);\n\t\t\t}\n\t\t} else {\n\t\t\tmapsToOutput = maps;\n\t\t\tfor (var i = 0; i < noYearMaps.length; i++) {\n\t\t\t\tmapsToOutput.push(noYearMaps[i]);\n\t\t\t}\n\t\t}\n\t\tnoYearMaps = [];\n\t}\n\toutputMaps(mapsToOutput, mapsNode);\n}", "function datagrid_toggle_sort_selects() {\n var jq_dds = $('.datagrid .header .sorting dd');\n if (jq_dds.length == 0) return;\n var dd1 = jq_dds.eq(0)\n var dd2 = jq_dds.eq(1)\n var dd3 = jq_dds.eq(2)\n var sb1 = dd1.find('select');\n var sb2 = dd2.find('select');\n var sb3 = dd3.find('select');\n\n if( sb1.val() == '' ) {\n dd2.hide();\n sb2.val('');\n dd3.hide();\n sb3.val('');\n } else {\n dd2.show();\n if( sb2.val() == '' ) {\n dd3.hide();\n sb3.val('');\n } else {\n dd3.show();\n }\n }\n\n $('dl.sorting select option').removeAttr('disabled');\n disable_sort(sb3);\n disable_sort(sb2);\n disable_sort(sb1);\n}", "function hideYears() {\n svg.selectAll('.year').remove();\n }", "function setValuesVisibility() {\n lodash.forEach(ctrl.sortOptions, function (value) {\n lodash.defaults(value, {visible: true});\n });\n }", "function disable_sort(sb) {\n if ($(sb).val() == '') return;\n var sbval = $(sb).val().replace(/^-/, \"\");\n $('dl.sorting select[id!=\"'+$(sb).attr('id')+'\"]').find(\n 'option[value=\"'+sbval+'\"], option[value=\"-'+sbval+'\"]'\n ).attr('disabled', 'disabled');\n}", "function hideAxis() {\n g.select('.x.axis')\n .transition().duration(500)\n .style('opacity', 0);\n }", "deselectAll() {\n\n if (this.currentTab === 'supergroups') {\n for (let sg in this.supergroups) {\n if (this.supergroups.hasOwnProperty(sg)) {\n this.supergroups[sg].visible = false;\n }\n }\n this.checkedSupergroups = [];\n }\n else if (this.currentTab === 'groups') {\n for (let g in this.groups) {\n if (this.groups.hasOwnProperty(g)) {\n this.groups[g].visible = false;\n }\n }\n this.checkedGroups = [];\n }\n\n MapLayers.nuts3.renderLayer();\n\n }", "function hideOVLayer(name) {\t\t\n \tvar layer = getOVLayer(name);\t\t\n \tif (isNav4)\n \tlayer.visibility = \"hide\";\n \t//if (document.all)\n\telse\n \t layer.visibility = \"hidden\";\n\t //layer.display=\"block\";\n}", "function hideInputs() {\n var selectedDistribution = jQuery(\"#distribution\").val();\n for (inputName in fEnableObj) {\n var inputField = jQuery(`input[name='${inputName}']`);\n if (fEnableObj[inputName] === selectedDistribution)\n inputField.parent(\"label\").removeClass(\"hidden\");\n else\n inputField.parent(\"label\").addClass(\"hidden\");\n }\n if (selectedDistribution === \"parcel\") {\n jQuery(\"#geometry-box\").prop(\"checked\", true);\n jQuery(\"select#geometry\").attr(\"disabled\", true);\n jQuery(\".inputfield.maxsize\").addClass(\"hidden\");\n } else {\n jQuery(\"select#geometry\").attr(\"disabled\", false)\n if (jQuery(\"#geometry\").val() == \"box\") {\n jQuery(\".inputfield.maxsize\").removeClass(\"hidden\");\n } else {\n jQuery(\".inputfield.maxsize\").addClass(\"hidden\");\n }\n }\n}", "function hideUncheckedShowChecked() {\n\t// Hide the unchecked options\n\tfor(var i = 0; i < unchecked.length; i++) {\n\t\tif($('#memberBody tr').hasClass(selectedState) || selectedState == 'state-All') {\n\t\t\t$('.party-' + unchecked[i].value).hide();\n\t\t}\n\t}\n\t// Show the checked options\n\tfilterStateAll();\n}", "function disableLegend(){\n\t$(\".legend_toggle\").prop(\"checked\",false);\n\tLayerControl.legend_toggled = false;\n}", "function hideControls() {\n /* FIXME: integrate with controlvars.css so all visibility is controlled\n * through a series of CSS rules */\n var controls = arguments;\n\n if (controls.length == 0) {\n controls = ocean.controls;\n }\n\n $.each(controls, function (i, control) {\n var parent = _controlVarParent(control);\n var group = parent.parent('.controlgroup');\n\n parent.hide();\n\n /* hide control group if required */\n if (group.children('.controlvar:visible').length == 0) {\n group.hide();\n }\n });\n}", "function hideGeoportalView() {\n var gppanel= viewer.getVariable('gppanel');\n gppanel.style.visibility= 'hidden';\n gppanel.style.position= 'absolute';\n gppanel.style.top= '-9999px';\n gppanel.style.left= '-9999px';\n}", "function toggle_postcodes_visibility() {\r\n // Toggle node\r\n for (let i = 0; i < nodes.length; i++) {\r\n if (this.value == nodes[i].location.split(\" \")[0]) {\r\n if (map.hasLayer(nodes[i].layer)) {\r\n nodes[i].layer.removeFrom(map);\r\n nodes[i].label.removeFrom(map);\r\n } else {\r\n nodes[i].layer.addTo(map);\r\n }\r\n }\r\n }\r\n\r\n // Toggle edges\r\n for (let i = 0; i < edges.length; i++) {\r\n if (this.value == edges[i].start_node.location.split(\" \")[0]) {\r\n if (map.hasLayer(edges[i].layer)) {\r\n edges[i].layer.removeFrom(map);\r\n edges[i].label.removeFrom(map);\r\n } else {\r\n edges[i].layer.addTo(map);\r\n }\r\n }\r\n }\r\n}", "function mapProgrameList() {\n\t\t$('.page-nepad-on-the-continent .view-map-program-list li a').each(function(){\n\t\t\tif($(this).text().length==0){\n\t\t\t $(this).parent().hide();\t\n\t\t\t}\n\t\t});\n\t\t$('#mapsvg svg path').click(function(){\n\t\t\t$('.page-nepad-on-the-continent .view-map-program-list li a').each(function(){\n\t\t\t\tif($(this).text().length==0){\n\t\t\t\t\t$(this).parent().hide();\t\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}", "function filter_by_month() {\n //get the value of the month and year the user wants to query\n let year_month = document.getElementById('query_month').value;\n if (year_month == \"\") return;\n let list = year_month.split(\"-\");\n let search_year = list[0];\n let search_month = list[1];\n\n table = document.getElementById(\"output_table\");\n tr = table.getElementsByTagName('tr');\n\n // Loop through all table rows, and hide those that don't match the year and month query\n for (i = 0; i < tr.length; i++) {\n td = tr[i].getElementsByTagName(\"td\")[0];\n if (td) {\n column_date = td.innerHTML.split(\"-\");\n if (column_date[0]==search_year && column_date[1]==search_month) {\n tr[i].style.display = \"\";\n } else {\n tr[i].style.display = \"none\";\n }\n }\n }\n }", "visibility(value) {\n this.isShowSelectWeek = (value === 'week');\n this.isShowSelectMonth = (value === 'month');\n\n return value;\n }", "function uncheckDistanceEducation(ctrl)\n{\n if(ctrl.selectedIndex > 0)\n document.getElementById(chkDistanceEduGlobal).checked = false;\n}", "function resetFilters(){\n \n console.log(\"resetFilters()\");\n d3.selectAll(\".mainFilterCheckbox\").property('checked', false);\n \n resetZoom();\n \n updateVis();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
retrieve the attempt data
async function getAttempt() { if(props.match.params.attemptNo=="highest"){ await microcredapi .get(`/module/attempt/${props.match.params.studentId}/${props.match.params.courseId}/${props.match.params.moduleId}`) .then(response => { updateQuestions(response.data.questions, response.data.answersMap, response.data.providedAnswerMap, response.data.score) }) }else{ await microcredapi .get(`/module/attempt/${props.match.params.studentId}/${props.match.params.courseId}/${props.match.params.moduleId}/${props.match.params.attemptNo}`) .then(response => { updateQuestions(response.data.questions, response.data.answersMap, response.data.providedAnswerMap, response.data.score) }) } }
[ "function getLastOfflineAttemptData() {\n // Check if last offline attempt is incomplete.\n return $mmaModScorm.isAttemptIncomplete(scormId, lastOffline, true, false, siteId).then(function(incomplete) {\n lastOfflineIncomplete = incomplete;\n return $mmaModScormOffline.getAttemptCreationTime(siteId, scormId, lastOffline).then(function(time) {\n lastOfflineCreated = time;\n });\n });\n }", "function fetchData() {\n // Wait for any ongoing sync to finish. We won't sync a SCORM while it's being played.\n return $mmaModScormSync.waitForSync(scorm.id).then(function() {\n // Get attempts data.\n return $mmaModScorm.getAttemptCount(scorm.id).then(function(attemptsData) {\n return determineAttemptAndMode(attemptsData).then(function() {\n // Fetch TOC and get user data.\n var promises = [];\n promises.push(fetchToc());\n promises.push($mmaModScorm.getScormUserData(scorm.id, attempt, offline).then(function(data) {\n userData = data;\n }));\n\n return $q.all(promises);\n });\n }).catch(showError);\n });\n }", "async function previousGameData() {\n try {\n // get game data\n const res01 = await fetch(previousGameURL);\n const data01 = await res01.json();\n const gameInfo = await data01.teams[0].previousGameSchedule.dates[0].games[0];\n // get team stats\n const res02 = await fetch(teamStatsURL);\n const data02 = await res02.json();\n const teamInfo = await data02.teams[0].teamStats[0].splits[0].stat;\n const result = formatGameResults(gameInfo, teamInfo);\n provideScore(result);\n } catch (err) {\n console.log('Seems there was an error fetching the game data...');\n }\n}", "getInviteUserData () {\n\t\treturn {\n\t\t\tteamId: this.team.id,\n\t\t\temail: this.userFactory.randomEmail(),\n\t\t\t// indicates to send back invite code with the response, \n\t\t\t// instead of just using it in an email\n\t\t\t_confirmationCheat: this.apiConfig.sharedSecrets.confirmationCheat\t\n\t\t};\n\t}", "getUserPresenceData(){\n callMsGraph(this.props.msalContext, graphConfig.presenceEndpoint, this.setPresenceInformation);\n }", "function getUserData(req){\nif (req.client.authorized){\n var subject = req.connection.getPeerCertificate().subject;\n return{\n user: subject.CN\n };\n\n }\nelse {\n return{user: \"NO CERT!\"};\n}\n\n\n}", "function getAppData() {\n $log.debug('success retrieving application data');\n return self.LApp.data;\n }", "getData() {\n\t\t\t// returns deep copy of _runoffResultsData\n\t\t\treturn JSON.parse(JSON.stringify(_runoffResultsData));\n\t\t}", "function GetLastActionDataHandler(req, res) {\n var lastActionData = wait.for(GetLastActionData, req);\n for (var i = 0; i < lastActionData.length; i++) {\n var abc = wait.for(common.getusername, lastActionData[i].owner);\n\t\tvar role = wait.for(common.getRole,lastActionData[i].owner);\n lastActionData[i].owner = abc;\n\t\tlastActionData[i].role = role;\n }\n res.send(lastActionData);\n}", "function getUserInfo() {\n return user;\n }", "getData() {\n return PRIVATE.get(this).opt.data;\n }", "async function extractSkillData(name) { \n var raw = await listSkills(name).catch(function (rej) {\n return {};\n });\n var skillData = {};\n if(raw[\"Ranged\"] != null) {\n for(var skill in raw) {\n skillData[skill] = raw[skill].xp/10;\n }\n } else {\n // runemetric profile is not public\n raw = await getHiscoreData(name).catch(function (rej) {\n return {};\n });\n for(var skill in raw) {\n skillData[skill] = parseInt(raw[skill].exp, 10);;\n }\n }\n return skillData;\n}", "function ReadData() \n\t{\n MyUser = getCookie(COOKIE_NAMES.user);\n MyPass = getCookie(COOKIE_NAMES.password);\n MyZoom = getCookie(COOKIE_NAMES.zoom);\n wlat = getCookie(COOKIE_NAMES.lat);\n wlon = getCookie(COOKIE_NAMES.lng);\n myloginid = getCookie(COOKIE_NAMES.id);\n mytel = getCookie(COOKIE_NAMES.tel);\n myid = getCookie(COOKIE_NAMES.myid);\n\tconsole.log(\"reading: \"+MyUser+ \" - \"+MyPass+ \" - \"+MyZoom+ \" - \"+wlat+ \" - \"+wlon+ \" - \"+myloginid+ \" - \"+mytel+ \" - \"+myid);\n\t}", "function getCompCount() {\n console.log(\"In getUser\");\n var awarded = 0;\n $.get(\"/app.json\", function(data) {\n completionCount = data;\n console.log(\"This is # of completed tasks in user.js: \"+data);\n count = completionCount;\n console.log(\"Count: \"+count);\n\n }).done(getBadges);\n\n }", "function recordAttempts() {\n\t\tattempts++;\n\t\t$('#attempts').html(attempts);\n\n\t\tif (attempts > 16 && attempts < 28) {\n\t\t\tstars = '<i class=\"fas fa-star\"></i><i class=\"fas fa-star\"></i><i class=\"far fa-star\"></i>';\n\t\t\t$('#stars').html(stars);\n\t\t} else if (attempts >= 28 && attempts < 36) {\n\t\t\tstars = '<i class=\"fas fa-star\"></i><i class=\"far fa-star\"></i><i class=\"far fa-star\"></i>';\n\t\t\t$('#stars').html(stars);\n\t\t} else if (attempts >= 36) {\n\t\t\tstars = '<i class=\"far fa-star\"></i><i class=\"far fa-star\"></i><i class=\"far fa-star\"></i>';\n\t\t\t$('#stars').html(stars);\n\t\t} else {\n\t\t\treturn;\n\t\t};\n\n\t}", "function attempt() {\r\n connections[id].attempts++;\r\n if (connections[id].attempts > retry) {\r\n connections[id].attempts = 0;\r\n connections[id].deny++;\r\n self.log(chalk.yellow(\"Access denied: too many attempts.\"));\r\n callback(\"Access denied: too many attempts.\", false);\r\n return;\r\n }\r\n if (connections[id].deny >= deny && unlockTime > 0) {\r\n setTimeout(function(){\r\n connections[id].deny = 0;\r\n }, unlockTime);\r\n connections[id].attempts = 0;\r\n self.log(chalk.yellow(\"Account locked out: too many login attempts.\"));\r\n callback(\"Account locked out: too many login attempts.\", false);\r\n return;\r\n }\r\n gather(function(user, pass){\r\n user = search(user, pass, users);\r\n if (user) {\r\n connections[id].attempts = 0;\r\n connections[id].deny = 0;\r\n callback(\"Successfully Authenticated.\", true);\r\n } else {\r\n state.pass = void 0;\r\n setTimeout(function(){\r\n if (connections[id].attempts <= retry) {\r\n self.log(\"Access denied.\");\r\n }\r\n attempt();\r\n }, retryTime);\r\n }\r\n });\r\n }", "async getId() {\n try {\n let userData = await AsyncStorage.getItem('userID')\n return userData\n } catch (error) {\n alert(error)\n }\n }", "function getRetriesCounter(type) {\r\n return xhrCounter[type];\r\n }", "async populateCrashRating(){\n let data = await nhtsa.getStars(this);\n /**\n * Overall Crashrating star count of vehicle.\n * @type {string}\n */\n this.CrashRaiting = data.data.Results[0].OverallRating;\n\n return data;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Solving for a hamiltonia cycle is NPcomplete, so this is a very specific solution that works purely for this size and starting position.
function hamiltonianCycle() { var current_x = x[0] / IMG_SIZE; var current_y = y[0] / IMG_SIZE; var head_x = x[0] / IMG_SIZE; var head_y = y[0] / IMG_SIZE; //Head to top while (current_y > 0) { current_y--; path.push(current_x + "," + current_y); } //Zig zag to the bottom (ending at bottom right corner) while (current_y < MAX_BOUND) { //Go right on even y if (current_y % 2 == 0) { while (current_x < MAX_BOUND) { current_x++; path.push(current_x + "," + current_y); } } //Go left on odd y else { while (current_x > head_x + 1) { current_x--; path.push(current_x + "," + current_y); } } current_y++; path.push(current_x + "," + current_y); } //To the left (bottom left corner) while (current_x > 0) { current_x--; path.push(current_x + "," + current_y); } //To the top again (top left corner) while (current_y > 0) { current_y--; path.push(current_x + "," + current_y); } //Zig zag down to second to last row while (current_y < MAX_BOUND) { //Go right on odd y if (current_y % 2 == 1) { while (current_x > 1) { current_x--; path.push(current_x + "," + current_y); } } //Go left on even y else { while (current_x < head_x - 1) { current_x++; path.push(current_x + "," + current_y); } } current_y++; path.push(current_x + "," + current_y); } //Undo the last move current_y--; path.pop(); //Go right one current_x++; path.push(current_x + "," + current_y); //Back up to the start (cycle complete) while (current_y > head_y) { current_y--; path.push(current_x + "," + current_y); } timer = setInterval(hamiltonianMove, DELAY/4); }
[ "function hamiltonianPath() {\n if (!isConnected()) {\n alert('This graph is not connected!');\n return;\n }\n stopAnimation();\n clearCyStyle();\n cy.elements().unselect();\n\n const nodes = cy.nodes();\n const len = nodes.length;\n /**\n * @param {cytoscape.NodeSingular[]} path\n * @param {boolean[]} visited\n * @param {number} idx\n * @param {Array<cytoscape.NodeSingular[]>} hamPaths\n * Record a hamiltonian path in this array\n * if a hamiltonian cycle is not found and a hamiltonian path exists\n * @return {boolean}\n * true - a hamiltonian cycle is found.\n * false - a hamiltonian cycle is not found.\n */\n function helper(path, visited, idx, hamPaths) {\n if (idx === len) {\n // if the edge connecting the first and the last vertex exists, then this is a hamiltonian cycle\n const lastEdge = path[path.length - 1].edgesWith(path[0]);\n if (lastEdge.length !== 0) return true;\n\n // otherwise it's a hamiltonian path\n // we record only one hamiltonian path\n if (hamPath.length === 0) hamPaths.push(path.concat());\n return false;\n }\n\n for (let i = 1; i < len; i++) {\n // check that the vertex is not in the path and it's adjacent to\n // the previous node in the path constructed\n if (!visited[i] && nodes[i].edgesWith(path[idx - 1]).length > 0) {\n // add this node to the path\n path[idx] = nodes[i];\n visited[i] = true;\n\n // continuing construction..\n const result = helper(path, visited, idx + 1, hamPaths);\n if (result) return result;\n\n // if adding it does not construct a hamiltonian cycle, remove it from the path\n path[idx] = undefined;\n visited[i] = false;\n }\n }\n return false;\n }\n /**\n * @type {cytoscape.NodeSingular[]}\n */\n let hamPath = new Array(len);\n /**\n * @type {Array<cytoscape.NodeSingular[]>}\n */\n const sols = [];\n\n const visited = new Array(len).map(x => false);\n visited[0] = true;\n\n // we start from node 0\n hamPath[0] = nodes['0'];\n const result = helper(hamPath, visited, 1, sols);\n\n if (!result) {\n if (sols.length === 0) {\n alert('No hamiltonian path/cycle is found!');\n return;\n }\n [hamPath] = sols;\n }\n\n console.log(sols);\n\n const p = new LinkedList();\n\n for (let i = 0; i < len - 1; i++) {\n const [v1, v2] = [hamPath[i], hamPath[i + 1]];\n p.add(v1);\n p.add(\n v1\n .select()\n .edgesWith(v2.select())\n .select()\n );\n }\n\n const lastNode = hamPath[hamPath.length - 1];\n p.add(lastNode);\n\n // select the last edge to form a cycle if it's a hamiltonian cycle\n if (result) {\n p.add(hamPath[0].edgesWith(lastNode).select());\n p.add(hamPath[0]);\n }\n\n clearResult();\n ca.add(cy.elements(':selected'));\n caReLayout();\n p.traverse(animation_check.checked, true);\n}", "function HamiltonianCycle(graph) {\n var vertices = graph.length,\n path = [];\n for (var i = 0; i < vertices; i++) {\n path[i] = -1;\n }\n\n /* Let us put vertex 0 as the first vertex in the path. If there is\n a Hamiltonian Cycle, then the path can be started from any point\n of the cycle as the graph is undirected */\n path[0] = 0;\n if (this.HamiltonianCycleUtil(graph, path, 1) === false) {\n console.log('\\nSolution does not exist');\n return false;\n }\n\n console.log('\\nSolution exists');\n console.log(path.join(' ') + ' ' + path[0]);\n return true;\n}", "function solve(w, h, data_array) {\n\tvar k = 0;\n\tvar city_xs = [];\n\tvar city_ys = [];\n\tvar city_is = [];\n\tfor (var y = 0; y < h; ++y) {\n\t\tfor (var x = 0; x <= w; ++x) {\n\t\t\tconst i = x + y * (w+1);\n\t\t\tif (data_array[i] == 1) {\n\t\t\t\t++k;\n\t\t\t\tcity_xs.push(x);\n\t\t\t\tcity_ys.push(y);\n\t\t\t\tcity_is.push(i);\n\t\t\t}\n\t\t}\n\t}\n\tif (k == 1) return data_array; // No changes required\n\n\tvar edges = buildEdges(w, h);\n\n\tconst mm = 1 << (k-1);\n\tconst mi = (w+1)*h;\n\tconst inf = 1000000000;\n\n\tvar dp = [[]]; // dummy unused first dimension\n\tfor (var mask = 1; mask < mm; ++mask) {\n\t\t// O(3^k n) part\n\t\tvar dists = []\n\t\tfor (var y = 0; y < h; ++y) {\n\t\t\tfor (var x = 0; x <= w; ++x) {\n\t\t\t\tconst i = x + y * (w+1);\n\t\t\t\tvar d = inf;\n\t\t\t\tfor (var submask = mask; submask != 0; submask = (submask - 1) & mask) {\n\t\t\t\t\tconst invmask = mask ^ submask;\n\t\t\t\t\tif (invmask == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\td = Math.min(d, dp[submask][i] + dp[invmask][i]);\n\t\t\t\t}\n\t\t\t\tif ((data_array[i] == 0) && (d != inf)) {\n\t\t\t\t\td -= 1; // Refund one payment of the node\n\t\t\t\t}\n\t\t\t\tdists.push(d);\n\t\t\t}\n\t\t}\n\t\t\n\t\tif ((mask & (mask - 1)) == 0) {\n\t\t\tfor (var j = 0; j < k-1; ++j) {\n\t\t\t\tif (mask & (1 << j)) {\n\t\t\t\t\tdists[city_is[j]] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// O(2^k n) part, so this doesn't affect the overall running time\n\t\tvar que = [];\n\t\tfor (var d = 0; d <= mi; ++d) {\n\t\t\tque.push([]);\n\t\t}\n\t\tfor (var i = 0; i <= mi; ++i) {\n\t\t\tif (dists[i] <= mi) {\n\t\t\t\tque[dists[i]].push(i);\n\t\t\t}\n\t\t}\n\t\tfor (var d = 0; d <= mi; ++d) {\n\t\t\tfor (var j = 0; j < que[d].length; ++j) {\n\t\t\t\t// Check if we have already handled this\n\t\t\t\tconst i = que[d][j];\n\t\t\t\tif (dists[i] < d) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Update distances\n\t\t\t\tfor (var ti = 0; ti < edges[i].length; ++ti) {\n\t\t\t\t\tconst t = edges[i][ti];\n\t\t\t\t\tconst c = d + (data_array[t] == 0 ? 1 : 0);\n\t\t\t\t\tif (dists[t] > c) {\n\t\t\t\t\t\tdists[t] = c;\n\t\t\t\t\t\tque[c].push(t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Save the DP and continue\n\t\tdp.push(dists);\n\t}\n\n\t// Construct solution from the DP\n\tvar visited = [];\n\tfor (var mask = 0; mask < mm; ++mask) {\n\t\tvar row = [];\n\t\tfor (var i = 0; i < mi; ++i) {\n\t\t\trow.push(false);\n\t\t}\n\t\tvisited.push(row);\n\t}\n\n\tconst start_ind = city_is[k-1];\n\tbuildPaths(start_ind, mm-1, visited, edges, data_array, dp);\n\n\tvar best = [];\n\tfor (var i = 0; i < mi; ++i) {\n\t\tif (data_array[i] == 0) {\n\t\t\tvar check = false;\n\t\t\tfor (var mask = 0; mask < mm; ++mask) {\n\t\t\t\tif (visited[mask][i]) {\n\t\t\t\t\tcheck = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (check) {\n\t\t\t\tbest.push(2);\n\t\t\t} else {\n\t\t\t\tbest.push(0);\n\t\t\t}\n\t\t} else {\n\t\t\tbest.push(data_array[i]);\n\t\t}\n\t}\n\treturn best;\n}", "static getHamiltonianPath(obj, callback) {\n\n\n // begin performing the analysis\n function doIt(obj) {\n debug('Attempting to get Hamilton paths for graph:', obj);\n\n var verticies = Object.keys(obj);\n \n for (var i=0; i<verticies.length; i++) {\n var visited = {};\n visited[verticies[i]] = 1;\n\n var path = [ verticies[i] ];\n\n getAvailableVertecies(obj, path, visited, callback);\n }\n }\n\n /**\n * Recursively called function to get the sequence of verticies along a path\n * \n * @param obj - object - A JSON object representing the directoinal graph being analyized (internal format)\n * @param path - array - The path being followed\n * @param visited - object - A hash of verticies which are in the path\n * @param callback - function - The callback function\n */\n function getAvailableVertecies(obj, path, visited, callback) {\n \n var avail = [];\n var edges = obj[path[path.length-1]];\n \n for (let vertex in edges) {\n // are we done yet?\n if (path.length == Object.keys(obj).length) {\n // make one final check, for circular path\n if (obj[path[path.length - 1]].hasOwnProperty(path[0])) {\n path.push(path[0]);\n \n if (typeof callback == 'function') {\n callback(path);\n }\n return;\n }\n }\n\n // confirm the vertex hasn't been visited already\n debug('visited: ', visited);\n debug('path:', path);\n if (visited.hasOwnProperty(vertex) === false) {\n visited[vertex] = 1;\n path.push(vertex);\n\n getAvailableVertecies(obj, path, visited, callback);\n } else {\n // there's a bug in here\n return;\n }\n }\n callback(null);\n }\n\n // convert the graph a a format which is easier to traverse, and begin searching\n debug('Original Graph Structure', obj);\n this.restructureGraph(obj, doIt);\n }", "function solveall(N) {\n for (var i = 2; i < N; i++) \n for (var j = i; j < N; j++) \n for (var k = j; k < N; k++) \n for (var l = 2; l < N; l++) \n for (var m = 2; m < N; m++) \n for (var n = 2; n < N; n++) {\n if (i == j && l > m) continue;\n if (j == k && m > n) continue;\n var p = solveangles([i,j,k,l,m,n]);\n if (p) {\n console.log(i,j,k,l,m,n);\n }\n }\n }", "function tentBasis(N, t) {\n var sol = [];\n for(var i = 0; i < N; i++) {\n if(i-1 > t) {\n sol.push(0);\n }\n else if(i > t) {\n sol.push( (t % 1.0));\n }\n else if(i+1 > t) {\n sol.push(1- (t % 1.0));\n }\n else {\n sol.push(0);\n }\n }\n\n return sol;\n}", "function sol(\n blocked = [\n [0, 1],\n [1, 0],\n ],\n source = [0, 0],\n target = [0, 2]\n) {\n // mark visited positions\n // once manhattan distance between source and current is greather than 200 return true (AT MOST 200 blocked positions!)\n // check source -> target AND target -> source\n const directions = [\n [0, 1],\n [0, -1],\n [1, 0],\n [-1, 0],\n ];\n\n const block = new Set();\n for (let b of blocked) {\n const [x, y] = b;\n block.add(`${x}-${y}`);\n }\n\n return dfs(source, target) && dfs(target, source);\n\n function dfs(cur, target, visited = new Set()) {\n if (cur[0] === target[0] && cur[1] === target[1]) return true;\n if (Math.abs(source[0] - cur[0]) + Math.abs(source[1] - cur[1]) > 200) {\n return true;\n }\n\n visited.add(`${cur[0]}-${cur[1]}`);\n const [x1, y1] = cur;\n for (let d of directions) {\n const [x2, y2] = d;\n let r = x1 + x2;\n let c = y1 + y2;\n const str = `${r}-${c}`;\n if (\n r >= 0 &&\n r < 1000000 &&\n c >= 0 &&\n c < 1000000 &&\n !block.has(str) &&\n !visited.has(str)\n ) {\n if (dfs([r, c], target, visited)) return true;\n }\n }\n return false;\n }\n}", "function solve(n) {\n let currentSquareRoot = 1;\n let previousSquareRoot = 1;\n\n while (currentSquareRoot ** 2 - previousSquareRoot ** 2 < n) {\n if (isPerfectSquare(currentSquareRoot ** 2 + n)) {\n return currentSquareRoot ** 2;\n }\n\n previousSquareRoot = currentSquareRoot;\n currentSquareRoot += 1;\n }\n\n return -1;\n}", "function solvePseudoku(array) {\n\n\t// this returns an array which is the completed Pseudoku puzzle\n\n\tvar arrayBlank = blankEntries(array);\n\n\tvar entryBlank = 4 ** arrayBlank.length;\n\n\n\tfor(var i = 0; i < entryBlank; i++)\n\t{\n\t\tvar candidate = makeCandidate(i, arrayBlank.length);\n\n\t\tvar candidateCheck = checkCandidate(array, candidate);\n\n\t\tif(candidateCheck)\n\t\t{\n\t\t\treturn array;\n\t\t}\n\t}\n\n\treturn \"No solution!\";\n\n}", "function newComputePi() {\n\t// Start at pH 7. Determine charge, contributed by N and C termini and charged amino acid side chains (performed by calcChargeAtpH).\n\t// Adjust pH upward or downward by currentStep and recompute the charge. Step in the correct direction again, this\n\t// time stepping 1/2 as far.\n\t// Continue with smaller corrective steps until charge doesn't change at two successive pHs.\n\t\n\tvar current_pH=7;\n\tvar currentStep=3.5;\n\tvar lastCharge=0;\n\tvar crntCharge=1; //something different from lastCharge to force once through the while loop\n\t\n\twhile (lastCharge!=crntCharge) {\n// \t\tconsole.log(\"pH=\"+current_pH+\" crntCharge=\"+crntCharge); // this is amusing to review in the console\n\t\tlastCharge=crntCharge;\n\t\tcrntCharge=newCalcChargeAtpH(current_pH);\n\t\tcrntCharge=(Math.round(crntCharge*1000))/1000; //round off to 3 places to the right of the decimal\n\t\t\n\t\tif (crntCharge>0){\n\t\t\t\tcurrent_pH=current_pH+currentStep;\n\t\t} else { \n\t\t\t\tcurrent_pH=current_pH-currentStep;\n\t\t}\n\t\t\n\t\tcurrentStep=currentStep/2;\n\t} //End while \n\t\n\treturn((Math.round(1000*current_pH))/1000);//rounded to 3 places after the decimal point\n\t\n\n} // END OF FUNCTION computePi", "SolveBend_PBD_Triangle() {\n const stiffness = this.m_tuning.bendStiffness;\n for (let i = 0; i < this.m_bendCount; ++i) {\n const c = this.m_bendConstraints[i];\n const b0 = this.m_ps[c.i1].Clone();\n const v = this.m_ps[c.i2].Clone();\n const b1 = this.m_ps[c.i3].Clone();\n const wb0 = c.invMass1;\n const wv = c.invMass2;\n const wb1 = c.invMass3;\n const W = wb0 + wb1 + 2.0 * wv;\n const invW = stiffness / W;\n const d = new b2_math_js_1.b2Vec2();\n d.x = v.x - (1.0 / 3.0) * (b0.x + v.x + b1.x);\n d.y = v.y - (1.0 / 3.0) * (b0.y + v.y + b1.y);\n const db0 = new b2_math_js_1.b2Vec2();\n db0.x = 2.0 * wb0 * invW * d.x;\n db0.y = 2.0 * wb0 * invW * d.y;\n const dv = new b2_math_js_1.b2Vec2();\n dv.x = -4.0 * wv * invW * d.x;\n dv.y = -4.0 * wv * invW * d.y;\n const db1 = new b2_math_js_1.b2Vec2();\n db1.x = 2.0 * wb1 * invW * d.x;\n db1.y = 2.0 * wb1 * invW * d.y;\n b0.SelfAdd(db0);\n v.SelfAdd(dv);\n b1.SelfAdd(db1);\n this.m_ps[c.i1].Copy(b0);\n this.m_ps[c.i2].Copy(v);\n this.m_ps[c.i3].Copy(b1);\n }\n }", "function solveHanoi(n) {\n let moves = [];\n const _solveHanoi = (n, from, to, spare) => {\n if (n < 1) {\n return;\n }\n if (n === 1) {\n const move = [from, to];\n moves.push(move);\n } else {\n _solveHanoi(n - 1, from, spare, to);\n _solveHanoi(1, from, to, spare);\n _solveHanoi(n - 1, spare, to, from);\n }\n };\n _solveHanoi(n, 0, 2, 1);\n\n // Timer is kept track of in order to allow user to cancel visualization\n // at any time by clearing all timers and resetting to original state.\n let timer;\n moves.forEach((move, i) => {\n timer = setTimeout(\n () => moveRing(move[0], move[1]),\n (1 + i) * (100 + 1000 / speed)\n );\n timers.push(timer);\n });\n }", "function gameOfLifeBestSolution(board) {\n const boardAsLivingCellsOnly = []\n board.forEach((row, rowIndex) => {\n row.forEach((cell, columnIndex) => {\n if (cell === 1) {\n boardAsLivingCellsOnly.push([rowIndex, columnIndex])\n }\n })\n })\n const nextLiveCells = []\n const nowDeadButPotentiallyAliveCells = []\n boardAsLivingCellsOnly.forEach((livingCell) => {\n const liveCellX = livingCell[0]\n const liveCellY = livingCell[1]\n const neighborCells = [[liveCellX - 1 , liveCellY - 1], [liveCellX - 1, liveCellY], [liveCellX - 1, liveCellY + 1], [liveCellX, liveCellY - 1], [liveCellX, liveCellY + 1], [liveCellX + 1, liveCellY - 1], [liveCellX + 1, liveCellY], [liveCellX + 1, liveCellY + 1]]\n\n let liveNeighborCellCount = 0\n neighborCells.forEach((neighborCell) => {\n if (boardAsLivingCellsOnly.find(liveCell => neighborCell[0] === liveCell[0] && neighborCell[1] === liveCell[1])) {\n liveNeighborCellCount += 1\n } else {\n nowDeadButPotentiallyAliveCells.push(neighborCell)\n }\n })\n if (liveNeighborCellCount === 2 || liveNeighborCellCount === 3) {\n nextLiveCells.push(livingCell)\n }\n })\n\n nowDeadButPotentiallyAliveCells.forEach((nowDeadCell) => {\n const nowDeadCellX = nowDeadCell[0]\n const nowDeadCellY = nowDeadCell[1]\n const neighborCells = [[nowDeadCellX - 1 , nowDeadCellY - 1], [nowDeadCellX - 1, nowDeadCellY], [nowDeadCellX - 1, nowDeadCellY + 1], [nowDeadCellX, nowDeadCellY - 1], [nowDeadCellX, nowDeadCellY + 1], [nowDeadCellX + 1, nowDeadCellY - 1], [nowDeadCellX + 1, nowDeadCellY], [nowDeadCellX + 1, nowDeadCellY + 1]]\n let liveNeighborCellCount = 0\n neighborCells.forEach((neighborCell) => {\n if (boardAsLivingCellsOnly.find(liveCell => neighborCell[0] === liveCell[0] && neighborCell[1] === liveCell[1])) {\n liveNeighborCellCount += 1\n }\n })\n if (liveNeighborCellCount === 3) {\n nextLiveCells.push(nowDeadCell)\n }\n })\n\n // need to dedup\n const xyHash = {}\n const dedupedNextLiveCells = []\n nextLiveCells.forEach((cell) => {\n if (!Array.isArray(xyHash[cell[0]])) {\n xyHash[cell[0]] = [cell[1]]\n dedupedNextLiveCells.push(cell)\n } else {\n const oldValueArray = xyHash[cell[0]]\n if (!oldValueArray.includes(cell[1])) {\n const newValueArray = oldValueArray.push(cell[1])\n xyHash[cell[0]] = newValueArray\n dedupedNextLiveCells.push(cell)\n }\n }\n })\n\n return dedupedNextLiveCells\n}", "function solve(goals, points, steps, nextMask, ignoreOpts, vSet) {\n pointsLength0 = points.length;\n stepsLength0 = steps.length;\n nextMask = nextMask || [ '**' ];\n ignoreOpts = ignoreOpts || {};\n if (typeof(ignoreOpts.min) !== 'number') { ignoreOpts.min = error; }\n if (ignoreOpts.min < error) { ignoreOpts.min = error; }\n if (typeof(ignoreOpts.max) !== 'number') { ignoreOpts.max = Infinity; }\n var info = sanitizeMask(nextMask);\n console.log('Solution pattern mask:', nextMask);\n var i, pattern, found = false, perm1, perm1Cfg, perm2, perm2Cfg;\n perm1Cfg = {\n val: 0,\n len: info.asters\n };\n if (info.wildIdx !== -1) {\n perm2Cfg = {\n val: 0,\n len: 0,\n onlyLines: info.onlyLines,\n onlyCircles: info.onlyCircles\n };\n console.log('+ length of (**) pattern =', perm2Cfg.len);\n while (!found) {\n perm2 = generatePerm(perm2Cfg);\n perm1Cfg.val = 0;\n while (!found) {\n perm1 = generatePerm(perm1Cfg);\n pattern = mixPattern(nextMask, perm1.pattern, perm2.pattern);\n console.log(' pattern:', pattern);\n PROGRESS = 0;\n found = solveWithFixedNext(goals, points, steps, pattern, 0, ignoreOpts, vSet);\n if (perm1.last) { break; }\n }\n if (found) { break; }\n if (perm2.last) {\n perm2Cfg.val = 0;\n perm2Cfg.len = perm2Cfg.len + 1;\n console.log('+ length of (**) pattern =', perm2Cfg.len);\n }\n }\n } else {\n while (!found) {\n perm1 = generatePerm(perm1Cfg);\n pattern = mixPattern(nextMask, perm1.pattern);\n console.log(' pattern:', pattern);\n PROGRESS = 0;\n found = solveWithFixedNext(goals, points, steps, pattern, 0, ignoreOpts, vSet);\n if (perm1.last) { break; }\n }\n if (!found) { console.log('\\n:-(\\n'); }\n }\n}", "solveSudoku(){\n\n const arr = game.collectInput();\n\n // if(!isSolvable(arr)){\n // alert('Not solvable');\n // return;\n // }\n\n if(solve(arr)){\n game.fillTiles(arr);\n }\n\n }", "function bellmanFord(edges, V, start) {\n let dist = Array(V).fill(Infinity);\n dist[start] = 0;\n\n // Only in the worst case does it take V-1 iterations for the Bellman-Ford\n // algorithm to complete. Another stopping condition is when we're unable to\n // relax an edge, this means we have reached the optimal solution early.\n let relaxedAnEdge = true;\n\n for (let v = 0; v < V - 1 && relaxedAnEdge; v++) {\n relaxedAnEdge = false;\n for (let edge of edges) {\n if (dist[edge.from] + edge.cost < dist[edge.to]) {\n dist[edge.to] = dist[edge.from] + edge.cost;\n relaxedAnEdge = true;\n }\n }\n }\n\n // Run algorithm a second time to detect which nodes are part\n // of a negative cycle. A negative cycle has occurred if we\n // can find a better path beyond the optimal solution.\n relaxedAnEdge = true;\n for (let v = 0; v < V - 1 && relaxedAnEdge; v++) {\n relaxedAnEdge = false;\n for (let edge of edges) {\n if (dist[edge.from] + edge.cost < dist[edge.to]) {\n dist[edge.to] = -Infinity;\n relaxedAnEdge = true;\n }\n }\n }\n return dist;\n}", "function allSolution(x,y,node){\n\tif(x==9){\n\t\tprintSolution(node);\n\t\tsolutionCount++;\n\t\treturn ;\n\t}\n\tif(y==9){\n\t\tallSolution(x+1,0,node);\n\t\treturn ;\n\t}\n\tif(puzzleGrid[x][y]!=0){\n\t\tallSolution(x,y+1,node);\n\t\treturn ;\n\t}\n\tfor(let i=1;i<10;i++){\n\t\tif(isValid(x,y,i)){\n\t\t\tpuzzleGrid[x][y]=i;\n\t\t\tallSolution(x,y+1,node);\n\t\t}\n\t\tpuzzleGrid[x][y] = 0;\n\t}\n}", "function inv()\n {\n\n let i = undefined ;\n let j = undefined ;\n let k = undefined ;\n let akk = undefined ;\n let akj = undefined ;\n let aik = undefined ;\n\n let r = new Matrix( this.nr , this.nc ) ;\n\n console.log( 'r=' , r ) ;\n\n for( i = 0; i < this.nr; ++i )\n\n for( j = 0; j < this.nc; ++j )\n \n if( this.idx( i , j ) < this.nv )\n \n r.v[ r.idx( i , j ) ] = this.v[ this.idx( i , j ) ] ;\n\n for( k = 0; k < r.nr; ++k )\n\n if( akk = r.v[ r.idx( k , k ) ] )\n {\n\n for( i = 0; i < r.nc; ++i )\n\n for( j = 0; j < r.nr; ++j )\n\n if( (i != k) && (j != k) )\n {\n\n akj = r.v[ r.idx( k , j ) ] ;\n\n aik = r.v[ r.idx( i , k ) ] ;\n\n r.v[ r.idx( i , j ) ] -= ( (akj * aik) / akk ) ;\n\n } ;\n\n for( i = 0; i < r.nc; ++i )\n\n if( i != k )\n\n r.v[ r.idx( i , k ) ] /= (- akk ) ;\n\n for( j = 0; j < r.nr; ++j )\n\n if( k != j )\n\n r.v[ r.idx( k , j ) ] /= akk ;\n\n r.v[ r.idx( k , k ) ] = ( 1.0 / akk ) ;\n\n } // end if{} +\n\n else\n\n r.v[ r.idx( k , k ) ] = undefined ;\n\n for( i = 0; i < this.nr; ++i )\n\n for( j = 0; j < this.nc; ++j )\n \n if( this.idx( i , j ) < this.nv )\n \n this.v[ this.idx( i , j ) ] = r.v[ r.idx( i , j ) ];\n\n return ;\n\n }", "function getDiameter(shell) {\n debugger;\n var p = 0;\n var i = 1;\n var h = shell.length - 1;\n\n var start = null;\n var end = null;\n\n var previousSquare = -1;\n var diameters = [];\n\n var currentSquare = square(shell[h], shell[p], shell[i]);\n while (currentSquare > previousSquare) {\n previousSquare = currentSquare;\n i++;\n currentSquare = square(shell[h], shell[p], shell[i]);\n }\n\n start = i - 1;\n i = start;\n previousSquare = -1;\n\n while (end < h) {\n currentSquare = square(shell[p], shell[p + 1], shell[i]);\n while (currentSquare > previousSquare) {\n previousSquare = currentSquare;\n i++;\n currentSquare = square(shell[p], shell[p + 1], shell[i % (h + 1)]);\n }\n\n end = i - 1;\n\n\n var candidates = [];\n for (var j = start; j <= end && j <= h; ++j) {\n candidates[candidates.length] = shell[j];\n }\n diameters[diameters.length] = new Line(shell[p], getFarthest(candidates));\n\n\n p++;\n start = end;\n i = start;\n previousSquare = -1;\n }\n\n var winner = diameters[0];\n for (i = 1; i < diameters.length; ++i) {\n if (winner.length() < diameters[i].length()) {\n winner = diameters[i];\n }\n }\n\n return winner;\n\n function getFarthest(points) {\n var farthest = points[0];\n\n for (var i = 1; i < points.length; ++i) {\n if (distance(shell[p], farthest) < distance(shell[p], points[i])) {\n farthest = points[i];\n }\n }\n return farthest;\n }\n\n function square(a, b, c) {\n var u = new Vector(b.x - a.x, b.y - a.y);\n var v = new Vector(c.x - a.x, c.y - a.y);\n return Math.abs(u.x * v.y - u.y * v.x);\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
a macro function stop all sound instances by iterating through lookup table
function stopAllSounds() { var that = this; for (var s in soundsLookup) { if (soundsLookup.hasOwnProperty(s)) { that.stop(s); } } }
[ "function unmuteAllSounds() {\n var that = this;\n for (var s in soundsLookup) {\n if (soundsLookup.hasOwnProperty(s)) {\n that.unmute(s);\n }\n }\n }", "function stop_other_audio_tracks()\n {\n for (var i = 1; i <= 3; i++)\n if (i != audio_player && audio_stream [i])\n audio_stream [i].stop();\n }", "function stopAudio() {\n for (var key in audioSrcList) {\n if (audioSrcList.hasOwnProperty(key)) {\n audioSrcList[key][0].pause();\n audioSrcList[key][0].currentTime = 0;\n }\n }\n}", "function pauseAllSounds() {\n var that = this;\n for (var s in soundsLookup) {\n if (soundsLookup.hasOwnProperty(s)) {\n that.pause(s);\n }\n }\n }", "function stop(alias) {\n var soundInstance = getSoundByAlias(alias);\n soundInstance.stopSound();\n }", "function muteAllSounds() {\n var that = this;\n for (var s in soundsLookup) {\n if (soundsLookup.hasOwnProperty(s)) {\n that.mute(s);\n }\n }\n }", "function unScareAlien(){\n aliens.forEach(alien => alien.isScared = false)\n }", "stop() {\n this.song_.stop();\n this.bitDepthSlider_.disable();\n this.reductionSlider_.disable();\n }", "function unloadAll() {\n for (let sound_name in audioTracks) {\n if (audioTracks.hasOwnProperty(sound_name)) {\n unload(sound_name);\n }\n }\n}", "function stopSnippet(){\n return playSong.pause();\n }", "function stopMusic() {\n music_audio.play();\n}", "function fadeMuteAllSounds(duration, animation, easing) {\n var that = this;\n for (var s in soundsLookup) {\n if (soundsLookup.hasOwnProperty(s)) {\n that.fadeMute(s, duration, animation, easing);\n }\n }\n }", "stop() {\n\n this.isPlaying = false; // set the 'playing' boolean to false\n\n // stop all tracks (basically only the currently playing track needs to be stopped, but for safety all are stopped)\n for (let i in this.allTracks) {\n this.allTracks[i].stop();\n }\n\n this.playing = 0; // reset to the beginning (next time it starts from the beginning)\n }", "function Sequence$cancel(){\n\t cancel();\n\t action && action.cancel();\n\t while(it = nextHot()) it.cancel();\n\t }", "stop() {\n this.queueLock = true;\n this.queue = [];\n this.audioPlayer.stop(true);\n }", "function endSound() {\n winSound.play();\n}", "function stopLoop() {\n clearInterval (Defaults.game.handle);\n }", "stop() {\n this.target = undefined;\n // @ts-expect-error\n const pathfinder = this.bot.pathfinder;\n pathfinder.setGoal(null);\n // @ts-expect-error\n this.bot.emit('stoppedAttacking');\n }", "async disable () {\n // Disconnect everything\n this.mic.disconnect()\n this.scriptNode.disconnect()\n\n // Stop all media stream tracks and remove them\n this.media.getAudioTracks().forEach(\n (element) => {\n element.stop()\n this.media.removeTrack(element)\n }\n )\n\n // Close the context and remove it\n await this.context.close()\n this.context = null\n\n this.stats.teardown() // hide stats page\n this.isActive = false\n console.log('Audio Detection Disabled')\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
SoundCloud XPCOM service component
function sbSoundCloud() { // Imports // XXX - Deprecate by migrating base-64 fn Cu.import("resource://soundcloud/OAuth.jsm"); this.wrappedJSObject = this; this.log = DebugUtils.generateLogFunction("sbSoundCloud"); this.listeners = new Listeners(); var login = Logins.get(); this.username = login.username; this.password = login.password; this._prefs = Cc['@mozilla.org/preferences-service;1'] .getService(Ci.nsIPrefService) .getBranch("extensions.soundcloud."); /** * Private "methods" */ /** * \brief Gets (or creates) a SoundCloud library. * * \param aLibrary SoundCloud Library object. * \param aUserId User id. If passed, user-specific library * will be created. * * \return sbILibrary */ this._getLibrary = function sbSoundCloud__getLibrary(aLibrary, aUserId) { var libraryManager = Cc["@songbirdnest.com/Songbird/library/Manager;1"] .getService(Ci.sbILibraryManager); var library = {}; var pref = aLibrary.guid + ".guid"; var guid = (this._prefs.prefHasUserValue(pref)) ? this._prefs.getCharPref(pref) : false; if (!guid) { var directory = Cc["@mozilla.org/file/directory_service;1"] .getService(Ci.nsIProperties) .get("ProfD", Ci.nsIFile); directory.append("db"); directory.append("soundcloud"); var file = directory.clone(); // Create local (per user) or global (all users) db if (aUserId) { file.append(aLibrary.guid + "-" + aUserId + "@soundcloud.com.db"); } else { file.append(aLibrary.guid + "@soundcloud.com.db"); } var libraryFactory = Cc["@songbirdnest.com/Songbird/Library/LocalDatabase/LibraryFactory;1"] .getService(Ci.sbILibraryFactory); var bag = Cc["@mozilla.org/hash-property-bag;1"] .createInstance(Ci.nsIWritablePropertyBag2); bag.setPropertyAsInterface("databaseFile", file); library = libraryFactory.createLibrary(bag); } else { library = libraryManager.getLibrary(guid); this._prefs.setCharPref(aLibrary.guid + ".guid", library.guid); } return library; } /** * \brief Adds media items to a SoundCloud library. * * \param aItems JSON object of items to add. * \param aLibrary Target library for added items. * */ this._addItemsToLibrary = function sbSoundCloud__addItemsToLibrary(aItems, aLibrary) { var self = this; if (aItems != null) { var itemArray = Cc["@songbirdnest.com/moz/xpcom/threadsafe-array;1"] .createInstance(Ci.nsIMutableArray); var propertiesArray = Cc["@songbirdnest.com/moz/xpcom/threadsafe-array;1"] .createInstance(Ci.nsIMutableArray); for (let i = 0; i < aItems.length; i++) { var title = aItems[i].title; var duration = aItems[i].duration * 1000; var username = aItems[i].user.username; var playcount = aItems[i].playback_count; var favcount = aItems[i].favoritings_count; var uri = aItems[i].uri; var waveformURL = aItems[i].waveform_url; // XXX - Need to make sure this does what I want it to var downloadURL = aItems[i].download_url || ""; var streamURL = aItems[i].stream_url; if (downloadURL.indexOf(SOCL_URL) != -1) downloadURL += "?consumer_key=" + CONSUMER_KEY; if (!streamURL || streamURL.indexOf(SOCL_URL) == -1) continue; streamURL += "?consumer_key=" + CONSUMER_KEY; var properties = Cc["@songbirdnest.com/Songbird/Properties/MutablePropertyArray;1"] .createInstance(Ci.sbIMutablePropertyArray); properties.appendProperty(SBProperties.trackName, title); properties.appendProperty(SBProperties.duration, duration); properties.appendProperty(SB_PROPERTY_USER, username); properties.appendProperty(SB_PROPERTY_PLAYS, playcount); properties.appendProperty(SB_PROPERTY_FAVS, favcount); properties.appendProperty(SB_PROPERTY_WAVEFORM, waveformURL); if (downloadURL) { properties.appendProperty(SB_PROPERTY_DOWNLOAD_URL, downloadURL); } var ios = Cc["@mozilla.org/network/io-service;1"] .getService(Ci.nsIIOService); itemArray.appendElement(ios.newURI(streamURL, null, null), false); propertiesArray.appendElement(properties, false); } var batchListener = { onProgress: function(aIndex) {}, onComplete: function(aMediaItems, aResult) { self.listeners.each(function(l) { l.onItemsAdded(); }); } }; aLibrary.batchCreateMediaItemsAsync(batchListener, itemArray, propertiesArray, false); } } /** * \brief Creates an HMAC-SHA1 signature for an OAuth request. * * \param aMessage Message to sign. * * \return HMAC-SHA1 signature string */ this._sign = function sbSoundCloud__sign(aMessage) { var baseString = this._getBaseString(aMessage); var signature = b64_hmac_sha1(encodeURIComponent(CONSUMER_SECRET) + "&" + encodeURIComponent(TOKEN_SECRET), baseString); return signature; } /** * \brief Retrieves a base string. * * \param aMessage Message to encode. * * \return Encoded base string */ this._getBaseString = function sbSoundCloud__getBaseString(aMessage) { var params = aMessage.parameters; var s = ""; for (let p in params) { if (params[p][0] != 'oauth_signature') { if (p == 0) { s = params[p][0] + "=" + params[p][1]; } else { s += "&" + params[p][0] + "=" + params[p][1]; } } } return aMessage.method + '&' + encodeURIComponent(aMessage.action) + '&' + encodeURIComponent(s); } /** * \brief Creates parameters for an OAuth request. * * \param aURL Request URL. * \param aMethodType Request method. * * \return URL encoded string of parameters */ this._getParameters = function sbSoundCloud__getParameters(aURL, aMethodType) { var accessor = { consumerSecret: CONSUMER_SECRET }; var message = { action: aURL, method: aMethodType, parameters: [] }; message.parameters.push(['oauth_consumer_key', CONSUMER_KEY]); message.parameters.push(['oauth_nonce', OAuth.nonce(11)]); message.parameters.push(['oauth_signature_method', SIG_METHOD]); message.parameters.push(['oauth_timestamp', OAuth.timestamp()]); if (OAUTH_TOKEN) message.parameters.push(['oauth_token', OAUTH_TOKEN]); message.parameters.push(['oauth_version', "1.0"]); message.parameters.push(['oauth_signature', this._sign(message)]); return urlencode(message.parameters); } this._nowplaying_url = null; this.__defineGetter__('nowplaying_url', function() { return this._nowplaying_url; }); this.__defineSetter__('nowplaying_url', function(val) { this._nowplaying_url = val; }); this.__defineGetter__('soundcloud_url', function() { return SOCL_URL; }); this.__defineGetter__('oauth_token', function() { let pref = this.username + ".oauth_token"; let token = (this._prefs.prefHasUserValue(pref)) ? this._prefs.getCharPref(pref) : false; return this._prefs.getCharPref(this.username + ".oauth_token"); }); /* this.__defineGetter__('autoLogin', function() { return prefsService.getBoolPref('extensions.soundcloud.autologin'); }); this.__defineSetter__('autoLogin', function(val) { prefsService.setBoolPref('extensions.soundcloud.autologin', val); this.listeners.each(function(l) { l.onAutoLoginChanged(val); }); }); */ // user-logged-out pref this.__defineGetter__('userLoggedOut', function() { return this._prefs.getBoolPref('loggedOut'); }); this.__defineSetter__('userLoggedOut', function(val) { this._prefs.setBoolPref('loggedOut', val); }); // the loggedIn state this._loggedIn = false; this.__defineGetter__('loggedIn', function() { return this._loggedIn; }); this.__defineSetter__('loggedIn', function(aLoggedIn){ this._loggedIn = aLoggedIn; this.listeners.each(function(l) { l.onLoggedInStateChanged(); }); }); // get the playback history service this._playbackHistory = Cc['@songbirdnest.com/Songbird/PlaybackHistoryService;1'] .getService(Ci.sbIPlaybackHistoryService); // add ourselves as a playlist history listener this._playbackHistory.addListener(this); this._mediacoreManager = Cc['@songbirdnest.com/Songbird/Mediacore/Manager;1'] .getService(Ci.sbIMediacoreManager); this._mediacoreManager.addListener(this); this._library = this._getLibrary(Libraries.SEARCH, null); this._downloads = this._getLibrary(Libraries.DOWNLOADS, null); this.__defineGetter__('library', function() { return this._library; }); this.__defineGetter__('dashboard', function() { let dashLib = (this._dashboard) ? this._dashboard : false; return dashLib; }); this.__defineGetter__('favorites', function() { let favLib = (this._favorites) ? this._favorites : false; return favLib; }); this.__defineGetter__('downloads', function() { return this._downloads; }); this._strings = Cc["@mozilla.org/intl/stringbundle;1"] .getService(Ci.nsIStringBundleService) .createBundle("chrome://soundcloud/locale/overlay.properties"); this._servicePaneService = Cc['@songbirdnest.com/servicepane/service;1'] .getService(Ci.sbIServicePaneService); // find a radio folder if it already exists var radioFolder = this._servicePaneService.getNode("SB:RadioStations"); if (!radioFolder) { radioFolder = this._servicePaneService.createNode(); radioFolder.id = "SB:RadioStations"; radioFolder.className = "folder radio"; radioFolder.name = this._strings.GetStringFromName("radio.label"); radioFolder.setAttributeNS(SB_NS, "radioFolder", 1); // for backward-compat radioFolder.setAttributeNS(SP_NS, "Weight", 2); this._servicePaneService.root.appendChild(radioFolder); } radioFolder.editable = false; var soclRadio = this._servicePaneService.getNode("SB:RadioStations:SoundCloud"); if (!soclRadio) { this._servicePaneNode = this._servicePaneService.createNode(); this._servicePaneNode.url = "chrome://soundcloud/content/directory.xul?type=search"; this._servicePaneNode.id = "SB:RadioStations:SoundCloud"; this._servicePaneNode.name = "SoundCloud"; this._servicePaneNode.image = 'chrome://soundcloud/skin/favicon.png'; this._servicePaneNode.editable = false; this._servicePaneNode.hidden = false; radioFolder.appendChild(this._servicePaneNode); } this.updateServicePaneNodes(); this._retry_count = 0; }
[ "function privateInitSoundcloud(){\n\t\t/*\n\t\t\tCalls the SoundCloud initialize function\n\t\t\tfrom their API and sends it the client_id\n\t\t\tthat the user passed in.\n\t\t*/\n\t\tSC.initialize({\n\t\t\tclient_id: config.soundcloud_client\n\t\t});\n\n\t\t/*\n\t\t\tGets the streamable URLs to run through Amplitue. This is\n\t\t\tVERY important since Amplitude can't stream the copy and pasted\n\t\t\tlink from the SoundCloud page, but can resolve the streaming\n\t\t\tURLs from the link.\n\t\t*/\n\t\tprivateGetSoundcloudStreamableURLs();\n\t}", "function checkForWinAmpAPI()\n{\n\tif (window.external &&\n\t\t\"Enqueue\" in window.external &&\n\t\t\"GetClassicColor\" in window.external &&\n\t\t\"font\" in window.external &&\n\t\t\"fontsize\" in window.external &&\n\t\t\"IsRegisteredExtension\" in window.external &&\n\t\t\"GetMetadata\" in window.external)\t// Can't be bothered yet to work out how to pass objects back from C++.\n\t{\n\t\twinAmpAPI = true;\n\t}\n\telse\n\t{\n\t\talert(\"The hosting container does not expose the redcaza JavaScript API, e.g.: window.external.Method.\\n You will not be able to listen to or view media.\");\n }\n}", "function AndroidSpeechCapabilityPlugin() {\r\n}", "function populateVoiceList() {\n window.speechSynthesis.getVoices();\n }", "function SDisco(im) {\n\tconsole.log('Initializing [Service Discovery] extension.');\n\t\n\t// Store a reference to the XmmpIM instance.\n\tthis._im = im;\n\tthis._cache = {};\n}", "function startAudioOnMaster() {\n let masterAudioMessage = JSON.stringify({\n client_type: EWSClientType.MASTER,\n message: EWSMessageType.START_AUDIO,\n raspberry_pi_id: 1,\n payload: 'ada4f2fd-1a6e-4688-bbf9-e20aadda5435'\n });\n\n client.send(masterAudioMessage, function (err){\n if(err) {\n setTimeout(() => {\n startAudioOnMaster()\n }, 500);\n }\n })\n}", "function speechStarted() {\n}", "function initApplication() \n{\n console.log(\"Loading sounds\\n\");\n\n var outval = {};\n var result;\n\n /*\n Create an oscillator DSP units for the tone.\n */\n result = gSystem.createDSPByType(FMOD.DSP_TYPE_OSCILLATOR, outval);\n CHECK_RESULT(result);\n gDSP = outval.val;\n\n result = gDSP.setParameterFloat(FMOD.DSP_OSCILLATOR_RATE, 440.0); /* Musical note 'A' */\n CHECK_RESULT(result);\n}", "function privateSoundcloudResolveStreamable(url, index){\n\t\tSC.get('/resolve/?url='+url, function( sound ){\n\t\t\t/*\n\t\t\t\tIf streamable we get the url and bind the client ID to the end\n\t\t\t\tso Amplitude can just stream the song normally. We then overwrite\n\t\t\t\tthe url the user provided with the streamable URL.\n\t\t\t*/\n\t\t\tif( sound.streamable ){\n\t\t\t\tconfig.songs[index].url = sound.stream_url+'?client_id='+config.soundcloud_client;\n\n\t\t\t\t/*\n\t\t\t\t\tIf the user want's to use soundcloud art, we overwrite the\n\t\t\t\t\tcover_art_url with the soundcloud artwork url.\n\t\t\t\t*/\n\t\t\t\tif( config.soundcloud_use_art ){\n\t\t\t\t\tconfig.songs[index].cover_art_url = sound.artwork_url;\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t\tGrab the extra metadata from soundcloud and bind it to the\n\t\t\t\t\tsong. The user can get this through the public function:\n\t\t\t\t\tgetActiveSongMetadata\n\t\t\t\t*/\n\t\t\t\tconfig.songs[index].soundcloud_data = sound;\n\t\t\t}else{\n\t\t\t\t/*\n\t\t\t\t\tIf not streamable, then we print a message to the user stating\n\t\t\t\t\tthat the song with name X and artist X is not streamable. This\n\t\t\t\t\tgets printed ONLY if they have debug turned on.\n\t\t\t\t*/\n\t\t\t\tprivateWriteDebugMessage( config.songs[index].name +' by '+config.songs[index].artist +' is not streamable by the Soundcloud API' );\n\t\t\t}\n\t\t\t/*\n\t\t\t\tIncrements the song ready counter.\n\t\t\t*/\n\t\t\tconfig.soundcloud_songs_ready++;\n\n\t\t\t/*\n\t\t\t\tWhen all songs are accounted for, then amplitude is ready\n\t\t\t\tto rock and we set the rest of the config.\n\t\t\t*/\n\t\t\tif( config.soundcloud_songs_ready == config.soundcloud_song_count ){\n\t\t\t\tprivateSetConfig( temp_user_config );\n\t\t\t}\n\t\t});\n\t}", "function callAPI(query) {\r\n\t$.get(\"https://api.soundcloud.com/tracks?client_id=b3179c0738764e846066975c2571aebb\",\r\n\t\t{'q': query,\r\n\t\t'limit': '200'},\r\n\t\tfunction(data) {\r\n\t\t\tconsole.log(\"Call API was called!\");\r\n\t\t\tprocessData(data);\r\n\t\t},'json'\r\n\t);\r\n}", "airHostessAudio() {\n\t $('#air-hostess').trigger('play');\n\t }", "function BSCarouselService() {\n\t}", "function WebGLSound() {}", "function start_conversation() {\n send_version();\n}", "function updateSyncControl(service, SyncControl) {\n service\n .documents(SyncControl)\n .update({\n data: { msg: 'pause' },\n })\n .then(response => {\n // console.log(response);\n console.log(\"== updateSyncControl ==\");\n })\n .catch(error => {\n console.log(error);\n });\n}", "constructor() { \n \n ComAdobeGraniteTranslationConnectorMsftCoreImplMicrosoftTranslationServiceFactoryImplProperties.initialize(this);\n }", "function tellMe(joke){\n // got this code from tts api documentation \n VoiceRSS.speech({\n key: '233e1729322c4d28829ef0d633b14196',\n src: joke,\n hl: 'en-us',\n v: 'Harry',\n r: 0, \n c: 'mp3',\n f: '44khz_16bit_stereo',\n ssml: false\n})\n}", "function soundEffectSuccessFun() {\n soundEffectSuccess.play();\n}", "function rocketLaunch() {\n playSound(\"audioRocketLaunch\");\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
import PlayerNumber from './Component/PlayerNumber'
function App() { return ( <div> <Player number1= '3'/> </div> ); }
[ "ImportComponent(string, string) {\n\n }", "getPlayerComponent(uid) {\n const agoraPlayer = this.selectComponent(`#rtc-player-${uid}`);\n return agoraPlayer;\n }", "ImportUnconfiguredComponents(string, Variant, Variant) {\n\n }", "function Player(){\n Paddle.call(this);\n \n this.x = 20;\n}", "if (!moduleName.startsWith('.')) {\n return `/${moduleName}`;\n }", "render(){ \n return(\n <div className = 'Connection'>\n <br />\n <p className=\"error\">{this.state.errorMessage}</p>\n <h1>Insert the id of another player:</h1>\n <br />\n <input type=\"text\" value={this.state.opponentId} onChange={this.handleChange} size=\"35\"/>\n <br /> <br /> <br />\n <input className=\"enter\" type=\"button\" onClick = { this.connectToOpponent } value=\"Enter\"/>\n <br /><br />\n <p className=\"peerId\"><b>Your peer id:</b> {this.props.localPeer.id} </p>\n </div>\n )\n }", "createPlayer() {\n this.player = new Player(this.level);\n }", "setPlayer(player){\n this.setState({player})\n }", "function bouUp () {\r\n return(\r\n \r\n <AppComponent/>\r\n\r\n //<displayWeather/>\r\n\r\n \r\n );\r\n}", "render() {\n\n\t\tconst { players, maxPlayers } = this.props;\n\n\t\treturn (\n\n\t\t\t<div>\n\t\t\t\t{ /* a text hint which informs the user how many more players are needed to meet the total number of players set by the user */}\n\t\t\t\t{ players.size < maxPlayers ?\n\t\t\t\t\t<p> { maxPlayers - players.size } more players needed </p>\n\t\t\t\t\t: <p> Congrats! All players submitted </p> \n\t\t\t\t}\n\t\t\t\t{ /* the map only runs if the condition that there is existing data on players has been met */}\n\t\t\t\t{players.count() ?\n\t\t\t\t\t<ul className=\"list-group\" style={ listGroupStyles }>\n\t\t\t\t\t\t{players.map(player => (\n\t\t\t\t\t\t\t<PlayerProfile \n\t\t\t\t\t\t\tkey={ player.get(\"id\") }\n\t\t\t\t\t\t\tid={ player.get(\"id\")}\n\t\t\t\t\t\t\tname={ player.get(\"playerName\")} \n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t))}\n\t\t\t\t\t</ul>\n\n\t\t\t\t\t:\n\t\t\t\t\t<p>No Players Added</p>\t\t\t\n\t\t\t\t}\n\t\t\t</div>\n\t\t)\n\t}", "function HumanPlayer() {\n this.score = 0;\n}", "function JokeApp() {\n var jokeComponents\n\n //this de hua more longer\n //jokeComponents = jokesData.map(joke => <Meme id={joke.id} question={joke.question} punchLine={joke.punchLine} />)\n\n //this de hua shorter, but need add something in the Meme.js --> add 'jd'\n jokeComponents = jokesData.map(joke => <Meme id={joke.id} jd={joke}/>)\n\n return (\n <div>\n {jokeComponents} \n </div>\n )\n}", "setNumPlayers( numPlayers ) {\n this.gameConfig.numPlayers = numPlayers;\n this.saveGameConfig();\n\n }", "function OnPlayerChange(event) {\n\tconst id = event.target.id\n\tlet player_copy_id = id.includes(performance_prefix)\n\t\t\t\t\t ? event.target.id.replace(performance_prefix, rank_prefix)\n\t\t\t\t\t : id.includes(rank_prefix)\n\t\t\t\t\t ? event.target.id.replace(rank_prefix, performance_prefix):\n\t\t\t\t\t null;\n\n\tif (player_copy_id != null) {\n\t\tconst row = event.target.parentElement.parentElement;\n\t\tconst player_copy = $$(player_copy_id, row);\n\t\tplayer_copy.value = event.target.value;\n\t}\n}", "openAudioPanel() {\n this.props.toogleOverlay();\n }", "function Player(name) {\n this.name = name;\n this.rollDie = 0;\n this.roundScore = 0;\n this.totalScore = 0;\n}", "render() {\n return (\n\n <div className=\"app\">\n \n <ScoreCounter count={this.state.count} highScore={this.state.highScore}></ScoreCounter>\n <Wrapper>\n \n {this.state.caps.map(cap => (\n <CapsCard\n id={cap.id}\n key={cap.id}\n image={cap.image}\n onCardClick={this.onCardClick} \n // position={cap.position}\n // country={cap.country}\n // name={cap.name}\n />\n ))}\n </Wrapper>\n \n </div>\n );\n }", "function App() {\n return (\n <div className=\"App\">\n <Provider store={store}>\n <BoardContainer></BoardContainer>\n </Provider>\n </div>\n );\n}", "render() {\n return (\n <div className=\"CurrentTeam\">\n {this.name + \" (\" + this.shortName + \")\"}\n </div>\n );\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
(generic implementation of callback_separate and callback_together overlap fns)
function _overlap_shapes_generic(a, b, callback, callback_separate) { var result = overlapped_shapes(a, b); if(result) { //a, b is always required callback(a, b); if(callback_separate) { //b,a only for callback_separate mode callback(b, a); } } return result; }
[ "function overlap_shapes_callback_separate(a, b, callback) {\n\treturn _overlap_shapes_generic(a, b, callback, true);\n}", "static conduct(a, b, callback, on) {\r\n callback(a, b)\r\n\r\n }", "function callback(callback){\n callback()\n}", "function collide_shapes_callback_together(a, b, callback) {\n\treturn _collide_shapes_generic(a, b, callback, false);\n}", "function multipleCallbacks (myObject, callback1, callback2){\n var myObject = {status: ['success', 'error']};\n var keyValue = Object.values(myObject.status);\n for (let i=0; i<keyValue.length; i++){\n if (keyValue[i] === 'success'){\n return callback1;\n } else return callback2;\n}\n}", "function protectedCallback( callback ) {\n return function() {\n try{ \n return callback.apply(oboeApi, arguments); \n }catch(e) {\n \n // An error occured during the callback, publish it on the event bus \n oboeBus(FAIL_EVENT).emit( errorReport(undefined, undefined, e));\n } \n } \n }", "assignCallbacks() {\n this.namespace.on('connection', (socket) => {\n this.onWhisper(socket);\n });\n }", "hasCallback() {}", "function normalizeOnEventArgs(args) {\n if (typeof args[0] === 'object') {\n return args;\n }\n \n var selector = null;\n var eventMap = {};\n var callback = args[args.length - 1];\n var events = args[0].split(\" \");\n \n for (var i = 0; i < events.length; i++) {\n eventMap[events[i]] = callback;\n }\n \n // Selector is the optional second argument, callback is always last.\n if (args.length === 3) {\n selector = args[1];\n }\n \n return [ eventMap, selector ];\n }", "function foo(callback){\n callback();\n}", "function dh_callback (type) {\r\n type = type.toLowerCase();\r\n for (var c=0;c<CallbackList[type].length;c++) {\r\n CallbackList[type][c][0].call(null, CallbackList[type][c][1], type);\r\n }\r\n CallbackList[type] = null;\r\n}", "function callback2(callback, boolean){\n if (boolean === true) {\n return callback\n } else {\n console.log(\"Ignoring the callback.\")\n }\n}", "static checkCallbackFnOrThrow(callbackFn){if(!callbackFn){throw new ArgumentException('`callbackFn` is a required parameter, you cannot capture results without it.');}}", "function addForgettableCallback(event, callback, listenerId) {\n \n // listnerId is optional and if not given, the original\n // callback will be used\n listenerId = listenerId || callback;\n \n var safeCallback = protectedCallback(callback);\n \n event.on( function() {\n \n var discard = false;\n \n oboeApi.forget = function(){\n discard = true;\n }; \n \n apply( arguments, safeCallback ); \n \n delete oboeApi.forget;\n \n if( discard ) {\n event.un(listenerId);\n }\n }, listenerId);\n \n return oboeApi; // chaining \n }", "function receiveCallback(data) {\n receiveWhois(session,data);\n }", "function myFilter(array, callback) {\n return callback(array);\n}", "callAllCallbacks() {\n this.callbackSets.forEach((set) => {\n this.callCallbackSet(set);\n });\n }", "function procesar (unArray, callback) {\n return callback (unArray)\n}", "function consume(param1, param2, cb){\n return cb(param1, param2);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A lazy accessor, complete with thrown error memoization and a decent amount of optimization, since it's used in a lot of code. Note that this uses reference indirection and direct mutation to keep only just the computation nonconstant, so engines can avoid closure allocation. Also, `create` is intentionally kept out of any closure, so it can be more easily collected.
function Lazy(create) { this.value = create this.get = this.init }
[ "function _computedLazy(fn) {\n return ko.computed({\n read: fn,\n deferEvaluation: true\n }).extend({\n notifyComparer: _simpleComparer\n })\n }", "createProxy() {\n\t\treturn new Proxy(this, {\n\t\t\tget(target, prop, receiver) {\n\t\t\t\tlet x = +prop;\n\t\t\t\treturn new Proxy(target, {\n\t\t\t\t\tget(target, prop, receiver) {\n\t\t\t\t\t\tlet z = +prop;\n\t\t\t\t\t\tlet { zSize, data} = target;\n\t\t\t\t\t\treturn data[ x*zSize + z];\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}", "function factory () {\n // Just forwards the call to the resolver by setting itself as context.\n function fn (value) {\n return resolver.call(fn, value);\n }\n\n created += 1;\n fn.id = created;\n\n // The state is attached to the function object so it's available to the\n // state-less functions when running under `this.`.\n fn.locks = 0;\n fn.chain = null;\n fn.resolved = [];\n fn.filters = [];\n fn.forks = [];\n\n // Expose the behaviour in the functor\n fn.pause = pause;\n fn.resume = resume;\n fn.filter = filter;\n fn.fork = fork;\n fn.merge = merge;\n fn.completed = completed;\n\n return fn;\n}", "function makeLazyGetResult(components) {\n\t\tlet visitorIdCache\n\t\t// This function runs very fast, so there is no need to make it lazy\n\t\tconst confidence = getConfidence(components)\n\t\t// A plain class isn't used because its getters and setters aren't enumerable.\n\t\treturn {\n\t\t\tget visitorId() {\n\t\t\t\tif (visitorIdCache === undefined) {\n\t\t\t\t\tvisitorIdCache = hashComponents(this.components)\n\t\t\t\t}\n\t\t\t\treturn visitorIdCache\n\t\t\t},\n\t\t\tset visitorId(visitorId) {\n\t\t\t\tvisitorIdCache = visitorId\n\t\t\t},\n\t\t\tconfidence,\n\t\t\tcomponents,\n\t\t\tversion,\n\t\t}\n\t}", "function createCache() {\n var keys = [];\n\n function cache(key, value) {\n // Use (key + \" \")\n if (keys.push(key + \" \") > Expr.cacheLength) {\n // Only keep the most recent entries.\n delete cache[keys.shift()];\n }\n return (cache[key + \" \"] = value);\n }\n return cache;\n }", "static async create(ref, defaultValue) {\n let cache, loaded = false;\n const proxyId = id_1.ID.generate(); //ref.push().key;\n let onMutationCallback;\n let onErrorCallback = err => {\n console.error(err.message, err.details);\n };\n const clientSubscriptions = []; //, snapshot?: any\n const applyChange = (keys, newValue) => {\n // Make changes to cache\n if (keys.length === 0) {\n cache = newValue;\n return true;\n }\n let target = cache;\n keys = keys.slice();\n while (keys.length > 1) {\n const key = keys.shift();\n if (!(key in target)) {\n // Have we missed an event, or are local pending mutations creating this conflict?\n return false; // Do not proceed\n }\n target = target[key];\n }\n const prop = keys.shift();\n if (newValue === null) {\n // Remove it\n target instanceof Array ? target.splice(prop, 1) : delete target[prop];\n }\n else {\n // Set or update it\n target[prop] = newValue;\n }\n return true;\n };\n // Subscribe to mutations events on the target path\n const subscription = ref.on('mutations').subscribe(async (snap) => {\n var _a;\n if (!loaded) {\n return;\n }\n const context = snap.context();\n const isRemote = ((_a = context.acebase_proxy) === null || _a === void 0 ? void 0 : _a.id) !== proxyId;\n if (!isRemote) {\n return; // Update was done by us, no need to update cache\n }\n const mutations = snap.val(false);\n const proceed = mutations.every(mutation => {\n if (!applyChange(mutation.target, mutation.val)) {\n return false;\n }\n if (onMutationCallback) {\n const changeRef = mutation.target.reduce((ref, key) => ref.child(key), ref);\n const changeSnap = new data_snapshot_1.DataSnapshot(changeRef, mutation.val, false, mutation.prev);\n onMutationCallback(changeSnap, isRemote);\n }\n return true;\n });\n if (!proceed) {\n console.error(`Cached value appears outdated, will be reloaded`);\n await reload();\n }\n });\n // Setup updating functionality: enqueue all updates, process them at next tick in the order they were issued \n let processPromise = Promise.resolve();\n const mutationQueue = [];\n const transactions = [];\n const pushLocalMutations = async () => {\n // Sync all local mutations that are not in a transaction\n const mutations = [];\n for (let i = 0, m = mutationQueue[0]; i < mutationQueue.length; i++, m = mutationQueue[i]) {\n if (!transactions.find(t => RelativeNodeTarget.areEqual(t.target, m.target) || RelativeNodeTarget.isAncestor(t.target, m.target))) {\n mutationQueue.splice(i, 1);\n i--;\n mutations.push(m);\n }\n }\n if (mutations.length === 0) {\n return;\n }\n // Run local onMutation & onChange callbacks in the next tick\n process_1.default.nextTick(() => {\n // Run onMutation callback for each changed node\n if (onMutationCallback) {\n mutations.forEach(mutation => {\n mutation.value = utils_1.cloneObject(getTargetValue(cache, mutation.target));\n const mutationRef = mutation.target.reduce((ref, key) => ref.child(key), ref);\n const mutationSnap = new data_snapshot_1.DataSnapshot(mutationRef, mutation.value, false, mutation.previous);\n onMutationCallback(mutationSnap, false);\n });\n }\n // Execute local onChange subscribers\n clientSubscriptions\n .filter(s => mutations.some(m => RelativeNodeTarget.areEqual(s.target, m.target) || RelativeNodeTarget.isAncestor(s.target, m.target)))\n .forEach(s => {\n const currentValue = utils_1.cloneObject(getTargetValue(cache, s.target));\n let previousValue = utils_1.cloneObject(currentValue);\n // replay mutations on previousValue in reverse order\n mutations\n .filter(m => RelativeNodeTarget.areEqual(s.target, m.target) || RelativeNodeTarget.isAncestor(s.target, m.target))\n .reverse()\n .forEach(m => {\n const relTarget = m.target.slice(s.target.length);\n if (relTarget.length === 0) {\n previousValue = m.previous;\n }\n else {\n setTargetValue(previousValue, relTarget, m.previous);\n }\n });\n // Run subscriber callback\n let keepSubscription = true;\n try {\n keepSubscription = false !== s.callback(Object.freeze(currentValue), Object.freeze(previousValue), false, { acebase_proxy: { id: proxyId, source: 'local_update' } });\n }\n catch (err) {\n onErrorCallback({ source: 'local_update', message: `Error running subscription callback`, details: err });\n }\n if (!keepSubscription) {\n s.subscription.stop();\n clientSubscriptions.splice(clientSubscriptions.findIndex(cs => cs.subscription === s.subscription), 1);\n }\n });\n });\n // Update database async\n const batchId = id_1.ID.generate();\n processPromise = mutations\n .reduce((mutations, m, i, arr) => {\n // Only keep top path mutations\n if (!arr.some(other => RelativeNodeTarget.isAncestor(other.target, m.target))) {\n mutations.push(m);\n }\n return mutations;\n }, [])\n .reduce((updates, m, i, arr) => {\n // Prepare db updates\n const target = m.target;\n if (target.length === 0) {\n // Overwrite this proxy's root value\n updates.push({ ref, value: cache, type: 'set' });\n }\n else {\n const parentTarget = target.slice(0, -1);\n const key = target.slice(-1)[0];\n const parentRef = parentTarget.reduce((ref, key) => ref.child(key), ref);\n const parentUpdate = updates.find(update => update.ref.path === parentRef.path);\n const cacheValue = getTargetValue(cache, target);\n if (parentUpdate) {\n parentUpdate.value[key] = cacheValue;\n }\n else {\n updates.push({ ref: parentRef, value: { [key]: cacheValue }, type: 'update' });\n }\n }\n return updates;\n }, [])\n .reduce(async (promise, update, i, updates) => {\n // Execute db update\n // i === 0 && console.log(`Proxy: processing ${updates.length} db updates to paths:`, updates.map(update => update.ref.path));\n await promise;\n return update.ref\n .context({ acebase_proxy: { id: proxyId, source: 'update', update_id: id_1.ID.generate(), batch_id: batchId, batch_updates: updates.length } })[update.type](update.value) // .set or .update\n .catch(err => {\n onErrorCallback({ source: 'update', message: `Error processing update of \"/${ref.path}\"`, details: err });\n });\n }, processPromise);\n await processPromise;\n };\n let syncInProgress = false;\n const syncPromises = [];\n const syncCompleted = () => {\n let resolve;\n const promise = new Promise(rs => resolve = rs);\n syncPromises.push({ resolve });\n return promise;\n };\n let processQueueTimeout = null;\n const scheduleSync = () => {\n if (!processQueueTimeout) {\n processQueueTimeout = setTimeout(async () => {\n syncInProgress = true;\n processQueueTimeout = null;\n await pushLocalMutations();\n syncInProgress = false;\n syncPromises.splice(0).forEach(p => p.resolve());\n }, 0);\n }\n };\n const flagOverwritten = (target) => {\n if (!mutationQueue.find(m => RelativeNodeTarget.areEqual(m.target, target))) {\n mutationQueue.push({ target, previous: utils_1.cloneObject(getTargetValue(cache, target)), value: null });\n }\n // schedule database updates\n scheduleSync();\n };\n const addOnChangeHandler = (target, callback) => {\n const targetRef = getTargetRef(ref, target);\n const subscription = targetRef.on('mutations').subscribe(async (snap) => {\n var _a;\n const context = snap.context();\n const isRemote = ((_a = context.acebase_proxy) === null || _a === void 0 ? void 0 : _a.id) !== proxyId;\n if (!isRemote) {\n // Any local changes already triggered subscription callbacks\n return;\n }\n // Construct previous value from snapshot\n const currentValue = getTargetValue(cache, target);\n let newValue = utils_1.cloneObject(currentValue);\n let previousValue = utils_1.cloneObject(newValue);\n // const mutationPath = snap.ref.path;\n const mutations = snap.val(false);\n mutations.every(mutation => {\n if (mutation.target.length === 0) {\n newValue = mutation.val;\n previousValue = mutation.prev;\n return true;\n }\n for (let i = 0, val = newValue, prev = previousValue, arr = mutation.target; i < arr.length; i++) { // arr = PathInfo.getPathKeys(mutationPath).slice(PathInfo.getPathKeys(targetRef.path).length)\n const last = i + 1 === arr.length, key = arr[i];\n if (last) {\n val[key] = mutation.val;\n if (val[key] === null) {\n delete val[key];\n }\n prev[key] = mutation.prev;\n if (prev[key] === null) {\n delete prev[key];\n }\n }\n else {\n val = val[key] = key in val ? val[key] : {};\n prev = prev[key] = key in prev ? prev[key] : {};\n }\n }\n return true;\n });\n process_1.default.nextTick(() => {\n // Run callback with read-only (frozen) values in next tick\n const keepSubscription = callback(Object.freeze(newValue), Object.freeze(previousValue), isRemote, context);\n if (keepSubscription === false) {\n stop();\n }\n });\n });\n const stop = () => {\n subscription.stop();\n clientSubscriptions.splice(clientSubscriptions.findIndex(cs => cs.subscription === subscription), 1);\n };\n clientSubscriptions.push({ target, subscription, callback });\n return { stop };\n };\n const handleFlag = (flag, target, args) => {\n if (flag === 'write') {\n return flagOverwritten(target);\n }\n else if (flag === 'onChange') {\n return addOnChangeHandler(target, args.callback);\n }\n else if (flag === 'subscribe' || flag === 'observe') {\n const subscribe = subscriber => {\n const currentValue = getTargetValue(cache, target);\n subscriber.next(currentValue);\n const subscription = addOnChangeHandler(target, (value, previous, isRemote, context) => {\n subscriber.next(value);\n });\n return function unsubscribe() {\n subscription.stop();\n };\n };\n if (flag === 'subscribe') {\n return subscribe;\n }\n // Try to load Observable\n const Observable = optional_observable_1.getObservable();\n return new Observable(subscribe);\n }\n else if (flag === 'transaction') {\n const hasConflictingTransaction = transactions.some(t => RelativeNodeTarget.areEqual(target, t.target) || RelativeNodeTarget.isAncestor(target, t.target) || RelativeNodeTarget.isDescendant(target, t.target));\n if (hasConflictingTransaction) {\n // TODO: Wait for this transaction to finish, then try again\n return Promise.reject(new Error('Cannot start transaction because it conflicts with another transaction'));\n }\n return new Promise(async (resolve) => {\n // If there are pending mutations on target (or deeper), wait until they have been synchronized\n const hasPendingMutations = mutationQueue.some(m => RelativeNodeTarget.areEqual(target, m.target) || RelativeNodeTarget.isAncestor(target, m.target));\n if (hasPendingMutations) {\n if (!syncInProgress) {\n scheduleSync();\n }\n await syncCompleted();\n }\n const tx = { target, status: 'started', transaction: null };\n transactions.push(tx);\n tx.transaction = {\n get status() { return tx.status; },\n get completed() { return tx.status !== 'started'; },\n async commit() {\n if (this.completed) {\n throw new Error(`Transaction has completed already (status '${tx.status}')`);\n }\n tx.status = 'finished';\n transactions.splice(transactions.indexOf(tx), 1);\n if (syncInProgress) {\n // Currently syncing without our mutations\n await syncCompleted();\n }\n scheduleSync();\n await syncCompleted();\n },\n rollback() {\n // Remove mutations from queue\n if (this.completed) {\n throw new Error(`Transaction has completed already (status '${tx.status}')`);\n }\n tx.status = 'canceled';\n const mutations = [];\n for (let i = 0; i < mutationQueue.length; i++) {\n const m = mutationQueue[i];\n if (RelativeNodeTarget.areEqual(tx.target, m.target) || RelativeNodeTarget.isAncestor(tx.target, m.target)) {\n mutationQueue.splice(i, 1);\n i--;\n mutations.push(m);\n }\n }\n // Replay mutations in reverse order\n mutations.reverse()\n .forEach(m => {\n if (m.target.length === 0) {\n cache = m.previous;\n }\n else {\n setTargetValue(cache, m.target, m.previous);\n }\n });\n // Remove transaction \n transactions.splice(transactions.indexOf(tx), 1);\n }\n };\n resolve(tx.transaction);\n });\n }\n // else if (flag === 'runEvents') {\n // clientSubscriptions.filter(cs => cs.target.length <= target.length && cs.target.every((key, index) => key === target[index]))\n // .forEach(cs => {\n // const value = Object.freeze(cloneObject(getTargetValue(cache, cs.target)));\n // try {\n // cs.callback(value, value, false, { simulated: true });\n // }\n // catch(err) {\n // console.error(`Error running change callback: `, err);\n // }\n // });\n // }\n };\n const snap = await ref.get({ allow_cache: true });\n loaded = true;\n cache = snap.val();\n if (cache === null && typeof defaultValue !== 'undefined') {\n cache = defaultValue;\n await ref.set(cache);\n }\n let proxy = createProxy({ root: { ref, cache }, target: [], id: proxyId, flag: handleFlag });\n const assertProxyAvailable = () => {\n if (proxy === null) {\n throw new Error(`Proxy was destroyed`);\n }\n };\n const reload = async () => {\n // Manually reloads current value when cache is out of sync, which should only \n // be able to happen if an AceBaseClient is used without cache database, \n // and the connection to the server was lost for a while. In all other cases, \n // there should be no need to call this method.\n assertProxyAvailable();\n const newSnap = await ref.get();\n cache = newSnap.val();\n proxy = createProxy({ root: { ref, cache }, target: [], id: proxyId, flag: handleFlag });\n newSnap.ref.context({ acebase_proxy: { id: proxyId, source: 'reload' } });\n onMutationCallback && onMutationCallback(newSnap, true);\n // TODO: run all other subscriptions\n };\n return {\n async destroy() {\n await processPromise;\n subscription.stop();\n clientSubscriptions.forEach(cs => cs.subscription.stop());\n cache = null; // Remove cache\n proxy = null;\n },\n stop() {\n this.destroy();\n },\n get value() {\n assertProxyAvailable();\n return proxy;\n },\n get hasValue() {\n assertProxyAvailable();\n return cache !== null;\n },\n set value(val) {\n // Overwrite the value of the proxied path itself!\n assertProxyAvailable();\n if (typeof val === 'object' && val[isProxy]) {\n // Assigning one proxied value to another\n val = val.getTarget(false);\n }\n flagOverwritten([]);\n cache = val;\n proxy = createProxy({ root: { ref, cache }, target: [], id: proxyId, flag: handleFlag });\n },\n reload,\n onMutation(callback) {\n // Fires callback each time anything changes\n assertProxyAvailable();\n onMutationCallback = (...args) => {\n try {\n callback(...args);\n }\n catch (err) {\n onErrorCallback({ source: 'mutation_callback', message: 'Error in dataproxy onMutation callback', details: err });\n }\n };\n },\n onError(callback) {\n // Fires callback each time anything goes wrong\n assertProxyAvailable();\n onErrorCallback = (...args) => {\n try {\n callback(...args);\n }\n catch (err) {\n console.error(`Error in dataproxy onError callback: ${err.message}`);\n }\n };\n }\n };\n }", "function wrapLazyLoader(loader) {\n return function () {\n if (options.get) {\n _value = options.get.call(target);\n }\n\n if (!_value && loader) {\n var result = loader(name);\n\n // ensure set is called with target as this\n if (options.set) {\n options.set.call(target, result);\n }\n\n // set our backing field regardless\n _value = result;\n }\n return _value;\n }\n }", "function makeCounter() {\n function counter() {\n return (counter.count += 1);\n }\n\n counter.set = value => (counter.count = value);\n\n counter.decrement = () => (counter.count -= 1);\n\n return counter;\n}", "async function createCacheInstance() {\n // TODO - accept configured caches through environment variables (or other?)\n return CacheInstance;\n}", "function createDBDelegateGetter(getterAttr) {\n return function(db) {\n return (db ? db[getterAttr] : null);\n }\n}", "function MotorcycleFactory(name) {\n const newMotorcycle = Object.assign(\n {},\n { wheelie },\n new Vehicle(name, 2),\n );\n function wheelie() {\n return 'Wheee!';\n }\n return Object.freeze(newMotorcycle);\n}", "getField(iid, base, offset, val, isComputed, isOpAssign, isMethodCall) {\n this.state.coverage.touch(iid);\n Log.logHigh('Get field ' + ObjectHelper.asString(base) + '.' + ObjectHelper.asString(offset) + ' at ' + this._location(iid));\n\n //If dealing with a SymbolicObject then concretize the offset and defer to SymbolicObject.getField\n if (base instanceof SymbolicObject) {\n Log.logMid('Potential loss of precision, cocretize offset on SymbolicObject field lookups');\n return {\n result: base.getField(this.state, this.state.getConcrete(offset))\n }\n }\n\n //If we are evaluating a symbolic string offset on a concrete base then enumerate all fields\n //Then return the concrete lookup\n if (!this.state.isSymbolic(base) && \n this.state.isSymbolic(offset) &&\n typeof this.state.getConcrete(offset) == 'string') {\n this._getFieldSymbolicOffset(base, offset);\n return {\n result: base[this.state.getConcrete(offset)]\n }\n } \n\n //Otherwise defer to symbolicField\n const result_s = this.state.isSymbolic(base) ? this.state.symbolicField(this.state.getConcrete(base), this.state.asSymbolic(base), this.state.getConcrete(offset), this.state.asSymbolic(offset)) : undefined;\n const result_c = this.state.getConcrete(base)[this.state.getConcrete(offset)];\n\n return {\n result: result_s ? new ConcolicValue(result_c, result_s) : result_c\n };\n }", "function LocalCache( fn, initCalls, timeout ) {\n\n var cachedFunction = function() {\n return cachedFunction.this( this || cachedFunction._this ).apply( argumentsToArray( arguments ) )\n }\n\n cachedFunction.__proto__ = LocalCache.prototype;\n\n cachedFunction.fn = fn;\n cachedFunction.calls = initCalls || {};\n cachedFunction.timeout = timeout || -1;\n cachedFunction._this = null;\n cachedFunction.forceNext = false;\n\n return cachedFunction;\n\n}", "get(target, prop, receiver) {\n const path = [...this.path, prop];\n const handler = new RpcProxyHandler(this.callHandler, path);\n return new Proxy(async function noop() {}, handler);\n }", "function cacheFn(fn) {\n var cache = {};\n return function(arg) {\n if (cache[arg]) {\n return cache[arg];\n } else {\n cache[arg] = fn(arg);\n return cache[arg];\n }\n };\n}", "function LazyFlag(name, regMaster, bitsInLeft) {\n util.assert(this && (this instanceof LazyFlag), \"LazyFlag ctor ::\"\n + \" error - constructor not called properly\");\n /*util.assert(regMaster && (regMaster instanceof jemul8.LazyFlagRegister)\n , \"LazyFlag constructor ::\"\n + \" no valid master LazyFlagRegister specified.\");*/\n\n this.cpu = null; // Set on installation\n\n this.bitsInLeft = bitsInLeft;\n this.bitmaskDirtyGet = 1 << bitsInLeft;\n // NB: zero-extend shift-right operator used to force\n // unsigned result with one's-complement negation\n // (eg. 0xFFFFFFFF >> 0 == -1, but 0xFFFFFFFF >>> 0 == 0xFFFFFFFF)\n // NB2: opposite is to \"num | 0\"\n this.bitmaskDirtySet = (~this.bitmaskDirtyGet) >>> 0;\n\n // NB: It is EXTREMELY important that .value is ALWAYS stored\n // as a 0 or 1, otherwise the use of identity operators throughout\n // the code (=== & !==) will fail if comparing booleans to ints!\n this.value = 0;\n\n this.name = name;\n this.regMaster = regMaster;\n\n switch (name) {\n case \"CF\":\n this.hsh_get = hsh_getCF;\n this.get = getWithLookup;\n break;\n case \"PF\":\n this.get = getPF;\n break;\n case \"AF\":\n this.hsh_get = hsh_getAF;\n this.get = getWithLookup;\n break;\n case \"ZF\":\n this.get = getZF;\n break;\n case \"SF\":\n this.get = getSF;\n break;\n case \"OF\":\n this.hsh_get = hsh_getOF;\n this.get = getWithLookup;\n break;\n // Unsupported Lazy Flag type\n default:\n util.problem(\"LazyFlag constructor :: Unsupported Lazy Flag\");\n }\n\n // Add to master LazyFlagsRegister's hash\n regMaster.hsh_flg[ bitsInLeft ] = this;\n }", "function acquire (chain) {\n var resolver = pool.pop() || factory();\n\n // Reset the state of the resolver\n resolver.locks = 0;\n resolver.chain = chain;\n while (resolver.resolved.length > 0) {\n resolver.resolved.pop();\n }\n while (resolver.filters.length > 0) {\n resolver.filters.pop();\n }\n\n return resolver;\n}", "set value(_) {\n throw \"Cannot set computed property\";\n }", "function proxy(){\n\n var proxyFactory = function(){\n\n //The wrapped function to call.\n var fnToCall = arguments.length === 2 ? arguments[0][arguments[1]] : arguments[0];\n\n //A counter used to note how many times proxy has been called.\n var xCalled = 0;\n\n //An array whose elements note the context used to calll the wrapped function.\n var contexts = [];\n\n //An array of arrays used to note the arguments that were passed to proxy.\n var argsPassed = [];\n\n //An array whose elements note what the wrapped function returned.\n var returned = [];\n\n ///\n ///Privileged functions used by API\n ///\n\n //Returns the number of times the wrapped function was called.\n var getCalledCount = function(){\n return xCalled;\n };\n\n //If n is within bounds returns the context used on the nth \n //call to the wrapped function, otherwise returns undefined.\n var getContext = function(n){\n if(n >= 0 && n < xCalled){\n return contexts[n];\n }\n };\n\n //If called with 'n' and 'n' is within bounds then returns the \n //array found at argsPassed[n], otherwise returns argsPassed.\n var getArgsPassed = function(){\n if(arguments.length === 1 && arguments[0] >= 0 && arguments[0] < argsPassed.length){\n return argsPassed[arguments[0]];\n }else{\n return argsPassed;\n }\n };\n\n //If called with 'n' and 'n' is within bounds then returns \n //value found at returned[n], otherwise returns returned.\n var getReturned = function(){\n if(arguments.length === 1 && arguments[0] >= 0 && arguments[0] < returned.length){\n return returned[arguments[0]];\n }else{\n return returned;\n }\n };\n\n //If 'n' is within bounds then returns an \n //info object, otherwise returns undefined.\n var getData= function(n){\n if(n >= 0 && n < xCalled){\n var args = getArgsPassed(n);\n var context = getContext(n);\n var ret = getReturned(n);\n var info = {\n count: n + 1,\n argsPassed: args,\n context: context,\n returned: ret\n };\n return info;\n }\n };\n\n //If you just want to know if the wrapped function was called \n //then call wasCalled with no args. If you want to know if the \n //callback was called n times, pass n as an argument.\n var wasCalled = function(){\n return arguments.length === 1 ? arguments[0] === xCalled : xCalled > 0;\n };\n\n //A higher order function - iterates through the collected data and \n //returns the information collected for each invocation of proxy.\n var dataIterator = function(callback){\n for(var i = 0; i < xCalled; i++){\n callback(getData(i));\n }\n };\n\n //The function that is returned to the caller.\n var fn = function(){\n //Note the context that the proxy was called with.\n contexts.push(this);\n //Note the arguments that were passed for this invocation.\n var args = [].slice.call(arguments);\n argsPassed.push(args.length ? args : []);\n //Increment the called count for this invocation.\n xCalled += 1;\n //Call the wrapped function noting what it returns.\n var ret = fnToCall.apply(this, args);\n returned.push(ret);\n //Return what the wrapped function returned to the caller.\n return ret;\n };\n\n ///\n ///Exposed Lovwer level API - see Privileged functions used by API above.\n ///\n\n fn.getCalledCount = getCalledCount;\n\n fn.getContext = getContext;\n\n fn.getArgsPassed = getArgsPassed;\n\n fn.getReturned = getReturned;\n\n fn.getData = getData;\n\n ///\n ///Exposed Higher Order API - see Privileged functions used by API above.\n ///\n \n fn.wasCalled = wasCalled;\n\n fn.dataIterator = dataIterator;\n\n //Replaces object's method property with proxy's fn.\n if(arguments.length === 2){\n arguments[0][arguments[1]] = fn; \n }\n\n //Return fn to the caller.\n return fn;\n };\n\n //Convert arguments to an array, call factory and returns its value to the caller.\n var args = [].slice.call(arguments);\n return proxyFactory.apply(null, args);\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Starts the wire game
function startWireGame() { decrement(time); var colors = ['red', 'yellow', 'green', 'blue', 'black']; var $wireSelect = $('.wireS'); changeMouse($wireSelect); // Random colors for top row colors = shuffleArray(colors); for (var i = 0; i < $wireSelect.length; i++) { $wireSelect.eq(i).css('background-color', colors[i]); } var $wireSlot = $('.wireSlot'); changeMouse($wireSlot); var $wirePlace = $('.wire'); // Random colors for bottom row colors = shuffleArray(colors); for (var i = 0; i < $wirePlace.length; i++) { $wirePlace.eq(i).css('background-color', colors[i]); } var wireSelected = null; //Countdown $wireSelect.on('click', function (event) { wireSelected = $(this); wireSelected.css('border', 'solid gold 4px'); }); $wireSlot.on('click', function (event) { if (wireSelected !== null) { wireSelected.css('border', 'solid black 2px'); $(this).css('background-color', wireSelected.css('background-color')); checkWin($wirePlace, $wireSlot); } }); }
[ "startGame() {\r\n this.generateInitialBoard();\r\n this.printBoard();\r\n this.getMoveInput();\r\n }", "start() {\n \n //Start the game loop\n this.gameLoop();\n }", "function run(){\n\n console.log(\"Attempting Setup\");\n stage = new PIXI.Stage(0x66FF99);\n canvas = document.getElementById(\"game\");\n renderer = PIXI.autoDetectRenderer(800, 300,{view: canvas});\n document.body.appendChild(renderer.view);\n\n\tmain_menu();\n\tconsole.log(\"Game Start!\");\n\tupdate();\n}", "function run(){\n\n console.log(\"Attempting Setup\");\n //stage = new PIXI.Stage(0x66FF99)\n\tstage = new PIXI.Stage(0xFFF);\n canvas = document.getElementById(\"game\");\n renderer = PIXI.autoDetectRenderer(800, 300,{view: canvas});\n document.body.appendChild(renderer.view);\n\n\tmain_menu();\n\tconsole.log(\"Game Start!\");\n\tupdate();\n}", "function initSimon() {\n $('[data-action=start]').on('click', startGame);\n\n }", "startGame() {\n let self = this\n this.props.changeSetupConfigClass(\"setupconfig__holder setupconfig__holder__deactive\")\n setTimeout(()=>{\n self.props.changeResetCoords(true)\n self.props.changeMarkerCoords([0,0])\n self.props.changeResetCoords(false)\n self.props.changeActiveHandler(this.props.game.id, false, true)\n self.props.changeActiveState(this.props.game.id, true)\n }, 1600)\n }", "function startNewGame(){\n\ttoggleNewGameSettings();\n\tnewGame();\n}", "function clickStart() {\n $('#start').click(function (event) {\n // This starts the game when the start button is clicked\n moleSquare();\n\n // This starts the timer when the start button is clicked\n timer();\n });\n }", "function startGame() {\n initialise();\n setInterval(timer, 10);\n}", "function startBattle(client, msg) {\n sample(client, msg, \"start\");\n timeleft(client, msg, \"start\");\n submit(client, msg, \"start\");\n}", "function start()\n{\n\t// ask user for driver\n\tvar driverType=irr.driverChoiceConsole();\n\tif (driverType==irr.EDT_COUNT)\n\t\treturn 1;\n\n\t// create device\n\n\tvar device = irr.createDevice(driverType, new irr.dimension2d_u32(640, 480));\n\n\tif (device == null)\n\t\treturn 1; // could not create selected driver.\n\n\t/*\n\tBefore we start with the interesting stuff, we do some simple things:\n\tStore pointers to the most important parts of the engine (video driver,\n\tscene manager, gui environment) to safe us from typing too much, add an\n\tirrlicht engine logo to the window and a user controlled first person\n\tshooter style camera. Also, we let the engine know that it should store\n\tall textures in 32 bit. This necessary because for parallax mapping, we\n\tneed 32 bit textures.\n\t*/\n\n\tvar driver = device.getVideoDriver();\n\tvar smgr = device.getSceneManager();\n\tvar env = device.getGUIEnvironment();\n\n\tdriver.setTextureCreationFlag(irr.ETCF_ALWAYS_32_BIT, true);\n\n\t// add irrlicht logo\n\tenv.addImage(driver.getTexture(\"../../media/irrlichtlogo2.png\"), new irr.position2d_s32(10,10));\n\n\t// add camera\n\tvar camera = smgr.addCameraSceneNodeFPS();\n\tcamera.setPosition(new irr.vector3df(-200,200,-200));\n\n\t// disable mouse cursor\n\tdevice.getCursorControl().setVisible(false);\n\n\n\t/*\n\tBecause we want the whole scene to look a little bit scarier, we add\n\tsome fog to it. This is done by a call to IVideoDriver::setFog(). There\n\tyou can set various fog settings. In this example, we use pixel fog,\n\tbecause it will work well with the materials we'll use in this example.\n\tPlease note that you will have to set the material flag EMF_FOG_ENABLE\n\tto 'true' in every scene node which should be affected by this fog.\n\t*/\n\tdriver.setFog(new irr.SColor(0,138,125,81), irr.EFT_FOG_LINEAR, 250, 1000, 0.003, true, false);\n\n\t/*\n\tTo be able to display something interesting, we load a mesh from a .3ds\n\tfile which is a room I modeled with anim8or. It is the same room as\n\tfrom the specialFX example. Maybe you remember from that tutorial, I am\n\tno good modeler at all and so I totally messed up the texture mapping\n\tin this model, but we can simply repair it with the\n\tIMeshManipulator::makePlanarTextureMapping() method.\n\t*/\n\n\tvar roomMesh = smgr.getMesh(\"../../media/room.3ds\");\n\tvar room = null;\n\n\tif (roomMesh)\n\t{\n\t\tsmgr.getMeshManipulator().makePlanarTextureMapping(roomMesh.getMesh(0), 0.003);\n\n\t\t/*\n\t\tNow for the first exciting thing: If we successfully loaded the\n\t\tmesh we need to apply textures to it. Because we want this room\n\t\tto be displayed with a very cool material, we have to do a\n\t\tlittle bit more than just set the textures. Instead of only\n\t\tloading a color map as usual, we also load a height map which\n\t\tis simply a grayscale texture. From this height map, we create\n\t\ta normal map which we will set as second texture of the room.\n\t\tIf you already have a normal map, you could directly set it,\n\t\tbut I simply didn't find a nice normal map for this texture.\n\t\tThe normal map texture is being generated by the\n\t\tmakeNormalMapTexture method of the VideoDriver. The second\n\t\tparameter specifies the height of the heightmap. If you set it\n\t\tto a bigger value, the map will look more rocky.\n\t\t*/\n\n\t\tvar normalMap = driver.getTexture(\"../../media/rockwall_height.bmp\");\n\n\t\tif (normalMap)\n\t\t\tdriver.makeNormalMapTexture(normalMap, 9.0);\n\n\t\t/*\n\t\tBut just setting color and normal map is not everything. The\n\t\tmaterial we want to use needs some additional informations per\n\t\tvertex like tangents and binormals. Because we are too lazy to\n\t\tcalculate that information now, we let Irrlicht do this for us.\n\t\tThat's why we call IMeshManipulator::createMeshWithTangents().\n\t\tIt creates a mesh copy with tangents and binormals from another\n\t\tmesh. After we've done that, we simply create a standard\n\t\tmesh scene node with this mesh copy, set color and normal map\n\t\tand adjust some other material settings. Note that we set\n\t\tEMF_FOG_ENABLE to true to enable fog in the room.\n\t\t*/\n\n\t\tvar tangentMesh = smgr.getMeshManipulator().createMeshWithTangents(roomMesh.getMesh(0));\n\n\t\troom = smgr.addMeshSceneNode(tangentMesh);\n\t\troom.setMaterialTexture(0, driver.getTexture(\"../../media/rockwall.jpg\"));\n\t\troom.setMaterialTexture(1, normalMap);\n\n\t\troom.getMaterial(0).SpecularColor.set(0,0,0,0);\n\n\t\troom.setMaterialFlag(irr.EMF_FOG_ENABLE, true);\n\t\troom.setMaterialType(irr.EMT_PARALLAX_MAP_SOLID);\n\t\t// adjust height for parallax effect\n\t\troom.getMaterial(0).MaterialTypeParam = 0.035;\n\n\t\t// drop mesh because we created it with a create.. call.\n\t\ttangentMesh.drop();\n\t}\n\n\t/*\n\tAfter we've created a room shaded by per pixel lighting, we add a\n\tsphere into it with the same material, but we'll make it transparent.\n\tIn addition, because the sphere looks somehow like a familiar planet,\n\twe make it rotate. The procedure is similar as before. The difference\n\tis that we are loading the mesh from an .x file which already contains\n\ta color map so we do not need to load it manually. But the sphere is a\n\tlittle bit too small for our needs, so we scale it by the factor 50.\n\t*/\n\n\t// add earth sphere\n\n\tvar earthMesh = smgr.getMesh(\"../../media/earth.x\");\n\n\tif (earthMesh)\n\t{\n\t\t//perform various task with the mesh manipulator\n\t\tvar manipulator = smgr.getMeshManipulator();\n\n\t\t// create mesh copy with tangent informations from original earth.x mesh\n\t\tvar tangentSphereMesh =\tmanipulator.createMeshWithTangents(earthMesh.getMesh(0));\n\n\t\t// set the alpha value of all vertices to 200\n\t\tmanipulator.setVertexColorAlpha(tangentSphereMesh, 200);\n\n\t\t// scale the mesh by factor 50\n\t\tvar m = new irr.matrix4();\n\t\tm.setScale (new irr.vector3df(50,50,50) );\n\t\tmanipulator.transformMesh( tangentSphereMesh, m );\n\n\t\tvar sphere = smgr.addMeshSceneNode(tangentSphereMesh);\n\n\t\tsphere.setPosition(new irr.vector3df(-70,130,45));\n\n\t\t// load heightmap, create normal map from it and set it\n\t\tvar earthNormalMap = driver.getTexture(\"../../media/earthbump.jpg\");\n\t\tif (earthNormalMap)\n\t\t{\n\t\t\tdriver.makeNormalMapTexture(earthNormalMap, 20.0);\n\t\t\tsphere.setMaterialTexture(1, earthNormalMap);\n\t\t\tsphere.setMaterialType(irr.EMT_NORMAL_MAP_TRANSPARENT_VERTEX_ALPHA);\n\t\t}\n\n\t\t// adjust material settings\n\t\tsphere.setMaterialFlag(irr.EMF_FOG_ENABLE, true);\n\n\t\t// add rotation animator\n\t\tvar anim = smgr.createRotationAnimator(new irr.vector3df(0,0.1,0));\n\t\tsphere.addAnimator(anim);\n\t\tanim.drop();\n\n\t\t// drop mesh because we created it with a create.. call.\n\t\ttangentSphereMesh.drop();\n\t}\n\n\t/*\n\tPer pixel lighted materials only look cool when there are moving\n\tlights. So we add some. And because moving lights alone are so boring,\n\twe add billboards to them, and a whole particle system to one of them.\n\tWe start with the first light which is red and has only the billboard\n\tattached.\n\t*/\n\n\t// add light 1 (nearly red)\n\tvar light1 = smgr.addLightSceneNode(0, new irr.vector3df(0,0,0), new irr.SColorf(0.5, 1.0, 0.5, 0.0), 800.0);\n\n\tlight1.setDebugDataVisible ( irr.EDS_BBOX );\n\n\n\t// add fly circle animator to light 1\n\tvar anim = smgr.createFlyCircleAnimator (new irr.vector3df(50,300,0),190.0, -0.003);\n\tlight1.addAnimator(anim);\n\tanim.drop();\n\n\t// attach billboard to the light\n\tvar bill = smgr.addBillboardSceneNode(light1, new irr.dimension2d_f32(60, 60));\n\n\tbill.setMaterialFlag(irr.EMF_LIGHTING, false);\n\tbill.setMaterialFlag(irr.EMF_ZWRITE_ENABLE, false);\n\tbill.setMaterialType(irr.EMT_TRANSPARENT_ADD_COLOR);\n\tbill.setMaterialTexture(0, driver.getTexture(\"../../media/particlered.bmp\"));\n\n\t/*\n\tNow the same again, with the second light. The difference is that we\n\tadd a particle system to it too. And because the light moves, the\n\tparticles of the particlesystem will follow. If you want to know more\n\tabout how particle systems are created in Irrlicht, take a look at the\n\tspecialFx example. Maybe you will have noticed that we only add 2\n\tlights, this has a simple reason: The low end version of this material\n\twas written in ps1.1 and vs1.1, which doesn't allow more lights. You\n\tcould add a third light to the scene, but it won't be used to shade the\n\twalls. But of course, this will change in future versions of Irrlicht\n\twhere higher versions of pixel/vertex shaders will be implemented too.\n\t*/\n\n\t// add light 2 (gray)\n\tvar light2 = smgr.addLightSceneNode(0, new irr.vector3df(0,0,0), new irr.SColorf(1.0, 0.2, 0.2, 0.0), 800.0);\n\n\t// add fly circle animator to light 2\n\tanim = smgr.createFlyCircleAnimator(new irr.vector3df(0,150,0), 200.0, 0.001, new irr.vector3df(0.2, 0.9, 0.0));\n\tlight2.addAnimator(anim);\n\tanim.drop();\n\n\t// attach billboard to light\n\tbill = smgr.addBillboardSceneNode(light2, new irr.dimension2d_f32(120, 120));\n\tbill.setMaterialFlag(irr.EMF_LIGHTING, false);\n\tbill.setMaterialFlag(irr.EMF_ZWRITE_ENABLE, false);\n\tbill.setMaterialType(irr.EMT_TRANSPARENT_ADD_COLOR);\n\tbill.setMaterialTexture(0, driver.getTexture(\"../../media/particlewhite.bmp\"));\n\n\t// add particle system\n\tvar ps = smgr.addParticleSystemSceneNode(false, light2);\n\n\t// create and set emitter\n\tvar em = ps.createBoxEmitter(new irr.aabbox3d_f32(-3,0,-3,3,1,3), new irr.vector3df(0.0,0.03,0.0), 80,100, new irr.SColor(0,255,255,255), new irr.SColor(0,255,255,255), 400,1100);\n\tem.setMinStartSize(new irr.dimension2d_f32(30.0, 40.0));\n\tem.setMaxStartSize(new irr.dimension2d_f32(30.0, 40.0));\n\n\tps.setEmitter(em);\n\tem.drop();\n\n\t// create and set affector\n\tvar paf = ps.createFadeOutParticleAffector();\n\tps.addAffector(paf);\n\tpaf.drop();\n\n\t// adjust some material settings\n\tps.setMaterialFlag(irr.EMF_LIGHTING, false);\n\tps.setMaterialFlag(irr.EMF_ZWRITE_ENABLE, false);\n\tps.setMaterialTexture(0, driver.getTexture(\"../../media/fireball.bmp\"));\n\tps.setMaterialType(irr.EMT_TRANSPARENT_VERTEX_ALPHA);\n\n\n\tvar receiver = new irr.IEventReceiverWrapper();\n\toverrideEventReceiver(receiver, room, env, driver);\n\tdevice.setEventReceiver(receiver);\n\n\t/*\n\tFinally, draw everything. That's it.\n\t*/\n\n\tvar lastFPS = -1;\n\n\twhile(device.run())\n\tif (device.isWindowActive())\n\t{\n\t\tdriver.beginScene(true, true, 0);\n\n\t\tsmgr.drawAll();\n\t\tenv.drawAll();\n\n\t\tdriver.endScene();\n\n\t\tvar fps = driver.getFPS();\n\n\t\tif (lastFPS != fps)\n\t\t{\n\t\t\tvar str = \"Per pixel lighting example - cpgf Irrlicht JavaScript Binding [\";\n\t\t\tstr = str + driver.getName();\n\t\t\tstr = str + \"] FPS:\";\n\t\t\tstr = str + fps;\n\n\t\t\tdevice.setWindowCaption(str);\n\t\t\tlastFPS = fps;\n\t\t}\n\t}\n\n\tdevice.drop();\n\n\treturn 0;\n}", "function startBird() {\n fly();\n}", "function startBattle() {\n console.log(numBattles);\n if (numBattles < 0) {\n console.log(chalk.yellow(\"VICTORY!\"));\n console.log(player.name + \" moves further into the dungeon...\");\n numBattles++;\n }\n\n // if player hitpoints are less than or equal to 0 (dead), console log GAME OVER and end game...\n if (player.hitpoints <= 0) {\n gameOver();\n }\n // Reset the enemy HP in this area, and say what the enemy is\n var enemy = randomEnemy();\n console.log(player.name + \" the \" + player.class + \" encountered a \" + Enemy.name + \"!\");\n console.log(chalk.red(\"Battle Start!\"));\n battleMenu();\n}", "start() {\n\t\t// generate local_id\n\t\tnetwork.init(local_id);\n\t}", "function startGame() {\n createButtons();\n createCards();\n displayCards();\n}", "start() {\n if (!this.eb) {\n this.eb = new EventBus(this.busUrl);\n this.eb.onopen = function() {\n simulatorVerticle.eb.registerHandler(CALLSIGN_FLASH,simulatorVerticle.heartBeatHandler);\n simulatorVerticle.eb.registerHandler(CALLSIGN_BO,simulatorVerticle.carMessageHandler)\n };\n };\n this.enabled=true;\n }", "function rocketLaunch() {\n playSound(\"audioRocketLaunch\");\n }", "function start(){\n\n // this is the real number of players updated\n updateNumberOfPlayers();\n\n plEvenOdd = numberOfPlayers;\n\n plEvenOdd % 2 !== 0 ? ++numberOfPlayers : numberOfPlayers;\n\n plEvenOdd % 2 == 0 ? updateTotalRounds() : updateTotalRoundsOdd();\n\n // update totalRounds\n // updateTotalRounds();\n\n // change classes to display screen 3\n screen3(); \n\n\n plEvenOdd % 2 == 0 ? getNames() : getNamesOdd();\n\n // get the player names\n // getNames();\n // put all the names inside position array\n // getPosition(); ******************ready to delete*****************\n\n\n\n \n\n plEvenOdd % 2 == 0 ? makeCouple() : makeCoupleOdd();\n\n // create couples based on player position\n // makeCouple();\n\n // diplay round\n displayRound();\n\n \n // update the current round\n updateCurrentRound();\n\n plEvenOdd % 2 == 0 ? displayCouples() : displayCouplesOdd();\n\n // display couple + passes input\n // displayCouples(); \n}", "function startGameHandler() {\r\n \"use strict\";\r\n // Hide the intro screen, show the game screen\r\n introScreen.style.display = \"none\";\r\n gameScreen.style.display = \"block\";\r\n rocket.img.style.display = \"block\";\r\n ufo.img.style.display = \"block\";\r\n\r\n // set up torp start position values for end of run check.\r\n torpedo.startY = rocket.y;\r\n torpedo.startX = rocket.x;\r\n\r\n // set the timer to check for things like torp end of run, ufo hits, explosions etc.\r\n // If we don't do this and force a render, then the torp will persist on the screen until \r\n // the player moves the rocket and forces the render.\r\n timeCheck = setInterval(checkExplode, CHECK_EXPLODE_TIMEINTERVAL); // using same interval as used to display torp movement to check if it exploded.\r\n\r\n}// end start Game Handler." ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recalculate the MOQ/IOQ flag for the product State saving
function recalculate_moqioq_flag(product_id) { var selected_supplier =order_list[product_id].selected_supplier; //if no supplier is selected return if (selected_supplier == -1) return; //get supplier moq, ioq var moq = order_list[product_id].pricing_list[selected_supplier].moq; var ioq = order_list[product_id].pricing_list[selected_supplier].ioq; var product_qty = order_list[product_id].quantity; if ((product_qty<moq)||((product_qty-moq)%ioq!=0)) order_list[product_id].moqioqflag = false; else order_list[product_id].moqioqflag = true; //See if off invoice applies - TBI var supplier_id = order_list[product_id].selected_supplier; if (supplier_id!=-1) { var minimum_quantity = order_list[product_id].pricing_list[supplier_id].minimum_quantity; var offinvoice = order_list[product_id].pricing_list[supplier_id].offinvoice; var pecentinvoice = order_list[product_id].pricing_list[supplier_id].percentinvoice; var valueinvoice = order_list[product_id].pricing_list[supplier_id].valueinvoice; if (product_qty>=minimum_quantity) { if (offinvoice==1) { if (valueinvoice!=0) { order_list[product_id].selected_price = parseFloat(order_list[product_id].pricing_list[supplier_id].price) - valueinvoice; order_list[product_id].selected_discount = valueinvoice; } else if (percentinvoice!=0) { order_list[product_id].selected_price = parseFloat(order_list[product_id].pricing_list[supplier_id].price) * (1- (parseFloat(percentinvoice)/100)); order_list[product_id].selected_discount = parseFloat(order_list[product_id].pricing_list[supplier_id].price) * (parseFloat(percentinvoice)/100); } } order_list[product_id].selected_rebate = order_list[product_id].pricing_list[supplier_id].rebate; //TBI } else { order_list[product_id].selected_price =parseFloat(order_list[product_id].pricing_list[supplier_id].price).toFixed(2); //order_list[product_id].selected_price = parseFloat(order_list[product_id].pricing_list[supplier_id].price) } } /*if ((product_qty<moq)||((product_qty-moq)%ioq!=0) order_list[product_id].moqioqflag = false; else order_list[product_id].moqioqflag = true; */ //redraw - TBD }
[ "function recalculate_moqioq_flag(product_id)\n{\n\tvar selected_supplier =order_list[product_id].selected_supplier;\n\t//if no supplier is selected return \n\tif (selected_supplier == -1) return;\n\t//get supplier moq, ioq\n\tvar moq = order_list[product_id].pricing_list[supplier_id].moq;\n\tvar ioq = order_list[product_id].pricing_list[supplier_id].ioq;\n\tvar product_qty = order_list[product_id].quantity;\n\tif ((product_qty<moq)||((product_qty-moq)%ioq!=0)\n\t\torder_list[product_id].moqioqflag = false;\t\t\n\telse \n\t\torder_list[product_id].moqioqflag = true;\t\t\n\t//redraw - TBD\n}", "function validateSaved() {\n\t\t//Getting the save status\n\t\tvar status = productKey.getSaveStatus();\n\t\t//Visually displaying the save status\n\t\tVALIDATION_STATUS_HANDLE.innerHTML = status;\n\n\t\t//Toggling the save status\n\t\tif (productKey.isSaved()) {\n\t\t\t//Toggle the saved state from true to false\n\t\t\tproductKey.setSaved(false);\n\t\t} else {\n\t\t\t//Toggle the saved state from false to true\n\t\t\tproductKey.setSaved(true);\n\t\t}\n\n\t}", "applyWadiExpress() {\n this.setState((prevState) => ({\n wadiExpressEnabled: !prevState.wadiExpressEnabled,\n isLoading: true\n }), () => {\n this.getProducts({ page: pageNumber, search: this.props.productList.search })\n });\n }", "function processSetsState() {\n oresult.bsets = true;\n bok = true;\n sstate = '';\n }", "function MEX_Save() {\n if (mod_MEX_dict.is_permit_admin){\n MEXQ_Save();\n }\n } // MEX_Save", "function cmdUpdate_ClickCase100() {\n console.log(\"cmdUpdate_ClickCase100\");\n //fetch WO summary\n GenerateWOSummary();\n //fetch WO summary - scrap + unaccountable qty\n GenerateWOSummaryScrap();\n\n console.log(\"cmdUpdate_ClickCase100.1\", $scope.CompletedQty);\n //if ($scope.McType.toLowerCase() == \"inhouse\") {\n // ReCheck($scope.selectedWOID);\n // //CheckWOOpnStatus();\n // console.log(\"saveCompleteModal2\", $scope.CompletedQty);\n // $(\"#saveCompleteModal-current\").val($scope.CompletedQty);\n\n //} else {\n // ReCheck($scope.selectedWOID);\n // //CheckSubconWOOpnStatus();\n // console.log(\"saveCompleteModal3\", $scope.CompletedQty);\n // $(\"#saveCompleteModal-current\").val($scope.CompletedQty);\n\n //}\n\n\n }", "_clearChangeFlags() {\n // @ts-ignore TS2531 this method can only be called internally with internalState assigned\n this.internalState.changeFlags = {\n dataChanged: false,\n propsChanged: false,\n updateTriggersChanged: false,\n viewportChanged: false,\n stateChanged: false,\n extensionsChanged: false,\n propsOrDataChanged: false,\n somethingChanged: false\n };\n }", "async function setItemState(state) {\n switch (itemType) {\n case ItemType.issue:\n await client.rest.issues.update({\n owner: item.owner,\n repo: item.repo,\n issue_number: item.number,\n state: state,\n });\n break;\n\n case ItemType.pr:\n await client.rest.pulls.update({\n owner: item.owner,\n repo: item.repo,\n pull_number: item.number,\n state: state,\n });\n break;\n }\n}", "async function saveCurrentStates(onStart) {\n if (onStart) {\n await shutterConfigCheck();\n }\n\n let currentStates = {};\n let shutterName = [];\n let num = 0;\n\n const _currentStates = await adapter.getStateAsync('shutters.currentStates').catch((e) => adapter.log.warn(e));\n if (_currentStates && _currentStates.val && _currentStates.val !== null) {\n try {\n currentStates = JSON.parse(_currentStates.val);\n } catch (err) {\n adapter.log.debug('settings cannot be read from the state');\n currentStates = {};\n }\n }\n\n for (const s in shutterSettings) {\n const nameDevice = shutterSettings[s].shutterName.replace(/[.;, ]/g, '_');\n shutterName.push(shutterSettings[s].shutterName);\n num++;\n\n if (currentStates && currentStates[`${nameDevice}`] && !onStart) {\n currentStates[`${nameDevice}`].currentAction = shutterSettings[s].currentAction;\n currentStates[`${nameDevice}`].currentHeight = shutterSettings[s].currentHeight;\n currentStates[`${nameDevice}`].triggerAction = shutterSettings[s].triggerAction;\n currentStates[`${nameDevice}`].triggerHeight = shutterSettings[s].triggerHeight;\n currentStates[`${nameDevice}`].oldHeight = shutterSettings[s].oldHeight;\n currentStates[`${nameDevice}`].firstCompleteUp = shutterSettings[s].firstCompleteUp;\n currentStates[`${nameDevice}`].alarmTriggerAction = shutterSettings[s].alarmTriggerAction;\n currentStates[`${nameDevice}`].alarmTriggerLevel = shutterSettings[s].alarmTriggerLevel;\n currentStates[`${nameDevice}`].lastAutoAction = shutterSettings[s].lastAutoAction;\n } else if (currentStates && currentStates[`${nameDevice}`] && onStart) {\n adapter.log.debug(nameDevice + ': save settings');\n shutterSettings[s].currentAction = currentStates[`${nameDevice}`].currentAction;\n shutterSettings[s].currentHeight = currentStates[`${nameDevice}`].currentHeight;\n shutterSettings[s].triggerAction = currentStates[`${nameDevice}`].triggerAction;\n shutterSettings[s].triggerHeight = currentStates[`${nameDevice}`].triggerHeight;\n shutterSettings[s].oldHeight = currentStates[`${nameDevice}`].oldHeight;\n shutterSettings[s].firstCompleteUp = currentStates[`${nameDevice}`].firstCompleteUp;\n shutterSettings[s].alarmTriggerAction = currentStates[`${nameDevice}`].alarmTriggerAction;\n shutterSettings[s].alarmTriggerLevel = currentStates[`${nameDevice}`].alarmTriggerLevel;\n shutterSettings[s].lastAutoAction = currentStates[`${nameDevice}`].lastAutoAction;\n } else if (currentStates && !currentStates[`${nameDevice}`] && onStart) {\n adapter.log.debug(nameDevice + ': settings added');\n currentStates[`${nameDevice}`] = null;\n\n const states = ({\n \"shutterName\": shutterSettings[s].shutterName,\n \"currentAction\": shutterSettings[s].currentAction,\n \"currentHeight\": shutterSettings[s].currentHeight,\n \"triggerAction\": shutterSettings[s].triggerAction,\n \"triggerHeight\": shutterSettings[s].triggerHeight,\n \"oldHeight\": shutterSettings[s].oldHeight,\n \"firstCompleteUp\": shutterSettings[s].firstCompleteUp,\n \"alarmTriggerLevel\": shutterSettings[s].alarmTriggerLevel,\n \"alarmTriggerAction\": shutterSettings[s].alarmTriggerAction,\n \"lastAutoAction\": shutterSettings[s].lastAutoAction\n });\n\n currentStates[`${nameDevice}`] = states;\n }\n if (num === shutterSettings.length && onStart) {\n\n for (const i in currentStates) {\n if (shutterName.indexOf(currentStates[i].shutterName) === -1) {\n const name = currentStates[i].shutterName.replace(/[.;, ]/g, '_')\n adapter.log.debug(name + ': settings deleted');\n delete currentStates[`${name}`];\n }\n\n await sleep(2000);\n await adapter.setStateAsync('shutters.currentStates', { val: JSON.stringify(currentStates), ack: true })\n .catch((e) => adapter.log.warn(e));\n }\n } else if (num === shutterSettings.length && !onStart) {\n await adapter.setStateAsync('shutters.currentStates', { val: JSON.stringify(currentStates), ack: true })\n .catch((e) => adapter.log.warn(e));\n }\n await sleep(100);\n }\n}", "function updateState() {\n\t\t\tvar state = {\n\t\t\t\tday : scope.day,\n\t\t\t\tdriverName : scope.selectedDriverRun && scope.selectedDriverRun.driverName,\n\t\t\t\tstartRun : scope.selectedDriverRun && scope.selectedDriverRun.startRun,\t\t\t\t\n\t\t\t\tstore : scope.store\n\t\t\t};\t\n\t\t\t_.chain(state).extend(scope.mapOptions);\n\t\t\tparent.history.pushState(state, 'driverrun', '?' + jQuery.param(state));\n\t\t}", "function processPreState() {\n oresult.bpre = true;\n bok = true;\n sstate = '';\n }", "toggle() {\n\t\tthis.save({\n\t\t\tcompleted: !this.get('completed')\n\t\t});\n\t}", "function Notify() {\n\t\t//fined not checked products from all\n\t\tconst arrayCount = stateProducts.filter(product => (product.bought !== 'checked' && true))\n\t\tsetCount(() => arrayCount.length);\n\t\treturn (arrayCount.length);\n\t}", "toggleCheckbox() {\n this.setState({\n saveShippingInfo: !this.state.saveShippingInfo\n });\n }", "reset() {\r\n\t\tthis.changeState(this.initial);\r\n\t}", "function _processStateChanges(data) {\n _processGeneralNavigationData(data);\n\n _processNavigatingFromProductSearch(data);\n _processNavigatingToProductSearch(data);\n }", "restock(){\n var q = this.context.quantities\n var success = false //true if at least one denomination has valid input\n var fail = false //true if at least one denomination has invalid input\n var successMessage = \"\"\n var failMessage = \"\"\n this.state.quantities.map((quantity, index) => {\n if(quantity > Number.MAX_SAFE_INTEGER){\n failMessage += \"Too many $\"+ this.state.values[index] +\" bills. \" \n fail = true\n q[index] = this.context.quantities[index]\n }\n else if (quantity < 0){\n failMessage += \"Too few $\"+ this.state.values[index] +\" bills. \"\n fail = true\n q[index] = this.context.quantities[index]\n }\n else if(quantity !== this.context.quantities[index]){\n successMessage += \"Successfully updated $\"+ this.state.values[index] + \" bills. \"\n success = true\n q[index] = parseInt(quantity, 10)\n }\n\n });\n if(fail){\n alert(failMessage)\n this.setState({quantities: q, hasChanged: false})\n }\n if(success){ \n alert(successMessage) \n this.context.setQuantities(q)\n this.setState({quantities: q, hasChanged: false})\n }\n }", "onPromotionEnded(event) {\n if (event.context.modelName == this.props.modelName) this.loadRetrainedModel();\n }", "storeState(){\n if(this.storePath()){\n storeLocal(this.storePath(), this.state)\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
orders segments by rotation to make turning consistent
orderSegments() { this.segments.sort(this.compareSegment); }
[ "rotate() {\r\n //each piece has a different center of rotation uhoh, see image for reference\r\n //https://vignette.wikia.nocookie.net/tetrisconcept/images/3/3d/SRS-pieces.png/revision/latest?cb=20060626173148\r\n for (let c in this.coords) {\r\n this.coords[c][0] += this.rotationIncrements[this.rotationIndex][c][0]\r\n this.coords[c][1] += this.rotationIncrements[this.rotationIndex][c][1]\r\n }\r\n this.rotationIndex = (this.rotationIndex + 1) % 4\r\n }", "setCorrectRotation (raoad) {\r\n var pointBefore = this._lastRoad.children[0].children\r\n\r\n var SlopEndPosition2 = pointBefore[\r\n pointBefore.length - 1\r\n ].parent.convertToWorldSpace(pointBefore[pointBefore.length - 1].position)\r\n var SlopEndPosition1 = pointBefore[\r\n pointBefore.length - 2\r\n ].parent.convertToWorldSpace(pointBefore[pointBefore.length - 2].position)\r\n\r\n var slopEndY = SlopEndPosition2.y - SlopEndPosition1.y\r\n var slopEndX = SlopEndPosition2.x - SlopEndPosition1.x\r\n\r\n var point = raoad.children[0].children\r\n var SlopStartPosition2 = point[1].parent.convertToWorldSpace(\r\n point[1].position\r\n )\r\n var SlopStartPosition1 = point[0].parent.convertToWorldSpace(\r\n point[0].position\r\n )\r\n\r\n var slopeStartY = SlopStartPosition2.y - SlopStartPosition1.y\r\n var slopeStartX = SlopStartPosition2.x - SlopStartPosition1.x\r\n\r\n var angleBefore = Math.atan2(slopEndX, slopEndY)\r\n var angleStart = Math.atan2(slopeStartX, slopeStartY)\r\n\r\n raoad.rotation = cc.radiansToDegrees(angleBefore - angleStart)\r\n }", "function rotate(){\r\n unDraw();\r\n currentRotation++;\r\n if(currentRotation === current.length){ // so it doesn't go higher that array\r\n currentRotation = 0;\r\n }\r\n current = piecesArray[random][currentRotation];\r\n draw();\r\n }", "function flipping_spinning_bitcoin_rotation_movements() {\n \n var flipping_spinning_bitcoin_rotation_speed = ( flipping_spinning_bitcoin_motion_factor * 1 * 28 );\n \n if(is_bitcoin_flipping) {\n \n bitcoin_flipping_factor_counter += flipping_spinning_bitcoin_rotation_speed;\n flipping_spinning_bitcoin_collada.rotation.x += flipping_spinning_bitcoin_rotation_speed;\n \n }\n \n if(is_bitcoin_spinning) {\n \n bitcoin_spinning_factor_counter += flipping_spinning_bitcoin_rotation_speed;\n flipping_spinning_bitcoin_collada.rotation.z += flipping_spinning_bitcoin_rotation_speed;\n \n }\n \n}", "function rotate90CCW1(m) {\n m = cloneDeep(m);\n const size = m.length;\n // console.log(m.map(i => i.join(', ')).join('\\n'), '\\n');\n\n for (let i = 0; i < Math.floor(size / 2); i++) {\n const first = i;\n const last = size - 1 - i;\n for (let j = first; j < last; j++) {\n const k = j - i;\n const tmp = m[first][last - k];\n // console.log('first:', first, 'last:', last, 'k:', k, 'tmp:', tmp, '\\n');\n\n m[first][last - k] = m[last - k][last];\n m[last - k][last] = m[last][first + k];\n m[last][first + k] = m[first + k][first];\n m[first + k][first] = tmp;\n // console.log(m.map(i => i.join(', ')).join('\\n'), '\\n');\n }\n }\n\n return m;\n}", "function rotarMatriz(pieza,direction) {\n\n //Transposicion\n for(y=0;y<pieza.length;++y){\n for(x=0;x<y;++x){\n [pieza[x][y],pieza[y][x]]=[pieza[y][x],pieza[x][y]];\n }\n }\n\n //Reverse\n\n if(direction>0){\n pieza.forEach(function (fila) {\n fila.reverse();\n });\n }else{\n pieza.reverse();\n }\n\n\n}", "shiftData(data, angle) {\n return _.each(data, function(set) {\n var initial = set.initial[0];\n\n set.mercator[0] = App.arithmetics.wrapTo180(initial + App.arithmetics.wrapTo180(angle));\n\n return set;\n });\n }", "function positionCorner4(cube) {\n //a through b\n for (var a = -1; a < 12; a++) {\n singleRotation(a);\n\n for(var b = -1; b < 12; b++) {\n singleRotation(b);\n\n if (checkWhiteCross(cube) && checkCorner4(cube) && (cube[down][2][0] == 'W') && (cube[down][0][0] == 'W') && (cube[down][0][2] == 'W')) {\n //console.log(a + \" \" + b);\n //console.log(outputCross(a, b, -1, -1, -1, -1, -1));\n var txt = outputCross(a, b, -1, -1, -1, -1, -1);\n commandPositionWhiteCorner4 += txt;\n return;\n }\n\n singleRotation(11-b);\n } //b\n singleRotation(11-a);\n } //a\n\n //console.log(\"b\");\n\n //a through c\n for (var a = -1; a < 12; a++) {\n singleRotation(a);\n\n for(var b = -1; b < 12; b++) {\n singleRotation(b);\n\n for(var c = -1; c < 12; c++) {\n singleRotation(c);\n\n if (checkWhiteCross(cube) && checkCorner4(cube) && (cube[down][2][0] == 'W') && (cube[down][0][0] == 'W') && (cube[down][0][2] == 'W')) {\n //console.log(a + \" \" + b + \" \" + c);\n //console.log(outputCross(a, b, c, -1, -1, -1, -1));\n var txt = outputCross(a, b, c, -1, -1, -1, -1);\n commandPositionWhiteCorner4 += txt;\n return;\n }\n\n singleRotation(11-c);\n } //c\n singleRotation(11-b);\n } //b\n singleRotation(11-a);\n } //a\n\n //console.log(\"c\");\n\n //a through d\n for (var a = -1; a < 12; a++) {\n singleRotation(a);\n\n for(var b = -1; b < 12; b++) {\n singleRotation(b);\n\n for(var c = -1; c < 12; c++) {\n singleRotation(c);\n\n for(var d = -1; d < 12; d++) {\n singleRotation(d);\n\n if (checkWhiteCross(cube) && checkCorner4(cube) && (cube[down][2][0] == 'W') && (cube[down][0][0] == 'W') && (cube[down][0][2] == 'W')) {\n //console.log(a + \" \" + b + \" \" + c + \" \" + d);\n //console.log(outputCross(a, b, c, d, -1, -1, -1));\n var txt = outputCross(a, b, c, d, -1, -1, -1);\n commandPositionWhiteCorner4 += txt;\n return;\n }\n\n singleRotation(11-d);\n } //d\n singleRotation(11-c);\n } //c\n singleRotation(11-b);\n } //b\n singleRotation(11-a);\n } //a\n\n //console.log(\"d\");\n}", "_updateInitialRotation() {\n this.arNodeRef.getTransformAsync().then((retDict)=>{\n let rotation = retDict.rotation;\n let absX = Math.abs(rotation[0]);\n let absZ = Math.abs(rotation[2]);\n \n let yRotation = (rotation[1]);\n \n // if the X and Z aren't 0, then adjust the y rotation.\n if (absX > 1 && absZ > 1) {\n yRotation = 180 - (yRotation);\n }\n this.setState({\n rotation : [0,yRotation,0],\n nodeIsVisible: true,\n });\n });\n }", "positionate () {\n foreach(arrow => arrow.positionate(), this.arrows)\n }", "function rotateClockwise(){\n let result = [];\n let obj={};\n for (let i=arguments[0].length-1; i>=0; i--){\n for(let j=0; j<arguments[0][i].length; j++){\n let arr = [arguments[0][i][j]];\n if (Array.isArray(obj[j])){\n \t//result[val.toLowerCase()] = (result[val.toLowerCase()] || 0) + 1;\n obj[j].push(arguments[0][i][j]);\n }else{\n obj[j] = arr;\n }\n }\n }\n for(var key in obj){\n result.push(obj[key]);\n }\n return result;\n}", "function rotatePoints(points, angle, origin) {\r\n return points.map(function(point) {\r\n return rotatePoint(point, angle, origin);\r\n });\r\n }", "calculateRotation() {\n const extentFeature = this._extentFeature;\n const coords = extentFeature.getGeometry().getCoordinates()[0];\n const p1 = coords[0];\n const p2 = coords[3];\n const rotation = Math.atan2(p2[1] - p1[1], p2[0] - p1[0]) * 180 / Math.PI;\n\n return -rotation;\n }", "function rotateZ(rads) {\n var cosTheta, sinTheta;\n cosTheta = Math.cos(rads);\n sinTheta = Math.sin(rads);\n return function (point) {\n var x = point.x * cosTheta - point.y * sinTheta;\n var y = point.y * cosTheta + point.x * sinTheta;\n return new Point(x, y, point.z);\n };\n}", "function segments(values) {\n var segments = [], i = 0, n = values.length\n while (++i < n) segments.push([[i - 1, values[i - 1]], [i, values[i]]]);\n return segments;\n}", "function rotateHedgehogOrientation(oldPos, newPos) {\n var angle = oldPos.angleTo(newPos) * 180 / Math.PI;\n var cos = cosinusBetweenVectors(oldPos, newPos);\n hedgehog.rotateOnAxis(new THREE.Vector3(0, 1, 0), angle);\n}", "rotatorPosition(step) {\n // return this.rotator.centerPosition(step, this.stator.rotatorPosition(step), this.stator.angle(step));\n return this.rotator.center(this.stator.toothPose(step), step + this.offset);\n }", "function moveLeg(position, motor, angle) {\r\n\tswitch (motor){\r\n\t\tcase 0:\r\n\t\t\tif (position > 2)\r\n\t\t\t\tangle = -angle;\r\n\t\t\t(spider.children[position]).children[0].rotation.y = angle * Math.PI / 180;\r\n\t\t\tbreak;\r\n\t\tcase 1:\r\n\t\t\t((spider.children[position]).children[0]).children[0].rotation.z = angle * Math.PI / 180;\r\n\t\t\tbreak;\r\n\t\tcase 2:\r\n\t\t\t((((spider.children[position]).children[0]).children[0]).children[0]).children[0].rotation.z = (-angle - 90) * Math.PI / 180;\r\n\t\t\tbreak;\r\n\t}\r\n}", "function positionCorner3(cube) {\n //a through b\n for (var a = -1; a < 12; a++) {\n singleRotation(a);\n\n for(var b = -1; b < 12; b++) {\n singleRotation(b);\n\n if (checkWhiteCross(cube) && checkCorner3(cube) && (cube[down][2][0] == 'W') && (cube[down][0][0] == 'W')) {\n //console.log(a + \" \" + b);\n //console.log(outputCross(a, b, -1, -1, -1, -1, -1));\n var txt = outputCross(a, b, -1, -1, -1, -1, -1);\n commandPositionWhiteCorner3 += txt;\n return;\n }\n\n singleRotation(11-b);\n } //b\n singleRotation(11-a);\n } //a\n\n //console.log(\"b\");\n\n //a through c\n for (var a = -1; a < 12; a++) {\n singleRotation(a);\n\n for(var b = -1; b < 12; b++) {\n singleRotation(b);\n\n for(var c = -1; c < 12; c++) {\n singleRotation(c);\n\n if (checkWhiteCross(cube) && checkCorner3(cube) && (cube[down][2][0] == 'W') && (cube[down][0][0] == 'W')) {\n //console.log(a + \" \" + b + \" \" + c);\n //console.log(outputCross(a, b, c, -1, -1, -1, -1));\n var txt = outputCross(a, b, c, -1, -1, -1, -1);\n commandPositionWhiteCorner3 += txt;\n return;\n }\n\n singleRotation(11-c);\n } //c\n singleRotation(11-b);\n } //b\n singleRotation(11-a);\n } //a\n\n //console.log(\"c\");\n\n //a through d\n for (var a = -1; a < 12; a++) {\n singleRotation(a);\n\n for(var b = -1; b < 12; b++) {\n singleRotation(b);\n\n for(var c = -1; c < 12; c++) {\n singleRotation(c);\n\n for(var d = -1; d < 12; d++) {\n singleRotation(d);\n\n if (checkWhiteCross(cube) && checkCorner3(cube) && (cube[down][2][0] == 'W') && (cube[down][0][0] == 'W')) {\n //console.log(a + \" \" + b + \" \" + c + \" \" + d);\n //console.log(outputCross(a, b, c, d, -1, -1, -1));\n var txt = outputCross(a, b, c, d, -1, -1, -1);\n commandPositionWhiteCorner3 += txt;\n return;\n }\n\n singleRotation(11-d);\n } //d\n singleRotation(11-c);\n } //c\n singleRotation(11-b);\n } //b\n singleRotation(11-a);\n } //a\n\n //console.log(\"d\");\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the average between the current set of stats and the provided stats
average(stats) { return this.add(stats).scale(0.5); }
[ "function calculateAverage(){\n var sum = 0;\n for(var i = 0; i < self.video.ratings.length; i++){\n sum += parseInt(self.video.ratings[i], 10);\n }\n\n self.avg = sum/self.video.ratings.length;\n }", "function updateAverage($teams) {\n\tfor (var i = 0; i < $teams.length; i++) {\n\t\t$team = $($teams[i]);\n\t\tvar $players = $team.find('.player');\n\t\tvar n = 0;\n\t\tvar total = 0.0;\n\t\tvar nExp = 0;\n\t\tvar totalExp = 0.0;\n\t\tfor (var j = 0; j < $players.length; j++) {\n\t\t\tvar rating = parseInt($players.eq(j).attr('data-rating'));\n\t\t\tif (!isNaN(rating)) {\n\t\t\t\tn += 1;\n\t\t\t\ttotal += rating;\n\t\t\t}\n\t\t\tvar ratingExp = parseInt($players.eq(j).attr('data-exp-rating'));\n\t\t\tif (!isNaN(ratingExp)) {\n\t\t\t\tnExp += 1;\n\t\t\t\ttotalExp += ratingExp;\n\t\t\t}\n\t\t}\n\t\tif (n > 0) {\n\t\t\t$team.find('.average-rating').text((total / n).toFixed(2));\n\t\t} else {\n\t\t\t$team.find('.average-rating').text('');\n\t\t}\n\t\tif (nExp > 0) {\n\t\t\t$team.find('.average-exp-rating').text((totalExp / nExp).toFixed(2));\n\t\t} else {\n\t\t\t$team.find('.average-exp-rating').text('');\n\t\t}\n\t}\n}", "function calculateAverage(ratings){\n var sum = 0;\n for(var i = 0; i < ratings.length; i++){\n sum += parseInt(ratings[i], 10);\n }\n\n var avg = sum/ratings.length;\n\n return avg;\n }", "getAverageDamage() {\n const avgAttacks = (this.minAttacks + this.maxAttacks) / 2;\n const avgDmg = (this.minDamage + this.maxDamage) / 2 * avgAttacks;\n const critDmg = this.crit / 100 * avgDmg * 2;\n\n return avgDmg + critDmg;\n }", "function average() {\n\tvar total = 0;\n\tfor (var i = 0; i < this.grades.length; ++i) {\n\t\ttotal += this.grades[i];\n\t}//end for\n\treturn print(total / this.grades.length);\n}//end average function", "function calcAverage (tips) {\n var sum = 0;\n for (var i = 0; i < tips.length; i++) {\n sum += tips[i];\n }\n return sum / tips.length;\n}", "calculateStudentAverage(){\n this.totalPoints = calculateTotal(this)\n this.average = Number((this.totalPoints/this.submissions.length).toFixed(2))\n\n }", "function calcAverage(tips){\n var sum = 0\n for(var i = 0; i < tips.length; i++){\n sum = sum + tips[i]\n }\n return sum / tips.length\n }", "getAverageResults() {\n return this.resultsAverages\n }", "function averageDistributions(distributions) {\n // initialization\n var sumY = 0.0;\n var sumY2 = 0.0;\n var sumWeight = 0.0; // the sum of the weights that we calculate, which we use to normalize\n \tvar stdDevIsZero = false;\n var sumVariance = 0.0;\t// variance is another name for standard deviation squared\n\t var outputWeight = 0.0;// the sum of the given weights, which we use to assign a weight to our guess\n\t var count = 0.0;\t// the number of distributions being used\n\t var weight;\n\t var y;\n\t var stdDev;\n\t message(\"averaging distributions \\r\\n\");\t \n\t var i;\n\t var currentDistribution;\n \t// iterate over each distribution and weight them according to their given weights and standard deviations\n\t for (i = 0; i < distributions.length; i++) {\n\t currentDistribution = distributions[i];\n\t message(\"mean = \" + currentDistribution.getMean() + \" stdDev = \" + currentDistribution.getStdDev() + \" weight = \" + currentDistribution.getWeight() + \"\\r\\n\");\n\t stdDev = currentDistribution.getStdDev();\n\t // only consider nonempty distributions\n\t if (currentDistribution.getWeight() > 0) {\n \t\t\t// If the standard deviation of any distribution is zero, then compute the average of only distributions with zero standard deviation\n \t\t\tif (stdDev == 0) {\n \t\t\t if (!stdDevIsZero) {\n \t\t\t stdDevIsZero = true;\n \t\t\t sumVariance = 0.0;\n \t\t\t sumY = sumY2 = 0.0;\n \t\t\t outputWeight = count = sumWeight = 0.0;\n \t\t\t }\n \t\t\t}\n \t\t\t// Figure out whether we care about this distribution or not\n\t\t\t if ((stdDev == 0) || (!stdDevIsZero)) {\n\t\t\t\t // get the values from the distribution\n\t\t\t\t y = currentDistribution.getMean();\n\t\t\t\t if (stdDev == 0.0) {\n\t\t\t\t\t // If stddev is zero, then just use the given weight\n\t\t\t\t\t weight = currentDistribution.getWeight();\n\t\t\t\t } else {\n\t\t\t\t\t // If stddev is nonzero then weight based on both the stddev and the given weight\n\t\t\t\t\t weight = currentDistribution.getWeight() / stdDev;\n\t\t\t\t }\n\t\t\t\t // add to the running totals\n\t\t\t\t sumY += y * weight;\n\t\t\t\t sumY2 += y * y * weight;\n\t\t\t\t sumWeight += weight;\n\t\t\t\t sumVariance += stdDev * stdDev * weight;\n\t\t\t\t outputWeight += currentDistribution.getWeight();\n\t\t\t\t count += 1.0;\n\t\t\t }\n\t }\n\t }\n\t var result;\n\t if (sumWeight == 0) {\n\t result = new Distribution(0, 0, 0);\n\t }\n\t else{\n\t\t // If we did have a distribution to predict from then we can calculate the average and standard deviations\n\t\t var newAverage = sumY / sumWeight;\n\t\t var variance1 = (sumY2 - sumY * sumY / sumWeight) / sumWeight;\n\t\t message(\"variance1 = \");\n\t\t message(variance1);\n\t\t message(\"\\r\\n\");\n\t\t var variance2 = sumVariance / sumWeight;\n\t\t message(\"variance2 = \");\n\t\t message(variance2);\n\t\t message(\"\\r\\n\");\n\t\t //stdDev = Math.sqrt(variance1 + variance2);\n\t\t stdDev = Math.sqrt(variance2);\n\t\t result = new Distribution(newAverage, stdDev, outputWeight);\n\t }\n\t \n\t message(\"resultant distribution = \");\n\t printDistribution(result);\n\t message(\"\\r\\n average of all distributions:\" + (sumY / sumWeight) + \"\\r\\n\");\n \treturn result;\n }", "function calculateAverage(grades) {\n // grades is an array of numbers\n total = 0\n for(let i = 0; i <grades.length; i++){\n total += grades[i];\n }\n return Math.round(total / grades.length);\n}", "function calculateAverage(){\n\t// combined_average_video_confidence = 0\n\taverage_confidence_list = []\n\tfor(i = 0; i < grid.array.length; i++) {\n\t\tcurr_video = grid.array[i]\n\t\tsum_video_confidence = 0\n\t\tfor(j = 0; j < curr_video.grades.length; j++) {\n\t\t\tgrade = curr_video.grades[j]\n\t\t\tsum_video_confidence += grade.confidence\n\t\t}\n\t\taverage_video_confidence = sum_video_confidence / curr_video.grades.length\n\t\taverage_confidence_list.push(average_video_confidence)\n\t}\t\t\n\t// return combined_average_video_confidence /= grid.array.length\n\t// return calculateAverage\n\treturn average_confidence_list\n}", "function average(){\n\t\t\tvar sum = 0;\n\t\t\tlist.forEach(function(item){\n\t\t\t\tsum += item.age;\n\t\t\t});\n\n\t\t\treturn sum / list.length;\n\t\t}", "average(marks) {}", "function averageTestScore(testScores) {\n let average = 0;\n for (const score of testScores) {\n average += score;\n }\n return average / testScores.length;\n}", "function avgValue(array)\n{\n\tvar sum = 0;\n\tfor(var i = 0; i <= array.length - 1; i++)\n\t{\n\t\tsum += array[i];\n\t}\n\tvar arrayLength = array.length;\n\treturn sum/arrayLength;\n}", "function avg(num1, num2, num3){\n return (num1 + num2 + num3)/3;\n }", "function avg(v){\n s = 0.0;\n for(var i=0; i<v.length; i++)\n s += v[i];\n return s/v.length;\n}", "function find_average() {\n number_of_accounts = accounts.length;\n console.log(\"Number of bank accounts: \" + number_of_accounts);\n total = total_cash();\n average = total / number_of_accounts;\n console.log(\"Average bank account value: £\" + average);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Functions / Get number of tweets posted by logged in user
function getNumberOfTweets(userId) { tweetService.getTweetsByAuthor(userId).then(function(data) { if (data !== null) { return data.length; } else { // TODO: Handle error return null; } }); }
[ "function showLastTweets() {\n\tvar params = {screen_name: 'trgmedina'};\n\n\tclient.get('statuses/user_timeline', { count: 20 }, function(error, tweets, response) {\n\t if (error) {\n\t console.log('Error occurred: ' + error);\n return;\n\t }\n\t else {\n\t \tfor (var i = 0; i < tweets.length; i++) {\n\t \t\tconsole.log(JSON.stringify(tweets[i].text));\n\t \t}\n\t }\n\t});\n}", "function plusTweets(){\n\tvar twet=$(\"#tweetnbre\").html();\n\tvar val=parseInt(twet);\n\t\tval++;\n\t$(\"#tweetnbre\").html(val);\n}", "function loadTweetData() {\n T.get(\"friends/list\", { screen_name: userName, count: 5 }, function(\n err,\n data,\n response\n ) {\n if (err) {\n // console.log(err);\n throw err;\n } else {\n myFriends = data.users;\n // console.log(data.users);\n }\n });\n\n T.get(\"direct_messages/sent\", { count: 5 }, function(err, data, response) {\n if (err) {\n console.log(err);\n } else {\n myChats = data;\n // console.log(data);\n }\n });\n\n T.get(\"statuses/user_timeline\", { screen_name: userName, count: 5 }, function(\n err,\n data,\n response\n ) {\n if (err) {\n console.log(err);\n } else {\n myTweets = data;\n // console.log(data);\n }\n });\n}", "function getTwitterTweets(screen_name) {\n socket.emit('user_tweets', { screen_name: screen_name });\n }", "function getUsersCount(){\n const messageObject = {\n type: 'usersCount',\n content: wss.clients.size,\n };\n wss.broadcast(JSON.stringify(messageObject));\n}", "async function ViewerCounts(userName) {\n const user = await twitchClient.helix.users.getUserByName(userName);\n if (!user) {\n return false;\n }\n return (await twitchClient.helix.streams.getStreamByUserId(user.id)) != null;\n}", "function moinsTweets(){\n\tvar twet=$(\"#tweetnbre\").html();\n\tvar val=parseInt(twet);\n\tval--;\n\t$(\"#tweetnbre\").html(val);\n}", "function search(query, number){\n\t\tvar params = {\n\t\tq: query,\n\t\tcount: number\n\t}\n\n\tT.get('search/tweets', params, gotData);\n\n\tfunction gotData(err, data, response){\n\t\tvar tweets = data.statuses;\n\t\tfor (var i=0; i<tweets.length; i++){\n\t\t\tconsole.log(tweets[i].text);\n\t\t}\n\t}\n}", "function showTweets(maxTw) {\n\tvar client = new Twitter(twitterKeys);\n\tvar twitParams = {screen_name: 'PmAlias'};\n\tclient.get('statuses/user_timeline', twitParams, function(error, tweets, response) {\n\t if (!error) {\n\t\t\ttweets = tweets.concat(tweets,tweets,tweets,tweets,tweets);\n\t\t\tconsole.log(tweets.length);\n\t\t\t// Limit to the most recent <maxTw> tweets\n\t\t\tif (tweets.length > maxTw) {\n\t\t\t\t// Sort in reverse date order to get most recent at the top\n\t\t\t\tsortTweets(tweets,'descending');\n\t\t\t\t// Keep the most recent tweets up to maxTw\n\t\t\t\ttweets = tweets.slice(0,maxTw);\n\t\t\t}\n\t\t\t// Sort in date order\n\t\t\tsortTweets(tweets,'ascending');\n\t\t\t\n\t \tfor (var i=0,len=tweets.length;i<len;i++) {\n\t\t\t\tconsole.log(\n\t\t\t\t\tmoment(tweets[i].created_at,'ddd MMM DD HH:mm:ss +SSSS YYYY')\n\t\t\t\t\t.format('MM/DD/YYYY hh:mm:ss A'),' ',tweets[i].text);\n\t\t\t}\n\t }\n\t});\n}", "function getRandom() {\n\tvar l = tweets.length; // grab length of tweet array\n\tvar ran = Math.floor(Math.random()*l); // grab random user\n\n\treturn tweets[ran];\n}", "function get_tweets_in_current_area() {\n\tfoundTweetCount = 0;\n\t$(\"#loading_button\").css(\"display\", \"inline-block\");\n\n\t// Check if the browser supports HTML 5 Geolocation.\n\tif(navigator.geolocation) {\n\t\t// If it does, get the user's current geolocation, and search for tweets in that area.\n\t\tnavigator.geolocation.getCurrentPosition(function(position) {\n\t\t\tvar lat_long_str = position.coords.latitude + \",\" + position.coords.longitude + \",5mi\";\n\t\t\t$(\"#results\").html(\"\");\n\t\t\t$(\"#results\").css(\"height\", \"100%\");\n\t\t\t$.get(\"scripts/php/search_twitter.php?geo=\"+lat_long_str, function(response) {\n\t\t\t\tjsonData = JSON.parse(response);\n\t\t\t\tnextSetOfTweets = jsonData.search_metadata.next_results;\n\t\t\t\tbuildTweetCard(jsonData);\n\t\t\t}).then(function() {\n\t\t\t\t$(\"#found_results\").html(\"Showing \"+foundTweetCount+\" tweets (scroll down to load more).\");\n\t\t\t});\n\t\t});\n\t}\n}", "function viewUserTweets(userStr){\n userProfile = true;\n resetUserTweets(userStr); // clears all tweets\n var UserTweets = _.filter(streams.home,function(tweet){\n if (tweet.user == userStr){\n generateTweet(tweet); // generates tweet with tweet object\n }\n });\n addBackButton();\n }", "function getTwitterStream(keyword) {\n twitter.stream('statuses/filter', {track: keyword}, function (stream) {\n stream.on('data', function (data) {\n //increasing and manipuilating data received from the json object\n numbOfTweets++;\n numbOfFollowers = numbOfFollowers + data.user.followers_count;\n cycleCount++;\n cycleFollow = cycleFollow + data.user.followers_count;\n tweetNames.push(data.user.screen_name);\n tweetContent.push(data.text);\n averageCount = numbOfFollowers/numbOfTweets;\n //emit the new tweet even\n io.sockets.emit('new_tweet', {tweetCount: numbOfTweets, followerCount:numbOfFollowers, tweetNames:tweetNames,tweetContent:tweetContent,averageCount:averageCount});\n });\n //if anything goes wrong error the application\n stream.on('error', function (err) {\n console.log('ERROR');\n console.log(err);\n });\n });\n}", "function nextTweet(element) {\n var result = tweets.pop();\n if (tweets.length == 0) {\n _iterateTweets();\n }\n\n if (element == undefined) {\n return result;\n } else {\n\tconsole.log(result.favorite_count);\n\tconsole.log(result.retweet_count);\n element.find(\".profile_pic\").attr(\"src\", result.profile_image_url);\n element.find(\".username\").text(\"@\" + result.screen_name);\n element.find(\".date\").text(result.created_at);\n element.find(\".tweet .text\").text(result.text);\n element.find(\".favorites\").text(result.favorite_count + \" favorites\");\n element.find(\".retweets\").text(result.retweet_count + \" retweets\");\n\n\tvar popularity = result.favorite_count + result.retweet_count;\n\tsetColorGradient(element, popularity);\n }\n\n}", "async getBookmarkCount() {\n const [result] = await this.client('bookmark').count();\n const value = parseInt(result['count(*)']) ?? 0;\n return value;\n }", "function twitterFeed(){\n\n\t//taking input\n\tconsole.log(\"Key word to find sentiment: \");\n\tprocess.stdin.setEncoding('utf8');\n\tprocess.stdin.on('readable', function(input) {\n\t\tvar word = process.stdin.read();\n\t \n\t\tif (word !== null) {\n\t\t\tstreamInput(word);\n\t\t}\n\t});\n\n\tprocess.stdin.on('end', function() {\n\t process.stdout.write('end');\n\t});\n\n\t//Authentication with twitter\n\tvar client = new Twitter({\n\t consumer_key: \"1LsrwvTSs3XAWeJE5fFcDp378\",\n\t consumer_secret: \"Vo7sfjoEOD7DP6haSFR2p4AFTE01qxfHTVSA8k1dgdARNlUQw1\",\n\t access_token_key: \"4329704114-FtRczjVFxQMo6x2tzA2tfyyud1fOchMEjI7xBPq\",\n\t access_token_secret: \"fyGrcotLQq7V1k94gergfJTXFcaHWcYBaV5nM3B5PSyvn\"\n\t});\n\n\t//stream and output\n\tfunction streamInput(keyWord){ \n\t\tvar numberOfTweets = 0; \n\n\t\t\tclient.stream('statuses/filter', {track: keyWord}, function(stream) {\t\t\t\t\n\t\t\tstream.on('data', function(tweet) {\n\t\t\t \t\n\t\t\t \t//number of tweets to take in\n\t\t\t \tif(numberOfTweets < 1000){ \n\t\t\t\t console.log(tweet.text);\n\t\t\t\t if(typeof(tweet.text) == 'string'){\n\t\t\t\t\t testVector.push(tweet.text);\n\t\t\t\t\t numberOfTweets++;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\telse{\n\t\t\t\t\teventEmitter.emit('tweetsReady', testVector);\n\t\t\t\t\tstopStream(stream);\n\t\t\t\t}\t\n\t\t\t});\n\n\t\t\tstream.on('error', function(error) {\n\t\t\t throw error;\n\t\t\t process.exit(1);\n\t\t\t});\n\t\t});\n\t}\n\n\n\tfunction stopStream (s){\n\t\ts.destroy();\n\t}\n}", "getNumTasks() {\n return Tasks.find({owner:Meteor.userId()}).count();\n }", "async reviewCount() {\n const {appid, openid} = this.ctx.wxuser;\n const data = await this.service.register.reviewCount({openid, appid});\n this.ctx.body = {\n success: true,\n data,\n };\n }", "static getEntryCount(feedId){\n\t\tlet kparams = {};\n\t\tkparams.feedId = feedId;\n\t\treturn new kaltura.RequestBuilder('syndicationfeed', 'getEntryCount', kparams);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Visit a parse tree produced by PlSqlParserpartition_extention_clause.
visitPartition_extention_clause(ctx) { return this.visitChildren(ctx); }
[ "visitPartition_extension_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitQuery_partition_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitIndex_partitioning_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitPartition_by_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitTable_partitioning_clauses(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitModel_column_partition_part(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitIndex_subpartition_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitList_partition_desc(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitList_partitions(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitSystem_partitioning(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitSubpartition_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitSubpartition_template(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitSubpartition_by_list(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitSubquery_operation_part(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitNew_partition_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitAlter_index_partitioning(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitTable_partition_description(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitIndex_partition_description(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitList_subpartition_desc(ctx) {\n\t return this.visitChildren(ctx);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
drawPlayer() Draw the player as an ellipse with alpha based on health
function drawPlayer() { fill(playerFill,playerHealth); ellipse(playerX,playerY,playerRadius*2); }
[ "function drawPlayer() {\n push();\n tint(255,playerHealth);\n image(playerHunter,playerX,playerY,playerRadius*5, playerRadius*5);\n pop();\n}", "function createPlayer() {\n fill(230);\n circle(playerX, playerY, 40);\n}", "function setupPlayer() {\n playerX = 4*width/5;\n playerY = height/2;\n playerHealth = playerMaxHealth;\n}", "drawBoss() {\n ctx.drawImage(this.boss,\n 0, 0, this.boss.width, this.boss.height,\n this.x_boss_pos, this.y_icon_pos,\n icon_width, icon_height);\n \n // Health outer\n ctx.strokeStyle = \"black\";\n ctx.strokeRect(this.x_boss_pos - 100, this.y_icon_pos + icon_height + 10, icon_width + 100, 25);\n\n // Health drawing\n ctx.fillStyle = \"red\";\n ctx.fillRect(this.x_boss_pos - 100, this.y_icon_pos + icon_height + 10, this.health, 25);\n\n ctx.fillStyle = \"black\";\n ctx.font = '20px Arial';\n ctx.fillText(\"Health: \" + this.health, this.x_boss_pos - 150 - 100, this.y_icon_pos + icon_height + 25);\n }", "function drawGoal(x, y, size, alpha){\r\n\tvar blue = color(\"blue\");\r\n\tblue.setAlpha(alpha);\r\n\r\n\tfill(blue);\r\n circle(x+size/2, y+size/2, size*5/6);\r\n erase();\r\n circle(x+size/2, y+size/2, size*7/12);\r\n noErase();\r\n fill(blue);\r\n circle(x+size/2, y+size/2, size/3);\r\n}", "drawHealth() {\n document.querySelector(\".monster-health__remain\").style.width =\n (this.health / this.startHealth) * 100 + \"%\";\n document.querySelector(\n \".monster-health__remain\"\n ).innerHTML = this.health;\n }", "updateHealth(health) {\n // width is defined in terms of the player's health\n this.width = health * 5;\n }", "drawPlayerMenu() {\n if (currentChar != \"none\") {\n push();\n // 2 supporting skills\n for (let i = 0; i < currentChar.abilities[0].length; i++) {\n strokeWeight(3);\n stroke(0);\n // if moused over, it is highlighted\n if (mouseOver.name === currentChar.abilities[0][i].name) {\n fill(0);\n } else {\n fill(255);\n }\n rectMode(CORNER);\n rect(width/7+(i*width/3.5), height-height/4.5, width/4, height/6);\n // name, cost and ability\n noStroke();\n // if moused over, it is highlighted\n if (mouseOver.name === currentChar.abilities[0][i].name) {\n fill(255);\n } else {\n fill(0);\n }\n textAlign(CENTER, CENTER);\n textSize(width/80+height/80);\n text(currentChar.abilities[0][i].name, width/3.75+(i*width/3.5), height-height/6);\n let abilityCostText = \"Cost: \" + currentChar.abilities[0][i].cost + \" Energy\";\n text(abilityCostText, width/3.75+(i*width/3.5), height-height/8);\n textSize(width/150+height/150);\n text(currentChar.abilities[0][i].description, width/3.75+(i*width/3.5), height-height/12);\n // if this is an ultimate, then let the player know\n if (currentChar.abilities[0][i].ultimate === true) {\n textSize(width/100+height/100);\n if (currentChar.ultCharge === 100) {\n fill(0, 255, 0);\n text(\"Ultimate Ready!\", width/3.75+(i*width/3.5), height-height/5);\n } else {\n fill(255, 0, 0);\n text(\"Ultimate Charging\", width/3.75+(i*width/3.5), height-height/5);\n }\n }\n // if this non-ultimate ability has been used this turn and cannot be used again\n if (currentChar.abilities[0][i].used === true && currentChar.abilities[0][i].ultimate === false) {\n textSize(width/100+height/100);\n fill(255, 0, 0);\n text(\"Used This Turn\", width/3.75+(i*width/3.5), height-height/5);\n }\n }\n pop();\n }\n }", "function draw()\r\n\t{\r\n\t\tvar canvas = document.getElementById('canvas');\r\n\t\tif(canvas.getContext)\r\n\t\t{\r\n\t\t\tvar context = canvas.getContext('2d');\r\n\t\t\t// draw body\r\n\t\t\tif(this.state == playerStates.respawning) context.fillStyle= \"rgba(0,200,0,0.4)\"; // set fillStyle to dark green\r\n\t\t\telse context.fillStyle= \"rgb(0,200,0)\"; // set fillStyle to dark green\r\n\t\t\t\t\r\n\t\t\tcontext.fillRect(this.rect.pos.x,this.rect.pos.y,this.rect.dim.width,this.rect.dim.height);\r\n\t\t\t\r\n\t\t\t// left arm\r\n\t\t\tcontext.fillRect(this.arms.leftArm.pos.x,this.arms.leftArm.pos.y,this.arms.leftArm.dim.width,this.arms.leftArm.dim.height);\r\n\t\t\t// right arm\r\n\t\t\tcontext.fillRect(this.arms.rightArm.pos.x,this.arms.rightArm.pos.y,this.arms.rightArm.dim.width,this.arms.rightArm.dim.height);\r\n\t\t\t// left leg\r\n\t\t\tcontext.fillRect(this.legs.leftLeg.pos.x,this.legs.leftLeg.pos.y,this.legs.leftLeg.dim.width,this.legs.leftLeg.dim.height);\r\n\t\t\t//right leg\r\n\t\t\tcontext.fillRect(this.legs.rightLeg.pos.x,this.legs.rightLeg.pos.y,this.legs.rightLeg.dim.width,this.legs.rightLeg.dim.height);\r\n\t\t\t\r\n\t\t\t// switch to black for eyes\r\n\t\t\tcontext.fillStyle= \"rgb(0,0,0)\"; // set fillStyle to black\r\n\t\t\t// left eye\r\n\t\t\tcontext.fillRect(this.eyes.left.pos.x,this.eyes.left.pos.y,this.eyes.left.dim.width,this.eyes.left.dim.height);\r\n\t\t\t//right eye\r\n\t\t\tcontext.fillRect(this.eyes.right.pos.x,this.eyes.right.pos.y,this.eyes.right.dim.width,this.eyes.right.dim.height);\r\n\t\t\t\r\n\t\t\tif(this.drawJumpZone)\r\n\t\t\t{\r\n\t\t\t\t// draw jumpzone\r\n\t\t\t\tif(this.jumpZone.inZone)\r\n\t\t\t\t\tcontext.strokeStyle= \"rgb(0,255,0)\"; // set fillStyle to green\r\n\t\t\t\telse\r\n\t\t\t\t\tcontext.strokeStyle= \"rgb(255,0,0)\"; // set fillStyle to red\r\n\t\t\t\t\r\n\t\t\t\tcontext.lineWidth = 2;\r\n\t\t\t\tcontext.strokeRect(this.jumpZone.rect.pos.x, this.jumpZone.rect.pos.y, this.jumpZone.rect.dim.width, this.jumpZone.rect.dim.height);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t// draw lives\r\n\t\t\tthis.lifeBar.draw();\r\n\t\t}\r\n\t}", "drawLobbyView() {\n this.drawState();\n\n this.ctx.font = '20px Arial';\n this.ctx.fillStyle = '#FFF';\n this.ctx.textAlign = 'center';\n this.ctx.fillText('Waiting on another player...', this.canvas.width / 2,\n this.canvas.height / 2 - 60);\n this.ctx.fillStyle = '#000';\n }", "function showHealth(player, el) {\n\tvar percent = (player.health * 10) + \"%\"\n\t$(el).children(\".health-bar\").css(\"width\", percent);\n\tconsole.log(\"Health has been updated\");\n}", "function decreaseHealth(playerObject, player) {\n\tplayerObject.health--;\n\tsetTimeout(function(){showRed();}, 200);\n}", "drawPlayersScore() {\n fill('#BDBDBD');\n textFont('Helvetica', 28);\n text(this.player1.score, 4 * this.lateralPadding, 40);\n text(this.player2.score, canvasWidth - 4 * this.lateralPadding - 10, 40);\n }", "function createPlayer() {\n\n entityManager.generatePlayer({\n cx : 240,\n cy : 266,\n });\n\n}", "function drawParticles() {\n // Orb (ellipse) figures that trail, used a for loop to run the code frequently.\n for (var i = 0; i < orbs.length; i++) {\n// Incorporated methods such as move and display for the orbs to move at a constant while being displayed in various colors.\n orbs[i].move();\n orbs[i].display();\n }\n\n if (lvlsflicker) {\n strokeWeight(4);\n stroke(random(255), random(20), 100);\n fill(0);\n push();\n translate(random(width), random(height));\n sphere(random(100), 5, 5);\n pop();\n }\n\n}", "function draw() {\n\n // Cases to handle Game over.\n if (player.dead) {\n Game.over = true;\n staticTexture.gameOver(player.dead);\n }\n else if (enemy.dead) {\n Game.over = true;\n staticTexture.gameOver(player.dead);\n }\n \n // check for player commands\n playerAction();\n\n // Multiple IF to check if it is players turn or Enemy, also if Projectile exist or not.\n if (Game.projectile != null) {\n Game.projectile.draw();\n }\n if (Game.playerTurn == true && Game.projectile != null) {\n if (Game.checkCollision(Game.projectile, enemy)) {\n Game.hit(enemy)\n Game.playerTurn = false;\n }\n }\n if (Game.playerTurn == false) {\n enemy.enemyTurn(player);\n if (Game.checkCollision(Game.projectile, player)) {\n Game.hit(player)\n Game.playerTurn = true;\n }\n }\n if (Game.projectile != null && !Game.checkCollision(Game.projectile, game) && player.firearm == 0) {\n Game.miss();\n }\n for (var i = 0; i < Game.map.length; i++) {\n if (Game.checkCollision(Game.projectile, Game.map[i])) {\n Game.projectile.clear();\n \n staticTexture.clear(Game.map[i])\n Game.map[i] = null;\n Game.miss();\n\n }\n }\n player.draw();\n enemy.draw();\n // If game over, stop callback.\n if (Game.over == false) {\n window.requestAnimationFrame(draw);\n }\n }", "function drawPausePopup(){\n ctx.fillStyle = menu.background.color;\n ctx.fillRect(gameWindow.x,gameWindow.y,200,70);\n\n ctx.strokeStyle = menu.borderColor;\n ctx.lineWidth = menu.borderWidth;\n ctx.strokeRect(gameWindow.x,gameWindow.y,200,70);\n\n var pauseText = new Text(gameWindow.x+20,gameWindow.y+50,\"Paused\",-1,\"black\",50);\n pauseText.paint();\n}", "drawFacing(context, actor){\n\t\tcontext.fillStyle = 'rgba('+(255-actor.cd)+',0,0,1)';\n\t\tcontext.beginPath(); \n\t\tcontext.arc(actor.fx + actor.x, actor.fy + actor.y, actor.r / 3, 0, 2 * Math.PI, false); \n\t\tcontext.fill(); \n\t}", "function drawclouds(){\n noStroke();\n ellipse(50,50,60,50);\n ellipse(80,40,60,50);\n ellipse(130,50,60,50);\n ellipse(70,70,60,50);\n ellipse(110,65,60,50);\n}", "function boss3_arm_render() {\n if (boss3_middle_constants.prototype.hp > 0) {\n boss3_hatch_render.call(this);\n return;\n }\n context.fillStyle = \"yellow\";\n simpleSquare_render.call(this);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get notes of user inside ckeditor in iprofile when user visit another user profile.
function getNotesForProfile(event) { var uid = event.id ; if (CKEDITOR.instances['note_'+uid]) { CKEDITOR.instances['note_'+uid].destroy(); } CKEDITOR.replace( 'note_'+uid, { uiColor: '#6C518F', toolbar:[ [ 'Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink' ], [ 'FontSize', 'TextColor', 'BGColor' ] ], removePlugins: 'elementspath' }); $("#displayNotes").fadeToggle('fast',function(){ //Destroy instance of editor that has already made in previous call. if ($("#displayNotes").is(":hidden")) { // do this } else { jQuery.ajax({ url: "/" + PROJECT_NAME + "links/get-note", type: "POST", dataType: "json", data: { "user_id" : uid }, timeout: 50000, success: function(jsonData) { CKEDITOR.instances["note_"+uid].setData(jsonData); }, error: function(xhr, ajaxOptions, thrownError) { //alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); } }); }
[ "function loadJokes() {\n const user = localStorage.getItem(\"userInfo\")\n const userInfo = JSON.parse(user)\n const userID = userInfo[0]._id\n // console.log(\"also hi\")\n API.getUsersById(userID)\n .then(res => {\n // console.log(res.data)\n setJokes(res.data[0].savedJokes)\n })\n .catch(err => console.log(err));\n }", "static async listNotesBySubtab(sub_id, user) {\n\n const query = `\n SELECT * FROM notes\n WHERE notes.sub_id = $1 AND notes.user_id = (SELECT id FROM users WHERE email=$2)\n ORDER BY created_at DESC;\n `\n\n const result = await db.query(query, [sub_id, user.email]);\n\n // return notes\n return result.rows;\n }", "function getUserIdentifications(userDB){\n return userDB.allDocs({\n include_docs : true,\n startkey: 'id',\n endkey: 'id\\ufff0'\n }).then(function(docs){\n return docs.rows;\n });\n}", "function currentProfile() {\n return {\n handle: $('#handle').text(),\n email: $('#email').text(),\n keys: [{\n name: 'default',\n signature: $('.signature').first().text()\n }]\n };\n}", "function showOtherUser(){\n removeFollowList();\n removeSearchArea();\n var userId = this.dataset.user; // get the user of the clicked name or image\n showedUser = userId;\n removeWritenFields();\n removeErrorSuccesFields();\n document.getElementById(\"profileSection\").style.display = \"block\";\n document.getElementById(\"messagesSection\").style.display = \"none\";\n hideAllProfileSection();\n document.getElementById(\"showProfile\").style.display = \"block\";\n\n getOtherProfile(userId);\n}", "getUserProfile(userId) {\n var url = '/db/users/user/' + userId;\n RestHandler.Get(url, (err, res) => {\n\n this.spliceFilledOutFieldsIntoAvailableFields(res.body, 'userInfo', '/db/fields', (profileData) => {\n this.spliceFilledOutFieldsIntoAvailableFields(profileData, 'sites', '/db/sites', (profileData) => {\n this.profileEdits.user = res.body.user\n console.log(profileData);\n this.setState({\n profileData: profileData,\n public: profileData.user.public === 1 ? false : true,\n permission: profileData.user.permission === 1 ? true : false,\n });\n });\n });\n });\n }", "function getUserInfo() {\n return user;\n }", "function loadUserInfoFromCookie()\n {\n userName = $.cookie(\"perc_userName\");\n isAdmin = $.cookie(\"perc_isAdmin\") == 'true' ? true : false;\n isDesigner = $.cookie(\"perc_isDesigner\") == 'true' ? true : false;\n isAccessibilityUser = $.cookie(\"perc_isAccessibilityUser\") == 'true' ? true : false;\n\t \n $.perc_utils.info(\"UserInfo\", \"userName: \" + userName + \", isAdmin: \" + isAdmin + \", isDesigner: \" + isDesigner + \", isAccessibilityUser: \" + isAccessibilityUser);\n }", "async updateUserInformations() {\n try{\n this.user = await this.get(\"users/me/\");\n store.dispatch('updateUser', this.user);\n window.sessionStorage.setItem(\"user\", JSON.stringify(this.user));\n } catch(error){\n console.log(\"Error while updating user info \" + error);\n }\n }", "get userProfile() {\n return spPost(ProfileLoaderFactory(this, \"getuserprofile\"));\n }", "function GetUser() {\n\n\tvar client = new SpiderDocsClient(SpiderDocsConf);\n\n\tclient.GetUser('administrator', 'Welcome1')\n\t\n .then(function (user) {\n debugger;\n console.log(user);\n });\n}", "function getTopicInfo()\n\t{\tvar userid= {};\n\t\tvar posts ={};\n\t\t\t\t\t\n\t\t\tPostFactory.getTopicInfo($routeParams, function (result){\t\n\t\t\tif(result){\n\t\t\t\t$scope.topicInfo = result;\n\t\t\t\t//Adding the id of the user who posted the topic to an object to reuse the getClikeduser\n\t\t\t\t//method in userfactory\n\t\t\t\tuserid.id = result._user; \n\t\t\t\t//Reusing userfactory getclickeduser method to get the username of the user who posted the topic\n\t\t\t\tUserFactory.getClickedUser(userid, function (output){\n\t\t\t\t\t $scope.topicInfo.username = output.username;\n\t\t\t\t\t $scope.topicInfo.loggeduser=JSON.parse(localStorage.userinfo);\t//adding the logged in users info to send while saving the post\n\t\t\t\t});\n\t\t\t\t \n\t\t\t}\n\t\t})\n\t}", "function afficherComments(){\n let idAf = document.querySelector('#description > span');\n const idWine = (idAf.innerHTML).split('# ');\n let inputLogin = document.querySelector('#frmLogin > input[type=text]');\n let inputPwd = document.querySelector('#frmLogin > input[type=password]');\n let tabComments = [];\n let loginUser = inputLogin.value;\n let pwdUser = inputPwd.value;\n const credentials = btoa(loginUser+':'+ pwdUser);\n const afficheNote = document.querySelector('#nav-44518-content-2'); //affichage des commentaires\n //if(loginUser != \"\"){\n let cpt = 1;\n let wineId = idWine[1];\n const options = {\n 'method': 'GET',\n //'mode': 'cors',\n //'headers': {\n //'content-type': 'application/json; charset=utf-8',\n //'Authorization': 'Basic '+ credentials //Try with other credentials (login:password)\n //}\n };\n\n const fetchURL = '/api/wines/'+wineId+'/comments';\n\n fetch(apiURL + fetchURL, options).then(function(response) {\n if(response.ok) {\n response.json().then(function(data){\n console.log(data);\n if(data.length != 0){\n for(let i=0; i<data.length; i++){\n console.log(data[i].content);\n for(let j=0; j<users.length; j++){\n if(users[j].id == data[i].user_id){\n tabComments.push(cpt + '.' + data[i].content + ' ( ' + users[j].name + ' )' + '<br>');\n }\n }\n\n cpt++;\n }\n afficheNote.innerHTML = tabComments;\n }else{\n afficheNote.innerHTML = \"Pas de commentaires\"\n }\n });\n }\n });\n // }else{\n // console.log('KO');\n // }\n}", "userRecommended() {\n return this._get({\n url: 'https://app-api.pixiv.net/v1/user/recommended'\n });\n }", "function selectUserForEdit(user) {\n setUserData(user)\n }", "function getAdminProfile() {\n FYSCloud.API.queryDatabase(\n \"SELECT * FROM profile WHERE user_id = ?\",\n [admin[0].user_id]\n\n ).done(function(adminDetails) {\n admin = adminDetails[0];\n // check if there is an avatar\n if(admin.avatar !== null) {\n $('#navbarAvatar').attr('src', admin.avatar);\n }\n }).fail(function(reason) {\n console.log(reason);\n });\n }", "function editProfile() {\n var pageMeta;\n var accountPersonalDataAsset;\n var Content = app.getModel('Content');\n\n if (!request.httpParameterMap.invalid.submitted) {\n app.getForm('profile').clear();\n\n app.getForm('profile.customer').copyFrom(customer.profile);\n app.getForm('profile.login').copyFrom(customer.profile.credentials);\n app.getForm('profile.addressbook.addresses').copyFrom(customer.profile.addressBook.addresses);\n }\n accountPersonalDataAsset = Content.get('myaccount-personaldata');\n\n // pageMeta = require('~/cartridge/scripts/meta');\n // pageMeta.update(accountPersonalDataAsset);\n // @FIXME bctext2 should generate out of pagemeta - also action?!\n app.getView({\n bctext2: Resource.msg('account.user.registration.editaccount', 'account', null),\n Action: 'edit',\n ContinueURL: URLUtils.https('Account-EditForm')\n }).render('account/user/editprofile');\n}", "function reviewNotify(userObj){\r\n // Loop over all users followers\r\n console.log(\"In reviewNotify\");\r\n console.log(userObj);\r\n for(let i = 0; i < userObj.followers.length; i++){\r\n let userToNotify = users[userObj.followers[i].id];\r\n let msg = userObj.username + \" has created a new review.\";\r\n\r\n sendNotif(msg, userToNotify);\r\n }\r\n}", "function loadNotes(hash){\n\n console.log(\"Retrieving the current library...\");\n chrome.storage.local.get({'library': []}, function(lib){\n raw_notes = lib.library;\n\n /* If the user has no notes, create a default new one and open it for them */\n if (raw_notes.length == 0) {\n createNote(\"Welcome to Notility!\", HTMLDocumentation, \"\");\n openNote(-1);\n return;\n }\n\n renderNotes();\n /* If the notes are being loaded from a hash search, filter the appropriate notes */\n if (hash) {\n chooseFilter(hash);\n document.getElementById(\"searcher\").value = hash;\n }\n\n /* Open a note for editing */\n chrome.storage.local.get({'activeNote':-1},function(activeID){\n openNote(activeID.activeNote);\n changeNoteHighlight(activeID.activeNote);\n });\n\n });\n \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Click listener; on click, change to clicked cube (room)
clickListener(e) { if (this.selectedMapCube !== null && this.selectedMapCube != this.selectedCube) { this.enhancedCubes = []; this.scaffoldingCubesCords = null; this.selectedCube = this.selectedMapCube; let directions = this.ref.methods.getDirections(this.selectedMapCube); // this.ref.updateRoom(this.selectedMapCube, directions); this.ref.room.navigateToRoom(this.selectedMapCube, directions, true); this.repaintMapCube(ref.cubes, "", [], null, false, this.selectedMapCube); //this.repaintMapCube(hoverCubeArr, this.selectedMapCube.label); } }
[ "function yellowClick() {\n\tyellowLight();\n\tuserPlay.push(3);\n\tuserMovement();\t\n}", "function goToRoom(newRoom)\n{\n\t// As soon as it's entered, the new room's description is printed.\n\tlookAtRoom(newRoom);\n\t// The current room is set to the newly entered room.\n\tcurrentRoom = newRoom;\n}", "click () {\n this.get('router').transitionTo('chat.room', this.get('data'))\n this.get('ready')()\n }", "function C101_KinbakuClub_RopeGroup_Click() {\n\n\t// Regular and inventory interactions\n\tClickInteraction(C101_KinbakuClub_RopeGroup_CurrentStage);\n\tvar ClickInv = GetClickedInventory();\n\t\n\tC101_KinbakuClub_RopeGroup_CalcParams();\n\n}", "function add_room_click() {\n $('li[data-level=\"one\"]').off();\n $('li[data-level=\"one\"]').click(function() {\n if ($('body').hasClass('selecting')) {\n var gridster_id = $(this).attr('data-id');\n var current_gridster = gridsters_holder[gridster_id];\n var html = '<li class=\"workstation type-one\"><div class=\"delete\"></div></li>';\n var coords = get_free_coords(current_gridster);\n console.log(coords);\n // if found a free spot, create the station widget and add change and delete event handlers to it\n if (coords) {\n var new_workstation = current_gridster.add_widget(html, 1, 1, coords.col, coords.row);\n new_workstation.click(function(event) {\n event.stopPropagation();\n change_station_type($(this));\n });\n new_workstation.find('.delete').click(function(event) {\n event.stopPropagation();\n delete_workstation($(this));\n });\n }\n }\n });\n }", "function purpleRoom(){\n room.style.backgroundColor = '#9c1de7'; /** Change of room color. */\n story.innerHTML = 'Du är nu i det lila rummet. Här finns det ett fönster och en dörr. Vill du gå till (Fönstret eller Dörren)?';\n btn.innerHTML = 'Svara'; \n btn.onclick = leavePurpleRoom;\n\n /**\n * Function leavePurpleRoom selected\n * Option to go to another door or go to window.\n */\n function leavePurpleRoom() {\n const option = user.value;\n user.value = '';\n \n if(option === 'dörren' || option === 'DÖRREN' || option === 'Dörren'){\n orangeRoom();\n\n }else if(option === 'fönstret' || option === 'FÖNSTRET' || option === 'Fönstret'){\n story.innerHTML = 'Pang! Oj! fönstret gick sönder. Någon kastade in en sten. Vill du titta vem det var? (Ja eller Nej)';\n btn.innerHTML = 'Vad gör du?'; \n btn.onclick = outsideWindow;\n\n /**\n * Function outsideWindow selected.\n * Option to look out the window or not.\n */\n function outsideWindow() {\n const option = user.value;\n user.value = '';\n\n \n if(option === 'ja' || option === 'JA' || option === 'Ja'){\n story.innerHTML = 'Du tittar ut genom fönstret och ser en inbrottstjuv. Vem ringer du (Polisen eller Glasmästaren)?';\n btn.innerHTML = 'Vem ringer du?'; //Changing the buttons text.\n btn.onclick = callPolice;\n\n /**\n * Function callPolice selected\n * Options who to call between the police or the glazier\n */\n function callPolice(){\n const option = user.value;\n user.value = '';\n\n \n if(option === 'polisen' || option === 'POLISEN' || option === 'Polisen'){\n story.innerHTML = 'Polisen kom direkt och tog fast tjuven! Bra jobbat!';\n btn.style.display = 'none';\n user.style.display = 'none';\n link.innerHTML = `Tillbaks till 'Val av rum'`; \n\n }else if(option === 'glasmästaren' || option === 'GLASMÄSTAREN' || option === 'Glasmästaren'){\n story.innerHTML = 'Glasmästaren kom en timme senare och bytte ut fönstret fast tjuven hann undan.';\n btn.style.display = 'none';\n user.style.display = 'none';\n link.innerHTML = `Tillbaks till 'Val av rum'`;\n }\n }\n\n }else if(option === 'nej' || option === 'NEJ' || option === 'Nej'){\n story.innerHTML = 'Jakten på de försvunna nycklarna fortsätter! Gå ut och fortsätta leta när du känner för det';\n btn.style.display = 'none';\n user.style.display = 'none';\n link.innerHTML = `Gå ut ur rummet`;\n }\n }\n }\n }\n}", "function redClick() {\n\tredLight();\n\tuserPlay.push(2);\n\tuserMovement();\t\n}", "function gridClickListener(event) {\n const ctx = canvas.getContext('2d');\n\n let [row, col] = translateClickPosition(event);\n\n console.log(\"clicked [\",row ,\"][\",col, \"]\");\n\n // start the timer once a grid cell is clicked (if it hasn't been started already)\n if (!timer) setTimer();\n\n if (event.ctrlKey) {\n // mark a cell with a question mark\n minesweeper.toggleQuestion(row, col);\n } else if (event.shiftKey) {\n // flag a cell\n minesweeper.toggleFlag(row, col);\n } else {\n // cell was left clicked, reveal the cell\n minesweeper.revealCell(row, col);\n }\n\n // check if game is won or lost\n if (minesweeper.isGameWon()) {\n renderGameWon(ctx);\n } else if (minesweeper.isGameLost()) {\n renderGameLost(ctx);\n } else {\n // game is not over, so render the grid state\n renderGrid(ctx);\n mineCounter.innerText = minesweeper.remainingFlags().toString(10).padStart(3, \"0\");\n }\n\n}", "function cube_click_white(a_value, b_value, d_value){\t\n\tconsole.log('cube_click_white('+a_value+','+b_value+','+d_value+')');\n\t\n\tcurrent_HTU = make_HTU_number(d_value, b_value, a_value);\n\tcurrent_minicube = get_minicube(a_value, b_value, d_value);\n\tconsole.log('cube_click_white('+a_value+','+b_value+','+d_value+')='+current_HTU+'. Now choose a letter');\n\tfind_letter_cubes(current_minicube);\n/* colour the cube yellow while working on it */\n\tconsole.log('Change cube '+current_minicube.HTU_string+' to yellow');\n\tcurrent_minicube.src = './cube_raw2/cube_raw2_yellow.png'\n\tcurrent_minicube.cube_colour = 'yellow';\n\tmini_draw_H_TML(a_value, b_value, d_value);\n/* If we've already started go straight to fitting the word rather than geting a letter */\t\n\tid = 'cube_'+current_minicube.HTU_string;\n\t//debug_cube_space=document.getElementById('cube_space');\n\t//console.log('cube_space='+debug_cube_space);\n\t//console.log('cube_space.inner='+debug_cube_space.innerHTML);\n\t//console.log('number_string='+current_minicube.HTU_number);\n\tword_cube=document.getElementById(id);\n\tconsole.log('word_cube='+word_cube);\n\told_src = word_cube.innerHTML;\n\tnew_src = '';\n\toriginal_cube_name = './cube_raw2/cube_raw2_white.png';\n\tif(old_src.indexOf(original_cube_name) > 0) {\n\t\t//console.log('45: untouched mini-cube original_cube_name='+original_cube_name );\n\t\tword_cube.src = new_src;\n\t} else {\n\t\t//mini-cube was not the original - it already had a letter\n\t\t//Find the filename for that letter on a yellow mini-cube\n\t\tfor (k=0; k <= alphabet_list.length; k++) {\n\t\t\tletter = alphabet_list[k];\n\t\t\told_cube_name = \"./cube_raw2/cube_raw2_\"+letter+\".png\";\n\t\t\tif (old_src.indexOf(old_cube_name) >= 0) {\n\t\t\t\tnew_src = \"./cube_raw2/cube_raw2_yellow_\"+letter+\".png\";\n\t\t\t}\t\n\t\t}\n\t}\n\tconsole.log('change '+word_cube.innerHTML+'to'+new_src);\n\tword_cube.innerHTML = new_src;\t\n\tword_cube.onclick = \"\"; \n\t\n}", "function greenRoom(){\n\n room.style.backgroundColor = '#12e2a3'; /** Change of room color. */\n story.innerHTML = 'I det gröna rummet finns det en kruka och en byrå. Vilken vill du kolla i? (Krukan eller Byrån)'; //Story for this function\n btn.innerHTML = 'Svara'; /** Change of text inside of button. */\n btn.onclick = plantOrDresser;\n \n /**\n * Function plantOrDresser selected.\n * Options between plant or dresser.\n */\n function plantOrDresser(){\n const option = user.value;\n user.value = '';\n\n if(option === 'krukan' || option === 'KRUKAN' || option === 'Krukan'){\n story.innerHTML = 'Nej, där fanns det bara jord. Vill du kolla i byrån? (Ja eller Nej)';\n btn.onclick = checkDresser;\n\n /**\n * Function for checking the dresser\n * Options to check or not.\n */\n function checkDresser(){\n const option = user.value;\n user.value = '';\n\n if(option === 'ja' || option === 'JA' || option === 'Ja'){\n story.innerHTML = 'Kanon! Du hittade nyckeln. Vill du lämna den till ägaren? (Ja eller Nej)';\n btn.onclick = returnKey;\n\n }else if(option === 'nej' || option === 'NEJ' || option === 'Nej'){\n story.innerHTML = 'Det finns inte så mycket annat att göra i detta rum';\n btn.style.display = 'none';\n user.style.display = 'none';\n link.innerHTML = 'Gå ut ur rummet'; /** Link to room menu*/\n }\n }\n\n }else if(option === 'byrån' || option === 'BYRÅN' || option === 'Byrån'){\n story.innerHTML = 'Kanon! Du hittade nyckeln. Vill du lämna den till ägaren? (Ja eller Nej)';\n btn.innerHTML = 'Svara';\n btn.onclick = returnKey;\n \n }\n }\n}", "function skyPressed(){\n var type_list = building_list[select];\n var frame = type_list[game.rnd.between(0, type_list.length - 1)];\n var num_peo = 1;\n if (frame == 'schoolHouse_v2') num_peo = 5;\n newBuilding = new Building(game, 'buildingButtons', frame, game.input.mousePointer.x + game.camera.x, num_peo);\n\n}", "function mousePressed(){\n for (var i = 0; i < numCubes; i++){\n speedX [i] = 0.0;\n speedY [i] = 0.0;\n }\n \n }", "function clickOnItem() {\n var dogTrait = this.id;\n var dogPart = this.dataset.cat;\n dog[dogPart] = dogTrait;\n\n // time to display the cart\n createCartList(dog);\n}", "function openAndMatch (e) {\n squares.forEach(function (square) {\n square.addEventListener('click', function () { \n ++count; \n//ROTATE THE SQUARE\n square.style.transform = \"rotateY(180deg)\";\n square.classList.add('clicked');\n// ADD THE CLICKED SQUARE TO THE ARRAY TO CHECK IF THEY MATCH\n clickedArray.push(square);\n if (count === 1) {\n timer();\n }\n if (clickedArray.length === 2) {\n checkMatch();\n }\n else if (clickedArray.length === 3) {\n delete square.solved;\n reset();\n clickedArray.push(square);\n }\n })\n })\n}", "function orangeRoom(){\n room.style.backgroundColor = '#ff6d24'; /** Change of room color. */\n story.innerHTML = 'Du är nu i det oranga rummet, här finns det en till dörr och en bokhylla. Vilken vill du kolla? (Dörren eller Bokhyllan) ';\n btn.innerHTML = 'Svara';\n btn.onclick = checkDoorOrShelf;\n \n /**\n * Function checkDoorOrShelf seleted.\n * Options between the door or the bookshelf.\n */\n function checkDoorOrShelf(){\n const option = user.value;\n user.value = '';\n\n \n if(option === 'dörren' || option === 'DÖRREN' || option === 'Dörren'){\n purpleRoom();\n\n }else if(option === 'bokhyllan' || option === 'BOKHYLLAN' || option === 'Bokhyllan'){\n story.innerHTML = 'Här fanns det bara massa tråkiga lexikon... Vill du gå igenom den andra dörren nu? (Ja eller Nej)';\n btn.onclick = outOrNot;\n\n /**\n * Function outOrNot sleected.\n * Options to go throught the other door or not.\n */\n function outOrNot(){\n const option = user.value;\n user.value = '';\n\n \n if(option === 'ja' || option === 'JA' || option === 'Ja'){\n purpleRoom();\n \n }else if(option === 'nej' || option === 'NEJ' || option === 'Nej'){\n story.innerHTML = 'Hm... Det fanns inte så mycket mer att göra här.';\n btn.style.display = 'none';\n user.style.display = 'none';\n link.innerHTML = 'Gå ut ur rummet';\n }\n }\n }\n }\n}", "setCurrentRoom(newRoom) {\n\t\t\tcurrentRoom = newRoom;\n\t\t}", "function vampireRoom() {\n // CHANGE STATE VARIABLE TO vampireRoom!\n States.currentState = 'vampireRoom';\n // Do vampire room stuff\n c(\"There's a vampire in this room! She's extra friendly and has geeky glasses. You think she is cute.\");\n}", "joinRoom(room) {\n this.room = room;\n\n this.room.addClient(this);\n }", "function drawSkybox(){\r\n switchShaders(true);\r\n \r\n // Draw the cube by binding the array buffer to the cube's vertices\r\n // array, setting attributes, and pushing it to GL.\r\n gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexBuffer);\r\n gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, 3, gl.FLOAT, false, 0, 0);\r\n // Set the texture coordinates attribute for the vertices.\r\n gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexBuffer);\r\n gl.vertexAttribPointer(shaderProgram.vertexNormalAttribute, 3, gl.FLOAT, false, 0, 0);\r\n\r\n // Specify the texture to map onto the face.\r\n gl.activeTexture(gl.TEXTURE0);\r\n gl.bindTexture(gl.TEXTURE_CUBE_MAP, cubeTexture);\r\n gl.uniform1i(gl.getUniformLocation(shaderProgram, \"uSampler\"), 0);\r\n\r\n // Draw the cube.\r\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeTriIndexBuffer);\r\n setMatrixUniforms();\r\n gl.drawElements(gl.TRIANGLES, 36, gl.UNSIGNED_SHORT, 0);\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Repush all events from the spreadsheet to the Calendar. Trigger: menu item.
function pushAll() { console.log('Menu link clicked: Push all') if (validateAction() == true) { pushAllEventsToCalendar(); } else { console.log('Sheet is not in the allowed list, skipping.') } }
[ "function pushAllEventsToCalendar() {\n console.log('Pushing all events to calendar');\n var dataRange = sheet.getDataRange();\n // Process the range.\n processRange(dataRange);\n console.log('Finished pushing all events');\n}", "function deleteAndPushAll() {\n console.log('Menu link clicked: Delete and push all')\n if (validateAction() == true) {\n deleteAllEvents();\n pushAllEventsToCalendar();\n }\n else {\n console.log('Sheet is not in the allowed list, skipping.')\n }\n}", "function clearCalendar() {\n calEvents = {};\n storeCal();\n initCalendar();\n }", "function populateCalPageEvents() {\n upcomingEvents.reverse();\n \n // Builds the array of Weekly Events that will later have the upcoming events pushed into it.\n // Setting the condition number (i <= 10) will change how many weekly events are added\n // to the cal. Special events will still display if they occur after this cut off.\n for (i = 0; i <= 90; i++) {\n\n var calEndDate = new Date();\n var weeklyCalEntry = calEndDate.setDate(calEndDate.getDate() + i);\n var weeklyCalEntryString = new Date(weeklyCalEntry);\n\n if (weeklyCalEntryString.getDay() === 1) {\n calWeeklyEventsList.push({'eventDate' : weeklyCalEntryString.toDateString(), 'eventName' : weeklyEvents[0].eventName, 'eventDesc' : weeklyEvents[0].eventDesc, 'eventImgWide' : weeklyEvents[0].eventImgWide, 'eventTime' : weeklyEvents[0].eventTime, 'eventLink' : weeklyEvents[0].eventLink});\n }\n /*\n else if (weeklyCalEntryString.getDay() === 4) {\n calWeeklyEventsList.push({'eventDate' : weeklyCalEntryString.toDateString(), 'eventName' : weeklyEvents[1].eventName, 'eventDesc' : weeklyEvents[1].eventDesc, 'eventImgWide' : weeklyEvents[1].eventImgWide, 'eventTime' : weeklyEvents[1].eventTime, 'eventLink' : weeklyEvents[1].eventLink});\n }\n */\n else if (weeklyCalEntryString.getDay() === 5) {\n calWeeklyEventsList.push({'eventDate' : weeklyCalEntryString.toDateString(), 'eventName' : weeklyEvents[2].eventName, 'eventDesc' : weeklyEvents[2].eventDesc, 'eventImgWide' : weeklyEvents[2].eventImgWide, 'eventTime' : weeklyEvents[2].eventTime, 'eventLink' : weeklyEvents[2].eventLink});\n }\n\n else if (weeklyCalEntryString.getDay() === 6) {\n calWeeklyEventsList.push({'eventDate' : weeklyCalEntryString.toDateString(), 'eventName' : weeklyEvents[3].eventName, 'eventDesc' : weeklyEvents[3].eventDesc, 'eventImgWide' : weeklyEvents[3].eventImgWide, 'eventTime' : weeklyEvents[3].eventTime, 'eventLink' : weeklyEvents[3].eventLink});\n }\n }\n\n // Adds upcoming events to the weekly events\n for (i = 0; i <= upcomingEvents.length - 1; i++) {\n calWeeklyEventsList.push(upcomingEvents[i]);\n }\n\n // Sorts the cal events\n calWeeklyEventsList.sort(function(a,b){var c = new Date(a.eventDate); var d = new Date(b.eventDate); return c-d;});\n\n // Pushes Cal events into the cal page\n function buildCal(a) {\n calendarEvents.innerHTML = a;\n }\n\n // Removes Weekly if a special event is set to overide\n for (i = 0; i <= calWeeklyEventsList.length - 1; i++) {\n \n // If a Special Event is set to Override, remove the previous weekly entry\n if (calWeeklyEventsList[i].eventWklOvrd === 1) {\n calWeeklyEventsList.splice(i-1, 1);\n }\n // Else, Do nothing\n else {\n\n }\n }\n\n // Fixes the Special Event Dates for the cal and builds the Event entry. Push to the buildCal function.\n var formatedDate;\n var formatedTime;\n \n for (i = 0; i <= calWeeklyEventsList.length - 1; i++) {\n\n if (calWeeklyEventsList[i].eventTix !== undefined) {\n \n if (calWeeklyEventsList[i].eventTix != 'none') {\n formatedDate = calWeeklyEventsList[i].eventDate.toDateString();\n formatedTime = calWeeklyEventsList[i].eventDate.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'}); \n\n buildCal(calendarEvents.innerHTML + '<div class=\"home-page-event-content fix\"><h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><span class=\"event-day\">' + formatedDate + ', ' + formatedTime + '</span><br><span class=\"event-name\">' + calWeeklyEventsList[i].eventName + '</span></a></h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><img src=\"' + calWeeklyEventsList[i].eventImgWide + '\" alt=\"An event poster for ' + calWeeklyEventsList[i].eventArtist + ' performing at the Necto Nightclub in Ann Arbor, Michigan on ' + (calWeeklyEventsList[i].eventDate.getMonth() + 1) + '/' + calWeeklyEventsList[i].eventDate.getDate() + '/' + calWeeklyEventsList[i].eventDate.getFullYear() + '.\"></a><p>' + calWeeklyEventsList[i].eventDesc + '</p><div class=\"row event-nav\"><a href=\"' + calWeeklyEventsList[i].eventLink + '\"class=\"col col-4-xs\">VIEW EVENT</a><a href=\"bottle-service-vip-reservations.html?=calpagelink\" class=\"col col-4-xs\">REQUEST VIP</a><a href=\"' + calWeeklyEventsList[i].eventTix + '\" onclick=\"trackOutboundLink(' + \"'\" + calWeeklyEventsList[i].eventTix + \"'\" + '); return true;\" class=\"col col-4-xs \">BUY TICKETS</a></div></div><br><br>');\n }\n\n else {\n formatedDate = calWeeklyEventsList[i].eventDate.toDateString();\n formatedTime = calWeeklyEventsList[i].eventDate.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});\n buildCal(calendarEvents.innerHTML + '<div class=\"home-page-event-content fix\"><h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><span class=\"event-day\">' + formatedDate + ', ' + formatedTime + '</span><br><span class=\"event-name\">' + calWeeklyEventsList[i].eventName + '</span></a></h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><img src=\"' + calWeeklyEventsList[i].eventImgWide + '\" alt=\"An event poster for ' + calWeeklyEventsList[i].eventArtist + ' performing at the Necto Nightclub in Ann Arbor, Michigan on ' + (calWeeklyEventsList[i].eventDate.getMonth() + 1) + '/' + calWeeklyEventsList[i].eventDate.getDate() + '/' + calWeeklyEventsList[i].eventDate.getFullYear() + '.\"></a><p>' + calWeeklyEventsList[i].eventDesc + '</p><div class=\"row event-nav\"><a href=\"' + calWeeklyEventsList[i].eventLink + '\"class=\"col col-6-xs\">VIEW EVENT</a><a href=\"bottle-service-vip-reservations.html?=calpagelink\" class=\"col col-6-xs \">REQUEST VIP</a></div></div><br><br>');\n }\n }\n\n else {\n buildCal(calendarEvents.innerHTML + '<div class=\"home-page-event-content fix\"><h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><span class=\"event-day\">' + calWeeklyEventsList[i].eventDate + ', ' + calWeeklyEventsList[i].eventTime + '</span><br><span class=\"event-name\">' + calWeeklyEventsList[i].eventName + '</span></a></h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><img src=\"' + calWeeklyEventsList[i].eventImgWide + '\" alt=\"A image of ' + calWeeklyEventsList[i].eventName + ', a weekly event at the Necto Nightclub in Ann Arbor, Michigan.\"></a><p>' + calWeeklyEventsList[i].eventDesc + '</p><div class=\"row event-nav\"><a href=\"' + calWeeklyEventsList[i].eventLink + '\"class=\"col col-6-xs\">VIEW EVENT</a><a href=\"bottle-service-vip-reservations.html?=calpagelink\" class=\"col col-6-xs \">REQUEST VIP</a></div></div><br><br>');\n }\n }\n \n}", "function setCalendarAppts() {\n\n var data = getCalendarData();\n var columnHeaders = getColumnHeaders();\n\n // column headers \n var isCompleteColumnId = columnHeaders.indexOf(CONFIG_COLUMNS_DONE);\n var taskColumnId = columnHeaders.indexOf(CONFIG_COLUMNS_TASK);\n var dateColumnId = columnHeaders.indexOf(CONFIG_COLUMNS_DUEDATE);\n var googleCalColumnId = columnHeaders.indexOf(CONFIG_COLUMNS_GOOGLECALENDARID); \n\n // find events with dates\n for (var i = 1; i < data.length; i++) {\n\n\n // if date but not google calendar entry, add it\n if (!data[i][isCompleteColumnId]) {\n var event;\n if (data[i][dateColumnId] && !data[i][googleCalColumnId]) {\n\n Logger.log('Add Task: ' + data[i][taskColumnId]);\n \n var eventDate = data[i][dateColumnId];\n var eventTimeHour = Utilities.formatDate(eventDate, CONFIG_TIMEZONE, 'HH');\n var eventTimeMinute = Utilities.formatDate(eventDate, CONFIG_TIMEZONE, 'mm');\n\n // always add \"today\" if less than today\n var isOverdue = false;\n if (eventDate.getDate() < new Date().getDate()) {\n eventDate.setDate(new Date().getDate());\n isOverdue = true;\n }\n\n // create event\n event = CalendarApp.getDefaultCalendar().createAllDayEvent(\"TASK: \" + data[i][taskColumnId], eventDate);\n \n // if event is overdue\n if (isOverdue && CONFIG_GCAL_OVERDUE_COLOUR != null) {\n event.setColor(CONFIG_GCAL_OVERDUE_COLOUR);\n }\n \n // WIP - set time if time exists in entry\n if (eventTimeHour + \":\" + eventTimeMinute != \"00:00\") {\n eventDate.setHours(eventTimeHour);\n eventDate.setMinutes(eventTimeMinute);\n event.setTime(eventDate, eventDate); // set correct time here\n }\n \n // add the event ID to the spreadsheet\n SpreadsheetApp.openById(CONFIG_SHEETID).getSheetByName(CONFIG_SHEET_TODO).getRange(i + 1, googleCalColumnId + 1).setValue(event.getId());\n\n }\n else if (data[i][dateColumnId] && data[i][googleCalColumnId]) {\n\n Logger.log('Modify Task: ' + data[i][taskColumnId]);\n \n // fetch the event using the ID\n event = CalendarApp.getDefaultCalendar().getEventById(data[i][googleCalColumnId]);\n\n // update time if time is set in due date \n var eventSheetDate = data[i][dateColumnId];\n var eventTimeHour = Utilities.formatDate(eventSheetDate, CONFIG_TIMEZONE, 'HH');\n var eventTimeMinute = Utilities.formatDate(eventSheetDate, CONFIG_TIMEZONE, 'mm');\n \n // auto-advance to today in CALENDAR (not sheet)\n if (eventSheetDate < new Date()) {\n event.setAllDayDate(new Date());\n \n // change color if event is overdue\n if (CONFIG_GCAL_OVERDUE_COLOUR != null) {\n event.setColor(CONFIG_GCAL_OVERDUE_COLOUR);\n }\n\n }\n else\n {\n // update calendar date to revised sheet date\n event.setAllDayDate(eventSheetDate);\n }\n\n // update title\n event.setTitle(data[i][taskColumnId]);\n eventDate = event.getStartTime();\n if (eventTimeHour + \":\" + eventTimeMinute != \"00:00\") {\n eventDate.setHours(eventTimeHour);\n eventDate.setMinutes(eventTimeMinute);\n event.setTime(eventDate, eventDate); // set correct time here\n }\n\n\n\n }\n\n }\n\n }\n\n}", "function populateHomePageShortCalEvents() {\n upcomingEvents.reverse();\n \n // Builds the array of Weekly Events that will later have the upcoming events pushed into it.\n // Setting the condition number (i <= 10) will change how many weekly events are added\n // to the cal. Special events will still display if they occur after this cut off.\n for (i = 0; i <= 14; i++) {\n\n var calEndDate = new Date();\n var weeklyCalEntry = calEndDate.setDate(calEndDate.getDate() + i);\n var weeklyCalEntryString = new Date(weeklyCalEntry);\n\n if (weeklyCalEntryString.getDay() === 1) {\n calWeeklyEventsList.push({'eventDate' : weeklyCalEntryString.toDateString(), 'eventName' : weeklyEvents[0].eventName, 'eventDesc' : '', 'eventImgWide' : weeklyEvents[0].eventImgWide, 'eventTime' : weeklyEvents[0].eventTime, 'eventLink' : weeklyEvents[0].eventLink});\n }\n /*\n else if (weeklyCalEntryString.getDay() === 4) {\n calWeeklyEventsList.push({'eventDate' : weeklyCalEntryString.toDateString(), 'eventName' : weeklyEvents[1].eventName, 'eventDesc' : weeklyEvents[1].eventDesc, 'eventImgWide' : weeklyEvents[1].eventImgWide, 'eventTime' : weeklyEvents[1].eventTime, 'eventLink' : weeklyEvents[1].eventLink});\n }\n */\n else if (weeklyCalEntryString.getDay() === 5) {\n calWeeklyEventsList.push({'eventDate' : weeklyCalEntryString.toDateString(), 'eventName' : weeklyEvents[2].eventName, 'eventDesc' : '', 'eventImgWide' : weeklyEvents[2].eventImgWide, 'eventTime' : weeklyEvents[2].eventTime, 'eventLink' : weeklyEvents[2].eventLink});\n }\n\n else if (weeklyCalEntryString.getDay() === 6) {\n calWeeklyEventsList.push({'eventDate' : weeklyCalEntryString.toDateString(), 'eventName' : weeklyEvents[3].eventName, 'eventDesc' : '', 'eventImgWide' : weeklyEvents[3].eventImgWide, 'eventTime' : weeklyEvents[3].eventTime, 'eventLink' : weeklyEvents[3].eventLink});\n }\n }\n\n // Adds upcoming events to the weekly events\n for (i = 0; i <= upcomingEvents.length - 1; i++) {\n calWeeklyEventsList.push(upcomingEvents[i]);\n }\n\n // Sorts the cal events\n calWeeklyEventsList.sort(function(a,b){var c = new Date(a.eventDate); var d = new Date(b.eventDate); return c-d;});\n\n // Pushes Cal events into the cal page\n function buildCal(a) {\n calendarEvents.innerHTML = a;\n }\n\n // Removes Weekly if a special event is set to overide\n for (i = 0; i <= calWeeklyEventsList.length - 1; i++) {\n \n // If a Special Event is set to Override, remove the previous weekly entry\n if (calWeeklyEventsList[i].eventWklOvrd === 1) {\n calWeeklyEventsList.splice(i-1, 1);\n }\n // Else, Do nothing\n else {\n\n }\n }\n\n // Fixes the Special Event Dates for the cal and builds the Event entry. Push to the buildCal function.\n var formatedDate;\n var formatedTime;\n \n for (i = 0; i <= calWeeklyEventsList.length - 1; i++) {\n\n if (calWeeklyEventsList[i].eventTix !== undefined) {\n \n if (calWeeklyEventsList[i].eventTix != 'none') {\n formatedDate = calWeeklyEventsList[i].eventDate.toDateString();\n formatedTime = calWeeklyEventsList[i].eventDate.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'}); \n\n buildCal(calendarEvents.innerHTML + '<div class=\"home-page-event-content col col-3-xs\"><h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><span class=\"event-day\">' + formatedDate + ', ' + formatedTime + '</span><br><span class=\"event-name\">' + calWeeklyEventsList[i].eventArtist + '</span></a></h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><img src=\"' + calWeeklyEventsList[i].eventImgWide + '\" alt=\"An event poster for ' + calWeeklyEventsList[i].eventArtist + ' performing at the Necto Nightclub in Ann Arbor, Michigan on ' + (calWeeklyEventsList[i].eventDate.getMonth() + 1) + '/' + calWeeklyEventsList[i].eventDate.getDate() + '/' + calWeeklyEventsList[i].eventDate.getFullYear() + '.\"></a><p>' + '</p><div class=\"row event-nav\"><a href=\"' + calWeeklyEventsList[i].eventLink + '\"class=\"col col-4-xs\">VIEW EVENT</a><a href=\"bottle-service-vip-reservations.html?=calpagelink\" class=\"col col-4-xs\">VIP</a><a href=\"' + calWeeklyEventsList[i].eventTix + '\" onclick=\"trackOutboundLink(' + \"'\" + calWeeklyEventsList[i].eventTix + \"'\" + '); return true;\" class=\"col col-4-xs \">TICKETS</a></div></div><br><br>');\n }\n\n else {\n formatedDate = calWeeklyEventsList[i].eventDate.toDateString();\n formatedTime = calWeeklyEventsList[i].eventDate.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});\n buildCal(calendarEvents.innerHTML + '<div class=\"home-page-event-content col col-3-xs\"><h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><span class=\"event-day\">' + formatedDate + ', ' + formatedTime + '</span><br><span class=\"event-name\">' + calWeeklyEventsList[i].eventName + '</span></a></h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><img src=\"' + calWeeklyEventsList[i].eventImgWide + '\" alt=\"An event poster for ' + calWeeklyEventsList[i].eventArtist + ' performing at the Necto Nightclub in Ann Arbor, Michigan on ' + (calWeeklyEventsList[i].eventDate.getMonth() + 1) + '/' + calWeeklyEventsList[i].eventDate.getDate() + '/' + calWeeklyEventsList[i].eventDate.getFullYear() + '.\"></a><p>' + '</p><div class=\"row event-nav\"><a href=\"' + calWeeklyEventsList[i].eventLink + '\"class=\"col col-6-xs\">VIEW EVENT</a><a href=\"bottle-service-vip-reservations.html?=calpagelink\" class=\"col col-6-xs \">VIP</a></div></div><br><br>');\n }\n }\n\n else {\n buildCal(calendarEvents.innerHTML + '<div class=\"home-page-event-content col col-3-xs\"><h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><span class=\"event-day\">' + calWeeklyEventsList[i].eventDate + ', ' + calWeeklyEventsList[i].eventTime + '</span><br><span class=\"event-name\">' + calWeeklyEventsList[i].eventName + '</span></a></h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><img src=\"' + calWeeklyEventsList[i].eventImgWide + '\" alt=\"A image of ' + calWeeklyEventsList[i].eventName + ', a weekly event at the Necto Nightclub in Ann Arbor, Michigan.\"></a><p>' + calWeeklyEventsList[i].eventDesc + '</p><div class=\"row event-nav\"><a href=\"' + calWeeklyEventsList[i].eventLink + '\"class=\"col col-6-xs\">VIEW EVENT</a><a href=\"bottle-service-vip-reservations.html?=calpagelink\" class=\"col col-6-xs \">VIP</a></div></div><br><br>');\n }\n }\n \n}", "function editEvent(){\n for(var i = 0; i < eventInput.length; i++){\n eventInput[i].addEventListener(\"change\", function(){\n this.previousElementSibling.lastElementChild.previousElementSibling.innerHTML = this.value;\n for(var i = 0; i < currentMonth.days.length; i++){\n if(clickedCell.firstChild.textContent === currentMonth.days[i].cell.firstChild.textContent){\n currentMonth.days[i].events.push(this.value);\n break;\n };\n }\n });\n }\n}", "function confirmationSelectionHandler(){\n const header = SheetsLibrary.getHeaderAsObjFromSheet(ActiveSheet, 1);\n const allEvents = SheetsLibrary.getAllRowsAsObjInArr(ActiveSheet, 1);\n const events = SheetsLibrary.getSelectedRowsAsObjInArr(ActiveSheet, 1);\n const selectedEvent = events[0];\n console.log(selectedEvent);\n if( !isReady() ) return\n\n try {\n // Update Jour Fixe Calendar Event\n const jourFixeCal = CAL.getCalendarById(officeHourId);\n const eventInCal = jourFixeCal.getEventById(selectedEvent.id);\n const newTitleForEvent = \"Jour Fixe | \" + selectedEvent.user;\n const start = eventInCal.getStartTime();\n const end = eventInCal.getEndTime();\n \n let calDescription = getSFLinkFromEmail(selectedEvent.Email) ? `Hier ist der Link zu deinen Botschafter-Kampagnen: ` + getSFLinkFromEmail(selectedEvent.Email) : \"\"; \n \n // Create Calendar Event in personal Call\n const myCal = CAL.getCalendarById(myCalId);\n const newCalEvent = myCal.createEvent( newTitleForEvent, start, end);\n eventInCal.setTitle( newTitleForEvent );\n\n if( newCalEvent ){\n // Add the Meet Link to the Description\n // Need to either get the Meet Link, if it is there, or create a Meeting using the Advanced Calendar API\n const meetLink = getMeetLink(newCalEvent.getId()); //Calendar.Events.get(myCalId, newCalEvent.getId());\n if( meetLink )\n calDescription += `\\nHier ist der Link zum Gespräch: ${meetLink}`;\n newCalEvent.setDescription( calDescription );\n eventInCal.setDescription( calDescription );\n \n updateField( selectedEvent.rowNum, header.status, newCalEvent.getId() );\n disableOtherEventsFromThisSubmission(); \n newCalEvent.addGuest( selectedEvent.Email );\n sendConfirmationToBotschafter( {\n email: selectedEvent.Email,\n subject: `Bestätigung Jour-Fixe am ${selectedEvent.Datum}`,\n body: `Hi ${selectedEvent.user},\\nhiermit bestätige ich deinen Jour-Fixe-Termin am ${selectedEvent.Datum} um ${selectedEvent.Uhrzeit}.\\nLiebe Grüße,\\nShari`\n });\n }\n } catch(err) {\n console.error(\"Fehler: \"+err);\n alert(\"Could not create Event: \"+err.message);\n }\n\n // Disable other events from the same submission \n function disableOtherEventsFromThisSubmission( ){\n const eventsFromThisSubmission = allEvents.filter( event => event.submissionId === selectedEvent.submissionId && event.id != selectedEvent.id ) ;\n eventsFromThisSubmission.forEach( event => updateField( event.rowNum, header.status, \"disabled\") );\n }\n \n // Checks to see if event selected is empty and not disabled\n function isReady(){\n if( events.length > 1 ){\n alert(\"Bitte nur eine auswählen\");\n return\n }\n \n if( selectedEvent.status === \"disabled\" ){\n alert(\"Eintrag ist disabled und kann nicht erstellt werden\");\n return\n }\n \n if( selectedEvent.status != \"\" ){\n alert(\"Eintrag hat bereits einen Status und kann deshalb nicht neu erstellt werden.\");\n return\n }\n \n return true\n }\n}", "function refreshWorksheetData(){\n const worksheet = props.selectedSheet;\n worksheet.getDataSourcesAsync().then(sources => {\n for (var src in sources){\n sources[src].refreshAsync().then(function () {\n console.log(sources[src].name + ': Refreshed Successfully');\n });\n }\n })\n }", "function onOpen() {\r\n var sheet = SpreadsheetApp.getActiveSpreadsheet();\r\n var entries = [{\r\n name : \"SendOneEntry\",\r\n functionName : \"failedFormSubmit\"\r\n }];\r\n sheet.addMenu(\"GBSP\", entries);\r\n}", "function resetAllEvents(){\n\t\t\tevents.forEach( ev => { \n\t\t\t\tev.button.gotoAndStop(0);\n\t\t\t\tev.button.cursor = \"pointer\";\n\t\t\t\tev.choosen = false; \n\t\t\t});\n\t\t\t// update instructions\n\t\t\tself.instructions.gotoAndStop(0);\n\t\t\t// update side box\n\t\t\tself.sideBox.gotoAndStop(0);\n\t\t}", "function onOpen() {\n var spreadsheet = SpreadsheetApp.getActive();\n var menuItems = [\n {name: 'Send Emails', functionName: 'sendEmails'}\n ];\n spreadsheet.addMenu('Send Emails', menuItems);\n}", "function trackMapGotoLastEventDate()\n{\n _resetCalandarDates();\n trackMapClickedUpdateAll();\n}", "function successfulCalendarPush(data) {\r\n var info = JSON.parse(data);\r\n liveCalExists = true;\r\n // Set styles of View Live and De/Reactivate buttons depending on state\r\n setCalLiveButtonStyles();\r\n var msg = info[\"message\"];\r\n var viewRights = info[\"view_rights\"];\r\n successfulLiveCalStateChange(msg);\r\n setViewRightState(viewRights);\r\n showDepEmployeeViews();\r\n showSetDepEmployeeViews();\r\n }", "function ReDateShifts()\n\t{\n\t\tfor(var i = 0; i < shifts.length; i++)\n\t\t{\n\t\t\tif(typeof shifts[i].date == 'string')\n\t\t\t{\n\t\t\t\tshifts[i].date = new Date(shifts[i].date);\n\t\t\t}\n\t\t}\n\t}", "function refresh_all_action_items() {\n\tconsole.log(\"now refreshing\");\n\t$(\"div#projects div.project\").each( function() {\n\t\trefresh_action_items(this);\n\t});\n}", "function performActions() {\n\n // prepare event data\n event_data = $.integrate( entry_data, event_data );\n event_data.content = content_elem;\n event_data.entry = entry_elem;\n delete event_data.actions;\n\n // perform menu entry actions\n if ( entry_data.actions )\n if ( typeof ( entry_data.actions ) === 'function' )\n entry_data.actions( $.clone( event_data ), self );\n else\n entry_data.actions.forEach( action => $.action( action ) );\n\n // perform callback for clicked menu entry\n self.onclick && $.action( [ self.onclick, $.clone( event_data ), self ] );\n\n }", "function assignTask(){\n var priority_sheet=SpreadsheetApp.getActiveSpreadsheet().getSheetByName(\"priority_queue\"); \n var all_priority_range = priority_sheet.getDataRange();\n var all_priority_data = all_priority_range.getValues();\n var eventCal=CalendarApp.getCalendarById(\"impanyu@gmail.com\");\n var currentTime=new Date();\n for(i=1;i<all_priority_range.getNumRows();i++){//read all tasks for processing\n var current_row=all_priority_data[i];\n var requested_starting_time=current_row[column_index[\"requested starting time\"]];\n var requested_ending_time=current_row[column_index[\"requested ending time\"]];\n var requested_starting_date=new Date(requested_starting_time);\n if(requested_ending_time && requested_starting_time && currentTime<requested_starting_date) {//find a task need to be registered into calendar\n var task_name=\"\";\n var link=current_row[column_index[\"link\"]];\n var task_info=\"info: \"+current_row[column_index[\"task info\"]];\n if(link) task_info+=\"\\nlink: \"+link;\n if(current_row[column_index[\"task group\"]]) task_name+=current_row[column_index[\"task group\"]]+\" \";\n task_name+=current_row[column_index[\"task name\"]];\n eventCal.createEvent(task_name, requested_starting_time, requested_ending_time,{description:task_info}); \n \n }\n }\n}", "function rebuildMenu() {\n let timelabel = \"\";\n if (nextNotification.isBefore(moment())) {\n timelabel = \"Take a Break!\";\n } else {\n timelabel = \"Next break \" + moment().to(nextNotification);\n }\n contextMenu = Menu.buildFromTemplate([\n {\n label: timelabel,\n type: \"normal\",\n },\n {\n type: \"separator\",\n },\n {\n label: \"Reset timer\",\n type: \"normal\",\n click: () => {\n nextNotification = getNextNotificationDate();\n startInterval();\n rebuildMenu();\n },\n },\n {\n label: \"Snooze 5 minutes\",\n type: \"normal\",\n click: () => {\n snooze();\n },\n },\n {\n label: \"Settings\",\n type: \"normal\",\n click: () => {\n //html file\n openPreference();\n },\n },\n {\n type: \"separator\",\n },\n {\n label: \"Quit\",\n role: \"quit\",\n },\n ]);\n appIcon.setContextMenu(contextMenu);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
| Function loadAuthorizer | Purpose: |
function loadAuthorizer(credentialsFile, cb) { if (credentialsFile) { fs.readFile(credentialsFile, function (err, data) { if (err) { logger.error('Mosca credentials file not found') cb(err) return } var authorizer = new Authorizer() try { authorizer.users = JSON.parse(data) cb(null, authorizer) } catch (err) { logger.error('Mosca invalid credentials') cb(err) } }) } else { cb(null, null) } }
[ "function Authorizer(props) {\n return __assign({ Type: 'AWS::ApiGateway::Authorizer' }, props);\n }", "async function load (req, res, next, id) {\n try {\n req.course = await User.get({ '_id': id })\n return next()\n } catch (e) {\n next(e)\n }\n}", "function loadFromUserType() {\n console.log(\"UserService: Loading additional information for user type: %s\", userType);\n\n factory.isCompany = function () {\n return userType === \"Company\";\n };\n\n factory.isStudent = function () {\n return userType === \"Student\";\n };\n\n factory.isAdmin = function () {\n return userType === \"Admin\";\n };\n\n if (userType === \"Student\") {\n // Then, this user must be in the student list as well\n var studentList = clientContext.get_web().get_lists().getByTitle(\"StudentList\");\n var camlQuery = new SP.CamlQuery();\n var query = \"<View><Query><Where>\" +\n \"<Eq><FieldRef Name='Email' /><Value Type='Text'>\" + factory.user.email + \"</Value></Eq>\" +\n \"</Where></Query></View>\";\n camlQuery.set_viewXml(query);\n var entries = studentList.getItems(camlQuery);\n\n clientContext.load(entries);\n clientContext.executeQueryAsync(function () {\n console.log(\"UserService: Additional user information loaded from student list\");\n var enumerator = entries.getEnumerator();\n if (!enumerator.moveNext()) {\n // not a student\n console.log(\"UserService: User is not a student\");\n factory.isStudent = function () {\n return false;\n };\n\n userType = null;\n } else {\n factory.user.name = enumerator.get_current().get_item(\"FullName\");\n }\n\n factory.userLoaded = true;\n\n }, onError);\n\n } else if (userType === \"Company\") {\n // Then, this user must be in the student list as well\n var companyList = clientContext.get_web().get_lists().getByTitle(\"CompanyList\");\n var camlQuery = new SP.CamlQuery();\n var query = \"<View><Query><Where>\" +\n \"<Eq><FieldRef Name='Email' /><Value Type='Text'>\" + factory.user.email + \"</Value></Eq>\" +\n \"</Where></Query></View>\";\n camlQuery.set_viewXml(query);\n var entries = companyList.getItems(camlQuery);\n\n clientContext.load(entries);\n clientContext.executeQueryAsync(function () {\n console.log(\"UserService: Additional company information loaded from company list\");\n var enumerator = entries.getEnumerator();\n if (!enumerator.moveNext()) {\n // not a company\n console.log(\"UserService: User is not a Company\");\n factory.isCompany = function () {\n return false;\n };\n\n userType = null;\n } else {\n factory.user.company = enumerator.get_current().get_item(\"Company\");\n }\n\n factory.userLoaded = true;\n }, onError);\n } else {\n factory.userLoaded = true;\n }\n }", "function loadUser() {\r\n makeHTTPRequest(`/usuarios/0`, 'GET', '', cbOk1);\r\n}", "function loadCollaborators(doc, cb) {\n $.ajax({\n type: 'GET',\n headers: {\n \"Authorization\": \"token \" + token()\n },\n url: Substance.settings.hub_api + '/documents/' + doc.id + '/collaborators',\n success: function(publications) {\n cb(null, publications);\n },\n error: function() {\n cb(\"Loading collaborators failed. Can't access server\");\n },\n dataType: 'json'\n });\n}", "authorize() {\n this.auth = this.auth || new Promise((resolve, reject) => {\n this._client.authorize((err, tokens) => err ? \n reject(err) : \n resolve(this._client));\n });\n return this.auth;\n }", "function load(req, res, next, userId) {\n Client.get(userId)\n .then((client) => {\n req.client = client;\n return next();\n })\n .catch(e => next(e));\n}", "function loadConsumer(recipientId, user) {\n if (user == null)\n return;\n return function (dispatch) {\n return new parse_1.default.Query(ParseModels_1.Consumer).equalTo('user', user).first().then(function (consumer) {\n if (consumer) {\n dispatch({ type: types.CONSUMER_LOADED, data: { recipientId: recipientId, consumer: consumer } });\n }\n else {\n dispatch({ type: types.CONSUMER_NOT_FOUND, data: { user: user } });\n }\n }).fail(function (e) {\n dispatch({ type: types.CONSUMER_NOT_FOUND, data: { user: user } });\n });\n };\n}", "load() {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n if (this.session.isAuthenticated) {\n let user = await this.store.queryRecord('user', { me: true });\n this.set('user', user);\n resolve(user);\n } else {\n reject(new Error('User not authenticated.'));\n }\n });\n }", "_loadDispatch(path, onLoad){\n fetch(path)\n .then(resp => resp.json())\n .then(data => onLoad(data));\n }", "componentWillMount() {\n const token = window.localStorage.getItem(\"jwt\");\n if (token) {\n agent.setToken(token);\n }\n\n this.props.onLoad(token ? agent.Auth.current() : null, token);\n console.log(\"agent auth current:\" + agent.Auth.current());\n }", "static loadRoles() {\n let roleList = [];\n let dataFile = fs.readFileSync('./data/roles.json', 'utf8');\n if (dataFile === '') return roleList;\n\n let roleData = JSON.parse(dataFile);\n\n roleData.forEach((element) => {\n roleList.push(\n new Role(\n element.roleID,\n element.title,\n element.description,\n element.image,\n element.color,\n element.emote\n )\n );\n });\n\n return roleList;\n }", "init() {\r\n\r\n this.configure();\r\n console.log(\"authAzure user: \")\r\n console.log(this.user());\r\n \r\n if (this.user()) {\r\n console.log('already signed in.');\r\n // Check if the current ID token is still valid based on expiration date\r\n if (this.checkIdToken()) {\r\n // set accessToken\r\n console.log('Acquiring accessing token ...')\r\n this.acquireToken().then (accessToken => {\r\n this.accessToken = accessToken \r\n console.log('accessToken: '+ this.accessToken); \r\n store.dispatch('auth/loginSuccess'); \r\n });\r\n }\r\n } else {\r\n console.log('not signed in');\r\n } \r\n }", "function loadClientSecrets() {\n fs.readFile('client_secret.json', (err, content) => {\n if (err) {\n console.log('Error loading client secret file: ' + err);\n return;\n }\n // Authorize a client with the loaded credentials, then call the\n // Google Sheets API.\n authorize(JSON.parse(content), getPackageData);\n });\n}", "function userOnload(){\n checkLoginAndSetUp(); \n sidebar();\n fetchOUs();\n}", "_configureAuthentication() {\n this.authenticator = new Authenticator(this.appConfig.oauth);\n }", "function OAuthManager() {\n}", "async function load(req, res, next) {\n req.userpromocode = await UserPromocode.get(req.params.userpromocodeId);\n return next();\n}", "function loadUser() {\n console.log(\"loadUser() started\");\n showMessage(\"Loading the currently logged in user ...\");\n osapi.jive.core.users.get({\n id : '@viewer'\n }).execute(function(response) {\n console.log(\"loadUser() response = \" + JSON.stringify(response));\n user = response.data;\n $(\".user-name\").html(user.name);\n loadUsers();\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getSubtreeWeight // Function: // Recursively traverses down the tree to get the total weight // of a node's subtree // Return value: // integer //
function getSubtreeWeight(subregion) { if (subregion == null) { return 0; } else { if (TREE_DEBUG_MSGS && DEBUG_MSGS) console.log("weight: " + subregion.weight); return subregion.weight + _getSubtreeWeight(subregion.first ) + _getSubtreeWeight(subregion.second) + _getSubtreeWeight(subregion.third ) + _getSubtreeWeight(subregion.fourth); } }
[ "function SBParticipant_getWeight()\n{\n return extPart.getWeight(this.name, this.node);\n}", "calculateTreeWidth() {\n let leftSubtreeWidth = nodeSize + 2 * nodePadding;\n let rightSubtreeWidth = leftSubtreeWidth;\n if (this.left != null) {\n leftSubtreeWidth = this.left.calculateTreeWidth();\n }\n if (this.right != null) {\n rightSubtreeWidth = this.right.calculateTreeWidth();\n }\n this.width = leftSubtreeWidth + rightSubtreeWidth;\n return this.width;\n }", "function extUtils_getWeightNum(weight)\n{\n if (typeof weight == \"string\")\n {\n var pos = weight.indexOf(\"+\");\n weight = parseInt((pos > 0)? weight.substring(pos+1) : weight);\n }\n\n return weight;\n}", "getWeight() {\r\n let pounds = this.weight * 2.205;\r\n let weight = Math.round(pounds * 10) / 100;\r\n return `${weight} lbs.`;\r\n }", "numDescendants() {\n let num = 1;\n for (const branch of this.branches) {\n num += branch.numDescendants();\n }\n return num;\n }", "crotonWeight(state) {\n var crotonWeight = 0;\n for (var i = 0; i < state.recordsList.length; i++) {\n if (state.recordsList[i].reservoir === \"Croton\") {\n var weight = state.recordsList[i].weight;\n crotonWeight += weight;\n }\n }\n return crotonWeight;\n }", "function extPart_getWeight(partName, theNode)\n{\n //get the weight information\n var retVal = extPart.getLocation(partName);\n\n //if the insert weight is nodeAttribute, add the position of the matched string\n if (retVal == \"nodeAttribute\")\n {\n //get the node string\n var nodeStr = extUtils.convertNodeToString(theNode);\n\n var foundPos = extUtils.findPatternsInString(nodeStr, extPart.getQuickSearch(partName),\n extPart.getSearchPatterns(partName));\n\n if (foundPos)\n {\n retVal += \"+\" + foundPos[0] + \",\" + foundPos[1];\n }\n }\n\n return retVal;\n}", "function nodeValue(tree) {\n let retval = 0;\n let children = tree.children;\n let metadata = tree.metadata;\n\n if (tree.children.length === 0) {\n retval = sumMetadata(tree);\n } else {\n for (let meta of metadata) {\n if (meta > children.length || meta === 0) continue;\n let step = children[meta-1];\n retval = retval + nodeValue(step);\n }\n }\n return retval;\n}", "function calculateWeightOfOneSheet(kgs) {\n weightOfOneSheet = kgs / 100;\n return weightOfOneSheet;\n}", "getWeights(){\n return this.weights;\n }", "function weight(cw) {\n return w[cw & 0xf] + w[(cw >> 4) & 0xf] + w[(cw >> 8) & 0xf] +\n w[(cw >> 12) & 0xf] + w[(cw >> 16) & 0xf] + w[(cw >> 20) & 0xf];\n}", "function calculateHeavy(node) {\n let rh, lh; // heights of left and right tree\n if (node.left === undefined || node.left === null) {\n lh = -1;\n }\n else {\n lh = node.left.height;\n }\n\n if (node.right == undefined || node.right == null) {\n rh = -1;\n }\n else {\n rh = node.right.height;\n }\n\n let diff = rh - lh; // Difference in height\n let heavy;\n if (diff >= -1 && diff <= 1) {\n heavy = \"neutral\";\n } else if (rh > lh) {\n heavy = \"right\";\n }\n else {\n heavy = \"left\";\n }\n return heavy;\n}", "function randomWeight() {\n return Math.round(Math.random() * 5)\n}", "calculateWeightOfMoves() {\n let weights = [20, 20, 20, 20, 20];\n let lossNum = Object.values(this.losses)\n .reduce((acc, curr) => acc + curr, 0);\n let lossPercentages = Object.values(this.losses)\n .map(num => {\n return lossNum > 0 ? num / lossNum : 0;\n });\n\n weights = weights\n .map((weight, idx) => weight - (weight * lossPercentages[idx]));\n\n let leftoverWeight = (100 - weights\n .reduce((acc, curr) => acc + curr, 0)) / weights.length;\n\n return weights.map(weight => Math.round(weight + leftoverWeight));\n }", "function bmi(weight,height){\n\n if((weight / (height ** 2)) <= 18.5){\n return `Underweight`\n }\n if((weight / (height ** 2)) <= 25.0){\n return `Normal`\n }\n if((weight / (height ** 2)) <= 30.0){\n return `Overweight`\n }\n if((weight / (height ** 2)) > 30){\n return `Obese`\n }\n}", "function getUrlWeight(url){\n var weights = {\n '/Account/': 0, // Customer Sign-In\n '/Report.aspx': 0, // Printable report\n '/GiveFeedback/': 0, // Give feedback about a member\n '/Search/': 0.1, // Good for building the network, but I think there are infinite search variations exposed\n '/Gallery.aspx': 0.3, // Just photos of the member's work\n '/Reviews.aspx': 0.4, // Reviews about the member\n '/Reputation': 0.2 // Can't remember why I downgraded this...\n };\n // See if we can match it\n for(var key in weights){\n if(weights.hasOwnProperty(key)){\n if(url.pathname.indexOf(key) !== -1){\n return weights[key];\n }\n }\n }\n // Everything else is top priority\n return 1;\n}", "function sumOfPathNumbers(binaryTree) {\n let allPathsSum = [0];\n traverseTree(binaryTree, allPathsSum);\n return allPathsSum\n}", "findMaxEdgeValue(){\n let heaviestEdgeWeight = 0;\n for (let edge of this.props.edges) {\n if (edge.weight > heaviestEdgeWeight) {\n heaviestEdgeWeight = edge.weight;\n }\n }\n return heaviestEdgeWeight;\n }", "function wPadding(level_width,node_width){\n return (pageWidth-(node_width*level_width)) / (level_width+1);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
changes drawType of selctor is changed
function drawSelectionChanged() { drawType = drawSelector.value(); setImage(); }
[ "function menuDrawClick() {\n Data.Edit.Mode = EditModes.Draw;\n updateMenu();\n}", "function ToggleDraw(){\n self.canvas.isDrawingMode = !self.canvas.isDrawingMode;\n }", "selectData(val) {\n if (this._interpolation === \"attr_style_range\") {\n this._selectedData = val;\n for (const canvasData of this._multiCanvas) {\n this._updateCanvas(canvasData.typeId);\n }\n }\n }", "function drawSelected() {\n\tif (itemSelectedByPlayer == selectionPerson.itemf) {\n\t\tctx.drawImage(selectionPerson.itemf, canvas.width / 100 * 45, -canvas.height/9 + canvas.height/40, canvas.width/10, canvas.height/4);\n\t}\n\telse if (itemSelectedByPlayer == selectionPerson.hat) {\n\t\tctx.drawImage(selectionPerson.hat, canvas.width / 100 * 45, canvas.height/20 + canvas.height/40, canvas.width/10, canvas.height/4);\n\t}\n\telse if (itemSelectedByPlayer == selectionPerson.shirt) {\n\t\tctx.drawImage(selectionPerson.shirt, canvas.width / 100 * 45, -canvas.height/30 + canvas.height/40, canvas.width/10, canvas.height/4);\n\t}\n\telse if (itemSelectedByPlayer == selectionPerson.pants) {\n\t\tctx.drawImage(selectionPerson.pants, canvas.width / 100 * 45, -canvas.height/10 + canvas.height/40, canvas.width/10, canvas.height/4);\n\t}\n\telse if (itemSelectedByPlayer == selectionPerson.shoes) {\n\t\tctx.drawImage(selectionPerson.shoes, canvas.width / 100 * 45, -canvas.height/6 + canvas.height/40, canvas.width/10, canvas.height/4);\n\t}\n\telse if (itemSelectedByPlayer == selectionPerson.itemb) {\n\t\tctx.drawImage(selectionPerson.itemb, canvas.width / 100 * 45, -canvas.height/9 + canvas.height/40, canvas.width/10, canvas.height/4);\n\t}\n\t\n//\tselectArray[0].draw();\n}", "function changeType(sel_obj, ind, htmlId) {\r\n\r\n if (!htmlId) { // while configuring a new grid\r\n\r\n NewGridObj.dataTypes[ind] = parseInt(sel_obj.value);\r\n\r\n } else {\r\n\r\n\tvar gridId = getGridIdOfHtmlId(htmlId); // find grid id from step\r\n\tvar gO = CurFuncObj.allGrids[gridId]; // get grid obj from func\r\n\tgO.dataTypes[ind] = parseInt(sel_obj.value);\r\n }\r\n}", "function updateSelect() {\n for (var i=0;i<g_points.length;i++){\n figures.options[i+1] = new Option('Surface' +i, i);\n }\n}", "function sel_change(v, check, F, objs) {\n if (v == check) {\n sel_enable_objs(F, objs);\n } else {\n sel_disable_objs(F, objs);\n }\n}", "function featureTypeChanged() {\n // Style for coloring the outline of the entire feature type.\n let styleStrokeOnly = /** @type {!google.maps.FeatureStyleOptions} */ ({\n fillColor: \"white\",\n fillOpacity: 0.01,\n strokeColor: strokeColorPicker.value,\n strokeOpacity: 1.0,\n strokeWeight: 2.0,\n });\n\n revertStyles();\n selectedPlaceId = \"\";\n contentDiv.innerHTML = \"\";\n // Apply the style to the selected feature layer.\n switch (featureMenu.value) {\n case \"country\":\n countryLayer.style = styleStrokeOnly;\n break;\n case \"administrative_area_level_1\":\n admin1Layer.style = styleStrokeOnly;\n break;\n case \"administrative_area_level_2\":\n admin2Layer.style = styleStrokeOnly;\n break;\n case \"locality\":\n localityLayer.style = styleStrokeOnly;\n break;\n case \"postal_code\":\n postalCodeLayer.style = styleStrokeOnly;\n break;\n default:\n break;\n }\n}", "function mouseMoved(){\n if(selected !== null){\n selLine[0] = digraph.vertices[selected]['x'];\n selLine[1] = digraph.vertices[selected]['y'];\n selLine[2] = mouseX;\n selLine[3] = mouseY;\n }\n}", "function colorChange(selectObj, dataname) {\n var idx = selectObj.selectedIndex;\n var color = selectObj.options[idx].value;\n\n d3.select(\"#\" + dataname)\n .attr(\"style\", \"stroke: \" + color)}", "updateCropSelection(d, that, thisLi) {\n that.cropVis.selected_crop = d;\n that.updateCropOnMap(that);\n // Unhighlight previously selected crop and highlight selected crop\n d3.selectAll(\".clickedCropLi\").classed(\"clickedCropLi\", false);\n d3.select(thisLi).attr(\"class\", \"clickedCropLi\");\n let current_countries = [...that.cropVis.selected_countries];\n that.cropVis.selected_countries.clear();\n // that.cropVis.worldMap.clearHighlightedBoundaries();\n that.cropVis.barChart.deleteBarChart();\n that.cropVis.lineChart.deleteLineChart();\n that.cropVis.lineChart.alreadyExistingCountries.clear();\n that.cropVis.table.drawTable();\n for (let country of current_countries) {\n that.cropVis.selected_countries.add(country);\n that.cropVis.barChart.updateBarChart();\n }\n that.cropVis.lineChart.updateLineChart();\n that.cropVis.worldMap.updateAllMapTooltips(that);\n }", "selectionSetDidChange() {}", "function alterPolygon() {\n if (drawMode === true) return;\n\n var alteredPoints = [];\n var selectedP = d3.select(this);\n var parentNode = d3.select(this.parentNode);\n \n //select only the elements belonging to the parent <g> of the selected circle\n var circles = d3.select(this.parentNode).selectAll('circle');\n var polygon = d3.select(this.parentNode).select('polygon');\n\n\n var pointCX = d3.event.x;\n var pointCY = d3.event.y;\n\n\n //rendering selected circle on drag\n selectedP.attr(\"cx\", pointCX).attr(\"cy\", pointCY);\n\n //loop through the group of circle handles attatched to the polygon and push to new array\n for (var i = 0; i < polypoints.length; i++) {\n\n var circleCoord = d3.select(circles._groups[0][i]);\n var pointCoord = [circleCoord.attr(\"cx\"), circleCoord.attr(\"cy\")];\n alteredPoints[i] = pointCoord;\n\n }\n\n //re-rendering polygon attributes to fit the handles\n polygon.attr(\"points\", alteredPoints);\n bbox = parentNode._groups[0][0].getBBox();\n }", "function deselectDelegate(tblWidget, type, selected, deselect)\n{\n}", "onSelectX6TableColumnDataTypeChanged(v) {\n // this.gDynamic.x6TableColumnDataType = v;\n let nodeType = v;\n this.gCurrent.node.setData({\n dataType: v\n })\n\n switch (nodeType) {\n case \"int\":\n this.gCurrent.node.addPort({\n id: 'portLeft',\n group: \"groupLeft\",\n attrs: {\n circle: {\n connectionCount: 1,\n r: 5,\n magnet: true,\n stroke: '#AFDEFF',\n fill: '#FFF',\n strokeWidth: 1,\n },\n },\n });\n\n this.gCurrent.node.addPort({\n id: 'portRight',\n group: \"groupRight\",\n attrs: {\n circle: {\n connectionCount: 2,\n r: 5,\n magnet: true,\n stroke: '#AFDEFF',\n fill: '#FFF',\n strokeWidth: 1,\n },\n },\n });\n break\n default:\n this.gCurrent.node.removePort(\"portLeft\");\n this.gCurrent.node.removePort(\"portRight\");\n break\n }\n }", "function initSelection() {\n canvas.on({\n \"selection:created\": function __listenersSelectionCreated() {\n global.console.log(\"**** selection:created\");\n setActiveObject();\n toolbar.showActiveTools();\n },\n \"before:selection:cleared\": function __listenersBeforeSelectionCleared() {\n global.console.log(\"**** before:selection:cleared\");\n },\n \"selection:cleared\": function __listenersSelectionCleared() {\n global.console.log(\"**** selection:cleared\");\n toolbar.hideActiveTools();\n },\n \"selection:updated\": function __listenersSelectionUpdated() {\n global.console.log(\"**** selection:updated\");\n setActiveObject();\n toolbar.showActiveTools();\n },\n });\n}", "function disable_draw() {\n drawing_tools.setShape(null);\n}", "function updateShapePointer() {\n selectedShape.oldFillColor = selectedShape.fillColor;\n selectedShape.oldLineColor = selectedShape.lineColor;\n selectedShape.oldLineWidth = selectedShape.lineWidth;\n shapeArray[shapeArrayPointer++] = selectedShape;\n}", "function setSelectMode() {\n mode = modes.SELECT\n GameScene.setRegionSelectPlaneVis(true)\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function updates each friend element that appears on the page. Once a friend's element is clicked, their respective user names/share codes will appear, as well as a couple helpful buttons/interactive text fields.
function changeFriendElement(friendKey){ var friendData; for (var i = 0; i < userArr.length; i++){ if(friendKey == userArr[i].uid){ friendData = userArr[i]; break; } } if(friendData != null) { var userUid = friendData.uid; var friendName = friendData.name; var friendUserName = friendData.userName; var friendShareCode = friendData.shareCode; var liItemUpdate = document.getElementById("user" + userUid); liItemUpdate.innerHTML = friendName; liItemUpdate.className = "gift"; liItemUpdate.onclick = function () { var span = document.getElementsByClassName("close")[0]; var friendSendMessage = document.getElementById('sendPrivateMessage'); var friendInviteRemove = document.getElementById('userInviteRemove'); var friendNameField = document.getElementById('userName'); var friendUserNameField = document.getElementById('userUName'); var friendShareCodeField = document.getElementById('userShareCode'); if (friendShareCode == undefined) { friendShareCode = "This User Does Not Have A Share Code"; } friendNameField.innerHTML = friendName; friendUserNameField.innerHTML = "User Name: " + friendUserName; friendShareCodeField.innerHTML = "Share Code: " + friendShareCode; friendSendMessage.onclick = function() { generatePrivateMessageDialog(friendData); }; friendInviteRemove.onclick = function () { modal.style.display = "none"; deleteFriend(userUid); }; //show modal modal.style.display = "block"; //close on close span.onclick = function () { modal.style.display = "none"; }; //close on click window.onclick = function (event) { if (event.target == modal) { modal.style.display = "none"; } } }; } }
[ "function update_user_elements() {\n $('.echo-item-authorName, .echo-item-avatar').each( function() {\n if(!$(this).hasClass('initialized')) {\n var container = $(this).parents('.echo-item-container');\n \n var userName = container.find('.echo-item-authorName').text();\n var userID = container.find('.echo-item-metadata-userID .echo-item-metadata-value').text();\n \n var url = '/echo2-users.php?user_id=' + UrlEncoderTool.encode(userID) + '&d=' + new Date().getTime();\n \n $(this).html($('<a></a>').attr('href',url).attr('title', 'user page: ' + userName).addClass('echo-linkColor').html($(this).html()));\n $(this).find('img').removeAttr('height');\n $(this).addClass('initialized');\n }\n });\n }", "function createFriendElement(friendKey){\n var friendData;\n for (var i = 0; i < userArr.length; i++){\n if(friendKey == userArr[i].uid){\n friendData = userArr[i];\n break;\n }\n }\n\n if(friendData != null) {\n try{\n document.getElementById(\"TestGift\").remove();\n } catch (err) {}\n\n var userUid = friendData.uid;\n var friendName = friendData.name;\n var friendUserName = friendData.userName;\n var friendShareCode = friendData.shareCode;\n var liItem = document.createElement(\"LI\");\n liItem.id = \"user\" + userUid;\n liItem.className = \"gift\";\n liItem.onclick = function () {\n var span = document.getElementsByClassName(\"close\")[0];\n var friendSendMessage = document.getElementById('sendPrivateMessage');\n var friendInviteRemove = document.getElementById('userInviteRemove');\n var friendNameField = document.getElementById('userName');\n var friendUserNameField = document.getElementById('userUName');\n var friendShareCodeField = document.getElementById('userShareCode');\n\n if (friendShareCode == undefined || friendShareCode == \"\") {\n friendShareCode = \"This User Does Not Have A Share Code\";\n }\n\n friendNameField.innerHTML = friendName;\n friendUserNameField.innerHTML = \"User Name: \" + friendUserName;\n friendShareCodeField.innerHTML = \"Share Code: \" + friendShareCode;\n\n friendSendMessage.onclick = function() {\n generatePrivateMessageDialog(friendData);\n };\n\n friendInviteRemove.onclick = function () {\n modal.style.display = \"none\";\n deleteFriend(userUid);\n };\n\n //show modal\n modal.style.display = \"block\";\n\n //close on close\n span.onclick = function () {\n modal.style.display = \"none\";\n };\n\n //close on click\n window.onclick = function (event) {\n if (event.target == modal) {\n modal.style.display = \"none\";\n }\n };\n };\n var textNode = document.createTextNode(friendName);\n liItem.appendChild(textNode);\n\n userList.insertBefore(liItem, document.getElementById(\"userListContainer\").childNodes[0]);\n\n friendCount++;\n }\n }", "function addFriends() {\n clickNextButton(\"Add\", defaultAddFriendSelector);\n}", "function bindNameAndImagesToProfile(){\n var userPics = document.getElementsByClassName(\"userImage\");\n var userPseudoName = document.getElementsByClassName(\"pseudoName\");\n\n for(var x = 0; x < userPics.length; x++){\n // update the image of the user\n userPics[x].src = \"services/getAvatar.php?userId=\" + userPics[x].dataset.user + \"&size=small\"\n + \"&random=\"+new Date().getTime();\n // add event listener for click\n userPics[x].addEventListener(\"click\", showOtherUser);\n }\n\n for(var x = 0; x < userPseudoName.length; x++){\n userPseudoName[x].addEventListener(\"click\", showOtherUser);\n }\n unbindShowProfileUserShowOptions(); // unbind the click on the author in choise list\n}", "async function initFriendsListener() {\n\n await updateUserFriends()\n \n\n // fill initial group panel\n friendHeader.innerHTML = `Friends\n <button id=\"friend-invit-btn\" type=\"button\" class=\"btn btn-light\">Invit users</button>`;\n \n friendContent.innerHTML = getHtmlFriendsList( userFriends );\n\n // attach listener to add button friends\n let invitFriendBtn = document.getElementById(\"friend-invit-btn\");\n invitFriendBtn.addEventListener( 'click', () => invitFriendListener() );\n\n // attach listener to all see friends button\n let seeFriendBtn = [...document.getElementsByClassName(\"btn-list-friend\")];\n seeFriendBtn.forEach( btn => btn.addEventListener( 'click', () => seeFriendListener(btn) ));\n\n // attach listener to all see friends button\n let chatFriendBtn = [...document.getElementsByClassName(\"btn-chat-friend\")];\n chatFriendBtn.forEach( btn => btn.addEventListener( 'click', () => {\n const friendid = btn.getAttribute(\"data-friendid\");\n openChatBox(friendid);\n }));\n}", "function openFriendsMenuForSelectedFriend() {\n document.querySelectorAll('div[aria-label=\"Friends\"]')[0]\n .click();\n}", "function generateFriendButtons() {\n\n // Variable to hold whether or not the userFriends branch in the database is null\n userFriendsRef.on('value', (snapshot) => {\n\n // Calls the function to add an event listener to add friend button\n addFriendEventListener();\n\n if (snapshot.val() == null) {\n \n // If there is no friends branch in database, add an add friend button to each user box\n let usersArray = [].slice.call(document.querySelectorAll('.user-box'));\n // Generate add friend button\n let addFriendBtnEl = document.createElement('button');\n addFriendBtnEl.className = 'add-friend-btn';\n addFriendBtnEl.innerHTML = 'Add Friend';\n // Add the button to each user box\n for (let i = 0; i < usersArray.length; i++) {\n let usernamesInDB = usersArray[i].childNodes[1].innerHTML;\n // Adds the add friend button to all users, except the current user\n if (currentUser != usernamesInDB && usersArray[i].childNodes[3].innerHTML == '') {\n usersArray[i].childNodes[3].appendChild(addFriendBtnEl);\n }\n }\n // WHAT HAPPENS IF THERE IS A USERFRIENDS BRANCH IN THE DATABASE\n } else {\n\n // Get the current users in the database with friends\n let data = snapshot.val();\n let users = Object.keys(data);\n for (let i = 0; i < users.length; i++) {\n // Gets the user's username with friends\n let user = users[i];\n // Gets the object with the current user's friends\n let friendsObj = data[user];\n // Array of the keys for the friends object\n let friendsObjKeys = Object.keys(friendsObj);\n // Check to see if the current user is equal to the user with friends\n if (currentUser == user) {\n for (let i = 0; i < friendsObjKeys.length; i++) {\n let key = friendsObjKeys[i];\n // Stores the users friends name\n let usersFriendUserName = friendsObj[key].user;\n // Check to see if the friend's username is already in the array before pushing it\n if (currentUsersFriends.indexOf(usersFriendUserName) == -1) {\n currentUsersFriends.push(usersFriendUserName);\n }\n }\n }\n \n }\n // Create a friend button for all the user's that aren't the current user's friends\n // An array to hold all of the current users\n let usersArray = [].slice.call(document.querySelectorAll('.user-box'));\n // Generate add friend button\n let addFriendBtnEl = document.createElement('button');\n addFriendBtnEl.className = 'add-friend-btn';\n addFriendBtnEl.innerHTML = 'Add Friend';\n for (let i = 0; i < usersArray.length; i++) {\n let usernamesInDB = usersArray[i].childNodes[1].innerHTML;\n // Adds the add friend button to all users, except the current user and their friends\n if (currentUser != usernamesInDB && currentUsersFriends.indexOf(usersArray[i].childNodes[1].innerHTML) <= -1 && usersArray[i].childNodes[3].innerHTML == '') {\n usersArray[i].childNodes[3].appendChild(addFriendBtnEl);\n }\n }\n }\n });\n \n}", "function populate_followers_list() {\n $.get('/dashboard/get_followers', function (data) {\n $('#followers_list').html(data);\n \n // Click handler.\n $('#followers_list .add_following').confirmDiv(function (clicked_elem) {\n $.get('/dashboard/add_user_following', {\n following_id: clicked_elem.parent().attr('user_id')\n }, function (data) {\n populate_followers_list();\n });\n });\n \n // Make followers selectable\n $('#followers_list .user_entry').click(function() {\n if(!$(this).hasClass('selected_follower'))\n {\n // setup spinner\n var friends_opts = spinner_options();\n var friends_target = document.getElementById('friends_spinner');\n var friends_spinner = new Spinner(friends_opts).spin(friends_target);\n \n $('.user_entry.selected_follower').removeClass('selected_follower');\n $(this).addClass('selected_follower');\n $.get('/dashboard/get_profile', {\n user_id: $(this).attr('user_id')\n }, function (data) {\n $('#friends_content .right').hide();\n $('#friends_content .right').html(data);\n $('#friends_content .right').show(\"fast\");\n }).complete(function(){\n friends_spinner.stop();\n });\n }\n });\n });\n}", "function Friend(friendObj) {\n this.name = $(friendObj).find(\"div[class='fsl fwb fcb'] a:nth-child(1)\").text()\n this.pageUrl = $(friendObj).find(\"div[class=uiProfileBlockContent] a:nth-child(1)\").attr(\"href\")\n this.mutualFriends = []\n\n var idString = $(friendObj).find(\"div[class=uiProfileBlockContent] a:nth-child(1)\").attr(\"data-hovercard\")\n //regex that matches the string \"id=\" followed by one or more decimal digits and ending with an equals sign\n var regex = /id=(\\d+)=*/\n var uuidString;\n if(idString != undefined){\n uuidString = idString.match(regex)\n this.fbID = uuidString[1]\n } else {\n //case where friend has deactivated their account\n var inactiveIDString = $(friendObj).find(\"div[class=uiProfileBlockContent] a:nth-child(1)\").attr(\"ajaxify\")\n uuidString = inactiveIDString.match(regex)\n this.fbID = uuidString[1]\n }\n \n this.mutualFriendsUrl = \"https://www.facebook.com/browse/mutual_friends/?uid=\" + this.fbID\n return this\n}", "function displayCorrectButtons(friendLink) {\n if (!friendLink) {\n $scope.isFriend = false;\n } else if (friendLink.status === 1) {\n // Friend-link not complete\n if (friendLink.accepter_id === $rootScope.currentUser.id) {\n // Current user received request\n $scope.friendRequestReceived = true;\n } else {\n // current user sent request\n $scope.friendRequestSent = true;\n }\n } else {\n // Friend-link complete\n $scope.isFriend = true;\n }\n }", "function showOtherUser(){\n removeFollowList();\n removeSearchArea();\n var userId = this.dataset.user; // get the user of the clicked name or image\n showedUser = userId;\n removeWritenFields();\n removeErrorSuccesFields();\n document.getElementById(\"profileSection\").style.display = \"block\";\n document.getElementById(\"messagesSection\").style.display = \"none\";\n hideAllProfileSection();\n document.getElementById(\"showProfile\").style.display = \"block\";\n\n getOtherProfile(userId);\n}", "function removeFriends() {\n clickNextButton(\"injectedUnfriend\", defaultInjectedUnfriendButtonSelector);\n}", "function populate(randomUsers){\n // Variable declaration\n const newMembersDiv = document.getElementById('new-members');\n const recentActivityDiv = document.getElementById('recent-activity');\n const membersActivity = [\"posted YourApp's SEO Tips\", \"commented on Facebook's Changes for 2018\", \"liked the post Facebook's Change for 2018\", \"commented on YourApp's SEO Tips\"];\n const activityTime = ['1 day ago', '5 hours ago', '5 hours ago', '4 hours ago'];\n\n // Loop through random users to populate member sections\n for (let i = 0; i < randomUsers.length; i++){\n const member = randomUsers[i];\n\n // Wrapper div for user info\n const memberDiv = document.createElement('div');\n memberDiv.className = 'member-info';\n\n // Image avatar\n const imageDiv = document.createElement('div');\n const img = document.createElement('img');\n img.src = member.picture.thumbnail;\n img.alt = firstUp(member.name.first) + ' ' + firstUp(member.name.last);\n img.className = 'avatar';\n imageDiv.appendChild(img);\n memberDiv.appendChild(imageDiv);\n\n // Use the 4 first users to populate \"New Members\" specific info\n if (i <= 3){\n // Wrapping div\n const detailsDiv = document.createElement('div');\n\n // Name\n const name = document.createElement('p');\n name.className = 'member-name';\n name.innerHTML = firstUp(member.name.first) + ' ' + firstUp(member.name.last);\n detailsDiv.appendChild(name);\n\n // Email\n const email = document.createElement('p');\n email.innerHTML = member.email;\n email.className = 'member-email';\n detailsDiv.appendChild(email);\n memberDiv.appendChild(detailsDiv);\n\n // Signup Date\n const dateDiv = document.createElement('div');\n dateDiv.className = 'flex-item-last';\n const signupDate = document.createElement('p');\n const dateOptions = {month: '2-digit', day: '2-digit', year: '2-digit'};\n signupDate.innerHTML = new Date(member.registered.date).toLocaleDateString('en-US', dateOptions);\n signupDate.className = 'member-signup';\n dateDiv.appendChild(signupDate);\n\n memberDiv.appendChild(dateDiv);\n\n // Line break between members\n newMembersDiv.appendChild(memberDiv);\n if (i < 3){\n const line = document.createElement('hr');\n line.className = \"max-length\";\n newMembersDiv.appendChild(line);\n }\n }\n // The 4 last users populates \"Recent Activity\" specific info\n else {\n // Wrapping div\n const activityDiv = document.createElement('div');\n memberDiv.appendChild(activityDiv);\n\n // Activity\n const activity = document.createElement('p');\n activity.innerHTML = firstUp(member.name.first) + ' ' + firstUp(member.name.last) + membersActivity[i -4];\n activityDiv.appendChild(activity);\n\n // Time\n const time = document.createElement('p');\n time.innerHTML = activityTime[i -4];\n time.className = 'activity-time';\n activityDiv.appendChild(time);\n\n // Signup Date\n const arrowDiv = document.createElement('div');\n arrowDiv.className = 'flex-item-last';\n const arrow = document.createElement('p');\n arrow.innerHTML = '›'\n arrow.className = 'activity-arrow';\n arrowDiv.appendChild(arrow);\n memberDiv.appendChild(arrowDiv);\n\n // Add linebreak if not the last one\n recentActivityDiv.appendChild(memberDiv);\n if (i < 7){\n const line = document.createElement('hr');\n recentActivityDiv.appendChild(line);\n }\n }\n }\n}", "function renderExportFriendsLink() {\r\n // Paint the Export friends to the top of the page.\r\n var exportFriendsLink = $('#pageNav #navAccount ul li:nth-child(2)').clone();\r\n $('a', exportFriendsLink)\r\n .attr('id', 'export-friends-link')\r\n .attr('href', 'javascript:void(0);')\r\n .text('Export Friends!')\r\n .click(switchToWorkerTab);\r\n $('#pageNav #navAccount ul li:nth-child(2)').after(exportFriendsLink);\r\n}", "function changeGiftElement(giftData, giftOwner){\n var description = giftData.description;\n var link = giftData.link;\n var title = giftData.title + \" - for \" + giftOwner;\n var where = giftData.where;\n var uid = giftData.uid;\n var date = giftData.creationDate;\n\n console.log(\"Updating \" + uid);\n var editGift = document.getElementById(\"gift\" + uid);\n editGift.innerHTML = title;\n editGift.className = \"gift\";\n editGift.onclick = function (){\n var spanGift = document.getElementsByClassName(\"close\")[0];\n var descField = document.getElementById('giftDescription');\n var titleField = document.getElementById('giftTitle');\n var whereField = document.getElementById('giftWhere');\n var linkField = document.getElementById('giftLink');\n\n if (link != \"\"){\n linkField.innerHTML = \"Click me to go to the webpage!\";\n linkField.onclick = function() {\n var newGiftLink = \"http://\";\n if(link.includes(\"https://\")){\n link = link.slice(8, link.length);\n } else if (link.includes(\"http://\")){\n link = link.slice(7, link.length);\n }\n newGiftLink += link;\n window.open(newGiftLink, \"_blank\");\n };\n } else {\n linkField.innerHTML = \"There was no link provided\";\n linkField.onclick = function() {\n };\n }\n if(description != \"\") {\n descField.innerHTML = \"Description: \" + description;\n } else {\n descField.innerHTML = \"There was no description provided\";\n }\n titleField.innerHTML = title;\n if(where != \"\") {\n whereField.innerHTML = \"This can be found at: \" + where;\n } else {\n whereField.innerHTML = \"There was no location provided\";\n }\n if(date != undefined) {\n if (date != \"\") {\n giftCreationDate.innerHTML = \"Created on: \" + date;\n } else {\n giftCreationDate.innerHTML = \"Creation date not available\";\n }\n } else {\n giftCreationDate.innerHTML = \"Creation date not available\";\n }\n\n //show modal\n modal.style.display = \"block\";\n currentModalOpen = uid;\n console.log(\"Modal Open: \" + currentModalOpen);\n\n //close on close\n spanGift.onclick = function() {\n currentModalOpen = \"\";\n console.log(\"Closed modal\");\n modal.style.display = \"none\";\n };\n\n //close on click\n window.onclick = function(event) {\n if (event.target == modal) {\n currentModalOpen = \"\";\n console.log(\"Closed modal\");\n modal.style.display = \"none\";\n }\n };\n };\n }", "function publishStoryFriend() {\n randNum = Math.floor ( Math.random() * friendIDs.length ); \n\n var friendID = friendIDs[randNum];\n \n console.log('Opening a dialog for friendID: ', friendID);\n \n FB.ui({\n method: 'feed',\n to: friendID,\n name: 'I\\'m using the Hackbook web app',\n caption: 'Hackbook for Mobile Web.',\n description: 'Check out Hackbook for Mobile Web to learn how you can make your web apps social using Facebook Platform.',\n link: 'http://apps.facebook.com/mobile-start/',\n picture: 'http://www.facebookmobileweb.com/hackbook/img/facebook_icon_large.png',\n actions: [{ name: 'Get Started', link: 'http://apps.facebook.com/mobile-start/' }],\n user_message_prompt: 'Tell your friends about building social web apps.'\n }\n , \n function(response) {\n console.log('publishStoryFriend UI response: ', response);\n alert(response.accessToken);\n });\n}", "function user_avatars()\r\n{\r\n\tvar avatars = getElementsByClassName(document, 'img', 'user_avatar');\r\n\t\r\n\tfor(var i = 0; i < avatars.length; i++)\r\n\t{\r\n\t\tavatars[i].onclick = avatar_popup;\r\n\t}\r\n}", "function addNewFriend(newfriendname) {\n\n\t$.get(\"/addfriend/\", {jid: newfriendname} );\n\tsendRequest(connection, my_user_name, newfriendname);\n\t\n\t// replace the button with \"Added\"\n\t$('#search-table tr[friendname=\"' + newfriendname + '\"] td:eq(2)').replaceWith('<td>' + '<button disabled=\"disabled\" type=\"button\"> Added </button>' + '</td>');\n}", "function updateMemberList() {\n people_list = RTMchannel.getMembers().toString(); // gets list of channel members\n document.getElementById(\"people_list\").innerHTML = \"<u>People</u>: \" + people_list.toString();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is called when the the server instance is created. It starts listening for termination events that require the server to be stopped.
_startListeningForTermination() { this._terminationEvents.forEach((eventName) => { process.on(eventName, this._terminate); }); }
[ "_stopListeningForTermination() {\n this._terminationEvents.forEach((eventName) => {\n process.removeListener(eventName, this._terminate);\n });\n }", "startSocketServer() {\n // Create new socket.io server, listening on a specific path\n this.io = new Server(this.webServer, {\n path: SocketConfig.DEFAULT_PATH\n });\n\n // Setup handlers\n this.io.on('connect', (socket) => {\n logger.debug(`New socket (${socket.id}) connected to server`);\n\n socket.on('disconnect', (reason) => {\n logger.debug(`Socket (${socket.id}) disconnected`);\n });\n });\n }", "async registerListeners () {\n this.container.on(DockerEventEnum.STATUS_UPDATE, newStatus => this.updateStatus(newStatus));\n this.container.on(DockerEventEnum.CONSOLE_OUTPUT, data => this.onConsoleOutput(data));\n\n this.on(DockerEventEnum.STATUS_UPDATE, newStatus => {\n if (newStatus === ServerStatus.OFFLINE) {\n if (this.config.properties.deleteOnStop) {\n this.logger.info('Server stopped, deleting container...');\n this.remove()\n .catch(err => this.logger.error('Failed to delete the container!', { err }));\n } else if (this.config.properties.autoRestart) {\n this.logger.info('Restarting the server...');\n this.start();\n }\n }\n });\n }", "function setupTerminationHandlers(){\n // Process on exit and signals.\n process.on('exit', function() { terminator(); });\n\n // Removed 'SIGPIPE' from the list - bugz 852598.\n ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',\n 'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'\n ].forEach(function(element, index, array) {\n process.on(element, function() { terminator(element); });\n });\n }", "function onListening() {\n var addr = server.address();\n var bind = typeof addr === 'string'\n ? 'pipe ' + addr\n : 'port ' + addr.port;\n debug('HTTP Listening on ' + bind);\n}", "function onHttpsListening() {\r\n var addr = httpsServer.address();\r\n var bind = typeof addr === 'string'\r\n ? 'pipe ' + addr\r\n : 'port ' + addr.port;\r\n logger.info('HTTPS Server Started ' + new Date(Date.now()).toString());\r\n logger.info('Listening on ' + bind);\r\n}", "async start () {\n if (this.status !== ServerStatus.OFFLINE) {\n throw new ServerException('The server is already running!');\n }\n \n this.logger.info('The server is now starting.');\n this.updateStatus(ServerStatus.STARTING);\n await this.container.start();\n \n const inspect = await this.container.inspect();\n this.port = inspect.port;\n\n await this.container.attach();\n this.logger.info('Attached to the container, waiting for it to fully start.');\n }", "function initStartServer(){\n startServer();\n checkServerStatus(1);\n}", "start() {\n const PORT = process.env.PORT || this._config.port; // support heroku\n\n if (!this.isListening) {\n this[_server].listen(PORT, () => {\n this._log.debug(`Running on port ${PORT}`);\n });\n }\n }", "function onSSLListening() {\n let addr = ssl_server.address();\n let bind = typeof addr === 'string'\n ? 'pipe ' + addr\n : 'port ' + addr.port;\n debug('SSL Listening on ' + bind);\n}", "listen() {\n console.log('--- Listening on localhost:8000 ---');\n this.server.listen(8000);\n }", "_terminate() {\n if (this._instance) {\n this._instance.close();\n this._instance = null;\n this._stopListeningForTermination();\n this._options.onStop(this);\n }\n\n process.exit();\n }", "static createServer() {\n if (!Server.instance) {\n Server.instance = new Server();\n }\n return Server.instance;\n }", "static createExitHandling() {\r\n process.on('exit', \r\n Application.exitProgram.bind(null, 0,\r\n {message: 'hjbot exit. \\r\\n'}));\r\n\r\n process.on('SIGINT', \r\n Application.exitProgram.bind(null, 0,\r\n {message: 'Keyboard interrupt'}));\r\n\r\n process.on('SIGUSR1', \r\n Application.exitProgram.bind(null, 0,\r\n {message: 'hjbot process was killed'}));\r\n\r\n process.on('SIGUSR2', \r\n Application.exitProgram.bind(null, 0,\r\n {message: 'hjbot process was killed'}));\r\n\r\n process.on('UncaughtException', \r\n Application.exitProgram.bind(null, 0,\r\n {message: 'Uncaught exception occurred'}));\r\n }", "function initServer() {\n var options = {\n dataAdapter: new DataAdapter(config.api),\n errorHandler: mw.errorHandler(),\n appData: config.rendrApp\n };\n server = rendr.createServer(app, options);\n}", "function listening_handler() {\n\tconsole.log(`Now Listening on Port ${port}`);\n}", "writeBundle() {\n // Validate that there's no instance already running.\n if (!this._instance) {\n // Get the server basic options.\n const { https: httpsSettings, port } = this._options;\n // Create the server instance.\n this._instance = httpsSettings ?\n createHTTPSServer(httpsSettings, this._handler) :\n createHTTPServer(this._handler);\n\n // Start listening for requests.\n this._instance.listen(port);\n // Log some information messages.\n this._logger.warning(`Starting on ${this.url}`);\n this._logger.warning('waiting for Rollup...');\n // Start listening for process events that require the sever instance to be terminated.\n this._startListeningForTermination();\n // Open the browser.\n this._open();\n // Invoke the `onStart` callback.\n this._options.onStart(this);\n }\n }", "function setServerHandlers() {\n io.on('connection', (socket) => {\n socket.on('new game', onNewGame);\n socket.on('join request', onJoinRequest);\n socket.on('new player', onNewPlayer);\n socket.on('player ready', onPlayerReady);\n socket.on('game start', onGameStart);\n socket.on('card played', onCardPlayed);\n socket.on('draw card', onDrawCard);\n socket.on('player message', onPlayerMessage);\n socket.on('player quit', onPlayerQuit);\n socket.on('disconnect', onDisconnect);\n });\n}", "function start() {\n test();\n var httpService = http.createServer(serve);\n httpService.listen(ports[0], '0.0.0.0');\n\n var options = {\n key: key,\n cert: cert\n };\n var httpsService = https.createServer(options, serve);\n httpsService.listen(ports[1], '0.0.0.0');\n\n var clients = clientService(httpsService);\n clients.onNewPos(updateEvents);\n\n printAddresses();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Exit a parse tree produced by KotlinParserdeclaration.
exitDeclaration(ctx) { }
[ "exitNormalClassDeclaration(ctx) {\n\t}", "exitSingleTypeImportDeclaration(ctx) {\n\t}", "exitAnnotationTypeMemberDeclaration(ctx) {\n\t}", "exitMultiVariableDeclaration(ctx) {\n\t}", "exitMethodDeclarator(ctx) {\n\t}", "exitTypeImportOnDemandDeclaration(ctx) {\n\t}", "exitNormalInterfaceDeclaration(ctx) {\n\t}", "visitExit_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "exitKotlinFile(ctx) {\n\t}", "exitVariableDeclaratorList(ctx) {\n\t}", "exitConstructorDeclarator(ctx) {\n\t}", "exitParenthesizedType(ctx) {\n\t}", "exitOrdinaryCompilation(ctx) {\n\t}", "exitPreprocessorParenthesis(ctx) {\n\t}", "exitUnannTypeVariable(ctx) {\n\t}", "function Return() {\n \t\t\tdebugMsg(\"ProgramParser : Return\");\n \t\t\tvar line=lexer.current.line;\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\tvar ast=new ASTUnaryNode(\"return\",expr);\n \t\t\tast.line=line;\n \t\t\treturn ast;\n \t\t}", "exitInferredFormalParameterList(ctx) {\n\t}", "exitTypeParameterModifier(ctx) {\n\t}", "exitSingleStaticImportDeclaration(ctx) {\n\t}", "exitStatementWithoutTrailingSubstatement(ctx) {\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
change priorityInput view on input change
onPriorityInputChange(e){ if( e.target.value == '' || isANumber(e.target.value)) { const newValue = { ...this.props.value, selectedNode: { ...this.props.value.selectedNode, priority: e.target.value } }; this.props.onChange({ value: newValue }); } }
[ "function change(priority){\n if (priority == \"high\"){\n document.getElementById(\"priority\").selectedIndex = 0;\n }\n else if (priority =='medium'){\n document.getElementById(\"priority\").selectedIndex = 1; \n }\n else {\n document.getElementById(\"priority\").selectedIndex = 2; \n }\n}", "set CustomProvidedInput(value) {}", "function update_from_input() {\n try {\n colorBox('new', cpicker.target.value)\n cpicker.set(cpicker.target.value)\n } catch(err) {}\n }", "function onInput() {\n\t\t\t\tif ( typeof options.input === 'function' ) {\n\t\t\t\t\toptions.input.call( $input, function( params, callback ){\n\t\t\t\t\t\tbuild( params );\n\t\t\t\t\t} );\n\t\t\t\t}\n\t\t\t}", "focusInput(){\n this.amountInput.focus();\n }", "edit() {\n\t\tvar value = this.input.val();\n\n\t\tthis.$el.addClass('editing');\n\t\tthis.input.val(value).focus();\n\t}", "handleOrChoiceInputChange(event) {\n this.setState({\n orChoice: event.target.value === \"first\"\n });\n }", "function onChangeGoalAmount() {\n calNumberOfContribution();\n }", "function showAcceptedUserInputHint(input, label) {\n label.classList.add(\"active\");\n label.textContent = acceptedInputHints[input.id];\n}", "function updateConstraintForm(index, attrOpElement, attrOptsElement, attrValElement, fixedOps)\n {\n if (attrOptsElement == null)\n return;\n\n for (var i=0 ; i<fixedOps[index].length ; i++)\n {\n if (attrOpElement.value == fixedOps[index][i])\n {\n document.getElementById(\"operandEditSpan\" + index).style.display = \"none\";\n attrValElement.value = attrOptsElement.value; // constrain value\n return;\n }\n }\n\n\t\tif (document.getElementById(\"operandEditSpan\" + index)) {\n\t document.getElementById(\"operandEditSpan\" + index).style.display = \"\";\n\t }\n }", "function mirrorInput(event) {\n\toutputEl.innerHTML = inputEl.value;\n}", "onUpdateInput (e, isSub = false, field = null, index = -1, valueType = null) {\n const { challenge: oldChallenge } = this.state\n const newChallenge = { ...oldChallenge }\n if (!isSub) {\n switch (e.target.name) {\n case 'reviewCost':\n case 'copilotFee':\n newChallenge[e.target.name] = validateValue(e.target.value, VALIDATION_VALUE_TYPE.INTEGER, '$')\n break\n default:\n newChallenge[e.target.name] = e.target.value\n break\n }\n } else {\n switch (field) {\n case 'checkpointPrizes':\n switch (e.target.name) {\n case 'checkNumber':\n newChallenge[field][e.target.name] = validateValue(e.target.value, VALIDATION_VALUE_TYPE.INTEGER)\n break\n case 'checkAmount':\n newChallenge[field][e.target.name] = validateValue(e.target.value, VALIDATION_VALUE_TYPE.INTEGER, '$')\n }\n break\n case 'prizes':\n switch (valueType) {\n case VALIDATION_VALUE_TYPE.STRING:\n newChallenge[field][index]['amount'] = e.target.value.trim()\n newChallenge['focusIndex'] = index\n break\n case VALIDATION_VALUE_TYPE.INTEGER:\n newChallenge['focusIndex'] = index\n newChallenge[field][index]['amount'] = validateValue(e.target.value, VALIDATION_VALUE_TYPE.INTEGER)\n }\n break\n default:\n newChallenge[field][e.target.name] = e.target.value\n break\n }\n }\n\n // calculate total cost of challenge\n this.setState({ challenge: newChallenge })\n }", "function reformatPlayerSelection (playerInput) {\nreturn reformatInput(playerInput)\n }", "function recommenderSensitivityValueListener() {\n var recommenderSensitivity = document.getElementById(\"recommenderSensitivity\");\n recommenderSensitivity.addEventListener(\"input\", function() {\n var newVal = recommenderSensitivity.value;\n chrome.storage.local.get(function(storage) {\n var cachedSettings = storage[\"cachedSettings\"];\n var oldSettings = storage[\"settings\"];\n if (!cachedSettings) {\n if (!oldSettings) {\n // Use default settings\n oldSettings = initialSettings;\n }\n cachedSettings = oldSettings;\n }\n\n cachedSettings[\"recommenderSensitivity\"] = newVal;\n var recommenderSensitivityVal = document.getElementById(\"recommenderSensitivityVal\");\n recommenderSensitivityVal.innerHTML = newVal;\n chrome.storage.local.set({ \"cachedSettings\": cachedSettings });\n });\n });\n}", "function goToChangeSensitivity(){\n clientValuesFactory.setActiveWindow(windowViews.changeSensitivity);\n }", "update(value) {\n\t\tthis.input.value = value || ''\n\t\tthis.updateClasses()\n\t}", "function initPodsPriority() {\n var podsPriority = lodash.get(ctrl.version, 'spec.priorityClassName', '');\n\n if (lodash.isEmpty(podsPriority)) {\n var defaultPodsPriority = lodash.get(ConfigService, 'nuclio.defaultFunctionConfig.attributes.spec.priorityClassName', '');\n\n ctrl.selectedPodsPriority = lodash.isEmpty(defaultPodsPriority) ?\n lodash.find(ctrl.podsPriorityOptions, ['id', 'igz-workload-medium']) : defaultPodsPriority\n\n lodash.set(ctrl.version, 'spec.priorityClassName', ctrl.selectedPodsPriority.id);\n } else {\n ctrl.selectedPodsPriority = lodash.find(ctrl.podsPriorityOptions, ['id', podsPriority]);\n }\n }", "function updateAlphaInput() {\n\t\tlet hsvCol = new HSVColor (\n\t\t\tCPicker.markers.hue[0].angle,\n\t\t\tCPicker.markers.satv[0].sat,\n\t\t\tCPicker.markers.satv[0].val,\n\t\t\tctrPicker.alphaSlider.value\n\t\t);\n\t\t\n\t\tctrPicker.hexInput.value = hsvCol.getHexRGBA();\n\t\tctrPicker.alphaInput.value = (\n\t\t\tctrPicker.alphaSlider.value * 100\n\t\t).toFixed();\n\t}", "function displayInput(){\r\n\tdrawNewInput();\r\n\tscrollToEnd();\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the duplicated elements that come before the real budgie elements
updateListStart() { let numberAtTop; if (this.hasOddEnding()) { numberAtTop = this.numberLeftWithOddEnding(); } else { numberAtTop = this.isHorizontal() ? this.options.numberHigh : this.options.numberWide; } let realElements = Array.from(document.querySelectorAll(`.budgie-item-${this.budgieId}:not(.budgie-item-${this.budgieId}--duplicate)`)); // Trim the number of elements across one row to get rid of the bottom dupes let dupedElements = Array.from(document.querySelectorAll(`.budgie-item-${this.budgieId}.budgie-item-${this.budgieId}--duplicate`)); let topOfDupedElements = dupedElements.slice(0, dupedElements.length - this.elementsOnScreen()); // These elements should become the new duped top row let lastRowOfRealElements = realElements.slice(realElements.length - numberAtTop, realElements.length); const firstRealElement = realElements[0]; // If there are more existing elements than we need, then trim that list if(topOfDupedElements.length > lastRowOfRealElements.length) { let numberOff = topOfDupedElements.length - lastRowOfRealElements.length for(let i = 0; i < numberOff; i += 1) { topOfDupedElements[i].parentNode.removeChild(topOfDupedElements[i]); topOfDupedElements.shift(); } } // Exit early if the list is not long enough to scroll if(this.fitsInContainer()){ return; } // Update the existing elements, and add new if needed lastRowOfRealElements.forEach((element, index) => { let ele = element.cloneNode(true); ele.classList.add(`budgie-item-${this.budgieId}--duplicate`); if(topOfDupedElements[index]){ topOfDupedElements[index].outerHTML = ele.outerHTML } else { firstRealElement.parentNode.insertBefore(ele, firstRealElement); } }) }
[ "updateExistingItems(){\n this.items.forEach((item, index) => {\n Array.from(document.getElementsByClassName(`budgie-${this.budgieId}-${index}`)).forEach((element) => {\n // If the element has changed then update, otherwise do nothing\n\n let newElement = BudgieDom.createBudgieElement(this, item, index);\n // update the element if it does not currently match\n if (element.innerHTML !== newElement.innerHTML) {\n element.innerHTML = newElement.innerHTML;\n }\n });\n });\n }", "setItems(items){\n const currentFiller = this.numberLeftWithOddEnding()\n /**\n * Will return the indexes (from the old array) of items that were removed\n * @param oldArray\n * @param newArray\n */\n const removedIndexes = (oldArray, newArray) => {\n let rawArray = oldArray.map((oldItem, index) => {\n if(!newArray.some(newItem => newItem === oldItem)){\n return index;\n }\n })\n\n return rawArray.filter( index => (index || index === 0) );\n }\n\n\n /**\n * Will return the indexes (from the new array) of items that were added\n * @param oldArray\n * @param newArray\n */\n const addedIndexes = (oldArray, newArray) => {\n let rawArray = newArray.map((newItem, index) => {\n if(!oldArray.some(oldItem => oldItem === newItem)){\n return index;\n }\n })\n\n return rawArray.filter( index => (index || index === 0) );\n }\n\n\n this.previousItems = this.items.slice();\n this.items = items.slice();\n\n let indexesToRemove = removedIndexes(this.previousItems, this.items);\n let indexesToAdd = addedIndexes(this.previousItems, this.items);\n\n // console.log('add:', indexesToAdd, 'remove:', indexesToRemove)\n\n if(indexesToRemove.length > 0) {\n indexesToRemove.forEach(index => {\n this.removeLastItem(index);\n })\n }\n\n if(indexesToAdd.length > 0) {\n indexesToAdd.forEach(index => {\n this.addItemAtIndex(index);\n })\n }\n\n // When adding we have to update the index every time\n const realElements = Array.from(document.querySelectorAll(`.budgie-item-${this.budgieId}:not(.budgie-item-${this.budgieId}--duplicate)`));\n realElements.forEach((element, index) => {\n let className = Array.from(element.classList).filter(_className => _className.match(new RegExp(`budgie-${this.budgieId}-\\\\d`)));\n if(className !== `budgie-${this.budgieId}-${index}`) {\n element.classList.remove(className);\n element.classList.add(`budgie-${this.budgieId}-${index}`);\n }\n })\n\n // remove duplicate elements\n const dupedElements = Array.from(document.querySelectorAll(`.budgie-item-${this.budgieId}.budgie-item-${this.budgieId}--duplicate`));\n dupedElements.forEach(element => {\n element.parentNode.removeChild(element);\n })\n\n // remove filler elements\n const fillerElements = Array.from(document.querySelectorAll(`.budgie-item-${this.budgieId}--filler`));\n fillerElements.forEach(element => {\n element.parentNode.removeChild(element);\n })\n\n // Insert duplicated elements anew, if this is an infinite scroll\n if(this.options.infiniteScroll) {\n this.prependStartingItems();\n this.appendEndingItems();\n }\n\n // Add filler items to the end if needed\n if(this.numberLeftWithOddEnding() > 0) {\n realElements[realElements.length - this.numberLeftWithOddEnding()]\n .insertAdjacentElement('beforebegin', BudgieDom.createBudgieFillerElement(this))\n\n realElements[realElements.length - 1]\n .insertAdjacentElement('afterend', BudgieDom.createBudgieFillerElement(this))\n }\n\n this.clearMeasurements();\n this.budgieAnimate();\n }", "appendEndingItems(){\n let elementsOnScreen = this.elementsOnScreen();\n // Store a list of the non duplicated elements\n const realElements = Array.from(document.querySelectorAll(`.budgie-item-${this.budgieId}:not(.budgie-item-${this.budgieId}--duplicate)`));\n\n // If the number of elements is greater than the number that fit in the given area\n if(!this.fitsInContainer()){\n // Appends duplicate items equal to the number of elementsOnScreen\n realElements.slice(\n 0,\n elementsOnScreen\n )\n .forEach((element) => {\n let ele = element.cloneNode(true);\n ele.classList.add(`budgie-item-${this.budgieId}--duplicate`);\n ele.classList.add(`budgie-item-${this.budgieId}--duplicate-ending`);\n this.budgieContainer.insertAdjacentElement('beforeend', ele);\n });\n }\n }", "_compareAndCopy(newJst, topNode, jstComponent, forceUpdate, level) {\n let oldIndex = 0;\n let newIndex = 0;\n let itemsToDelete = [];\n let indicesToRemove = [];\n\n // console.log(\"CAC>\" + \" \".repeat(level*2), this.tag + this.id, newJst.tag+newJst.id);\n\n // Check to see if this the old and new node are the same\n if (this.id == newJst.id) {\n return false;\n }\n\n // First check the attributes, props and events\n // But only if we aren't the topNode\n if (!topNode) {\n if (forceUpdate || this.opts.forceUpdate || this.tag !== newJst.tag) {\n return true;\n }\n\n // Blindly copy the JST options\n this.opts = newJst.opts;\n \n // Just fix all the attributes inline\n for (let attrName of Object.keys(this.attrs)) {\n if (!newJst.attrs[attrName]) {\n delete this.attrs[attrName];\n if (this.isDomified) {\n this.el.removeAttribute(attrName);\n }\n }\n else if (newJst.attrs[attrName] !== this.attrs[attrName]) {\n this.attrs[attrName] = newJst.attrs[attrName];\n if (this.isDomified) {\n //refactor\n let val = newJst.attrs[attrName];\n if (this.jstComponent && (attrName === \"class\" || attrName === \"id\") &&\n val.match(/(^|\\s)-/)) {\n // Add scoping for IDs and Class names\n val = val.replace(/(^|\\s)(--?)/g,\n (m, p1, p2) => p1 + (p2 === \"-\" ?\n this.jstComponent.getClassPrefix() :\n this.jstComponent.getFullPrefix()));\n }\n this.el.setAttribute(attrName, val);\n }\n }\n }\n for (let attrName of Object.keys(newJst.attrs)) {\n if (!this.attrs[attrName]) {\n this.attrs[attrName] = newJst.attrs[attrName];\n if (this.isDomified) {\n //refactor\n let val = newJst.attrs[attrName];\n if (this.jstComponent && (attrName === \"class\" || attrName === \"id\") &&\n val.match(/(^|\\s)-/)) {\n // Add scoping for IDs and Class names\n val = val.replace(/(^|\\s)(--?)/g,\n (m, p1, p2) => p1 + (p2 === \"-\" ?\n this.jstComponent.getClassPrefix() :\n this.jstComponent.getFullPrefix()));\n }\n this.el.setAttribute(attrName, val);\n }\n }\n }\n\n if (this.props.length || newJst.props.length) {\n let fixProps = false;\n \n // Just compare them in order - if they happen to be the same,\n // but in a different order, we will do a bit more work than necessary\n // but it should be very unlikely that that would happen\n if (this.props.length != newJst.props.length) {\n fixProps = true;\n }\n else {\n for (let i = 0; i < this.props.length; i++) {\n if (this.props[i] !== newJst.props[i]) {\n fixProps = true;\n break;\n }\n }\n }\n \n if (fixProps) {\n if (this.isDomified) {\n for (let prop of this.props) {\n delete this.el[prop];\n }\n for (let prop of newJst.props) {\n this.el[prop] = true;\n }\n }\n this.props = newJst.props;\n }\n }\n \n // Fix all the events\n for (let eventName of Object.keys(this.events)) {\n if (!newJst.events[eventName]) {\n if (this.isDomified) {\n this.el.removeEventListener(eventName, this.events[eventName].listener);\n }\n delete this.events[eventName];\n }\n else if (newJst.events[eventName].listener !== this.events[eventName].listener) {\n if (this.isDomified) {\n this.el.removeEventListener(eventName, this.events[eventName].listener);\n this.el.addEventListener(eventName, newJst.events[eventName].listener);\n }\n this.events[eventName] = newJst.events[eventName];\n }\n }\n for (let eventName of Object.keys(newJst.events)) {\n if (!this.events[eventName]) {\n this.events[eventName] = newJst.events[eventName];\n if (this.isDomified) {\n this.el.addEventListener(eventName, newJst.events[eventName].listener);\n }\n }\n }\n \n }\n\n if (!forceUpdate && !this.opts.forceUpdate) {\n // First a shortcut in the case where all\n // contents are removed\n\n // TODO - can clear the DOM in one action, but\n // need to take care of the components so that they\n // aren't still thinking they are in the DOM\n // if (this.contents.length && !newJst.contents.length) {\n // if (this.el) {\n // this.el.textContent = \"\";\n // //this.contents = [];\n // //return false;\n // }\n // }\n \n \n // Loop through the contents of this element and compare\n // to the contents of the newly created element\n while (true) {\n let oldItem = this.contents[oldIndex];\n let newItem = newJst.contents[newIndex];\n\n if (!oldItem || !newItem) {\n break;\n }\n\n // Types of items in the contents must match or don't continue\n if (oldItem.type !== newItem.type) {\n break;\n }\n\n if (oldItem.type === JstElementType.JST_ELEMENT) {\n\n // This detects items that are being replaced by pre-existing items\n // They are too complicated to try to do in place replacements\n if (oldItem.value.id !== newItem.value.id && newItem.value._refCount > 1) {\n break;\n }\n \n // Descend into the JstElement and compare them and possibly copy their\n // content in place\n let doReplace = oldItem.value._compareAndCopy(newItem.value, false,\n jstComponent, undefined, level+1);\n if (doReplace) {\n break;\n }\n\n // Need to decrement the ref counts for items that didn't change\n if (oldItem.value.id === newItem.value.id) {\n this._deleteItem(newItem);\n }\n \n }\n else if (oldItem.type === JstElementType.JST_COMPONENT) {\n // If the tags are the same, then we must descend and compare\n if (oldItem.value._jstId !== newItem.value._jstId) {\n\n // Small optimization since often a list is modified with a\n // single add or remove\n\n let nextOldItem = this.contents[oldIndex+1];\n let nextNewItem = newJst.contents[newIndex+1];\n\n if (!nextOldItem || !nextNewItem) {\n // no value of optimizing when we are at the end of the list\n break;\n }\n\n if (nextNewItem.type === JstElementType.JST_COMPONENT &&\n oldItem.value._jstId === nextNewItem.value._jstId) {\n // We have added a single item - TBD\n let nextEl = oldItem.value._jstEl._getFirstEl();\n this._moveOrRenderInDom(newItem, jstComponent, nextEl);\n this.contents.splice(oldIndex, 0, newItem);\n newIndex++;\n oldIndex++;\n newItem = nextNewItem;\n }\n else if (nextOldItem.type === JstElementType.JST_COMPONENT &&\n nextOldItem.value._jstId === newItem.value._jstId) {\n // We have deleted a single item\n this.contents.splice(oldIndex, 1);\n itemsToDelete.push(oldItem);\n }\n else if (nextOldItem.type === JstElementType.JST_COMPONENT &&\n nextNewItem.type === JstElementType.JST_COMPONENT &&\n nextOldItem.value._jstId === nextNewItem.value._jstId) {\n // We have swapped in an item\n let nextEl = nextOldItem.value._jstEl._getFirstEl();\n this._moveOrRenderInDom(newItem, jstComponent, nextEl);\n this.contents[oldIndex] = newItem;\n oldIndex++;\n newIndex++;\n newItem = nextNewItem;\n itemsToDelete.push(oldItem);\n }\n else {\n break;\n }\n\n }\n\n // Don't bother descending into JstComponents - they take care of themselves\n \n }\n else if (oldItem.type === JstElementType.TEXTNODE) {\n\n if (oldItem.value !== newItem.value) {\n\n // For textnodes, we just fix them inline\n if (oldItem.el) {\n oldItem.el.textContent = newItem.value;\n }\n oldItem.value = newItem.value;\n }\n }\n\n oldIndex++;\n newIndex++;\n \n if (newItem.type === JstElementType.JST_COMPONENT) {\n // Unhook this reference\n newItem.value._unrender();\n }\n }\n }\n\n // Need to copy stuff - first delete all the old contents\n let oldStartIndex = oldIndex;\n let oldItem = this.contents[oldIndex];\n\n while (oldItem) {\n // console.log(\"CAC> \" + \" \".repeat(level*2), \"deleting old item :\", oldItem.value.tag, oldItem.value.id);\n itemsToDelete.push(oldItem);\n oldIndex++;\n oldItem = this.contents[oldIndex];\n }\n\n // Remove unneeded items from the contents list\n this.contents.splice(oldStartIndex, oldIndex - oldStartIndex);\n\n if (newJst.contents[newIndex]) {\n\n // Get list of new items that will be inserted\n let newItems = newJst.contents.splice(newIndex, newJst.contents.length - newIndex);\n\n //console.log(\"CAC> \" + \" \".repeat(level*2), \"new items being added:\", newItems);\n \n newItems.forEach(item => {\n if (item.type === JstElementType.JST_ELEMENT) {\n if (item.value.el && item.value.el.parentNode) {\n item.value.el.parentNode.removeChild(item.value.el);\n if (this.el) {\n this.el.appendChild(item.value.el);\n }\n else {\n delete(this.el);\n }\n }\n else if (this.el) {\n // Need to add it\n this.el.appendChild(item.value.dom(jstComponent));\n }\n else if (jstComponent && jstComponent.parentEl) {\n jstComponent.parentEl.appendChild(item.value.dom(jstComponent));\n }\n else {\n console.warn(\"Not adding an element to the DOM\", item.value.tag, item, this, jstComponent);\n }\n }\n else if (item.type === JstElementType.TEXTNODE) {\n if (this.el) {\n // Need to add it\n if (item.el) {\n if (item.el.parentNode) {\n item.el.parentNode.removeChild(item.el);\n }\n this.el.appendChild(item.el);\n }\n else {\n item.el = document.createTextNode(item.value);\n this.el.appendChild(item.el);\n }\n }\n else if (jstComponent && jstComponent.parentEl) {\n item.el = document.createTextNode(item.value);\n jstComponent.parentEl.appendChild(item.el);\n }\n else {\n console.warn(\"Not adding an element to the DOM\", item.value.tag, item, this, jstComponent);\n }\n }\n else if (item.type === JstElementType.JST_COMPONENT) {\n this._moveOrRenderInDom(item, jstComponent);\n }\n });\n this.contents.splice(oldStartIndex, 0, ...newItems);\n }\n\n for (let itemToDelete of itemsToDelete) {\n this._deleteItem(itemToDelete); \n } \n \n // console.log(\"CAC>\" + \" \".repeat(level*2), \"/\" + this.tag+this.id);\n return false;\n \n }", "function saveOriginalBuddiesOrder() {\n var length = buddiesColl.length;\n\n if (length && !buddiesColl.at(length - 1).get('originalIndex')) {\n buddiesColl.forEach(function (buddie, i) {\n buddie.set('originalIndex', i);\n });\n }\n}", "unify(p, q) {\n let root1 = this.find(q);\n let root2 = this.find(p);\n\n //these elements are already in the same group\n if (root1 === root2) return;\n\n //merge two components together\n //merge smaller component into the large one\n if (this.sz[root1] < this.sz[root2]) {\n this.sz[root2] += this.sz[root1];\n this.id[root1] = root2;\n } else {\n this.sz[root1] += this.sz[root2];\n this.id[root2] = root1;\n }\n\n this.numComponents--;\n }", "dedupeVertices() {\n const verts = bsy.VecUtils.toVec3Array(this.getVertices());\n const inds = this.getVertexIndices();\n const uniqueVerts = [];\n\n verts.forEach((v1, vertInd) => {\n // Check if the vertex exists in the array of unique vertices.\n const uniqueInd = uniqueVerts.findIndex(v2 => vec3.equals(v1, v2));\n\n if (uniqueInd === -1) {\n // New vertex encountered. Add it to the unique list of verts.\n uniqueVerts.push(v1);\n\n // Any index that previously pointed at this vertex needs to be\n // updated to point at the new index in the unique array.\n inds.forEach((ind, i, inds) => {\n if (ind === vertInd)\n inds[i] = uniqueVerts.length - 1;\n });\n }\n else {\n // Vertex found in the unique array. Point any indices that point at\n // the duplicate so that the point at the unique index.\n inds.forEach((ind, i, inds) => {\n if (ind === vertInd)\n inds[i] = uniqueInd;\n });\n }\n });\n\n this.getVertices().splice(0);\n this.getVertices().push(...bsy.VecUtils.flattenVec3Array(uniqueVerts));\n }", "function reorder() {\r\n var fromBottom;\r\n var tElements = $($(\"div.t-element\").get().reverse());\r\n tElements.each(function(index, element) {\r\n if (!fromBottom) fromBottom = $(element).outerHeight();\r\n $(element).css(\"bottom\", fromBottom + \"px\");\r\n fromBottom += $(element).outerHeight() + 10;\r\n });\r\n\r\n }", "function applyToDOM(){\n var hasSortedAll = elmObjsSorted.length===elmObjsAll.length;\n if (isSameParent&&hasSortedAll) {\n if (isFlex) {\n elmObjsSorted.forEach(function(elmObj,i){\n elmObj.elm.style.order = i;\n });\n } else {\n if (parentNode) parentNode.appendChild(sortedIntoFragment());\n else console.warn('parentNode has been removed');\n }\n } else {\n var criterium = criteria[0]\n ,place = criterium.place\n ,placeOrg = place==='org'\n ,placeStart = place==='start'\n ,placeEnd = place==='end'\n ,placeFirst = place==='first'\n ,placeLast = place==='last'\n ;\n if (placeOrg) {\n elmObjsSorted.forEach(addGhost);\n elmObjsSorted.forEach(function(elmObj,i) {\n replaceGhost(elmObjsSortedInitial[i],elmObj.elm);\n });\n } else if (placeStart||placeEnd) {\n var startElmObj = elmObjsSortedInitial[placeStart?0:elmObjsSortedInitial.length-1]\n ,startParent = startElmObj.elm.parentNode\n ,startElm = placeStart?startParent.firstChild:startParent.lastChild;\n if (startElm!==startElmObj.elm) startElmObj = {elm:startElm};\n addGhost(startElmObj);\n placeEnd&&startParent.appendChild(startElmObj.ghost);\n replaceGhost(startElmObj,sortedIntoFragment());\n } else if (placeFirst||placeLast) {\n var firstElmObj = elmObjsSortedInitial[placeFirst?0:elmObjsSortedInitial.length-1];\n replaceGhost(addGhost(firstElmObj),sortedIntoFragment());\n }\n }\n }", "function _updateElement() {\n\t\tself.observer.disconnect();\n\t\tself.element.innerHTML = self.history[self.index];\n\t\tself.observer.observe(self.element, OBSERVER_CFG);\n\t}", "function updateFromFilters(){\n\n //$(\"input\").prop('disabled', true);\n\n var newList = _(elements)\n .forEach(function(d){ map.removeLayer(d.marker) })\n .filter(computeFilter)\n .forEach(function(d){ d.marker.addTo(map) })\n .value();\n\n updateList(newList);\n updateFromMap();\n }", "function dupelements(arr,a,b){\n\tvar dup = []; \n for(var i=a+1;i<b;i++){\n\tdup.push(arr[i]);\n}\nreturn dup;}", "function addItemToCompare(el){\n console.log(\"add to compare button pressed!\")\n var listingID = el.parentNode.parentNode.id;\n \n console.log(listingID);\n console.log(strippedProductArray[listingID]);\n addUniqueItemToCompareList(strippedProductArray[listingID]);\n //var newCompareListItem = compareList.push();\n \n // var newCompareListItem = compareList.child(strippedProductArray[listingID].name);\n //newCompareListItem.set(strippedProductArray[listingID]); //console.log(productArray[listingID]);\n //compareList\n}", "function sacar(){\n \n var nuevo=productosSeleccionados(); \n var actual= viejos;\n eliminar = [];\n insertar=[];\n for (var i = 0; i < actual.length; i++) {\n var igual=false;\n for (var j = 0; j < nuevo.length & !igual; j++) {\n if(actual[i].ID_PRO == nuevo[j].ID_PRO) \n igual=true;\n }\n if(!igual) {\n var item={}; \n item.ID_PRO=actual[i].ID_PRO;\n eliminar.push(item);\n } \n //else insertar.push(nuevo[j]);\n }\n\n for (var i = 0; i < nuevo.length; i++) {\n var igual=false;\n for (var j = 0; j < actual.length & !igual; j++) {\n if(nuevo[i].ID_PRO == actual[j].ID_PRO) \n igual=true;\n }\n if(!igual){\n var item={}; \n item.ID_PRO=nuevo[i].ID_PRO;\n insertar.push(item);\n } \n //else insertar.push(nuevo[j]);\n }\n\n eliminar=removeDuplicates(eliminar,\"ID_PRO\");\n insertar=removeDuplicates(insertar,\"ID_PRO\");\n\n console.log(\"array para eliminar \"+JSON.stringify(eliminar));\n console.log(\"array para insertar \"+JSON.stringify(insertar));\n\n}", "add(...elements) {\n for (const element of elements) {\n if (this.set.indexOf(element) !== -1) {\n console.log(\"Element \" + element + \" already in set, skipping...\");\n } else {\n this.set.push(element);\n }\n }\n }", "function removeAllTheSameProducts(element) {\n element.closest('li.cart-item').remove();\n }", "relativeComplement(otherSet) {\n let newSet = new BetterSet();\n this.forEach(item => {\n if (!otherSet.has(item)) {\n newSet.add(item);\n }\n });\n return newSet;\n }", "cleanLineNumbers(element) {\n const elementCopy = element.cloneNode(true);\n const children = elementCopy.childNodes;\n // using for-of did not work as expected\n for (let i = 0; i < children.length; i++) {\n if (this.getLineNumber(children[i])) {\n children[i].remove();\n }\n if (children[i].childNodes.length > 0) {\n const cleanChildren = this.cleanLineNumbers(children[i]);\n elementCopy.replaceChild(cleanChildren, children[i]);\n }\n }\n return elementCopy;\n }", "function duplicateInput(e) {\n const value = bySel('.wo_input', e.target.parentNode).value;\n const node = createInput(value);\n byId('options').insertBefore(node, e.target.parentNode);\n updateWheel();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Variables used for iterating page numbers FUNCTIONS Set the extension on the sectionnav class name needed when first loading the web site and resizing
function setSectionExtension() { let currentWindow = null; currentWindow = checkWindowSize(); document.querySelector('.section-nav').classList.add(currentWindow); }
[ "function activateNavDots(name,sectionIndex){if(options.navigation&&$(SECTION_NAV_SEL)[0]!=null){removeClass($(ACTIVE_SEL,$(SECTION_NAV_SEL)[0]),ACTIVE);if(name){addClass($('a[href=\"#'+name+'\"]',$(SECTION_NAV_SEL)[0]),ACTIVE);}else{addClass($('a',$('li',$(SECTION_NAV_SEL)[0])[sectionIndex]),ACTIVE);}}}", "function addSlidesNavigation(section,numSlides){appendTo(createElementFromHTML('<div class=\"'+SLIDES_NAV+'\"><ul></ul></div>'),section);var nav=$(SLIDES_NAV_SEL,section)[0];//top or bottom\naddClass(nav,'fp-'+options.slidesNavPosition);for(var i=0;i<numSlides;i++){appendTo(createElementFromHTML('<li><a href=\"#\"><span class=\"fp-sr-only\">'+getBulletLinkName(i,'Slide')+'</span><span></span></a></li>'),$('ul',nav)[0]);}//centering it\ncss(nav,{'margin-left':'-'+nav.innerWidth/2+'px'});addClass($('a',$('li',nav)[0]),ACTIVE);}", "function calculateAndDisplayPageNavigationDots() {\n var noPages = numberOfPages();\n \n $(\".ql-pagenav\").attr(\"pages\", noPages);\n\n // if page dot doesn't exist, add\n for (var i = 0; i < noPages; i++) {\n if (!$(`.pagedot[pg='${i+1}']`).length) { $(\".ql-pagenav\").append(`<button class=\"pagedot\" pg=\"${i + 1}\"></button>`); }\n }\n\n // remove extra dots (i.e. if user deletes some stuff, and there's less pages)\n var dotsCount = $(\".ql-pagenav\").children().length;\n var extraDots = $(\".ql-pagenav\").children().slice(noPages, dotsCount);\n extraDots.remove();\n \n $(\".ql-pagenav\").removeClass(\"compact tiny\");\n if (noPages > 30) {\n $(\".ql-pagenav\").addClass(\"compact\");\n }\n\n checkIfPageChanged();\n}", "function redrawDotNav() {\n var scrollPosition = $(document).scrollTop();\n\n $('nav#primary a').removeClass('active');\n $('#main-nav li').removeClass('current_page_item');\n\n if (scrollPosition < (section2Top - menuBarHeight)) {\n $('nav#primary a.main').addClass('active');\n $('#main-nav li.menu-item-main').addClass('current_page_item');\n\n } else if (scrollPosition >= section2Top - menuBarHeight && scrollPosition < section3Top) {\n $('nav#primary a.experience').addClass('active');\n $('#main-nav li.menu-item-experience').addClass('current_page_item');\n\n } else if (scrollPosition >= section3Top && scrollPosition < section4Top) {\n $('nav#primary a.skills').addClass('active');\n $('#main-nav li.menu-item-skills').addClass('current_page_item');\n\n } else if (scrollPosition >= section4Top && scrollPosition < section5Top) {\n $('nav#primary a.training').addClass('active');\n $('#main-nav li.menu-item-training').addClass('current_page_item');\n\n } else if (scrollPosition >= section5Top && scrollPosition < section6Top) {\n $('nav#primary a.languages').addClass('active');\n $('#main-nav li.menu-item-languages').addClass('current_page_item');\n\n } else if (scrollPosition >= section6Top) {\n $('nav#primary a.contact').addClass('active');\n $('#main-nav li.menu-item-contact').addClass('current_page_item');\n }\n\n }", "function whenScroll() {\n for (let section of sections) {\n if (isInViewport(section)) {\n removeActiveClassFromSection(); //remove 'active_section' class from the previous active section\n section.classList.add('active_section'); //add 'active_section' class to the current active section\n\n //update the corresponding navigation link\n removeActiveClassFromLink(); //remove 'active' class from the previous active section\n let correspondingLink = searchMenuByText(section.getAttribute('data-nav'));\n correspondingLink.classList.add('active'); //add 'active' class to the corresponding link\n break;\n }\n }\n}", "function changeNavClass(nav_element) {\n document.getElementById(\"nav-about\").className = \"nav-icons\";\n document.getElementById(\"nav-research\").className = \"nav-icons\";\n document.getElementById(\"nav-publication\").className = \"nav-icons\";\n document.getElementById(\"nav-conference\").className = \"nav-icons\";\n document.getElementById(\"nav-teaching\").className = \"nav-icons\";\n\n document.getElementById(nav_element).className += \" active\";\n\n document.getElementById(\"location_icon\").className = \"fas fa-map-marker-alt\";\n document.getElementById(\"research_icon\").className = \"fa fa-flask fa-fw\";\n document.getElementById('book_icon').src=\"assets/images/icons/book-1.png\"\n document.getElementById(\"gear1\").style.display = \"none\";\n document.getElementById(\"gear2\").style.display = \"none\";\n\n }", "function setActivePage() {\n\t\t\tvar $carouselPage = $pager.find('.carousel-page');\n\t\t\t$carouselPage.each(function () {\n\t\t\t\t$(this).removeClass('current-page');\n\t\t\t\tif ($(this).index() == currentGroup) {\n\t\t\t\t\t$(this).addClass('current-page');\n\t\t\t\t}\n\t\t\t});\n\t\t}", "AsidePanelPages(){\n\t\t// All positions in navbar\n\t\tconst navs = document.querySelectorAll(\".pages-nav li\");\n\t\t// All pages\n\t\tconst pages = document.querySelectorAll(\".pages li\");\n\t\t// For each position add onclick function\n\t\tnavs.forEach((nav) => {\n\t\t\tnav.addEventListener(\"click\", () => {\n\t\t\t\tconst index = Array.from(navs).indexOf(nav);\n\t\t\t\t// Hide all active positions in navbar\n\t\t\t\tnavs.forEach((nav_item) => {\n\t\t\t\t\tnav_item.classList.remove(\"active\");\n\t\t\t\t});\n\t\t\t\t// Hide all active slides\n\t\t\t\tpages.forEach((page_item) => {\n\t\t\t\t\tpage_item.classList.remove(\"active\");\n\t\t\t\t});\n\t\t\t\t// Show active position in navbar and active page\n\t\t\t\tnav.classList.add(\"active\");\n\t\t\t\tpages[index].classList.add(\"active\");\n\t\t\t});\n\t\t});\n\t}", "function getPage() {\n\tvar sPath = window.location.pathname;\n\tvar sPage = sPath.substring(sPath.lastIndexOf('/') + 1);\n\tif (sPage == \"scheduled.jsf\") {\n\t\tdocument.getElementById(\"scheduledLink\").setAttribute(\"class\",\"active\");\n\t} else if (sPage == \"reports.jsf\") {\n\t\tdocument.getElementById(\"reportsLink\").setAttribute(\"class\",\"active\");\n\t} else {\n\t\tdocument.getElementById(\"homeLink\").setAttribute(\"class\",\"active\");\n\t}\n }", "function checkIfPageChanged() {\n if (!isPaperMode()) { return; }\n \n var scrollLeftPX = document.getElementsByClassName(\"ql-editor\")[0].scrollLeft || 0;\n var scrollLeftMM = px2mm(scrollLeftPX);\n\n var visiblePageNo = scrollLeftMM / (paper.width + paper.opticalSeparator);\n visiblePageNo = parseFloat(visiblePageNo.toFixed(1));\n\n $(\".pagedot\").removeClass(\"active\");\n \n var currentPageIndex = Math.floor(visiblePageNo);\n $(\".pagedot\").eq(currentPageIndex).addClass(\"active\");\n \n if (visiblePageNo % 1) { \n // some parts of next page is visible too\n $(\".pagedot\").eq(currentPageIndex + 1).addClass(\"active\");\n }\n}", "function setupPagingNavigationButtons(p_name, p_tpages, p_page) {\n var l_next_obj = jQuery('#' + p_name + '_Pager_center').find('td[id=\"next_' + p_name + '_Pager\"]');\n var l_first_obj = jQuery('#' + p_name + '_Pager_center').find('td[id=\"first_' + p_name + '_Pager\"]');\n var l_last_obj = jQuery('#' + p_name + '_Pager_center').find('td[id=\"last_' + p_name + '_Pager\"]');\n var l_prev_obj = jQuery('#' + p_name + '_Pager_center').find('td[id=\"prev_' + p_name + '_Pager\"]');\n\n if (p_tpages > 1) {\n if (p_page != p_tpages) {\n l_next_obj.removeClass('ui-state-disabled');\n l_last_obj.removeClass('ui-state-disabled');\n }\n if (p_page > 1) {\n l_prev_obj.removeClass('ui-state-disabled');\n l_first_obj.removeClass('ui-state-disabled');\n }\n }\n }", "function changeNav(total,startpage) {\r\n\tif (total > noi) {//results does not fit into one page\r\n\t\tvar html = \"\";\r\n\t\tvar startNum = cachePageNum-Math.floor(nop/2);\r\n\t\tvar totalPage = Math.ceil(total/noi);\r\n var displayTargetPage=\"\";\r\n if(document.getElementById('live_updateArea'))\r\n displayTargetPage=\"result-cached.html\";\r\n else\r\n displayTargetPage=\"result-offline.html\";\r\n\r\n\t\tif (startNum < 1)\r\n\t\t\tstartNum = 1;\r\n\t\tfor (var i = startNum; i < Math.min(nop+startNum,totalPage+1); i++) {\r\n\t\t\tif (i != cachePageNum)\r\n\t\t\t\thtml += ' <a href=\"'+displayTargetPage+'?cp='+i+'&lp='+livePageNum+'&s='+searchString+'\">'+i+'</a> ';\r\n\t\t\telse\r\n\t\t\t\thtml += ' '+i+' ';\r\n\t\t}\r\n\t\tif (cachePageNum != 1)\r\n\t\t\thtml='<a href=\"'+displayTargetPage+'?cp='+(cachePageNum-1)+'&lp='+livePageNum+'&s='+searchString+'\">Previous</a> &nbsp; &nbsp; &nbsp; &nbsp; '+html;\r\n\t\tif (cachePageNum != totalPage)\r\n\t\t\thtml += '&nbsp; &nbsp; &nbsp; &nbsp; <a href=\"'+displayTargetPage+'?cp='+(cachePageNum+1)+'&lp='+livePageNum+'&s='+searchString+'\">Next</a>';\r\n\t\tdocument.getElementById('nav').innerHTML=html;\r\n\t}\r\n}", "function switchPageStatus() {\n if(currPageNo === 1)\n $(\"div#pagination>ul>li#firstPage\").addClass(\"disabled\");\n else\n $(\"div#pagination>ul>li#firstPage\").removeClass(\"disabled\");\n if(currPageNo > 1)\n $(\"div#pagination>ul>li#prevPage\").removeClass(\"disabled\");\n else\n $(\"div#pagination>ul>li#prevPage\").addClass(\"disabled\");\n if(currPageNo < currMaxPage)\n $(\"div#pagination>ul>li#nextPage\").removeClass(\"disabled\");\n else\n $(\"div#pagination>ul>li#nextPage\").addClass(\"disabled\");\n if(currPageNo === currMaxPage)\n $(\"div#pagination>ul>li#lastPage\").addClass(\"disabled\");\n else\n $(\"div#pagination>ul>li#lastPage\").removeClass(\"disabled\");\n }", "function saveNavPanels() {\n var basePath = getBaseUri(location.pathname);\n var section = basePath.substring(1,basePath.indexOf(\"/\",1));\n writeCookie(\"height\", resizePackagesNav.css(\"height\"), section);\n}", "function initProgress()\n{\n /* Count the number of slides, give each slide a number */\n numslides = 0;\n for (const h of document.body.children)\n if (isStartOfSlide(h)) h.b6slidenum = ++numslides; // Save number in element\n\n /* Find all elements that are progress bars, unhide them. */\n progressElts = document.getElementsByClassName(\"progress\");\n for (const e of progressElts)\n if (typeof e.b6savedstyle === \"string\") e.style.cssText = e.b6savedstyle;\n\n /* Find all that should contain the current slide number, unhide them. */\n slidenumElts = document.getElementsByClassName(\"slidenum\");\n for (const e of slidenumElts)\n if (typeof e.b6savedstyle === \"string\") e.style.cssText = e.b6savedstyle;\n\n /* Find all that should contain the # of slides, fill and unhide them. */\n for (const e of document.getElementsByClassName(\"numslides\")) {\n if (typeof e.b6savedstyle == \"string\") e.style.cssText = e.b6savedstyle;\n e.textContent = numslides;\t// Set content to number of slides\n }\n\n /* Set the # of slides in a CSS counter on the BODY. */\n document.body.style.setProperty('counter-reset', 'numslides ' + numslides);\n\n}", "function initPage(){\r\n\t\t//add head class\r\n\t\t$(\"#headAssemblyLi\").addClass(\"active\");\r\n\t\t$(\"#leftNodeSelectLi\").addClass(\"active\");\r\n\t\tresetPage();\r\n\t\t$(\"#messageAlert, #messageLane\").hide();\r\n\t}", "function paginate() {\n var prev = document.querySelector(\"link[rel=prev]\");\n var next = document.querySelector(\"link[rel=next]\");\n var nav = document.createElement(\"nav\");\n nav.id = \"pagination\";\n if (prev)\n nav.innerHTML = \"<a class=prev href=\" + prev.href + \">\" + prev.title + \"</a>\";\n if (next)\n nav.innerHTML += \"<a class=next href=\" + next.href + \">\" + next.title + \"</a>\";\n if (prev || next)\n document.body.appendChild(nav);\n}", "function changePage(num) {\n const newPage = pageNum + num;\n if (newPage < 1 || newPage > pdfDoc.numPages) return;\n pageNum = newPage;\n setArrows(); //Hide and show arrow buttons according to the page number\n queueRenderPage(pageNum);\n}", "function setNavData()\n{\n //Calling the appropriate function to load header and footer based on the title of the page\n if (document.title == \"BIOPAGE\" || document.title == \"CONTACT\" || document.title == \"PROJECTS\") \n {\n loadHeader();\n loadFooter(); \n } \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete call from existing calls and make next call as current
function deleteCall(callId) { var callToDelete = self.get(callId); if(callToDelete) { for (var i = self.calls.length - 1; i >= 0; i--) { if (self.calls[i].id == callId) { self.calls.splice(i, 1); } } if(self.currentCall.id == callId) { self.currentCall = null; //make previous call as current for (var id in self.calls) { self.currentCall = self.calls[id]; break; } } } }
[ "function qNext() {\n var o = deferreds.shift(); //remove first element\n\n if( o ){\n o.deferred\n .fail(function( xml, textStatus ){\n qNext();\n });\n o.deferred\n .done(function( xml, textStatus ){\n recombined.push({\n xml: xml,\n category: o.category,\n index: o.index\n });\n self.setState({ data: recombined });\n qNext();\n });\n }\n }", "function populateWayRelationRefs (cb) {\n var pending = 0\n var error\n for (var i = 0; i < ops.length; i++) {\n if (ops[i].type === 'del') {\n pending++\n updateRefs(ops[i].id, ops[i].links, ops[i].value, function (err) {\n if (err) error = err\n if (!--pending) cb(error)\n })\n }\n }\n if (!pending) cb()\n }", "delete () {\n\t\t// This is to call the parent class's delete method\n\t\tsuper.delete();\n\n\t\t// Remove all remaining chain links\n\t\twhile (this.chains.length > 0) this.removeLastChain();\n\n\t\t// Clear the class's hook instance.\n\t\tHook.hookElement = null;\n\t}", "deleteMultiple() {}", "function clearCurrentQuery() {\n // don't clear the history if existing queries are already running\n if (cwQueryService.executingQuery.busy || pastQueries.length == 0)\n return;\n\n pastQueries.splice(currentQueryIndex,1);\n if (currentQueryIndex >= pastQueries.length)\n currentQueryIndex = pastQueries.length - 1;\n\n lastResult.copyIn(pastQueries[currentQueryIndex]);\n\n saveStateToStorage(); // save current history\n }", "deleteFirst(){\n return this.values.length > 0 ? new PlayQueue(this.values.slice(1)) : this;\n }", "removeFront() {\n this._taskArr.shift();\n /*\n if(this._taskArr.length === 1) {\n \n } else if(this._taskArr.length > 1) {\n let curr = this._taskArr[0];\n let next = this._taskArr[1];\n next.setStartTime(curr.startTime);\n this._taskArr.shift();\n }\n */\n }", "function stopCall() {\n // quit the current conference room\n bc.quitRoom(room);\n}", "function clearHistory() {\n // don't clear the history if existing queries are already running\n if (cwQueryService.executingQuery.busy)\n return;\n\n lastResult.copyIn(dummyResult);\n pastQueries.length = 0;\n currentQueryIndex = 0;\n\n saveStateToStorage(); // save current history\n }", "function reset(method, key) {\n if (exports.results.has(method)) {\n if (key)\n return exports.results.get(method).del(key);\n else\n return exports.results.get(method).reset();\n }\n}", "function KeepPoppingEmContacts(personToProcess) {\n\n console.log(\"People to be processed: \" + peopleBeingProcessed.length);\n ///Traverse people to contact list, sending texts to each one.\n //Pop from array if Declined or timed out. Stop if empty or accepted\n if (personToProcess.GetEmergencyContacts().length <= 0) {\n //Find person to remove from our array and remove them\n for (i = 0; i < peopleBeingProcessed.length; i++) {\n if (peopleBeingProcessed[i].number == personToProcess.number) personToProcess.splice\n }\n return NoContactsLeft();\n }\n else {\n contact = personToProcess.GetContact();\n // console.log(\"Contacts name is: \" + contact.number);\n TwilioTools.SendText({\n fromName: personToProcess.name, fromPhoneNumber: personToProcess.number,\n toName: \"\", toNumber: contact.number, Location: personToProcess.location\n })\n\n ///Once text message is sent out and nothing has happened, call this function again to get the next user\n setTimeout(function(){KeepPoppingEmContacts(personToProcess)}, 100000); ///6000m = 6 seconds, sets how long this should timeout for \n }\n}", "SHIFT_REQUEST(state, url = null, method = null) {\n const index = state.ajaxQueue.indexOf(`${url}_${method}`)\n\n url && method && index !== -1\n ? state.ajaxQueue.splice(index, 1)\n : state.ajaxQueue.pop()\n }", "_removeItem(item) {\n if (this.head === item) {\n this.head = item.next;\n }\n if (this.tail === item) {\n this.tail = item.prev;\n }\n if (item.prev) {\n item.prev.next = item.next;\n }\n if (item.next) {\n item.next.prev = item.prev;\n }\n delete this.map[item.key];\n this.length -= 1;\n }", "function removeCommand(index) {\n\t\tbuffer.splice(index, 1);\n\t\t\n\t\tvar previous = buffer[index - 1];\n\t\tvar next = buffer[index];\n\t\t\n\t\tif(previous && next) {\n\t\t\tif(mergeCommands(previous, next))\n\t\t\t\tremoveCommand(buffer.indexOf(next));\n\t\t}\n\t}", "async transferToCall(transferTargetCall) {\n const targetProfileInfo = await this.client.getProfileInfo(transferTargetCall.getOpponentMember().userId);\n const transfereeProfileInfo = await this.client.getProfileInfo(this.getOpponentMember().userId);\n const newCallId = genCallID();\n const bodyToTransferTarget = {\n // the replacements on each side have their own ID, and it's distinct from the\n // ID of the new call (but we can use the same function to generate it)\n replacement_id: genCallID(),\n target_user: {\n id: this.getOpponentMember().userId,\n display_name: transfereeProfileInfo.display_name,\n avatar_url: transfereeProfileInfo.avatar_url\n },\n await_call: newCallId\n };\n await transferTargetCall.sendVoipEvent(_event.EventType.CallReplaces, bodyToTransferTarget);\n const bodyToTransferee = {\n replacement_id: genCallID(),\n target_user: {\n id: transferTargetCall.getOpponentMember().userId,\n display_name: targetProfileInfo.display_name,\n avatar_url: targetProfileInfo.avatar_url\n },\n create_call: newCallId\n };\n await this.sendVoipEvent(_event.EventType.CallReplaces, bodyToTransferee);\n await this.terminate(CallParty.Local, CallErrorCode.Replaced, true);\n await transferTargetCall.terminate(CallParty.Local, CallErrorCode.Replaced, true);\n }", "function removeCandidatePosition() {\n \t candidatePositions.pop();\n \t numCandidates -= 1;\n } // removeCandidatePosition", "function undoSentRequests() {\n clickNextButton(\"Undo\", defaultUndoFriendSelector);\n}", "deletedVisit(responseData) {\n\t\t//Refresh the visit list. Yes, I am lazy.\n\t\tthis.loadVisits();\n\t\tthis.hideVisit();\n\t}", "deleteRuleset() {\n var rulesets = this.state.rulesets\n\n rulesets.splice(this.state.currentRuleset, 1) // Deletes the ruleset at the currentRuleset index\n\n if (rulesets.length > 0) { // If there is still more rulesets, just set currentRuleset to one less than before\n this.setState({rulesets: rulesets, currentRuleset: this.state.currentRuleset-1}, () => {\n this.updateData()\n })\n } else { // If there are no more rulesets, add an empty one and set currentRuleset to 0\n rulesets.push([\"placeholder\"])\n this.setState({rulesets: rulesets, currentRuleset: 0}, () => {\n this.updateData()\n })\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Toggle visibility of two div elements
function toggleDivs(elementToHide, elementToShow) { elementToHide.style.display = "none"; elementToShow.style.display = "block"; }
[ "function _toggleVisibility() {\n\n\t\tvisible = !visible;\n\n\t\tif (true === visible) {\n\t\t\tpanel.show();\n\t\t\t$(\"#phpviewlog-preview-icon\").addClass(\"active\");\n\t\t\tWorkspaceManager.recomputeLayout();\n\t\t} else {\n\t\t\tpanel.hide();\n\t\t\t$(\"#phpviewlog-preview-icon\").removeClass(\"active\");\n\t\t}\n\t}", "function toggleBetween(obj1, obj2) {\n\ttoggle(obj1);\n\ttoggle(obj2);\n}", "function toggleEvents() {\n events.style.display = events.style.display == \"none\" ? \"\" : \"none\";\n}", "function alternateDisplay(obj1,obj2)\n{\n obj1.style.display=\"inline\";\n obj2.style.display=\"none\";\n}", "function toggleToCompBoard(evt) {\n gameBoard1.style.display = \"none\";\n gameBoard2.style.display = \"\";\n compHeader.style.display = \"\";\n playerHeader.style.display = \"none\";\n}", "toggleButtons() {\n document.getElementById(\"newPinboard\").style.visibility = \"hidden\";\n document.getElementById(\"newPostIt\").style.visibility = \"visible\";\n }", "function switchItem2(toHide, toShow) {\r\n hideItem(toHide);\r\n showItem(toShow);\r\n}", "function toggleH264VisibleBlocks() {\r\n var switcher = checkH264();\r\n if (switcher) {\r\n $(\"#video-themes-coming-soon-note\").css('display', 'none');\r\n $(\"#video-themes-coming-soon-block\").css('display', 'block');\r\n }\r\n else {\r\n $(\"#video-themes-coming-soon-note\").css('display', 'block');\r\n $(\"#video-themes-coming-soon-block\").css('display', 'none');\r\n $(\".hideForWebm\").css(\"display\", \"none\");\r\n }\r\n}", "function showGridOne() {\n if (!gridOneVisible) {\n gridOne.style.display = \"inline\";\n gridTwo.style.display = \"none\";\n gridOneVisible = true;\n gridTwoVisible = false;\n }\n return null;\n}", "function toggle() {\n document.getElementById(\"logo\").classList.toggle(\"hide\");\n document.getElementById(\"name\").classList.toggle(\"visible\");\n}", "reverseVisibility(){\n for(let i = 0; i < this.children[2].children.length; i++){\n this.children[2].children[i].visible = !this.children[2].children[i].visible;\n }\n }", "toggleAll() {\n if (this.display_mode === 'hidden') this.showAll();\n else if (this.display_mode === 'shown') this.hideAll();\n }", "toggleDepartedColumn(){\n \t$('.departed-bucket').toggle();\n \t$('.chat-bucket').toggle();\n\t}", "function unhide()\r\n{\r\n if (document.querySelector('.pumpkin').style.visibility == \"visible\")\r\n {\r\n document.querySelector('.pumpkin').style.visibility = \"hidden\";\r\n }\r\n else\r\n {\r\ndocument.querySelector('.pumpkin').style.visibility = \"visible\";\r\n }\r\n}", "function toggleSlideShow() {\n $(\"#ss-full, #ss-scroll div\").toggleClass(\"ss-scroll-down\");\n}", "function toggle_users() {\n $(\"#users\").toggle();\n}", "function showDiv(song) {\n let buttonOne = document.getElementsByClassName(\"playlistButton\");\n let buttonTwo = document.getElementsByClassName(\"queueButton\")\n if (buttonOne[0].style.display == \"none\" && buttonTwo[0].style.display == \"none\") {\n buttonOne[0].style.setProperty(\"display\", \"block\")\n buttonTwo[0].style.setProperty(\"display\", \"block\")\n }\n else {\n buttonOne[0].style.setProperty(\"display\", \"none\")\n buttonTwo[0].style.setProperty(\"display\", \"none\")\n }\n }", "function toggle_display(idname)\n{\n\tobj = fetch_object(idname);\n\tif (obj)\n\t{\n\t\tif (obj.style.display == \"none\")\n\t\t{\n\t\t\tobj.style.display = \"\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tobj.style.display = \"none\";\n\t\t}\n\t}\n\treturn false;\n}", "function hide(card1, card2){\n\n //hide the cards\n card1.removeClass(\"open show\");\n card2.removeClass(\"open show\");\n\n //reset opened cards list\n openedCards = [];\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes a graphical a diff between the expected and actual images by rendering each to a canvas, getting the image data, and comparing the RGBA components of each pixel. The output is put into the diff canvas, with identical pixels appearing at 12.5% opacity and different pixels being highlighted in red.
function updateImageDiff() { if (currentExpectedImageTest != currentActualImageTest) return; var expectedImage = $('expected-image'); var actualImage = $('actual-image'); function getImageData(image) { var imageCanvas = document.createElement('canvas'); imageCanvas.width = image.width; imageCanvas.height = image.height; imageCanvasContext = imageCanvas.getContext('2d'); imageCanvasContext.fillStyle = 'rgba(255, 255, 255, 1)'; imageCanvasContext.fillRect( 0, 0, image.width, image.height); imageCanvasContext.drawImage(image, 0, 0); return imageCanvasContext.getImageData( 0, 0, image.width, image.height); } var expectedImageData = getImageData(expectedImage); var actualImageData = getImageData(actualImage); var diffCanvas = $('diff-canvas'); var diffCanvasContext = diffCanvas.getContext('2d'); var diffImageData = diffCanvasContext.createImageData(diffCanvas.width, diffCanvas.height); // Avoiding property lookups for all these during the per-pixel loop below // provides a significant performance benefit. var expectedWidth = expectedImage.width; var expectedHeight = expectedImage.height; var expected = expectedImageData.data; var actualWidth = actualImage.width; var actual = actualImageData.data; var diffWidth = diffImageData.width; var diff = diffImageData.data; var hadDiff = false; for (var x = 0; x < expectedWidth; x++) { for (var y = 0; y < expectedHeight; y++) { var expectedOffset = (y * expectedWidth + x) * 4; var actualOffset = (y * actualWidth + x) * 4; var diffOffset = (y * diffWidth + x) * 4; if (expected[expectedOffset] != actual[actualOffset] || expected[expectedOffset + 1] != actual[actualOffset + 1] || expected[expectedOffset + 2] != actual[actualOffset + 2] || expected[expectedOffset + 3] != actual[actualOffset + 3]) { hadDiff = true; diff[diffOffset] = 255; diff[diffOffset + 1] = 0; diff[diffOffset + 2] = 0; diff[diffOffset + 3] = 255; } else { diff[diffOffset] = expected[expectedOffset]; diff[diffOffset + 1] = expected[expectedOffset + 1]; diff[diffOffset + 2] = expected[expectedOffset + 2]; diff[diffOffset + 3] = 32; } } } diffCanvasContext.putImageData( diffImageData, 0, 0, 0, 0, diffImageData.width, diffImageData.height); diffCanvas.className = ''; if (!hadDiff) { diffCanvas.style.display = 'none'; $('diff-checksum').style.display = ''; loadTextResult(currentExpectedImageTest, 'expected-checksum'); loadTextResult(currentExpectedImageTest, 'actual-checksum'); } }
[ "function compareImages(image1base64, image2base64) {\n resemble(image1base64)\n .compareTo(image2base64)\n .ignoreColors()\n .onComplete(function(data) {\n var output = data.getImageDataUrl();\n splitImage(callback, output)\n });\n}", "function updateDiffImage()\n{\n var image = new Image;\n var canvas = document.querySelector(\"canvas#Canvas3\"),\n context = canvas.getContext(\"2d\");\n context.clearRect(0, 0,651,651);\n contextZoom3.clearRect(0, 0,651,651);\n let imageDiff = d3.select(\"#image-diff\").select(\"img\").attr(\"src\");\n image.src = imageDiff;\n image3.src = imageDiff;\n image.onload = load;\n image3.onload = loadZoom3;\n\n function load() {\n\n context.drawImage(this, 0, 0,294,294);\n }\n\n}", "function pixelEq (p1, p2) {\n const epsilon = 0.002;\n for (let i = 0; i < 3; ++i) {\n if (Math.abs(p1[i] - p2[i]) > epsilon) {\n return false;\n }\n }\n return true;\n}", "function colorBasedOnDiff(diff, left, a) {\n var v = !left || Math.abs(diff) > left ? 1\n : 200 * Math.sqrt(Math.abs(diff / left));\n if (diff >= 0)\n return color_1[\"default\"].rgb(200, 200 - v, 200 - v).alpha(a);\n return color_1[\"default\"].rgb(200 - v, 200, 200 - v).alpha(a);\n}", "wholePaintingCompare(data){\n let dataColorValues = dataParser(data);\n let matchPercent = 0;\n let matchTotals = 0;\n for (var i = 0; i < dataColorValues.length; i++) {\n let compareValue = this.singleColorCompare(dataColorValues[i].hex);\n if (compareValue != 0) {\n matchTotals++;\n }\n if (compareValue < dataColorValues[i].percent) {\n matchPercent += compareValue;\n } else {\n matchPercent += dataColorValues[i].percent\n }\n }\n return {\"percent\": matchPercent, \"total\": matchTotals};\n }", "getAverageImageColor(image) {\n let ctx = document.createElement('canvas').getContext('2d');\n\n ctx.canvas.width = CANVAS_WIDTH;\n ctx.canvas.height = CANVAS_WIDTH * image.height/image.width;\n\n // ctx.canvas.height = ctx.canvas.width * (image.height/image.width);\n ctx.drawImage(image, 0, 0, ctx.canvas.width, ctx.canvas.height);\n\n let data = ctx.getImageData(0,0,ctx.canvas.width,ctx.canvas.height),\n color = [0,0,0],\n hex = \"\",\n contrast = 0;\n\n for (let i = 0; i <= data.data.length - 1; i+=4) {\n if (data.data[i+3] != 1) {\n color[0] += data.data[i];\n color[1] += data.data[i+1];\n color[2] += data.data[i+2];\n }\n }\n\n color[0] = Math.round(color[0] / ((data.data.length - 1)/4)) * 2;\n color[1] = Math.round(color[1] / ((data.data.length - 1)/4)) * 2;\n color[2] = Math.round(color[2] / ((data.data.length - 1)/4)) * 2;\n\n let coloring = color.map((colors) => {\n if (colors > 255) return 255;\n return colors;\n });\n\n hex = this.rgbToHex(coloring[0],coloring[1],coloring[2]);\n this.GraphCore.App.Project.settings.startColor = hex;\n\n return hex;\n }", "function renderCompareImage(src, height, alt, className, parentQuery) {\n\n var imgDiv = document.createElement(\"div\")\n imgDiv.className = className\n\n var img = document.createElement(\"img\");\n \t\t\timg.src = src;\n \t\t\timg.style.height = height*5 + \"px\";\n \t\t\timg.alt = alt;\n\n \t\t\timgDiv.appendChild(img)\n\n \t\t\tvar parent = document.querySelector(parentQuery)\n \t\t\tparent.appendChild(imgDiv)\n }", "function checkMatch() {\n\tif (imageTwo != null && imageOne.attr('src') != imageTwo.attr('src')) {\n\t\tsetTimeout(hideImages,500);\n\t\tsetTimeout(resetImages,600);\n\t\tsetTimeout(incrementMoves,600);\n\t} else if (imageTwo != null && imageOne.attr('src') === imageTwo.attr('src')) {\n\t\tmatches++;\n\t\t$(imageOne).attr('alt','matched');\n\t\t$(imageTwo).attr('alt','matched');\n\t\tsetTimeout(resetImages,100);\n\t\tsetTimeout(incrementMoves,100);\n\t}\n}", "function overlay()\r\n{\r\n img[i].resize(vScale, vScale);\r\n img[i].loadPixels();\r\n loadPixels();\r\n\r\n for (var y = 0; y < img[i].height; y++) {\r\n for (var x = 0; x < img[i].width; x++) {\r\n \r\n var index = (x + y * img[i].width)*4\r\n var r = img[i].pixels[index+0];\r\n var g = img[i].pixels[index+1];\r\n var b = img[i].pixels[index+2];\r\n \r\n var bright = (r+g+b)/3;\r\n \r\n var threshold = 35;\r\n \r\n var checkIndex = x + y * cols;\r\n \r\n if (bright < threshold)\r\n {\r\n boxes[checkIndex].checked(false);\r\n } else {\r\n boxes[checkIndex].checked(true);\r\n }\r\n\r\n noStroke();\r\n rectMode(CENTER);\r\n rect(x*vScale, y*vScale, vScale, vScale);\r\n }\r\n } \r\n}", "function findDistances (img) {\n img.get = imgGet\n img.set = imgSet\n var view = new DataView(img.data.buffer)\n var nx = img.width\n var ny = img.height\n\n function distance (g, x, y, i) {\n return ((y - i) * (y - i) + g[i][x] * g[i][x])\n }\n\n function intersection (g, x, y0, y1) {\n return ((g[y0][x] * g[y0][x] - g[y1][x] * g[y1][x] + y0 * y0 - y1 * y1) / (2.0 * (y0 - y1)))\n }\n //\n // allocate arrays\n //\n var g = []\n for (var y = 0; y < ny; ++y) { g[y] = new Uint32Array(nx) }\n var h = []\n for (var y = 0; y < ny; ++y) { h[y] = new Uint32Array(nx) }\n var distances = []\n for (var y = 0; y < ny; ++y) { distances[y] = new Uint32Array(nx) }\n var starts = new Uint32Array(ny)\n var minimums = new Uint32Array(ny)\n //\n // column scan\n //\n for (var y = 0; y < ny; ++y) {\n //\n // right pass\n //\n var closest = -nx\n for (var x = 0; x < nx; ++x) {\n if (img.get(y, x, STATE) & INTERIOR) {\n g[y][x] = 0\n closest = x\n } else { g[y][x] = (x - closest) }\n }\n //\n // left pass\n //\n closest = 2 * nx\n for (var x = (nx - 1); x >= 0; --x) {\n if (img.get(y, x, STATE) & INTERIOR) { closest = x } else {\n var d = (closest - x)\n if (d < g[y][x]) { g[y][x] = d }\n }\n }\n }\n //\n // row scan\n //\n for (var x = 0; x < nx; ++x) {\n var segment = 0\n starts[0] = 0\n minimums[0] = 0\n //\n // down\n //\n for (var y = 1; y < ny; ++y) {\n while ((segment >= 0) &&\n (distance(g, x, starts[segment], minimums[segment]) > distance(g, x, starts[segment], y))) { segment -= 1 }\n if (segment < 0) {\n segment = 0\n minimums[0] = y\n } else {\n newstart = 1 + intersection(g, x, minimums[segment], y)\n if (newstart < ny) {\n segment += 1\n minimums[segment] = y\n starts[segment] = newstart\n }\n }\n }\n //\n // up\n //\n for (var y = (ny - 1); y >= 0; --y) {\n var d = Math.sqrt(distance(g, x, y, minimums[segment]))\n view.setUint32((img.height - 1 - y) * 4 * img.width + x * 4, d)\n if (y === starts[segment]) { segment -= 1 }\n }\n }\n}", "function greenColor(){\n if(fgImg==null){\n alert(\"Image not loaded\");\n }else{\n for(var pixel of greenImg.values()){\n var avg = (pixel.getRed()+pixel.getBlue()+pixel.getGreen())/3;\n if(avg<128){\n pixel.setRed(0);\n pixel.setGreen(2*avg);\n pixel.setBlue(0);\n }else{\n pixel.setRed(2*avg-255);\n pixel.setBlue(2*avg-255);\n pixel.setGreen(255);\n }\n }\n greenImg.drawTo(canvas);\n}\n}", "function colorMatch(a, b) {\r\n return a.r === b.r && a.g === b.g && a.b === b.b && a.a === b.a\r\n }", "function blankAndWhite(){\n if(fgImg==null){\n alert(\"Image not loaded\");\n }else{\n for(var pixel of greyImg.values()){\n var avg = (pixel.getRed()+pixel.getBlue()+pixel.getGreen())/3;\n pixel.setRed(avg);\n pixel.setBlue(avg);\n pixel.setGreen(avg);\n }\n greyImg.drawTo(canvas);\n }\n}", "function renderPixel(i, j, objects, ctx) {\n let totalColor = [0, 0, 0]; // r, g, b\n\n // for each sub-pixel, cast a ray and compute color (supersampling)\n for (let ic = i; ic < i + 1; ic += (1 / samplingWidth)) {\n for (let jc = j; jc < j + 1; jc += (1 / samplingHeight)) {\n // cast a ray (random position within the sub-pixel)\n const u = (l + (r - l) * (ic + (Math.random() / samplingWidth)) / nx) * imageAspectRatio;\n const v = b + (t - b) * (jc + (Math.random() / samplingHeight)) / ny;\n const rayOrigin = vec3.fromValues(3, 0, 15);\n let rayDirection = vec3.fromValues(u, v, -d);\n vec3.normalize(rayDirection, rayDirection);\n const ray = new Ray(rayOrigin, rayDirection);\n\n // compute and accumulate color of sub-pixels\n const finalColor = subpixelColor(ray, objects, 0);\n for (let c = 0; c < 3; c++) {\n totalColor[c] += finalColor[c];\n }\n }\n }\n // compute average color of the pixel\n let averageColor = [];\n for (let c = 0; c < 3; c++) {\n averageColor[c] = totalColor[c] / (samplingWidth * samplingHeight);\n }\n\n ctx.fillStyle = \"rgb(\" + averageColor[0] + \", \" + averageColor[1] +\n \", \" + averageColor[2] + \")\";\n ctx.fillRect(i, ny - 1 - j, 1, 1);\n}", "static hash(imageData, canvas) {\n let size = Average.size,\n pixelCount = (size * size);\n\n // console.log(`avgwidth:${imageData.width}. avgheight:${imageData.height}`);\n\n if (imageData.width != size || imageData.size != size) {\n // console.log(`Scaling the image`);\n imageData = Resample.nearestNeighbour(canvas, imageData, size, size);\n console.log(`new imagedata:${typeof imageData}`);\n console.log(imageData.data);\n }\n\n imageData = Colour.grayscale(canvas, imageData);\n\n let sum = 0;\n for (let i = 0; i < pixelCount; i++) {\n // already grayscale so just take the first channel\n console.log(`new imagedata:${typeof imageData}`);\n console.log(imageData.data);\n sum += imageData.data[4 * i];\n }\n\n let average = Math.floor(sum / pixelCount),\n hash = 0,\n one = 1;\n\n for (let i = 0; i < pixelCount; i++) {\n if (imageData.data[4 * i] > average) {\n hash |= one;\n }\n\n one = one << 1;\n }\n\n return hash;\n }", "async function draw_prediction(batch, predictions, labels,num_of_pics,start_index){\r\n\tvar guess_accuracy=0;\r\n\tvar drawing_place = document.getElementById(\"show_predictions\");\r\n\tvar tot_accuracy = document.createElement(\"h5\");\r\n\ttot_accuracy.setAttribute(\"id\",\"tot_accuracy\");\r\n\ttot_accuracy.setAttribute(\"align\",\"center\");\r\n\tdrawing_place.appendChild(tot_accuracy);\r\n\tvar row1;\r\n\tvar row2;\r\n\tfor(let i=0;i<num_of_pics; i++){\r\n\t\tvar string_row1 = \"row1\" + (i%5);\r\n\t\tvar string_row2 = \"row2\" + (i%5);\r\n\t\tif(i%5 == 0){\r\n\t\t\trow1 = document.createElement(\"div\");\r\n\t\t\trow1.setAttribute(\"class\",\"row\");\r\n\t\t\trow1.setAttribute(\"id\",string_row1);\t\r\n\t\t\trow2 = document.createElement(\"div\");\r\n\t\t\trow2.setAttribute(\"class\",\"row\");\r\n\t\t\trow2.setAttribute(\"id\",string_row2);\t\t\t\t\r\n\t\t}\r\n\t\t//get data of the relevant image and put it on a canvas element\r\n\t\tvar tf2pic=batch.xs.reshape([1000,32,32,3]).slice([i+start_index,0,0,0],[1,32,32,3]).reshape([32,32,3]);\r\n\t\tvar c = document.createElement(\"canvas\");\r\n\t\tc.setAttribute(\"width\",\"32\");\r\n\t\tc.setAttribute(\"height\",\"32\");\r\n\t\tconst imgRequest=tf.toPixels(tf2pic,c);\r\n\t\tconst [imgResponse]=await Promise.all([imgRequest]);\r\n\t\t\r\n\t\t//get the label and print it's correctness\r\n\t\tvar guess = document.createElement(\"p\");\r\n\t\tvar string1 = get_type(Number(predictions[i+start_index]));\r\n\t\tvar string2 = \"(\" + get_type(Number(labels[i+start_index]));\r\n\t\tif(string1 == \"\" || string2 == \"(\"){ //if an error was occured:\r\n\t\t\tconsole.log(\"there was a problem with some of the input data\");\r\n\t\t\treturn;\r\n\t\t}\r\n\t\telse if(predictions[i+start_index]==labels[i+start_index]){//if the guess was correct\r\n\t\t\tguess_accuracy++;\r\n\t\t\tstring2+= \") - correct\";\r\n\t\t\tguess.setAttribute(\"style\",\"color:#007000\");\r\n\t\t}\r\n\t\telse{//if the guess wasn't correct\r\n\t\t\tstring2+= \") - incorrect\";\r\n\t\t\tguess.setAttribute(\"style\",\"color:#e60000\");\r\n\t\t}\r\n\t\tvar guess_text = document.createTextNode(string1+string2);\r\n\t\tguess.appendChild(guess_text);\r\n\t\tcol1 = document.createElement(\"div\");\r\n\t\tcol1.setAttribute(\"class\",\"col\");\r\n\t\tcol2 = document.createElement(\"div\");\r\n\t\tcol2.setAttribute(\"class\",\"col\");\t\t\t\r\n\t\tcol1.appendChild(guess);\r\n\t\tcol2.appendChild(c);\r\n\t\trow1.appendChild(col1);\r\n\t\trow2.appendChild(col2);\r\n\t\tif((i+1)%5 == 0){\r\n\t\t\tdrawing_place.appendChild(row1);\r\n\t\t\tdrawing_place.appendChild(row2);\r\n\t\t}\r\n\t}\r\n\tfor(let i = num_of_pics; i< 1000 ; i++){\r\n\t\tif(predictions[i+start_index]==labels[i+start_index]){//if the guess was correct\r\n\t\t\tguess_accuracy++;\r\n\t\t}\r\n\t}\r\n\tdocument.getElementById(\"tot_accuracy\").innerHTML = \"Accuracy: \"+(guess_accuracy/1000)+\"%, 50 pictures for example:\"\r\n}", "function isPixelEqual(p1, p2) {\n return p1.r === p2.r &&\n p1.g === p2.g &&\n p1.b === p2.b &&\n p1.a === p2.a;\n }", "function countPixelsInImages() {\n var i, imageTotal = 0, currentImage = 0, images = document.getElementsByTagName('img');\n\n for (i = 0; i < images.length; i = i + 1) {\n currentImage = images[i].naturalWidth * images[i].naturalHeight\n imageTotal += currentImage;\n\n if (currentImage > benchmarkForImage && images[i].naturalWidth !== images[i].width) {\n logResizedImages.push(images[i].src);\n } else if (currentImage > benchmarkForImage) {\n logLargeImages.push(images[i].src);\n } \n }\n\n return imageTotal;\n }", "function ColorCube( resolution = 20,\n bright_threshold = 0.2,\n distinct_threshold = 0.4 ) {\n \"use strict\";\n\n\n\n // subclasses // // // // // // // // // // // // // // // // // // // //\n // // // // // // // // // // // // // // // // // // // // // // // // //\n\n\n\n /*\n CanvasImage Class\n\n Class that wraps the html image element and canvas.\n It also simplifies some of the canvas context manipulation\n with a set of helper functions.\n\n modified from Color Thief v2.0\n by Lokesh Dhakar - http://www.lokeshdhakar.com\n */\n let CanvasImage = function (image) {\n\n if (! image instanceof HTMLElement) {\n throw \"You've gotta use an html image element as ur input!!\";\n }\n\n let API = {};\n\n let canvas = document.createElement('canvas');\n let context = canvas.getContext('2d');\n\n // document.body.appendChild(canvas);\n\n canvas.width = image.width;\n canvas.height = image.height;\n\n context.drawImage(image, 0, 0, image.width, image.height);\n\n API.getImageData = () => {\n return context.getImageData(0, 0, image.width, image.height);\n };\n\n return API;\n };\n\n\n\n\n /*\n CubeCell Class\n\n class that represents one voxel within rgb colorspace\n */\n function CubeCell() {\n let API = {};\n\n // Count of hits\n // (dividing the accumulators by this value gives the average color)\n API.hit_count = 0;\n\n // accumulators for color components\n API.r_acc = 0.0;\n API.g_acc = 0.0;\n API.b_acc = 0.0;\n\n return API;\n }\n\n\n\n\n /*\n LocalMaximum Class\n\n Local maxima as found during the image analysis.\n We need this class for ordering by cell hit count.\n */\n function LocalMaximum(hit_count, cell_index, r, g, b) {\n let API = {};\n\n // hit count of the cell\n API.hit_count = hit_count;\n\n // linear index of the cell\n API.cell_index = cell_index;\n\n // average color of the cell\n API.r = r;\n API.g = g;\n API.b = b;\n\n return API;\n }\n\n\n\n\n\n // ColorCube // // // // // // // // // // // // // // // // // // // //\n // // // // // // // // // // // // // // // // // // // // // // // // //\n\n\n\n\n let API = {};\n\n // helper variable to have cell count handy\n let cell_count = resolution * resolution * resolution;\n\n // create cells\n let cells = [];\n for (let i = 0; i <= cell_count; i++) {\n cells.push( new CubeCell() );\n }\n\n // indices for neighbor cells in three dimensional grid\n let neighbour_indices = [\n [ 0, 0, 0],\n [ 0, 0, 1],\n [ 0, 0,-1],\n\n [ 0, 1, 0],\n [ 0, 1, 1],\n [ 0, 1,-1],\n\n [ 0,-1, 0],\n [ 0,-1, 1],\n [ 0,-1,-1],\n\n [ 1, 0, 0],\n [ 1, 0, 1],\n [ 1, 0,-1],\n\n [ 1, 1, 0],\n [ 1, 1, 1],\n [ 1, 1,-1],\n\n [ 1,-1, 0],\n [ 1,-1, 1],\n [ 1,-1,-1],\n\n [-1, 0, 0],\n [-1, 0, 1],\n [-1, 0,-1],\n\n [-1, 1, 0],\n [-1, 1, 1],\n [-1, 1,-1],\n\n [-1,-1, 0],\n [-1,-1, 1],\n [-1,-1,-1]\n ];\n\n // returns linear index for cell with given 3d index\n let cell_index = (r, g, b) => {\n return (r + g * resolution + b * resolution * resolution);\n };\n\n let clear_cells = () => {\n for (let cell of cells) {\n cell.hit_count = 0;\n cell.r_acc = 0;\n cell.g_acc = 0;\n cell.b_acc = 0;\n }\n };\n\n API.get_colors = (image) => {\n let canvasimage = new CanvasImage(image);\n\n let m = find_local_maxima(canvasimage);\n\n m = filter_distinct_maxima(m);\n\n let colors = [];\n for (let n of m) {\n let r = Math.round(n.r * 255.0);\n let g = Math.round(n.g * 255.0);\n let b = Math.round(n.b * 255.0);\n let color = rgbToHex(r, g, b);\n if (color === \"#NaNNaNNaN\") {continue;}\n colors.push(color);\n }\n\n return colors;\n };\n\n let componentToHex = (c) => {\n let hex = c.toString(16);\n return hex.length == 1 ? \"0\" + hex : hex;\n };\n\n let rgbToHex = (r, g, b) => {\n return \"#\" + componentToHex(r) + componentToHex(g) + componentToHex(b);\n };\n\n // finds and returns local maxima in 3d histogram, sorted by hit count\n let find_local_maxima = (image) => {\n // reset all cells\n clear_cells();\n\n // get the image pixels\n let data = image.getImageData().data;\n\n // iterate over all pixels of the image\n for(let i = 0; i < data.length; i += 4) {\n // get color components\n let red = data[i] / 255.0;\n let green = data[i+1] / 255.0;\n let blue = data[i+2] / 255.0;\n let alpha = data[i+3] / 255.0;\n\n // stop if brightnesses are all below threshold\n if (red < bright_threshold &&\n green < bright_threshold &&\n blue < bright_threshold) {\n // continue;\n }\n\n // weigh colors by alpha channel\n red *= alpha;\n green *= alpha;\n blue *= alpha;\n\n // map color components to cell indicies in each color dimension\n // TODO maybe this should round down? OG colorcube uses python's int()\n let r_index = Math.round( red * ( resolution - 1.0 ) );\n let g_index = Math.round( green * ( resolution - 1.0 ) );\n let b_index = Math.round( blue * ( resolution - 1.0 ) );\n\n // compute linear cell index\n let index = cell_index(r_index, g_index, b_index);\n\n // increase hit count of cell\n cells[index].hit_count += 1;\n\n // add pixel colors to cell color accumulators\n cells[index].r_acc += red;\n cells[index].g_acc += green;\n cells[index].b_acc += blue;\n }\n\n // we collect local maxima in here\n let local_maxima = [];\n\n // find local maxima in the grid\n for (let r = 0; r < resolution; r++) {\n for (let g = 0; g < resolution; g++) {\n for (let b = 0; b < resolution; b++) {\n\n let local_index = cell_index(r, g, b);\n\n // get hit count of this cell\n let local_hit_count = cells[local_index].hit_count;\n\n // if this cell has no hits, ignore it\n if (local_hit_count === 0) {\n continue;\n }\n\n // it's a local maxima until we find a neighbor with a higher hit count\n let is_local_maximum = true;\n\n // check if any neighbor has a higher hit count, if so, no local maxima\n for (let n in new Array(27)) {\n r_index = r + this.neighbor_indices[n][0];\n g_index = g + this.neighbor_indices[n][1];\n b_index = b + this.neighbor_indices[n][2];\n\n // only check valid cell indices\n if (r_index >= 0 && g_index >= 0 && b_index >= 0) {\n if (r_index < this.resolution && g_index < this.resolution && b_index < this.resolution) {\n if (this.cells[this.cell_index(r_index, g_index, b_index)].hit_count > local_hit_count) {\n // this is not a local maximum\n is_local_maximum = false;\n break;\n }\n }\n }\n }\n\n // if this is not a local maximum, continue with loop\n if (is_local_maximum === false) {\n continue;\n }\n\n // otherwise add this cell as a local maximum\n let avg_r = cells[local_index].r_acc / cells[local_index].hit_count;\n let avg_g = cells[local_index].g_acc / cells[local_index].hit_count;\n let avg_b = cells[local_index].b_acc / cells[local_index].hit_count;\n let localmaximum = new LocalMaximum(local_hit_count, local_index, avg_r, avg_g, avg_b);\n\n local_maxima.push( localmaximum );\n }\n }\n }\n\n // return local maxima sorted with respect to hit count\n local_maxima = local_maxima.sort(function(a, b) { return b.hit_count - a.hit_count; });\n\n return local_maxima;\n };\n\n // Returns a filtered version of the specified array of maxima,\n // in which all entries have a minimum distance of distinct_threshold\n let filter_distinct_maxima = (maxima) => {\n\n let result = [];\n\n // check for each maximum\n for (let m of maxima) {\n // this color is distinct until an earlier color is too close\n let is_distinct = true;\n\n for (let n of result) {\n // compute delta components\n let r_delta = m.r - n.r;\n let g_delta = m.g - n.g;\n let b_delta = m.b - n.b;\n\n // compute delta in color space distance\n let delta = Math.sqrt(r_delta * r_delta + g_delta * g_delta + b_delta * b_delta);\n\n // if too close, mark as non distinct and break inner loop\n if (delta < distinct_threshold) {\n is_distinct = false;\n break;\n }\n }\n\n // add to filtered array if is distinct\n if (is_distinct === true) {\n result.push(m);\n }\n }\n\n\n return result;\n };\n\n return API;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
initialize player's paddle with mousemove event
function setupPlayerPaddle() { // bind updatePaddleLocation to mouse click events console.log('setting up player paddle'); $('.pong-container').mousemove(function(event) { updatePaddleLocation('.player', event); }); }
[ "move() {\n // Derive mouse vertical direction.\n let touchYPosition = touches.length > 0 ? touches[touches.length - 1].y : this.position.y;\n let touchYDirection = touchYPosition - this.position.y;\n\n if (Math.abs(touchYDirection) <= this.height / 6) {\n this.setVelocity(createVector(0, 0));\n } else {\n this.setVelocity(createVector(0, touchYDirection < 0 ? -1 : 1));\n }\n\n // Update computer paddle position and redraw at new position.\n this._update();\n this.draw();\n }", "function paddleInCanvas(){\nif(mouseY+paddle1Height > height){\nmouseY=height-paddle1Height;\n}\nif(mouseY < 0){\nmouseY =0;\n}\n\n\n}", "function update(){\n ball.move();\n computer_paddle.follow();\n\n}", "constructor(x, y, paddle) {\n this.x = x;\n this.y = y;\n this.paddleW = 120;\n this.paddleH = 60;\n this.onPaddle = true;\n this.image = paddle;\n }", "function Paddle(x, y, width, height) {\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n this.x_speed = 0;\n this.y_speed = 0;\n}", "update(){\n\n if(this.y < CANVAS_TOP_BOUNDARY){\n this.resetPosition();\n alert('You won!');\n }\n else if (this.y > PLAYER_DEFAULT_Y){\n this.y = PLAYER_DEFAULT_Y;\n }\n else if (this.x > CANVAS_RIGHT_BOUNDARY){\n this.x = CANVAS_RIGHT_BOUNDARY\n }\n else if (this.x < CANVAS_LEF_BOUNDARY){\n this.x = CANVAS_LEF_BOUNDARY;\n }\n }", "function resetBallToInitialPosition() {\n ballXposition = canvasWidth / 2;\n ballYPosition = canvasHeight / 2;\n speedY = -3;\n paddleTopX = ballXposition - paddleDifference;\n hasUserMovedPaddle = false;\n isBallContactedWithPaddle = false;\n}", "function Player(){\n Paddle.call(this);\n \n this.x = 20;\n}", "function setup() {\n // Create canvas and set drawing modes\n createCanvas(640, 480);\n rectMode(CENTER);\n noStroke();\n fill(0,255,0);\n\n setupPaddles();\n setupBall();\n\n rightPaddlepoints = 0;\n leftPaddlepoints = 0;\n}", "function playerSetUp(p) {\n GeometrySplit.game.physics.arcade.enable(p);\n p.animations.add('current', [0, 1, 2, 1], 8);\n p.body.collideWorldBounds = true;\n p.body.gravity.y = 1000;\n p.body.maxVelocity.y = 850;\n p.body.bounce = {x: 0, y: 0};\n p.tint = 0x98FB98;\n players.add(p);\n}", "function drawPaddle() {\r\n ctx.beginPath();\r\n ctx.rect(paddleX, canvas.height-paddleHeight, paddleWidth, paddleHeight);\r\n ctx.fillStyle = \"#3b0000\";\r\n ctx.fill();\r\n ctx.closePath();\r\n }", "function keyPressed() {\n\tif (keyCode === UP_ARROW) {\n \tpaddle.direction = -1;\n \t} \n \telse if (keyCode === DOWN_ARROW) {\n \tpaddle.direction = +1;\n \t}\n}", "function paddle2Move(){\n var paddle2YCentre= paddle2Y+(PADDLE_THICKNESS/2);\n\n if(paddle2YCentre<ballY-20)\n paddle2Y += 6;\n else if(paddle2YCentre>ballY+20)\n paddle2Y -= 6;\n}", "function update() {\n player.update()\n computer.update(ball)\n ball.update(player.paddle, computer.paddle)\n}", "function moveBullet(paddle){\n // turn bullet on\n if(paddle.bulletOn===true){\n // use paddle.side to determine in which direction to shoot the bullet\n // in this case it's the left paddle's bullet:\n if(paddle.side===0){\n // update speed\n paddle.bulletx+=paddle.bulletvx;\n // turn off once we reach the side\n if(paddle.bulletx>width){\n paddle.bulletOn=false;\n }\n } else {\n // do the same for the other paddle's bullet\n paddle.bulletx-=paddle.bulletvx;\n if(paddle.bulletx<0){\n paddle.bulletOn=false;\n }\n }\n}\n}", "function mousePressed(){\r\n count-=1;\r\n if(gameState===\"PLAY\" && count>0){\r\n particle=new Particle(mouseX,10,10);\r\n }\r\n}", "function displayPaddle(paddle) {\n rect(paddle.x, paddle.y, paddle.w, paddle.h);\n}", "onLayerMouseMove() {}", "constructor(x,y,paddleWidth,paddleHeight) {\n super(x,y,paddleWidth,paddleHeight,color(255));\n }", "function draw() {\n background(bg);\n \n drawBall();\n drawLPaddle();\n drawRPaddle();\n ballCollision();\n rPaddleCollision();\n lPaddleCollision();\n drawScore();\n resetBallPosition();\n \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes a new instance of `XMLDocumentCB` `options.keepNullNodes` whether nodes with null values will be kept or ignored: true or false `options.keepNullAttributes` whether attributes with null values will be kept or ignored: true or false `options.ignoreDecorators` whether decorator strings will be ignored when converting JS objects: true or false `options.separateArrayItems` whether array items are created as separate nodes when passed as an object value: true or false `options.noDoubleEncoding` whether existing html entities are encoded: true or false `options.stringify` a set of functions to use for converting values to strings `options.writer` the default XML writer to use for converting nodes to string. If the default writer is not set, the builtin XMLStringWriter will be used instead. `onData` the function to be called when a new chunk of XML is output. The string containing the XML chunk is passed to `onData` as its first argument, and the current indentation level as its second argument. `onEnd` the function to be called when the XML document is completed with `end`. `onEnd` does not receive any arguments.
constructor(options, onData, onEnd) { var writerOptions; this.name = "?xml"; this.type = NodeType.Document; options || (options = {}); writerOptions = {}; if (!options.writer) { options.writer = new XMLStringWriter(); } else if (isPlainObject(options.writer)) { writerOptions = options.writer; options.writer = new XMLStringWriter(); } this.options = options; this.writer = options.writer; this.writerOptions = this.writer.filterOptions(writerOptions); this.stringify = new XMLStringifier(options); this.onDataCallback = onData || function() {}; this.onEndCallback = onEnd || function() {}; this.currentNode = null; this.currentLevel = -1; this.openTags = {}; this.documentStarted = false; this.documentCompleted = false; this.root = null; }
[ "function xmlStringFromDocDom(oDocDom, encodeSingleSpaceTextNodes) {\n\tvar xmlString = new String();\n\n\t// if the node is an element node\n\tif (oDocDom.nodeType == 1 && oDocDom.nodeName.slice(0,1) != \"/\") {\n\t\t// define the beginning of the root element and that element's name\n\t\txmlString = \"<\" + oDocDom.nodeName.toLowerCase();\n\n\t\t// loop through all qualified attributes and enter them into the root element\n\t\tfor (var x = 0; x < oDocDom.attributes.length; x++) {\n\t\t\tif (oDocDom.attributes[x].specified == true || oDocDom.attributes[x].name == \"value\") {\t// IE wrongly puts unspecified attributes in here\n\t\t\t\t//if (oDocDom.attributes[x].name == \"class\") {\n\t\t\t\t//\txmlString += ' class=\"' + oNode.attributes[x].value + '\"';\n\t\t\t\t//} else {\n\n\t\t\t\t// If this is not an input, then add the attribute is \"input\", then skip this.\n\t\t\t\tif (oDocDom.nodeName.toLowerCase() != \"input\" && oDocDom.attributes[x].name == \"value\" && oDocDom.attributes[x].specified == false) {\n\n\t\t\t\t// If this is an img element.\n\t\t\t\t} else if (oDocDom.nodeName.toLowerCase() == \"img\" && oDocDom.attributes[x].name == \"width\" ||\n\t\t\t\t\toDocDom.nodeName.toLowerCase() == \"img\" && oDocDom.attributes[x].name == \"height\") {\n\n\t\t\t\t} else {\n\n\t\t\t\t\txmlString += ' ' + oDocDom.attributes[x].name + '=\"' + oDocDom.attributes[x].value + '\"';\n\t\t\t\t}\n\t\t\t\t//}\n\t\t\t}\n\t\t}\n\n\t\t// if the xml object doesn't have children, then represent it as a closed tag\n//\t\tif (oDocDom.childNodes.length == 0) {\n//\t\t\txmlString += \"/>\"\n\n//\t\t} else {\n\n\t\t// if it does have children, then close the root tag\n\t\txmlString += \">\";\n\t\t// then peel through the children and apply recursively\n\t\tfor (var i = 0; i < oDocDom.childNodes.length; i++) {\n\t\t\txmlString += xmlStringFromDocDom(oDocDom.childNodes.item(i), encodeSingleSpaceTextNodes);\n\t\t}\n\t\t// add the final closing tag\n\t\txmlString += \"</\" + oDocDom.nodeName.toLowerCase() + \">\";\n//\t\t}\n\n\t\treturn xmlString;\n\n\t} else if (oDocDom.nodeType == 3) {\n\t\t// return the text node value\n\t\tif (oDocDom.nodeValue == \" \" && encodeSingleSpaceTextNodes == true) {\n\t\t\treturn \"#160;\";\n\t\t} else {\n\t\t\treturn oDocDom.nodeValue;\n\t\t}\n\t} else {\n\t\treturn \"\";\n\t}\n}", "function BADocument() { }", "constructor(doc) {\n _defineProperty(this, \"mutations\", void 0);\n\n _defineProperty(this, \"document\", void 0);\n\n _defineProperty(this, \"LOCAL\", void 0);\n\n _defineProperty(this, \"commits\", void 0);\n\n _defineProperty(this, \"buffer\", void 0);\n\n _defineProperty(this, \"onMutation\", void 0);\n\n _defineProperty(this, \"onRebase\", void 0);\n\n _defineProperty(this, \"onDelete\", void 0);\n\n _defineProperty(this, \"commitHandler\", void 0);\n\n _defineProperty(this, \"committerRunning\", void 0);\n\n _defineProperty(this, \"onConsistencyChanged\", void 0);\n\n this.buffer = new _SquashingBuffer.default(doc);\n this.document = new _Document.default(doc);\n\n this.document.onMutation = msg => this.handleDocMutation(msg);\n\n this.document.onRebase = msg => this.handleDocRebase(msg);\n\n this.document.onConsistencyChanged = msg => this.handleDocConsistencyChanged(msg);\n\n this.LOCAL = doc;\n this.mutations = [];\n this.commits = [];\n }", "function ProcessableXML() {\n\n}", "function DocEdit_initialize(text, priorNodeSegment, weight, relativeNode, optionFlags)\n{\n //public\n this.text = text;\n\n if (priorNodeSegment && dw.nodeExists(priorNodeSegment.node))\n {\n this.priorNodeSegment = priorNodeSegment;\n this.priorNode = priorNodeSegment.node || false;\n this.matchRangeMin = priorNodeSegment.matchRangeMin || 0;\n this.matchRangeMax = priorNodeSegment.matchRangeMax || 0;\n\n if (this.matchRangeMin == this.matchRangeMax)\n {\n // If we are here, we were given a priorNodeSegment which, though non-null and\n\t // in existance, is in fact bogus. Therefore, act like we were given no\n\t // priorNodeSegment at all (i.e., given a null for that param). It is dangerous\n\t // to use priorNodeSegment without clearing it here because we apparently have\n\t // data with bad integrety at this point.\n\t \n alert(\"ERROR: bad node segment offsets\");\n\t priorNodeSegment = null;\n }\n }\n \n if (!priorNodeSegment)\n {\n this.priorNode = false;\n this.matchRangeMin = -1;\n this.matchRangeMax = -1;\n }\n\n this.weight = weight || \"\"; //aboveHTML[+nn], belowHTML[+nn],\n //beforeSelection, afterSelection, replaceSelection,\n //beforeNode, afterNode, replaceNode,\n //nodeAttribute[+attribname]\n this.node = relativeNode || null; //optional: only used with \"...Node\" weights\n \n this.dontMerge = (optionFlags & docEdits.QUEUE_DONT_MERGE);\n\n this.dontPreprocessText = (optionFlags & docEdits.QUEUE_DONT_PREPROCESS_TEXT);\n this.dontFormatForMerge = (optionFlags & docEdits.QUEUE_DONT_FORMAT_FOR_MERGE);\n\n this.defaultWeight = 99;\n this.version = 5.0;\n\n //private\n this.insertPos = null;\n this.replacePos = null;\n this.bDontMergeTop = false;\n this.bDontMergeBottom = false;\n\n\n this.weightType = \"\"; //weight *might* have a preword, like aboveHTML or nodeAttribute\n this.weightNum = null; //weight *might* include a number (set below)\n this.weightInfo = \"\"; //weight *might* have extra info, like an attribute name (set below)\n\n //Initialize weight, weightNum, and weightInfo properties\n //Determine correct weight type, and assign extra weight properties\n if (this.weight)\n {\n //if weight is just number, change to aboveHTML+number\n if (this.weight == String(parseInt(this.weight))) //if just number (old style)\n {\n this.weightNum = parseInt(this.weight); //convert if number\n this.weightType = \"aboveHTML\";\n this.weight = this.weightType + \"+\" + this.weight; //default is aboveHTML\n }\n //if extra weight info (someWeight+someData), extract data\n else if (this.weight.indexOf(\"+\") > 0)\n {\n var data = this.weight.substring(this.weight.indexOf(\"+\")+1);\n this.weightType = this.weight.substring(0,this.weight.indexOf(\"+\"));\n\n //if weight is ??+number, extract the number\n if (data == String(parseInt(data)))\n {\n this.weightNum = parseInt(data); //convert if number\n\n //if weight is ??+??, save data as info\n }\n else\n {\n this.weightInfo = data;\n }\n }\n //if weight is aboveHTML or belowHTML, add default weight number\n else if (this.weight == \"aboveHTML\" || this.weight == \"belowHTML\")\n {\n this.weightType = this.weight;\n this.weight += \"+\"+String(this.defaultWeight);\n this.weightNum = this.defaultWeight;\n }\n //for backward compatibility,convert \"afterDocument\" to \"belowHTML\"\n else if (this.weight == \"afterDocument\")\n {\n this.weightType = \"belowHTML\";\n this.weight = this.weightType + \"+\" + String(this.defaultWeight);\n this.weightNum = this.defaultWeight;\n }\n }\n else //default if no weight given\n {\n this.weight = \"aboveHTML+\"+String(this.defaultWeight);\n this.weightType = \"aboveHTML\";\n this.weightNum = this.defaultWeight;\n }\n\n // Only merge above and below the HTML tag. Merging within\n // the body can cause problems with translators.\n if (this.weightType != \"aboveHTML\" && this.weightType != \"belowHTML\")\n {\n this.preventMerge = true;\n }\n\n}", "function getXMLDocument(){\n var xDoc=null;\n\n if( document.implementation && document.implementation.createDocument ){\n xDoc=document.implementation.createDocument(\"\",\"\",null);//Mozilla/Safari \n }else if (typeof ActiveXObject != \"undefined\"){\n var msXmlAx=null;\n try{\n msXmlAx=new ActiveXObject(\"Msxml2.DOMDocument\");//New IE\n }catch (e){\n msXmlAx=new ActiveXObject(\"Msxml.DOMDocument\"); //Older Internet Explorer \n }\n xDoc=msXmlAx;\n }\n if (xDoc==null || typeof xDoc.load==\"undefined\"){\n xDoc=null;\n }\n return xDoc;\n}", "function DocumentData()\r{\r this.selectedDocument = app.activeDocument; // save away the selected source inDesign Document\r if (this.selectedDocument.saved)\r this.selectedDocPath = this.selectedDocument.filePath;\r else\r this.selectedDocPath = Folder.myDocuments.fullName;\r // selectedDocPath = filePath to the source in Design document we are reading from \r $.writeln(\"selectedDocPath: \" + this.selectedDocPath);\r this.selectedDocFileName = getFileNameWithoutExtension(this.selectedDocument.name);\r this.outputFolder = new Folder(Folder.myDocuments.fullName + \"/BIP/\" + this.selectedDocFileName);\r this.imagesFolder = new Folder(Folder.myDocuments.fullName + \"/BIP/\" + this.selectedDocFileName + \"/images\");\r $.writeln(\"image folder: \" + this.imagesFolder);\r this.imagesFolder.create();\r // We are NOT doing anything with the copy of the InDesign doc using the new doc instead\r // save a copy of the indd document in the output folder don't try and open it yet\r//~ this.inDesignFileCopy = new File(this.outputFolder.fullName + \"/\" + this.selectedDocument.name);\r//~ $.writeln(\"copy path: \" + this.inDesignFileCopy.fullName);\r//~ this.selectedDocument.saveACopy(this.inDesignFileCopy);\r // docData.inDesignDocumentCopy = app.open(docData.inDesignFileCopy, true);\r this.globalFileName = this.selectedDocument.name;\r // xmlDocument = Create a new document where we are going to write out xml data, images etc then do Export To XML\r this.xmlDocument = app.documents.add();\r}", "function createXml (options, xmlObject) {\n const createdXml = js2xmlparser.parse('licenseSummary', xmlObject);\n if (!options.silent) {\n console.log(createdXml);\n }\n if (options.xml) {\n const fileName = options.xml.substring(0, options.xml.length - path.extname(options.xml).length);\n fs.writeFileSync(path.join(licensesDir, `${fileName}.xml`), createdXml);\n }\n}", "function musicXML(source, callback) {\n var part = kPartWise, musicXML, impl, type, xmlHeader;\n\n // Create the DOM implementation\n impl = domino.createDOMImplementation();\n\n // Create the DOCTYPE\n type = impl.createDocumentType(part.type, part.id, part.url);\n\n // Create the document itself\n musicXML = impl.createDocument('', '', null);\n\n // Create the <?xml ... ?> header\n xmlHeader = musicXML.createProcessingInstruction('xml',\n 'version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"');\n\n // Append both the header and the DOCTYPE\n musicXML.appendChild(xmlHeader);\n musicXML.appendChild(type);\n\n // Start serializing the MusicJSON document\n musicXML.appendChild(toXML(musicXML, source[part.type], part.type));\n\n callback(null, musicXML);\n}", "constructor(){ // Definindo construtor da classe BinaryTree\n this.root = null; // inicializa a raiz da arvore como sendo nula\n }", "function DocBookHandler(version)\n{\n // Add members to DocBookHandler type\n this.fDocBookVersion = version;\n this.fRootElemName = \"article\";\n this.fSectionElemName = \"section\";\n this.fIdAttrName = \"xml:id\";\n this.fCrossRefElemName = \"xref\";\n this.fLinkEndAttrName = \"linkend\";\n this.fXIncludeShowingPropKey = \"__DOCBOOK_XINCLUDES_SHOWING__\";\n this.fDidUpdateXIncludeOnce = false; // Help user get xincludes showing\n this.fShowXIncludesUponOpen = false; // Default to no showing XInclude targets on first open\n this.fBaseCssToAppendIndex = 1; // Default to using docbook_example1.css\n this.fTotalCssExamples = 3; // 3 example CSS files for showing DocBook\n this.fCssToAppend = \"\"; \n this.fIndexMarkersOn = false; \n}", "static convertDocumentToString(xmlDocument, depth){\n var result =\"\";\n var nodeName = String(xmlDocument.nodeName);\n\n // set the tabulation with the depth\n var tab = \"\";\n\n if(depth!=0){\n for(var i = 1; i < depth; i++ ){\n tab += \"\\t\";\n }\n // add the node and the attributes\n result += tab +\"<\" + nodeName\n $(xmlDocument.attributes).each(function(i,attr){\n result += \" \" + String(attr.name) + \"=\\\"\" + _.escape(String(attr.value)) +\"\\\"\"\n })\n if($(xmlDocument).text() != \"\" || $(xmlDocument).children().length > 0){\n result += \">\";\n }else{\n result += \"/>\";\n }\n }\n // add the children to the result\n if ($(xmlDocument).children().length > 0){\n result += \"\\n\";\n $(xmlDocument).children().each(function(i,child){\n result += Writer.convertDocumentToString(child, depth + 1) + \"\\n\";\n })\n result += tab;\n }else{\n result += $(xmlDocument).text();\n }\n\n if(depth!=0){\n if($(xmlDocument).text() != \"\" || $(xmlDocument).children().length > 0){\n result += \"</\" + nodeName + \">\";\n }\n }\n return result;\n }", "_buildDOM() {\n const HTML = this.render();\n if (!HTML) { return }\n this.DOMbuilder.build( HTML );\n }", "clone() {\n const copy = Object.create(Document.prototype, {\n [NODE_TYPE]: { value: DOC }\n });\n copy.commentBefore = this.commentBefore;\n copy.comment = this.comment;\n copy.errors = this.errors.slice();\n copy.warnings = this.warnings.slice();\n copy.options = Object.assign({}, this.options);\n if (this.directives)\n copy.directives = this.directives.clone();\n copy.schema = this.schema.clone();\n copy.contents = isNode(this.contents)\n ? this.contents.clone(copy.schema)\n : this.contents;\n if (this.range)\n copy.range = this.range.slice();\n return copy;\n }", "on(event, callback, cancelCallback) {\n if (this.path === '' && ['value', 'child_changed'].includes(event)) {\n // Removed 'notify_value' and 'notify_child_changed' events from the list, they do not require additional data loading anymore.\n console.warn(`WARNING: Listening for value and child_changed events on the root node is a bad practice. These events require loading of all data (value event), or potentially lots of data (child_changed event) each time they are fired`);\n }\n let eventPublisher = null;\n const eventStream = new subscription_1.EventStream(publisher => { eventPublisher = publisher; });\n // Map OUR callback to original callback, so .off can remove the right callback(s)\n const cb = {\n event,\n stream: eventStream,\n userCallback: typeof callback === 'function' && callback,\n ourCallback: (err, path, newValue, oldValue, eventContext) => {\n if (err) {\n this.db.debug.error(`Error getting data for event ${event} on path \"${path}\"`, err);\n return;\n }\n let ref = this.db.ref(path);\n ref[_private].vars = path_info_1.PathInfo.extractVariables(this.path, path);\n let callbackObject;\n if (event.startsWith('notify_')) {\n // No data event, callback with reference\n callbackObject = ref.context(eventContext || {});\n }\n else {\n const values = {\n previous: this.db.types.deserialize(path, oldValue),\n current: this.db.types.deserialize(path, newValue)\n };\n if (event === 'child_removed') {\n callbackObject = new data_snapshot_1.DataSnapshot(ref, values.previous, true, values.previous, eventContext);\n }\n else if (event === 'mutations') {\n callbackObject = new data_snapshot_1.MutationsDataSnapshot(ref, values.current, eventContext);\n }\n else {\n const isRemoved = event === 'mutated' && values.current === null;\n callbackObject = new data_snapshot_1.DataSnapshot(ref, values.current, isRemoved, values.previous, eventContext);\n }\n }\n eventPublisher.publish(callbackObject);\n }\n };\n this[_private].callbacks.push(cb);\n const subscribe = () => {\n // (NEW) Add callback to event stream \n // ref.on('value', callback) is now exactly the same as ref.on('value').subscribe(callback)\n if (typeof callback === 'function') {\n eventStream.subscribe(callback, (activated, cancelReason) => {\n if (!activated) {\n cancelCallback && cancelCallback(cancelReason);\n }\n });\n }\n let authorized = this.db.api.subscribe(this.path, event, cb.ourCallback);\n const allSubscriptionsStoppedCallback = () => {\n let callbacks = this[_private].callbacks;\n callbacks.splice(callbacks.indexOf(cb), 1);\n return this.db.api.unsubscribe(this.path, event, cb.ourCallback);\n };\n if (authorized instanceof Promise) {\n // Web API now returns a promise that resolves if the request is allowed\n // and rejects when access is denied by the set security rules\n authorized.then(() => {\n // Access granted\n eventPublisher.start(allSubscriptionsStoppedCallback);\n })\n .catch(err => {\n // Access denied?\n // Cancel subscription\n let callbacks = this[_private].callbacks;\n callbacks.splice(callbacks.indexOf(cb), 1);\n this.db.api.unsubscribe(this.path, event, cb.ourCallback);\n // Call cancelCallbacks\n eventPublisher.cancel(err.message);\n // No need to call cancelCallback, original callbacks are now added to event stream\n // cancelCallback && cancelCallback(err.message);\n });\n }\n else {\n // Local API, always authorized\n eventPublisher.start(allSubscriptionsStoppedCallback);\n }\n if (callback && !this.isWildcardPath) {\n // If callback param is supplied (either a callback function or true or something else truthy),\n // it will fire events for current values right now.\n // Otherwise, it expects the .subscribe methode to be used, which will then\n // only be called for future events\n if (event === \"value\") {\n this.get(snap => {\n eventPublisher.publish(snap);\n typeof callback === 'function' && callback(snap);\n });\n }\n else if (event === \"child_added\") {\n this.get(snap => {\n const val = snap.val();\n if (val === null || typeof val !== \"object\") {\n return;\n }\n Object.keys(val).forEach(key => {\n let childSnap = new data_snapshot_1.DataSnapshot(this.child(key), val[key]);\n eventPublisher.publish(childSnap);\n typeof callback === 'function' && callback(childSnap);\n });\n });\n }\n else if (event === \"notify_child_added\") {\n // Use the reflect API to get current children. \n // NOTE: This does not work with AceBaseServer <= v0.9.7, only when signed in as admin\n const step = 100;\n let limit = step, skip = 0;\n const more = () => {\n this.db.api.reflect(this.path, \"children\", { limit, skip })\n .then(children => {\n children.list.forEach(child => {\n const childRef = this.child(child.key);\n eventPublisher.publish(childRef);\n typeof callback === 'function' && callback(childRef);\n });\n if (children.more) {\n skip += step;\n more();\n }\n });\n };\n more();\n }\n }\n };\n if (this.db.isReady) {\n subscribe();\n }\n else {\n this.db.ready(subscribe);\n }\n return eventStream;\n }", "constructor() { \n \n InlineResponse2001DataDocument.initialize(this);\n }", "function Naivebayes(options) {\n // set options object\n this.options = {}\n if (typeof options !== 'undefined') {\n if (!options || typeof options !== 'object' || Array.isArray(options)) {\n throw TypeError('NaiveBayes got invalid `options`: `' + options + '`. Pass in an object.')\n }\n this.options = options\n }\n\n this.tokenizer = this.options.tokenizer || defaultTokenizer\n\n //initialize our vocabulary and its size\n this.vocabulary = {}\n this.vocabularySize = 0\n\n //number of documents we have learned from\n this.totalDocuments = 0\n\n //document frequency table for each of our categories\n //=> for each category, how often were documents mapped to it\n this.docCount = {}\n\n //for each category, how many words total were mapped to it\n this.wordCount = {}\n\n //word frequency table for each category\n //=> for each category, how frequent was a given word mapped to it\n this.wordFrequencyCount = {}\n\n //hashmap of our category names\n this.categories = {}\n}", "text(...args) {\n let opts = args[args.length - 1];\n\n if (typeof opts !== 'object') {\n opts = {};\n }\n\n if (!opts.lineGap) {\n opts.lineGap = lineGap;\n }\n\n if (opts.font) {\n this.doc.font(opts.font);\n } else {\n this.doc.font(lightFont);\n }\n\n if (opts.color) {\n this.doc.fillColor(opts.color);\n } else {\n this.doc.fillColor('black');\n }\n\n if (opts.size) {\n this.doc.fontSize(opts.size);\n } else {\n this.doc.fontSize(10);\n }\n\n return this.doc.text(...args);\n }", "constructor(config = {}) {\n\t\tconst doc = {\n\t\t\tencoding: 'utf8',\n\t\t\tdocumentBaseURL: '/',\n\t\t\twindow: {\n\t\t\t\tenvSettingObject: {}\n\t\t\t}\n\t\t};\n\t\tconst defaults = {\n\t\t\talreadyStarted: false,\n\t\t\tparserInserted: false,\n\t\t\tnonBlocking: true,\n\t\t\treadyToBeParserExecuted: false,\n\t\t\tscriptsType: null,\n\t\t\tfromAnExternalFile: false,\n\t\t\tscriptsScript: null,\n\t\t\t__isReady: false,\n\t\t\t__connected: false,\n\t\t\tasync: false,\n\t\t\tdefer: false,\n\t\t\ttextContent: '',\n\t\t\tnodeDocument: doc,\n\t\t\tparserDocument: doc,\n\t\t\tdisabled: false,\n\t\t\tnomodule: false,\n\t\t\tname: ''\n\t\t};\n\t\tObject.assign(this, defaults, config);\n\t\tconfig.src != undefined && (this.src = config.src);\n\t\tconfig.async != undefined && (this.async = config.async);\n\t\tconfig.connected != undefined && (this.connected = config.connected);\n\t\tconfig.textContent != undefined && (this.textContent = config.textContent);\n\t\tconfig.isReady != undefined && (this.isReady = config.isReady);\n\n\t\t/**\n\t\t * Mark the element as being \"parser-inserted\" and unset\n\t\t * the element's \"non-blocking\" flag.\n\t\t */\n\t\tif (this.parserInserted) {\n\t\t\tthis.nonBlocking = false;\n\t\t}\n\t}", "createCodeCell(options, parent) {\n if (!options.contentFactory) {\n options.contentFactory = this;\n }\n return new CodeCell(options).initializeState();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear the inner part of modules included in the compiler.externals, replace with SystemJS.import('three').then(res => exports = res)
function clearExternals(externals = [], compiler) { }
[ "async removeExtraneousNodeModules() {\n // this is only relevant for the root workspace\n if (!this.isWorkspaceRoot) {\n return;\n }\n\n const workspacesInfo = await (0, _scripts.yarnWorkspacesInfo)(this.path);\n const unusedWorkspaces = new Set(Object.keys(workspacesInfo)); // check for any cross-project dependency\n\n for (const name of Object.keys(workspacesInfo)) {\n const workspace = workspacesInfo[name];\n workspace.workspaceDependencies.forEach(w => unusedWorkspaces.delete(w));\n }\n\n unusedWorkspaces.forEach(name => {\n const {\n dependencies,\n devDependencies\n } = this.json;\n\n const nodeModulesPath = _path.default.resolve(this.nodeModulesLocation, name);\n\n const isDependency = dependencies && dependencies.hasOwnProperty(name);\n const isDevDependency = devDependencies && devDependencies.hasOwnProperty(name);\n\n if (!isDependency && !isDevDependency && _fs.default.existsSync(nodeModulesPath)) {\n _log.log.debug(`No dependency on ${name}, removing link in node_modules`);\n\n _fs.default.unlinkSync(nodeModulesPath);\n }\n });\n }", "function removeModule() {\n\t\tcommon.naclModule.parentNode.removeChild(common.naclModule);\n\t\tcommon.naclModule = null;\n\t}", "static disposeEngine (comp) {\n let _engine = null\n if (comp.tooltip) {\n comp.tooltip.dispose()\n }\n if (comp.scene) {\n _engine = comp.scene.getEngine()\n for (let i = comp.scene.meshes.length - 1; i >= 0; i--) {\n if (comp.scene.meshes[i]) {\n comp.scene.meshes[i].dispose(false, true)\n }\n }\n comp.scene.dispose()\n delete comp.scene\n }\n if (_engine) {\n _engine.stopRenderLoop()\n _engine.clear(BABYLON.Color3.White(), true, true, true)\n _engine.dispose()\n }\n }", "removeAll() {\n this.$plugins.forEach((entry) => {\n if (entry && entry.uninstall) {\n entry.uninstall(this);\n }\n });\n this.$plugins.clear();\n }", "function clearCache() {\n pancakes.clearCache();\n for (var key in opts.require.cache) {\n if (opts.require.cache.hasOwnProperty(key) &&\n !key.match(/node_modules/) &&\n !key.match(/\\/pancakes\\/lib\\//)) {\n\n delete opts.require.cache[key];\n }\n }\n }", "async InitWASM () {\n window.CUBE_GLOBAL.WASMCAL = await import('./wasm/main.wasm')\n window.CUBE_GLOBAL.WASM = true\n }", "async function main() {\n return [Promise.resolve(/*! import() eager */).then(__webpack_require__.bind(__webpack_require__, /*! ./all-imports.js */ \"./src/all-imports.js\"))];\n}", "onShutdown() {\n this.particleSystems.forEach( e => e.dispose() );\n this.particleSystems.clear();\n }", "resetEverything() {\n this.resetLoader();\n this.remove(0, Infinity);\n }", "restore() {\n this.emit(\"addDependencies\", Object.keys(this.componentPathsByDependentAssetId));\n }", "replaceInnerSource(compiler) {\n compiler.hooks.compilation.tap('InjectInnerWebpackPlugin', (compilation) => {\n compilation.hooks.processAssets.tap('InjectInnerWebpackPlugin', () => {\n this.compilationAssets = compilation.assets;\n const hooks = this.htmlWebpackPlugin.getHooks(compilation);\n\n hooks.afterTemplateExecution.tap('InjectInnerWebpackPlugin', (data) => {\n const template = getRawTemplate(data.plugin.userOptions.template, compiler.context);\n\n const assetList = this.assetListMap[template];\n assetList && assetList.forEach((assetItem) => {\n const {\n chunk,\n innerJsUrl,\n rawScript,\n } = assetItem;\n\n const jsBundle = getBundleByChunk(compilation.chunks, chunk);\n\n if (jsBundle) {\n const content = compilation.assets[jsBundle].source();\n\n data.html = this.getReplacedContent({\n rawScript,\n innerJsUrl,\n content,\n originContent: data.html,\n });\n }\n });\n\n const rawAssetList = this.rawAssetListMap[template];\n rawAssetList && rawAssetList.forEach((rawAssetItem) => {\n const {\n scriptEntryPath,\n innerJsUrl,\n rawScript,\n } = rawAssetItem;\n\n const content = fs.readFileSync(scriptEntryPath, {\n encoding: 'utf-8'\n });\n\n data.html = this.getReplacedContent({\n rawScript,\n innerJsUrl,\n content,\n originContent: data.html,\n });\n });\n });\n });\n });\n }", "clearScenes() {\n for (let iScene = 0; iScene < this.scenes.length; ++iScene) {\n let scene = this.scenes[iScene];\n scene.traverse(function (node) {\n let geometry = node.geometry;\n let material = node.material;\n let texture = node.texture;\n if (geometry) {\n geometry.dispose();\n }\n if (material) {\n material.dispose();\n }\n if (texture) {\n texture.dispose();\n }\n });\n while (scene.children.length) {\n let child = scene.children[0];\n scene.remove(child);\n }\n }\n }", "async function bootstrap() {\n\n // Load the WebAssembly Module\n // https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming\n const result = await WebAssembly.instantiateStreaming(\n fetch(\"lvglwasm.wasm\"),\n importObject\n );\n\n // Store references to WebAssembly Functions and Memory exported by Zig\n wasm.init(result);\n\n // Start the Main Function\n main();\n}", "function resetCube(num)\n{\n workspace.bboxes[num].x = workspace.originalBboxes[num].x;\n workspace.bboxes[num].y = workspace.originalBboxes[num].y;\n workspace.bboxes[num].z = workspace.originalBboxes[num].z;\n workspace.bboxes[num].yaw = workspace.originalBboxes[num].yaw;\n workspace.bboxes[num].delta_x = workspace.originalBboxes[num].delta_x;\n workspace.bboxes[num].delta_y = workspace.originalBboxes[num].delta_y;\n workspace.bboxes[num].delta_z = workspace.originalBboxes[num].delta_z;\n workspace.bboxes[num].width = workspace.originalBboxes[num].width;\n workspace.bboxes[num].height = workspace.originalBboxes[num].height;\n workspace.bboxes[num].depth = workspace.originalBboxes[num].depth;\n cube_array[num].position.x = workspace.bboxes[num].x;\n cube_array[num].position.y = -workspace.bboxes[num].y;\n cube_array[num].position.z = workspace.bboxes[num].z;\n cube_array[num].rotation.z = workspace.bboxes[num].yaw;\n cube_array[num].scale.x = workspace.bboxes[num].width;\n cube_array[num].scale.y = workspace.bboxes[num].height;\n cube_array[num].scale.z = workspace.bboxes[num].depth;\n}", "detach() {\n this.surface = null;\n this.dom = null;\n }", "function destroy() {\n if (!isBuilded) {\n return;\n }\n\n isBuilded = false;\n\n darlingjs.removeWorld('myGame');\n world = darlingjs.world('myGame', [\n 'myApp',\n 'ngFlatland',\n 'ngCyclic',\n 'ng3D',\n 'ngPhysics',\n 'ngBox2DEmscripten',\n 'ngPixijsAdapter',\n 'ngStats',\n 'ngPerformance',\n 'ngInfinity1DWorld',\n 'ngPlayer',\n 'ngParticleSystem',\n 'ngSound',\n 'ngHowlerAdapter',\n 'ngResources'\n ], {\n fps: 60\n });\n world.$c('ground', {});\n }", "function initializeAllModules() {\r\n var modules = mj.modules;\r\n for (var moduleName in modules) {\r\n if (moduleName != 'main' && modules.hasOwnProperty(moduleName)) {\r\n if (typeof modules[moduleName].setup == 'function') {\r\n modules[moduleName].setup();\r\n }\r\n trigger('initialize-' + moduleName, null, true);\r\n }\r\n }\r\n }", "destroy() {\n\t\tthis.directives.forEach(\n\t\t\tbinding => Reflex.unobserve(this, null, null, {tags:['#directive', binding]})\n\t\t);\n\t\tif (this.dataBlockScript && globalParams.hideDataBlockScript) {\n\t\t\tthis.prepend(this.dataBlockScript);\n\t\t}\n\t}", "function fixDragulaBody() {\r\n\twindow.dragula = require('dragula');\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
removeSubscriber: takes an object Id and a query hash, and dissociates the hash from the object.
function removeSubscriber(id, hash) { if (store[id]) { delete store[id].queries[hash]; } else if (localSubscribers[id]) { delete localSubscribers[id][hash]; if (Object.keys(localSubscribers[id]).length < 1) { delete localSubscribers[id]; } } }
[ "unsubscribe(id, headers = {}) {\n delete this.subscriptions[id];\n headers.id = id;\n return this._transmit(\"UNSUBSCRIBE\", headers);\n }", "function removeRecentSearchTerm( term ){\n recent.remove( term, function(){\n populateRecentSeachTerms();\n });\n}", "function unregister(uaid, data, cb) {\n\n async.waterfall([\n function(cb) {\n store.get('channel/' + data.channelID, cb);\n },\n function(channel, cb) {\n // the channel ID is unknown\n if (!channel) return cb('UnknownChannelID');\n\n // the UA doesn't match our current UA\n if (channel.uaid !== uaid) return cb('UAMismatch');\n\n store.delete('channel/' + data.channelID, cb);\n },\n function(cb) {\n // get UA info so we can remove this channel from its list\n store.get('uaid/' + uaid, cb);\n },\n function(ua, cb) {\n // remove the channel ID from the UA's list of channels\n ua.channelIDs.splice(ua.channelIDs.indexOf(data.channelID), 1);\n store.set('uaid/' + uaid, ua, cb);\n }\n ], cb);\n\n }", "removeStudent(id){\n this.students = this.students.filter(\n (student) => {\n return student.id !== id;\n }\n )\n }", "function removeProduct(dataMemory,removeObject) {\n if (dataMemory.getItem(removeObject) != null) {\n dataMemory.removeItem(removeObject);\n }\n}", "_removeServiceStreamDataListener ( ) {\n\n this.serviceStream.removeListener(\n 'data'\n , this.boundStreamListener\n );\n }", "function inputUnhook(obj) {\n for (var i = 0; i < inputObjects.length; i++) {\n if (inputObjects[i] == obj) {\n inputObjects.splice(i, 1);\n }\n }\n}", "function setHashKey(obj, h) {\n\t\tif (h) {\n\t\t\tobj.$$hashKey = h;\n\t\t}\n\t\telse {\n\t\t\tdelete obj.$$hashKey;\n\t\t}\n\t}", "remove(eventName) {\n if (this.eventStorage[eventName]) {\n delete this.eventStorage[eventName];\n }\n }", "undelegate(eventName, selector, listener, uid) {\n\n\t\tif (this.el){\n\t\t\tif (selector){\n\t\t\t\tconst items = [...this.el.querySelectorAll(selector)];\n\t\t\t\tif (items.length > 0 ) items.forEach((item) => item.removeEventListener(eventName, listener) );\n\t\t\t} else {\n\t\t\t\tthis.el.removeEventListener(eventName, listener);\n\t\t\t}\n\t\t}\n\t\t// remove event from array based on uid\n\t\t_.remove(this.delegatedEvents, (event) => {\n\t\t\treturn event.uid === uid;\n\t\t});\n\n\t\treturn this;\n\t}", "unsubscribe(eventType, handler) {\n const subscribers = this.events.get(eventType);\n if (!subscribers || !subscribers.has(handler)) {\n throw new Error(`Subscription not found for event: '${eventType}'`);\n }\n subscribers.delete(handler);\n this.events.set(eventType, subscribers);\n }", "function removeFromCollection(movieId) {\n\n // fetch the Collection first.\n let collectionName = document.getElementById('searchFilterText').textContent;\n let collectionId = null;\n\n let url = \"http://localhost:3000/userCollections?name=\" + collectionName;\n\n // Fetch Collection details\n httpSync(url, (responseText) => {\n let response = JSON.parse(responseText);\n let index = response[0].movies.indexOf(parseInt(movieId));\n collectionId = response[0].id;\n if (index > -1) {\n response[0].movies.splice(index, 1);\n }\n\n //Update the DB\n var url = 'http://localhost:3000/userCollections/' + collectionId;\n\n // create a Post Request\n var json = JSON.stringify(response[0]);\n httpPostOrPut(url, 'PUT', json);\n\n }, 'GET', null);\n\n // Update the Store\n //store.dispatch(setActionFilter(ActionFilters.SHOW_MOVIE_REMOVED));\n currentAction = ActionFilters.MOVIE_REMOVED;\n store.dispatch(removeMovieFromCollectionStore(collectionId, movieId));\n}", "async remove (id, params) {\n //need to use this in different scope\n const self = this;\n const roomId = id;\n //prolly get user model maybe (why is it caps???)\n const users = this.sequelizeClient.model.Users;\n //get user to be removed\n const {user} = params;\n //remove roomId from users \"rooms\" array (ide says i need an await here but i dont think i do)\n await users.update({'rooms': Sequelize.fn('array_remove', Sequelize.col('rooms'), roomId)},\n {'where': {'id': user}});\n //if user is connected to the rooms/roomId channel remove them\n self.app.channel(`rooms/${roomId}`).connections.forEach(function (connection){\n if(connection.user.id === user){\n self.app.channel(`room/${roomId}`).leave(connection);\n }\n });\n\n return id;\n }", "static async remove(id, item_type, link, ownershipCheck) {\n // Compose the query to find the comment.\n const query = {\n id,\n 'tags.tag.name': {\n $eq: link.tag.name,\n },\n };\n\n // If ownership verification is required, ensure that the person that is\n // assigning the tag is the same person that owns the comment.\n if (ownershipCheck) {\n // Modify the query to support an ownership verification.\n ownershipQuery(item_type, link, query);\n }\n\n // Get the Model to perform the update.\n return updateModel(item_type, query, {\n $pull: {\n tags: {\n 'tag.name': link.tag.name,\n },\n },\n });\n }", "function removeQuery(state, queryId) {\n const new_order = [];\n for(const id of state.order) {\n if(id !== queryId) {\n new_order.push(id);\n }\n }\n\n const new_state = Object.assign({}, state, {order: new_order});\n delete new_state[queryId];\n return new_state;\n}", "removeObject(remove) {\n var index = -1;\n \n if(remove instanceof Object) {\n index = this.objects.indexOf(remove); // Find the index of the object\n } else { // If it is an integer number\n index = remove;\n }\n \n if(index >= 0) {\n this.objects.splice(index, 1);\n }\n }", "function deleteVideoObject(videoIdNum) {\n setTimeout(() => fetch(`${databaseURL}/${videoIdNum}`, {method: \"DELETE\"})\n .then(function() {\n delete localDatabase[videoIdNum];\n document.querySelector(`div[data-id=\"${videoIdNum}\"]`).remove()\n }), 250)\n \n}", "removeTexture(texture) {\n // remove from our textures array\n this.textures = this.textures.filter(element => element.uuid !== texture.uuid);\n }", "function detachHistoryListener() {\n window.removeEventListener('hashchange', onHashChange);\n}", "function unsubscribe() {\n getSubscription().then(subscription => {\n return subscription.unsubscribe()\n .then(() => {\n console.log('Unsubscribed ', subscription.endpoint)\n return fetch('http://localhost:4040/unregister', \n {\n method: 'POST',\n headers: {'Content-Type' : 'application/json'},\n body: JSON.stringify({\n endpoint: subscription.endpoint\n })\n })\n })\n }).then(setSubscribeButton)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }