query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
Gather some caller info 3 stack levels up. See < | function getCaller3Info() {
var obj = {};
var saveLimit = Error.stackTraceLimit;
var savePrepare = Error.prepareStackTrace;
Error.stackTraceLimit = 3;
Error.captureStackTrace(this, getCaller3Info);
Error.prepareStackTrace = function (_, stack) {
var caller = stack[2];
obj.file = caller.getFileName();
obj.line = caller.getLineNumber();
var func = caller.getFunctionName();
if (func)
obj.func = func;
};
//this.stack;
Error.stackTraceLimit = saveLimit;
Error.prepareStackTrace = savePrepare;
return obj;
} | [
"function getStackFromCaller() {\n\t\t\treturn getStack(4,-1);\n\t\t}",
"function getCaller3Info() {\n\t if (this === undefined) {\n\t // Cannot access caller info in 'strict' mode.\n\t return;\n\t }\n\t var obj = {};\n\t var saveLimit = Error.stackTraceLimit;\n\t var savePrepare = Error.prepareStackTrace;\n\t Error.stackTraceLimit = 3;\n\t Error.captureStackTrace(this, getCaller3Info);\n\n\t Error.prepareStackTrace = function (_, stack) {\n\t var caller = stack[2];\n\t if (sourceMapSupport) {\n\t caller = sourceMapSupport.wrapCallSite(caller);\n\t }\n\t obj.file = caller.getFileName();\n\t obj.line = caller.getLineNumber();\n\t var func = caller.getFunctionName();\n\t if (func)\n\t obj.func = func;\n\t };\n\t this.stack;\n\t Error.stackTraceLimit = saveLimit;\n\t Error.prepareStackTrace = savePrepare;\n\t return obj;\n\t}",
"function getCaller3Info() {\n\t if (this === undefined) {\n\t // Cannot access caller info in 'strict' mode.\n\t return;\n\t }\n\t var obj = {};\n\t var saveLimit = Error.stackTraceLimit;\n\t var savePrepare = Error.prepareStackTrace;\n\t Error.stackTraceLimit = 3;\n\n\t Error.prepareStackTrace = function (_, stack) {\n\t var caller = stack[2];\n\t if (sourceMapSupport) {\n\t caller = sourceMapSupport.wrapCallSite(caller);\n\t }\n\t obj.file = caller.getFileName();\n\t obj.line = caller.getLineNumber();\n\t var func = caller.getFunctionName();\n\t if (func)\n\t obj.func = func;\n\t };\n\t Error.captureStackTrace(this, getCaller3Info);\n\t this.stack;\n\n\t Error.stackTraceLimit = saveLimit;\n\t Error.prepareStackTrace = savePrepare;\n\t return obj;\n\t}",
"function getCaller3Info() {\n if (this === undefined) {\n // Cannot access caller info in 'strict' mode.\n return;\n }\n var obj = {};\n var saveLimit = Error.stackTraceLimit;\n var savePrepare = Error.prepareStackTrace;\n Error.stackTraceLimit = 3;\n Error.captureStackTrace(this, getCaller3Info);\n\n Error.prepareStackTrace = function (_, stack) {\n var caller = stack[2];\n if (sourceMapSupport) {\n caller = sourceMapSupport.wrapCallSite(caller);\n }\n obj.file = caller.getFileName();\n obj.line = caller.getLineNumber();\n var func = caller.getFunctionName();\n if (func)\n obj.func = func;\n };\n this.stack;\n Error.stackTraceLimit = saveLimit;\n Error.prepareStackTrace = savePrepare;\n return obj;\n}",
"function getCaller3Info() {\n if (this === undefined) {\n // Cannot access caller info in 'strict' mode.\n return;\n }\n var obj = {};\n var saveLimit = Error.stackTraceLimit;\n var savePrepare = Error.prepareStackTrace;\n Error.stackTraceLimit = 3;\n\n Error.prepareStackTrace = function (_, stack) {\n var caller = stack[2];\n if (sourceMapSupport) {\n caller = sourceMapSupport.wrapCallSite(caller);\n }\n obj.file = caller.getFileName();\n obj.line = caller.getLineNumber();\n var func = caller.getFunctionName();\n if (func)\n obj.func = func;\n };\n Error.captureStackTrace(this, getCaller3Info);\n this.stack;\n\n Error.stackTraceLimit = saveLimit;\n Error.prepareStackTrace = savePrepare;\n return obj;\n}",
"function getCallerInfo() {\n try { throw new Error(''); } catch (err) {\n var callerLine = err.stack.split(\"\\n\")[4]; // get line of caller\n var index = callerLine.indexOf(\"at \");\n return callerLine.slice(index + 3, callerLine.length);\n }\n}",
"function getCallerFromStack() {\n\t\t\treturn getStack(4,1);\n\t\t}",
"function getStack() {\n var stack = callsite()[3];\n return [stack.getFileName(), stack.getLineNumber(), stack.getColumnNumber()].join(':')\n}",
"function traceCaller(n) {\r\n\tif (isNaN(n) || n < 0) n = 1;\r\n\tn += 1;\r\n\tvar s = (new Error()).stack,\r\n\t\ta = s.indexOf('\\n', 5);\r\n\twhile (n--) {\r\n\t\ta = s.indexOf('\\n', a + 1);\r\n\t\tif (a < 0) {\r\n\t\t\ta = s.lastIndexOf('\\n', s.length);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tb = s.indexOf('\\n', a + 1);\r\n\tif (b < 0) b = s.length;\r\n\ta = Math.max(s.lastIndexOf(' ', b), s.lastIndexOf('/', b));\r\n\tb = s.lastIndexOf(':', b);\r\n\ts = s.substring(a + 1, b);\r\n\treturn s;\r\n}",
"function traceCaller(n) {\n\tif ( isNaN(n) || n<0) \n\t\tn = 1;\n\tn += 1;\n\tvar s = ( new Error() ).stack\n\t\t, a = s.indexOf( '\\n', 5 );\n\twhile ( n-- ) {\n\t\ta = s.indexOf( '\\n', a+1 );\n\t\tif ( a<0 ) { \n\t\t\ta = s.lastIndexOf( '\\n', s.length ); \n\t\t\tbreak;\n\t\t}\n\t}\n\tb = s.indexOf( '\\n', a+1 ); \n\tif ( b < 0 ) \n\t\tb = s.length;\n\ta = Math.max( s.lastIndexOf( ' ', b ), s.lastIndexOf( '/', b ) );\n\tb = s.lastIndexOf( ':', b );\n\ts = s.substring( a+1, b );\n\treturn s;\n}",
"function prepareStackInfo() {\n \tvar stackInfo = [];\n \tframeInfo = [];\n \t\n \tfor (var i=callStackDepth-1; i >= 0; i--) {\n \t\t\n \t\tvar frameInfo = {};\n \t\tframeInfo.callFrameId = \"stack:\"+i;\n \t\tframeInfo.functionName = callStack[i].name;\n \t\tframeInfo.location = {\n \t\t\tscriptId : i == callStackDepth-1 ? lastFile : callStack[i+1].lastFile,\n \t\t\tlineNumber : i == callStackDepth-1 ? lastLine : callStack[i+1].lastLine,\n \t\t\tcolumnNumber : 0\n \t\t};\n \t\t\n \t\t// add frame 'scopeChain[]' info\n \t\tframeInfo.scopeChain = [];\n \t\tvar scope = { object : {}, type : 'local'};\n \t\t\n \t\tscope.object = {\n \t\t\ttype : 'object',\n \t\t\tobjectId : 'stack:' + i,\n \t\t\tclassName : 'Object',\n \t\t\tdescription : 'Object'\n \t\t};\n \t\tframeInfo.scopeChain.push(scope);\n \t\t\n \t\t// add frame 'this' info\n \t\tframeInfo['this'] = {\n \t\t\ttype : typeof(callStack[i].that),\n \t\t\tobjectId : 'stack:' + i + ':this',\n \t\t\tclassName : callStack[i].that.constructor.name,\n \t\t\tdescription : callStack[i].that.constructor.name\n \t\t};\n \t\t\n \t\tstackInfo.push(frameInfo);\n \t}\n \treturn stackInfo;\n }",
"function traceCaller(n) {\n if( isNaN(n) || n<0) n=1;\n n+=1;\n var s = (new Error()).stack;\n var a = s.indexOf('\\n',5);\n while(n--) {\n a=s.indexOf('\\n',a+1);\n if( a<0 ) { a=s.lastIndexOf('\\n',s.length); break;}\n }\n var b=s.indexOf('\\n',a+1); if( b<0 ) b=s.length;\n a=Math.max(s.lastIndexOf(' ',b), s.lastIndexOf('/',b));\n b=s.lastIndexOf(':',b);\n s=s.substring(a+1,b);\n return s;\n }",
"function traceCaller(n) {\n if( isNaN(n) || n<0) n=1;\n n+=1;\n let s = (new Error()).stack\n , a=s.indexOf('\\n',5);\n while(n--) {\n a=s.indexOf('\\n',a+1);\n if( a<0 ) { a=s.lastIndexOf('\\n',s.length); break;}\n }\n let b=s.indexOf('\\n',a+1); if( b<0 ) b=s.length;\n a=Math.max(s.lastIndexOf(' ',b), s.lastIndexOf('/',b));\n b=s.lastIndexOf(':',b);\n s=s.substring(a+1,b);\n return s;\n }",
"function callsites() {\n const _prepareStackTrace = Error.prepareStackTrace;\n Error.prepareStackTrace = (_, stack) => stack;\n const stack = new Error().stack?.slice(1);\n Error.prepareStackTrace = _prepareStackTrace;\n return stack;\n}",
"_getCallerInfo(callerStackDistance) {\n if (this.options.client.showCallerInfo) {\n let stack = utils.getStack().map(frame => {\n return {\n functionName: frame.getFunctionName(),\n methodName: frame.getMethodName(),\n fileName: frame.getFileName(),\n lineNumber: frame.getLineNumber(),\n columnNumber: frame.getColumnNumber()\n }\n })\n\n let caller = stack.find((frame, index, stack) => {\n // We're either looking for a console method call or a bunyan log call. This logic will break down if method names change.\n let twoBack = stack[index - 2]\n let sixBack = stack[index - 4]\n if (twoBack && twoBack.functionName === 'Logger._emit' && /\\/bunyan\\.js$/.test(twoBack.fileName)) {\n return true\n } else if (twoBack && sixBack && twoBack.methodName === 'emit' && sixBack.methodName === '_sendMessage') {\n return true\n }\n })\n\n if (!caller && typeof callerStackDistance === 'number') {\n caller = stack[callerStackDistance]\n }\n\n if (caller) {\n return {\n caller: caller.functionName || caller.methodName,\n file: caller.fileName,\n line: caller.lineNumber,\n column: caller.columnNumber\n }\n }\n }\n }",
"function CallStack_getCaller( fn )\n{\n\tif( fn.caller !== undefined )\n\t\treturn fn.caller;\n\tif( fn.arguments !== undefined && fn.arguments.caller !== undefined )\n\t\treturn fn.arguments.caller;\n\t\t\t\n\treturn undefined;\n}",
"function GlobalCallInfo ()\n{\n this.top_down_view = call_info.CallInfo ();\n\n\n this.process_call_stack = function (call_list_obj)\n {\n var clo = call_list_obj;\n\n for (var key in clo)\n {\n if (clo.hasOwnProperty (key))\n {\n this.top_down_view.add_call (clo[key]);\n }\n }\n };\n}",
"_getCallerInfo(callerStackDistance) {\n if (this.options.client.showCallerInfo) {\n const stack = utils.getStack().map((frame) => {\n return {\n functionName: frame.getFunctionName(),\n methodName: frame.getMethodName(),\n fileName: frame.getFileName(),\n lineNumber: frame.getLineNumber(),\n columnNumber: frame.getColumnNumber(),\n }\n })\n\n let caller = stack.find((frame, index, stack) => {\n // We're either looking for a console method call or a bunyan log call. This logic will break down if method names change.\n const twoBack = stack[index - 2]\n const sixBack = stack[index - 4]\n if (twoBack && twoBack.functionName === \"Logger._emit\" && /\\/bunyan\\.js$/.test(twoBack.fileName)) {\n return true\n } else if (twoBack && sixBack && twoBack.methodName === \"emit\" && sixBack.methodName === \"_sendMessage\") {\n return true\n }\n })\n\n if (!caller && typeof callerStackDistance === \"number\") {\n caller = stack[callerStackDistance]\n }\n\n if (caller) {\n return {\n caller: caller.functionName || caller.methodName,\n file: caller.fileName,\n line: caller.lineNumber,\n column: caller.columnNumber,\n }\n }\n }\n }",
"function getCaller() {\n var stack = getStack();\n\n // Remove superfluous function calls on stack\n stack.shift(); // getCaller --> getStack\n stack.shift(); // omfg --> getCaller\n\n // Return caller's caller\n return stack[0];\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the default driver to use for the cluster node instance | setDriver(driver) {
this.driver = driver;
this.pool = neo4j.getSessionPool(this.id, this.driver, 15);
} | [
"defaultDriver () {\n return this._config.default\n }",
"_initializeDriver() {\n if(Neo4jWrapper.drivers.get(this.host)) {\n this.driver = Neo4jWrapper.drivers.get(this.host);\n } else {\n this.driver = neo4j.driver(this.host, neo4j.auth.basic(this.username, this.password));\n Neo4jWrapper.drivers.set(this.host, this.driver);\n }\n return this.driver;\n }",
"setDriver(driver) {\n this.driver = driver;\n }",
"function setConfigDefault() {\n config.host = \"adearisdb.cwvcjn59heq2.us-east-2.rds.amazonaws.com\";\n config.user = \"adearis\";\n config.password = \"adearis1234\";\n config.database = \"adearisDB\";\n config.port = 5432;\n}",
"function instantiateDrivers(config, defaultDriverInstance) {\n config.actionConfigs.forEach(action => {\n action.driverInstance=action.driver?action.driver():defaultDriverInstance;\n });\n return config;\n}",
"function setConfigDefault(){\n config.host = 'adearisdb.cwvcjn59heq2.us-east-2.rds.amazonaws.com';\n config.user = 'adearis';\n config.password = 'adearis1234';\n config.database = 'adearisDB';\n config.port = 5432;\n}",
"driverFor(addr, username = _.get(this.base, 'username'), password = _.get(this.base, 'password')) {\n const tlsLevel = _.get(this.base, 'tlsLevel');\n const encrypted = (tlsLevel === 'REQUIRED' ? true : false);\n\n if (this.drivers[addr]) {\n return this.drivers[addr];\n }\n\n const allOptions = _.merge({ encrypted }, this.driverOptions);\n if (this.debug) {\n console.log('Driver connection', { addr, username, allOptions });\n }\n const driver = neo4j.driver(addr,\n neo4j.auth.basic(username, password), allOptions);\n\n this.drivers[addr] = driver;\n return driver;\n }",
"function instantiateDrivers(config, defaultDriverInstance) {\n config.actionConfigs.forEach(function (action) {\n action.driverInstance = action.driver ? action.driver() : defaultDriverInstance;\n });\n return config;\n }",
"driverFor(addr, username = _.get(this.base, 'username'), password = _.get(this.base, 'password')) {\n const tlsLevel = _.get(this.base, 'tlsLevel');\n const encrypted = (tlsLevel === 'REQUIRED' ? true : false);\n\n if (this.drivers[addr]) {\n return this.drivers[addr];\n }\n\n const allOptions = _.merge({ encrypted }, this.driverOptions);\n if (this.debug) {\n sentry.fine('Driver connection', { addr, username, allOptions });\n }\n const driver = neo4j.driver(addr,\n neo4j.auth.basic(username, password), allOptions);\n\n this.drivers[addr] = driver;\n return driver;\n }",
"setDriver(driver, value, report = true, forceReport = false, uom = null) {\r\n // Is driver valid?\r\n if (driver in this.drivers &&\r\n 'value' in this.drivers[driver] &&\r\n 'uom' in this.drivers[driver]) {\r\n\r\n if (uom && this.drivers[driver].uom !== uom) {\r\n this.drivers[driver].uom = uom;\r\n this.drivers[driver].changed = true;\r\n }\r\n\r\n value = this.convertValue(driver, value);\r\n\r\n if (this.drivers[driver].value !== value) {\r\n logger.info('Setting node %s driver %s: %s',\r\n this.address, driver, value);\r\n\r\n this.drivers[driver].value = value;\r\n this.drivers[driver].changed = true;\r\n }\r\n\r\n if (report) {\r\n this.reportDriver(driver, forceReport);\r\n }\r\n } else {\r\n logger.error('Driver %s is not valid for node %s', driver, this.address);\r\n }\r\n }",
"set driver(driverUri) {\n if (!driverUri) {\n return;\n }\n\n if (!driverUri.indexOf(\"://\") > 0) {\n driverUri = \"/\" + driverUri;\n }\n\n this.driverOrPpd = driverUri;\n }",
"setDriver(driverUri) {\n\n if (!driverUri.indexOf(\"://\") > 0) {\n driverUri = \"/\" + driverUri;\n }\n\n this._driverOrPpd = driverUri;\n\n }",
"function setBrowserDriver() {\n if(!!server.remote) return;\n if(!args.browser) {\n args.browser = \"firefox\";\n return;\n }\n if (args.browser === \"chrome\") {\n var chrome = require('selenium-webdriver/chrome');\n var service = new chrome.ServiceBuilder(config.get('tests.pathToChromeDriver')).build();\n chrome.setDefaultService(service);\n } \n else if(args.browser === \"ie\") {\n process.env.PATH = process.env.PATH + ';' + path.resolve (config.get('tests.pathToIEDriver'));\n }\n}",
"function setNodeSelectorsDefaultValue() {\n ctrl.nodeSelectors = lodash.chain(ConfigService).get('nuclio.defaultFunctionConfig.attributes.spec.nodeSelector', []).map(function (value, key) {\n return {\n name: key,\n value: value,\n ui: {\n editModeActive: false,\n isFormValid: key.length > 0 && value.length > 0,\n name: 'nodeSelector'\n }\n };\n }).value();\n }",
"connect() {\n\t\tconst mysql = require(\"mysql\"),\n\t\t\tcluster = mysql.createPoolCluster({\n\t\t\t\trestoreNodeTimeout: 1000\n\t\t\t}),\n\t\t\thasSlaves = (typeof this.config.mysql.slaves !== \"undefined\" && this.config.mysql.slaves instanceof Array);\n\n\t\tcluster.add('MASTER', this.config.mysql.master);\n\n\t\tif (!hasSlaves) {\n\t\t\tthis.config.mysql.slaves = [];\n\t\t}\n\n\t\tthis.config.mysql.slaves.forEach((slave, index) => {\n\t\t\tcluster.add(`SLAVE${(index+1)}`, slave);\n\t\t});\n\n\t\tthis.cluster = cluster;\n\t}",
"function setDefaultMonitor(monitor) {\n defaultMonitor = monitor;\n }",
"function setDefaultBackend(newBackend) {\n backend = newBackend\n}",
"setMeAsBootstrap() {\n Models.node_config.update({\n value: '[]',\n }, {\n where: {\n key: 'network_bootstrap_nodes',\n },\n }).then(() => {\n this.restartNode();\n });\n }",
"defaultConnection () {\n return Config.get('database.default')\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if the current game instance is full. | isGameFull(){
return Object.keys(this.players).length >= this.maxPlayers;
} | [
"isFull() {\n if (this.ammoCount >= this.canvasWidth * 0.6) {\n return true;\n }\n return false;\n }",
"isFull() {\n return this.container.getAllGameObjects().some(obj => obj.gameObject.takesWholeSector);\n }",
"function _isFull() {\n\t\treturn this._particleCount == this.system.totalParticles;\n\t}",
"isFull() {\n return this.length() === this.capacity;\n }",
"isFull() {\n if (this.currentUsers >= this.maxSize) {\n return true;\n }\n\n return false;\n }",
"function checkGameBoardIsFull()\n {\n var isFull = true;\n \n $('.game-cell-input').each(function(){\n isFull = !!($(this).val()) && isFull;\n });\n \n return isFull;\n }",
"isFull(){\n if(this.maxSize){\n return this.top + 1 === this.maxSize;\n }\n else{\n return false;\n }\n }",
"isGridFull() {\n if (this.player1.noOfMoves + this.player2.noOfMoves < this.maxNoOfMoves) {\n return false;\n }\n return true;\n }",
"canStartGame() {\r\n return this.players.length >= this.town.maximumMembers\r\n && this.town.status == 'FREE';\r\n }",
"is_full() {\n\t\treturn this._current_weight === this._max_weight;\n\t}",
"get isFull() {\n return this._length === this._maxLength;\n }",
"isBoardFull() {\n\t\t//Go row by row and col by col and check to see if there is any empty board spots. If there is, board is not full (false)\n\t\tfor (let row = 0; row < this.size; row++) {\n\t\t\tfor (let col = 0; col < this.size; col++) {\n\t\t\t\tif (this.board[row][col] === Othello.EMPTY) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}",
"isFull() {\n return this.items.length === this.maxItems;\n }",
"isEmpty() {\n if (this.ammoCount - 25 < 0) {\n return true;\n }\n return false;\n }",
"function isInventoryFull() {\n let window = bot.inventory\n return window.emptySlotCount() === 0;\n\n}",
"isFull() {\n return this.counter > 0 && this.counter % this.len === 0;\n }",
"get isFull() {\n return this.haliteAmount >= constants.MAX_HALITE;\n }",
"isFull() {\n return this.length >= this.limit;\n }",
"function isBoardFull() {\n\treturn (gFullCellCount === (gBoard.length - 2) * (gBoard[0].length - 2) - 1);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
input: an array of Needs:"prereq". output: an HTML string that list all prereq.. | function parsePrereq(prereq)
{
if (prereq.length == 0)
return "None";
return $.map(prereq, function(record, index)
{
return record.Needs.replace(/\[/g,"<span class='course_symbol fakeLink'>").replace(/\]/g,"</span>");
}).join("");
} | [
"function processPrereqs(prereqs) {\n if (prereqs == \"\") {\n\t\tprereqs = \"--\";\n\t}\n else {\n\t while (prereqs.search(/GIR:/) >= 0) {\n\t\t gir = prereqs.match(/GIR:.{4}/);\n\t\t prereqs = prereqs.replace(/GIR:.{4}/, girData[gir].join(\" or \"));\n\t }\n\t while (prereqs.search(/[\\]\\[]/) >= 0 ) {\n\t\t prereqs = prereqs.replace(/[\\]\\[]/, \"\");\n\t }\n }\n // Makes prereqs appear as links\n prereqs = coursesToLinks(prereqs);\n return prereqs;\n}",
"function printDevelopmentNeedsList(dueDate, title, description, progress, createdOn, category, isArchived){\n\tvar html = \" \\\n <tr> \\\n <td>\"+dueDate+\"</td> \\\n <td><span style=\\\"font-weight: bold;\\\">\"+title+\"\\n\\n</span><br/>\"+description+\"</td> \\\n <td>\"+progress+\"</td> \\\n <td>\"+timeStampToLongDate(createdOn)+\"</td> \\\n <td>\"+category+\"</td> \\\n \t\t <td>\"+isArchived+\"</td> \\\n </tr> \\\n \"\n return html;\n}",
"function getAddedPrereqs(){\n\t\tvar added_prereqs = [];\n\t\t$(\"#added_prereqs tr\").each((index, elem) => {\n\t\t \tadded_prereqs.push(elem.id);\n\t\t});\n\t\tif(added_prereqs==\"\")\n\t\t\treturn [\"0\"];\n\t\treturn added_prereqs;\n\t}",
"function GetPrereqs(course, cjo) {\r\n\tvar reqs;\r\n\tvar courses_jo = cjo.courses;\r\n\tfor(var i in courses_jo) {\r\n\t\tif(course.course_name == courses_jo[i].course_name) {\r\n\t\t\tif(jQuery.isEmptyObject(courses_jo[i].prerequisite)) return \"None\";\r\n\t\t\tif(jQuery.isEmptyObject(courses_jo[i].prerequisite.or_choice)) return \"None\";\r\n\t\t\treqs = courses_jo[i].prerequisite.or_choice.and_required.split(\",\");\r\n\t\t\tfor(var k = 0; k < reqs.length; k++) {\r\n\t\t\t\treqs[k] = reqs[k].substring(8); //cuts out \"CMP SCI \"\r\n\t\t\t}\r\n\t\t\tif(reqs.length != 0) return reqs[0];\r\n\t\t\treturn reqs;\r\n\t\t}\t\r\n\t}\r\n}",
"function printReplies(replies){\n var out = \"\";\n for (var i = 0; i <= replies.length - 1; i++){\n out += '<li>'+replies[i]+'</li>';\n };\n return out;\n}",
"_makePrereqs() {\n const prereqCells =\n Object.values(this._cells).filter(cell => !cell.isEmpty());\n const prereqs = Object.fromEntries(prereqCells.map(c => [c.id, []]));\n for (const cell of prereqCells) {\n for (const d of cell.dependents) {\n\tif (prereqs[d]) prereqs[d].push(cell.id);\n }\n }\n return prereqs;\n }",
"function generatePriorityList() {\n\tpriorityList.innerHTML = \"\";\n\tfor (let i = 0; i < subjects.length; i++) {\n\t\tpriorityList.innerHTML +=\n\t\t\t'<input type=\"checkbox\">' + subjects[i].title + \"<br />\";\n\t}\n}",
"function displayContributors() {\n for (var i in appState.questionsMeta.contribs) {\n var author = appState.questionsMeta.contribs[i]\n $('#q-contributors').append(`<li>${author}</li>`)\n }\n}",
"getGeneratedCourseRequirementsList() {\n var requirements_list = [];\n for(var i=0; i<this.result_course_requirements.length; i++) {\n requirements_list = requirements_list.concat(\n <div class={this.result_course_requirements[i][1] == true ? \"fulfilled\" : \"\"}>\n {this.getRequirementElement(this.result_course_requirements[i][0], true)}\n </div>\n );\n\n requirements_list.push(<li class=\"reqs-course-separator\"><hr></hr></li>);\n }\n\n return requirements_list;\n }",
"function add_prereq(){\n\t\t$(\".add_prereq\").click(function(){\n\t\t\tsearchPrereq();\n\t\t\t$(\".success_add_prereq\").remove();\n\t\t});\n\t}",
"function printObjectivesList(dueDate, title, description, progress, createdOn, proposedBy, isArchived){\n\tvar html = \" \\\n <tr> \\\n <td>\"+dueDate+\"</td> \\\n <td><span style=\\\"font-weight: bold;\\\">\"+title+\"</span><br/>\"+description+\"</td> \\\n <td>\"+progress+\"</td> \\\n <td>\"+createdOn+\"</td> \\\n <td>\"+proposedBy+\"</td> \\\n \t\t <td>\"+isArchived+\"</td> \\\n </tr> \\\n \"\n return html;\n}",
"function displayArray(prArray){\n\t\t//declare the placeholder for search area\n\t\tvar placeholder = \"Search for Product Report\";\n\t\t//links is an html list with jquery mobile markups for dividers\n\t\t//initalize links variable with firs tlist divider and the first\n\t\t//product report, then loop prArray to finish building links variable\n\t\tvar links = \"<li data-role='list-divider'>\" + prArray[0].series + \" Series</li><li><a href='\"+prArray[0].url+\"'>\"+prArray[0].title+\"</a></li>\";\n\t\tfor(i=1;i<prArray.length;i++){\n\t\t\tif(prArray[i].series!=prArray[i-1].series){\n\t\t\t\tlinks += \"<li data-role='list-divider'>\" + prArray[i].series + \" Series</li>\";\n\t\t\t\t}\n\t\t\tlinks += \"<li><a href='\"+prArray[i].url+\"'>\"+prArray[i].title+\"</a></li>\";\n\t\t}\n\t\t//set content of link-list-container div to contain a list with populated links variable, \n\t\t$('#link-list-container').html('<ul id=\"link-list\" data-role=\"listview\" data-inset=\"true\" data-filter=\"true\" data-filter-placeholder=\"'+placeholder+'\">'+links+'</ul>');\n\t\t//render link-list div as a jquery mobile listview\n\t\t$(\"#link-list\").listview();\n\t}",
"function dependencyHTML(visArray) {\n\t\tvar html = '', allDeps = [];\n\t\t\n\t\t// Standard dependencies\n\t\thtml += '<script src=\"/web-api/js/lib/jquery.min.js\"></script>\\n';\n\t\thtml += '<script src=\"/web-api/js/lib/jquery.xml2json.js\"></script>\\n';\n\t\thtml += '<script src=\"/web-api/js/lib/d3.min.js\"></script>\\n';\n\t\thtml += '<script src=\"/web-api/js/rmvpp-ext.js\"></script>\\n';\n\t\thtml += '<script src=\"/web-api/js/obieeUI.js\"></script>\\n\\n';\n\t\thtml += '\\n<script src=\"/web-api/js/obiee-v8.js\"></script>\\n';\n\t\thtml += '<link\trel=\"stylesheet\" type=\"text/css\" href=\"/web-api/css/obiee.css\">\\n';\n\t\thtml += '\\n<script src=\"/web-api/js/pluginAPI.js\"></script>\\n';\n\t\thtml += '<link\trel=\"stylesheet\" type=\"text/css\" href=\"/web-api/css/pluginAPI.css\">\\n';\n\t\thtml += '\\n<script src=\"/web-api/js/lib/jquery.sumoselect.min.js\"></script>\\n';\n\t\thtml += '<link\trel=\"stylesheet\" type=\"text/css\" href=\"/web-api/css/lib/sumoselect.css\">\\n';\n\t\thtml += '\\n<!-- Fonts -->\\n';\n\t\thtml += '<link href=\"http://fonts.googleapis.com/css?family=Open+Sans:400,700\" rel=\"stylesheet\" type=\"text/css\">\\n';\n\t\thtml += '<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css\">\\n';\n\t\t\n\t\tfor (var i=0; i < visArray.length; i++) {\n\t\t\tdeps = rmvpp[visArray[i].Plugin].dependencies;\n\n\t\t\tfor (var j=0; j < deps.js.length; j++) {\n\t\t\t\tvar dep = '<script src=\"' + deps.js[j] + '\"></script>\\n';\n\t\t\t\tif ($.inArray(dep, allDeps) == -1) { // Check if dependency already included\n\t\t\t\t\thtml += dep;\n\t\t\t\t\tallDeps.push(dep);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif ('css' in deps) {\n\t\t\t\tfor (var j=0; j < deps.css.length; j++ ) {\n\t\t\t\t\tvar dep = '<link rel=\"stylesheet\" type=\"text/css\" href=\"' + deps.css[j] + '\">\\n';\n\t\t\t\t\tif ($.inArray(dep, allDeps) == -1) { // Check if dependency already included\n\t\t\t\t\t\thtml += dep;\n\t\t\t\t\t\tallDeps.push(dep);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn html;\t\t\n\t}",
"function renderProducts(arr) {\r\n // 1. map() the Array through getCourseAsHtmlString into a new Array\r\n const arrOfHtml = arr.map(getProductsAsHtmlString)\r\n \r\n // 2. join() the new Array into a single String of HTML\r\n const strOfHtml = arrOfHtml.join('\\n')\r\n \r\n // 3. Put the String into the innerHTML of the document's #courses\r\n document.getElementById('products').innerHTML = strOfHtml;\r\n }",
"function printFeedbackList(providerEmail, providerName, feedbackDescription, providedOn){\n var html = \" \\\n <tr> \\\n <td><span style=\\\"font-weight: bold;\\\">\"+providerName+\"\\n\\n</span><br/>\"+providerEmail+\"</td> \\\n <td>\"+feedbackDescription+\"</td> \\\n <td>\"+providedOn+\"</td> \\\n </tr> \\\n \"\n return html;\n}",
"function getReferencesHTML(indeces){\n var s = '';\n if ((indeces != null) && (indeces.length > 0)) {\n var r = indeces.split(',');\n for (var i = 1; i <= r.length; i++) { \n s += '<p><sup>' + i + '</sup> ' + references[r[i-1]] + '</p>';\n }\n }\n if (s.length > 0) {\n s = '<p><span class=\"bold\">References</span></p>' + s;\n }\n return s;\n}",
"function displayArray(prArray){\n\t\tvar links = '<li data-role=\"list-divider\">' + prArray[0].series + ' Series</li>';\n links+=\"<li><a onClick=cb.showWebPage('\"+prArray[0].url+\"')>\"+prArray[0].title+\"</a></li>\";\n\t\tfor(i=1;i<prArray.length;i++){\n\t\t\tif(prArray[i].series!=prArray[i-1].series){\n\t\t\t\tlinks += '<li data-role=\"list-divider\">' + prArray[i].series + ' Series</li>';\n\t\t\t\t}\n\t\t\tlinks += \"<li><a onclick=cb.showWebPage('\"+prArray[i].url+\"')>\"+prArray[i].title+\"</a></li>\";\n\t\t}\n\t\t$('#link-list-container').html('<ul id=\"link-list\" data-role=\"listview\" data-inset=\"true\" data-filter=\"true\" data-filter-placeholder=\"Search for Product Report\">'+links+'</ul>');\n\t\t$(\"#link-list\").listview();\n\t}",
"function emotesArraytoHTML(emotes){\n\tret_str = \"\"\n\tvar i;\n\tfor(i = 0; i < emotes.length; i++){\n\t\tif(emotes[i][0] != 'null'){\n\t\t\tif(LITE){\n\t\t\t\tret_str += '<p><b>\"' + emotes[i][1] + '</b>\": ' + emotes[i][2] + '</p>';\n\t\t\t}\n\t\t\telse{\n\t\t\t\tret_str += '<p><img src=\"' + IDtoImage(emotes[i][0]) + '\">: ' + emotes[i][2] + '</p>';\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn ret_str;\n}",
"function constructPolicy(array) {\n var string = \"\";\n for (i = 0; i < array.length; i++) {\n string += \"<p>\" + array[i] + \"</p>\";\n }\n\n return string;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Increase stamina_points. Can not regenerate above maximum stamina | regenerateStamina(amountToRegenerate){
//Determine maximum
let maxToRegen = this.props.stats_current.stamina - this.props.stamina_points;
//If trying to regenerate more than maximum, only regen up to maximum
let appliedAmountToRegenerate = ((amountToRegenerate > maxToRegen) ? maxToRegen : amountToRegenerate);
this.incrementProperty('stamina_points', appliedAmountToRegenerate)
} | [
"function updateStamina() {\n // increase player stamina\n playerStamina += width / 3000;\n // Constrain the result to a sensible range\n playerStamina = constrain(playerStamina, 0, playerMaxStamina);\n //if the players stamina level drops below 5, reduce\n //player's max speed to 2, return to 4 after stamina regenerates.\n if (playerStamina < 5) {\n playerMaxSpeed = 2;\n } else {\n playerMaxSpeed = 4;\n }\n}",
"useStamina(amnt) {\n\t\tthis.stamina.current = Math.max(this.stamina.current - amnt, 0);\n\t}",
"resetStamina() {\n this.stamina += 2;\n if (this.stamina > 3)\n this.stamina = 3;\n }",
"function setStamina(staminaGiven) {\n let staminaBar = document.getElementById(\"stamina-bar\")\n userStamina += staminaGiven\n if(userStamina <= 0) {\n userStamina = 0\n } else if (userStamina >= 100) {\n userStamina = 100\n }\n // @ts-ignore\n staminaBar.value += staminaGiven\n staminaBar.innerText = `${userStamina}`\n}",
"addpoints(amount) {\r\n this.points = this.points + amount;\r\n }",
"function resetStamina()\n{\n stamina = maxStamina;\n updateFrame();\n}",
"function updateStamina(current,max){\n var staminaWidth = Math.ceil(max/5);\n var staminaHeight = 5;\n if (staminaWidth>40){\n staminaWidth = 40;\n staminaHeight = Math.ceil(max/40);\n } else if (staminaWidth === 1){\n staminaHeight = max;\n }\n staminaHeight = staminaHeight*10;\n staminaWidth = staminaWidth*10;\n $(\"#staminawrapper\").empty()\n .width(staminaWidth+\"px\")\n .height(staminaHeight+\"px\");\n current = parseInt(current);\n for (x=0;x<(current);x++){\n $(\"#staminawrapper\").append(\"<img src='/images/stamina2.png' id='stamina\"+x+\"' class='staminaimage'>\");\n }\n var leftover = (max - current);\n for (x=0;x<leftover;x++){\n $(\"#staminawrapper\").append(\"<img src='/images/staminaempty.png' class='staminaimage'>\");\n }\n}",
"awardPoints(numPoints) {\n this.points += numPoints;\n }",
"function givePoints(points) {\n var state = loadState();\n var current = findCurrentTeam(state.teams, state.game.currentlyPlayingTeamId);\n\n for (var i = 0; i < state.teams.length; i++) {\n var team = state.teams[i];\n if (team.id == currentTeam.id) {\n team.points += points;\n team.lastScore = points;\n }\n }\n saveState(state.game, state.teams);\n }",
"addPoint() {\n this.points += 1;\n this.updateScore();\n }",
"statIncrease(stat) {\n if (this.statPoints > 0) {\n this[stat] += 1;\n this.statPoints -= 1;\n updateUI();\n updateSkills();\n } else {\n alert(\"You do not have any stat points!\");\n }\n }",
"function increasePoints() {\n\tvar points = parseInt(pointsLabel.innerHTML);\n\tnewPoints = 20 / (seconds + 1) + 3;\n\tnewPoints = Math.round(newPoints);\n\tnewPoints *= 100;\n\tpoints += newPoints;\n\tpointsLabel.innerHTML = points;\n}",
"modifyCreationPoints (increaseFlag) {\n\t\tif (increaseFlag) {\n\t\t\tthis.creationPoints += 1;\n\t\t\tthis.totalCreationPoints += 1;\n\t\t} else if (this.creationPoints !== 0 && this.totalCreationPoints > HumanAges[this.age].startingCP) {\n\t\t\tthis.creationPoints -= 1;\n\t\t\tthis.totalCreationPoints -= 1;\n\t\t}\n\t}",
"function updateSpt(hero){\n\thero.spt = 0;\n\thero.spt += (hero.weapon != -1 ? data.skills[hero.weapon].sp : 0);\n\t//TODO: Look into this and refine db to prevent negative sp from being added\n\tif (hero.refine != -1 && data.refine[hero.refine].sp > data.skills[hero.weapon].sp){\n\t\thero.spt += data.refine[hero.refine].sp - data.skills[hero.weapon].sp\n\t}\n\thero.spt += (hero.assist != -1 ? data.skills[hero.assist].sp : 0);\n\thero.spt += (hero.special != -1 ? data.skills[hero.special].sp : 0);\n\thero.spt += (hero.a != -1 ? data.skills[hero.a].sp : 0);\n\thero.spt += (hero.b != -1 ? data.skills[hero.b].sp : 0);\n\thero.spt += (hero.c != -1 ? data.skills[hero.c].sp : 0);\n\thero.spt += (hero.s != -1 ? data.skills[hero.s].sp : 0);\n}",
"function burn_player_stamina(amount){\r\n for (var i = 0; i < amount; i++){\r\n player.stamina --;\r\n if (player.stamina < 0){\r\n player.stamina = 0;\r\n change_player_health(-2);\r\n }\r\n }\r\n update_player_info();\r\n}",
"function setTotalPoints(num) {\n totalPoints = num;\n}",
"function add_point() {\n\t\tpoints++;\n\t\t$('#points').html(points);\n\t\tif (0 == (points % 15)) {\n\t\t\tincrease_speed();\n\t\t}\n\t}",
"function update_Points() {\n\t\tvar txt_points = document.getElementById(\"txtPoints\");\n\t\tif (loc_visited[current_loc] === 0) {\n\t\t\tpoints += 5;\n\t\t\ttxt_points.value = points;\n\t\t}\n\t}",
"function getStaminaModifier(stamina){\r\n if(stamina === undefined || typeof stamina !== 'number'|| stamina <=2 || stamina >=19){\r\n //invalid\r\n return -3;\r\n }\r\n\t\tif(stamina >=4 && stamina <=5){\r\n\t\t\treturn -2;\r\n\t\t}\r\n\t\telse if(stamina >=6 && stamina <=8){\r\n\t\t\treturn -1;\r\n\t\t}\r\n\t\telse if(stamina >=9 && stamina <=12){\r\n\t\t\treturn + 0;\r\n\t\t}\r\n\t\telse if(stamina >=13 && stamina <=15){\r\n\t\t\treturn + 1;\r\n\t\t}\t\r\n\t\telse if(stamina >=16 && stamina <=17){\r\n\t\t\treturn + 2;\r\n\t\t}\t\t\r\n\t\telse if(stamina ==18){\r\n\t\t\treturn + 3;\r\n\t\t}\t\r\n\t\treturn -3;\r\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
force the color of all icons to dark | function adjustIconColorDocument() {
$('.oi-icon').each(function(e) {
if(!$(this).hasClass('colored')) {
$(this).css('fill', '#3E2F24');
$(this).addClass('colored');
}
});
} | [
"get invert_colors_off () {\n return new IconData(0xe0c4,{fontFamily:'MaterialIcons'})\n }",
"function changeCurrentColors(icon) {\n if(icon == \"clear-night\" || icon == \"partly-cloudy-night\") {\n return 'black';\n } else {\n return '#E3DB25';\n }\n }",
"get invert_colors () {\n return new IconData(0xe891,{fontFamily:'MaterialIcons'})\n }",
"updateIcons_() {\n var color = this.getColor();\n if (color) {\n adjustIconSet(this.getId(), osColor.toHexString(color));\n }\n }",
"function revertIconColor() {\n\tsearchIcon.style.color = '#757575'\n}",
"function setDarkScheme(){/* exported setDarkScheme */$(\"body\").removeClass(\"light\").addClass(\"dark\"),$(\"#btnSettings\").attr(\"src\",AssetPaths.SETTINGS)}",
"tintIcon(icon,format,force = false) {\n const tintIcons = this.settings.widget.tintIcons\n const never = tintIcons == this.enum.icons.never || !tintIcons\n const notDark = tintIcons == this.enum.icons.dark && !this.darkMode && !this.settings.widget.instantDark\n const notLight = tintIcons == this.enum.icons.light && this.darkMode && !this.settings.widget.instantDark\n if (!force && (never || notDark || notLight)) { return }\n icon.tintColor = this.provideColor(format)\n }",
"get settings_brightness () {\n return new IconData(0xe8bd,{fontFamily:'MaterialIcons'})\n }",
"static dark() {\n window.localStorage.setItem('colorScheme', 'dark')\n this.#isDark = true;\n this.#applyScheme();\n }",
"renderIcon(context) {\n if (context.isDarkMode) {\n return <FontAwesomeIcon icon={faSun} color=\"#FFA500\" />;\n } else {\n return <FontAwesomeIcon icon={faMoon} />;\n }\n }",
"get format_color_reset () {\n return new IconData(0xe23b,{fontFamily:'MaterialIcons'})\n }",
"get brightness_auto () {\n return new IconData(0xe1ab,{fontFamily:'MaterialIcons'})\n }",
"addHoverColor() {\n styles.icon.color = '#FFD700';\n }",
"function toggleDarkness(){\n\t\n\tfor(var i=0; i<transformables.length; i++){\n\t\t$(transformables[i]).toggleClass(\"dark\");\n\t}\n}",
"function setLightScheme(){/* exported setLightScheme */$(\"body\").removeClass(\"dark\").addClass(\"light\"),$(\"#btnSettings\").attr(\"src\",AssetPaths.SETTINGS_LIGHT)}",
"get colorize () {\n return new IconData(0xe3b8,{fontFamily:'MaterialIcons'})\n }",
"function updateDark() {\n dark = settings.get(\"user/general/@skin\").indexOf(\"dark\") !== -1;\n menuItem.checked = dark;\n }",
"teamifyIcon(){\r\n if(this.color == \"red\"){\r\n L.DomUtil.addClass(this.#icon._icon, 'eastIcon');\r\n } else\r\n if(this.color == \"blue\"){\r\n L.DomUtil.addClass(this.#icon._icon, 'westIcon');\r\n } else\r\n if(this.color == \"green\"){\r\n L.DomUtil.addClass(this.#icon._icon, 'centralIcon');\r\n }else \r\n if(this.color == \"purple\"){\r\n L.DomUtil.addClass(this.#icon._icon, 'gallifrayIcon');\r\n }\r\n }",
"function darkMode(array) {\n array.forEach(element => {\n element.style.color = \"#aaaaaa\";\n element.style.backgroundColor = \"#333333\";\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
a thing to ask for a command | function askForPrompt() {
prompt.start();
prompt.get({"properties":{"name":{"description":"Enter a command", "required": true}}}, function (err, result) {
commandFinder(result.name)
})
} | [
"function cli_ask (question) {\n var rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n return new ishido.Promise(function (resolve, reject) {\n rl.question(question, function (answer) {\n rl.close();\n resolve(answer);\n });\n\n });\n }",
"function ask(question) {\n return prompt(question);\n}",
"async function selectCommand() {\n const question = {\n type: 'autocomplete',\n name: 'command',\n message: 'Which command to run?',\n limit: 5,\n suggest(input, choices) {\n return choices.filter(choice => choice.message.toLowerCase().startsWith(input.toLowerCase()));\n },\n choices: exports.commandList.filter(c => c.display !== false).map(c => ({ name: c.name, value: c })),\n };\n return enquirer_1.prompt(question);\n}",
"function commandInput(command, userInput)\n\t{\n\t\tswitch(command){\n\t\t\tcase \"do-what-it-says\":\n\t\t\treadRandom();\n\t\t\tbreak;\n\t\t\tcase \"my-tweets\":\n\t\t\tmyTweets();\n\t\t\tbreak;\n\t\t\tcase \"spotify-this-song\":\n\t\t\tspotifySong(userInput);\n\t\t\tbreak;\n\t\t\tcase \"movie-this\":\n\t\t\tmovieInfo(userInput);\n\t\t\tbreak;\n\t\t}\n\t}",
"function spotifyCommand(){\n inquirer.prompt([\n {\n name: \"song\",\n message:\"What song would you like to search?\"\n }\n ]).then(function(answer){\n if(answer.song === \"\"){\n spotifyThis(defaulted.song)\n } else {\n commandParam = answer.song;\n spotifyThis(commandParam);\n }\n })\n}",
"function commandInput(command, userInput) {\n\tswitch(command){\n\t\tcase \"do-what-it-says\": \n\t\treadRandom();\n\t\tbreak;\n\t\tcase \"my-tweets\": \n\t\tmyTweets();\n\t\tbreak;\n\t\tcase \"spotify-this-song\": \n\t\tspotifySong(userInput);\n\t\tbreak;\n\t\tcase \"movie-this\":\n\t\tmovieInfo(userInput);\n\t\tbreak;\n\n\t}\n}",
"function ask(question) {\n return new Promise((resolve, reject) => {\n rl.question(question, (input) => {\n resolve(input);\n });\n });\n}",
"function prompt(str) {}",
"function getCommand(command){\n command = command.replace(/-/g, \"\").replace(/\\s/g, \"\").toLowerCase(); // Remove dashes and whitespace to allow user to input commands without dash or space and in CAPS\n switch (command) {\n case \"mytweets\":\n getTweets()\n logtxt(command)\n break;\n case \"spotifythissong\":\n spotifyThisSong();\n logtxt(command)\n break;\n case \"moviethis\":\n omdbSearch();\n logtxt(command)\n break;\n case \"dowhatitsays\":\n randomCommand();\n logtxt(command)\n break;\n default:\n console.log(\"Not a valid Command Input!\");\n logtxt(\"Not a valid Command Input!\");\n inquirer.prompt(questionObject.commandQuestion).then(function(answer){\n command = (answer.reset).toLowerCase();\n getCommand(command);\n });\n }; // End Switch\n}",
"function userCommand(cmd, cmdOption) {\n switch (cmd) {\n case \"my-tweets\":\n api.getTweets(cmd);\n return;\n case \"movie-this\":\n movie = cmdOption;\n api.getMovie(cmd, cmdOption);\n return;\n case \"do-what-it-says\":\n api.getFileInput(cmd);\n return;\n case \"spotify-this-song\":\n api.getSpotify(cmd, cmdOption);\n return;\n default:\n console.log(\"FAILURE: unable to process command.\");\n break;\n }\n return;\n}",
"function prompt(question, callback) {\n\tvar iface = readline.createInterface({\n\t\tinput: process.stdin,\n\t\toutput: process.stdout\n\t});\n\tiface.question(question, function(answer) {\n\t\tiface.close();\n\t\tcallback(answer);\n\t});\n}",
"command(command) {}",
"function selectCommand(liriCommand,queryInput) {\n\n\t\n\t//if command my-tweets\n\tif(liriCommand==='my-tweets')\n\t{\n\t\t//console.log('werwerw')\n\t\ttweet()\n\t}\n\t//if command is spotify-this-song\n\telse if(liriCommand==='spotify-this-song')\n\t{\t\n\t\t//console.log(input)\n\t\tspotify(queryInput)\n\t}\n\n\t//if command movie-this\n\telse if(liriCommand==='movie-this')\n\t{\n\t\tomdb(queryInput)\n\t}\n\t//if command do-what-it-says\n\telse if(liriCommand===\"do-what-it-says\") {\n\n\t\tdothis()\n\t}\n}",
"function promptForCommandKey(sessionID) {\n\trl.question(\"> Insert Command Key: \", function (commandKey) {\n\t\t\n\t\trequests.requestCommandKey(sessionID, commandKey);\n\t\tconsole.log('> OK.\\n')\n\n\t\tpromptForCommandKey(sessionID);\n\t});\n}",
"function checkCommand(){\n if(command === \"movie-this\"){\n movieThis(search);\n }\n else if(command === \"concert-this\"){\n concertThis(search);\n }\n\n else if(command === \"spotify-this-song\"){\n spotifyThis(search);\n }\n}",
"function switchCommand(){\n\tswitch(command){\n\t\tcase \"my-tweets\":\n\t\t\tmyTweets();\n\t\t\tbreak;\n\t\tcase \"spotify-this-song\":\n\t\t\tspotifyThisSong(userChoice);\n\t\t\tbreak;\n\t\tcase \"movie-this\":\n\t\t\tmovieThis(userChoice);\n\t\t\tbreak;\n\t\tcase \"do-what-it-says\":\n\t\t\tdoWhatItSays();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tconsole.log(\"Please enter a valid command.\");\n\t\t\tconsole.log('\"my-tweets\", \"spotify-this-song\", \"movie-this\", \"do-what-it-says\"');\n\t\t\tbreak;\n\t}\n}",
"function command(input, input2){\n\tif(input == \"mytweets\"){\n\t\tcommands.mytweets();\n\t}\n\telse if(input == \"spotifythissong\"){\n\t\t// if(input2 is null){\n\t\t// \tcommands.spotifythissong(\"The Sign\")\n\t\t// }\n\t\t// else{\n\t\t\tcommands.spotifythissong(input2)\n\t\t// }\n\t}\n\n\telse if(input == \"moviethis\"){\n\tcommands.moviethis(input2)\n\t}\n\telse if(input == \"dowhatitsays\"){\n\tcommands.dowhatitsays(input, input2);\n\t}\n}",
"function switchCommands(command, input) {\n switch (command) {\n case \"concert-this\":\n showArtistEvents(input);\n break;\n case \"spotify-this-song\":\n showSpotifySong(input);\n break;\n case \"movie-this\":\n showMovieData(input);\n break;\n case \"do-what-it-says\":\n showRandomTextResult();\n break;\n default:\n console.log(\"Command you entered is not recognized.\".red.italic);\n }\n}",
"function ask(msg)\r\n{\r\n var result = Host.GUI.ask(msg) // != Host.GUI.Constants.kYes\r\n return result;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Bugzilla: 1656351 Polarion: assignee: nansari startsin: 5.10 casecomponent: Services initialEstimate: 1/6h testSteps: 1. Create a service catalog with type orchestration template (heat or Aws) 2. Navigate to order page of service 3. Order the above service from global region expectedResults: 1. 2. 3. From global region, the ordering of catalog should be successful pass | function test_service_catalog_orchestration_global_region() {} | [
"function test_service_chargeback_multiple_vms() {}",
"function tc_Coventry_maintenance_testing_review_period_boundaries_suggested_tab()\n{\n login('cl3@regression','INRstar_5','Shared');\n add_patient('SORB_Coventry', 'review_period_validation', 'M', 'Shared'); \n add_treatment_plan('W','Coventry','','Shared','');\n \n add_historic_treatment(aqConvert.StrToDate(aqDateTime.AddDays(aqDateTime.Today(), (-7))), \"2.0\", \"2.0\", \"0\", \"7\", \"2.5\");\n add_pending_maintenance_treatment('2.0', aqConvert.StrToDate(aqDateTime.AddDays(aqDateTime.Today(), (0))));\n\n var sorb_button = sorb_button_suggested_path();\n var button = check_button(sorb_button);\n \n if(button==\"enabled\")\n {\n Log.Message(\"button in correct state\") \n \n click_sorb_button(\"suggested\"); \n \n var sorb_page_heading_path = get_sorb_heading_path();\n var heading = sorb_page_heading_path.contentText;\n \n if(heading==\"Skip or Boost\\n(based on Suggested schedule)\")\n {\n Log.Message(\"SORB page exists on > 7 day review before override\")\n } \n else Log.Warning(\"Test Failed - SORB Button Validation - Coventry maintenance testing review period boundaries\" + \" - SORB page was not displayed after clicking button\" )\n \n //Cancel and go to next review period check\n cancel_pending_sorb_treatment();\n } \n if(button==\"disabled\")\n {\n Log.Warning(\"Test Failed - SORB Button Validation - Coventry maintenance testing review period boundaries\")\n } \n//---------------override for 7 day review period\n override_review(7);\n \n var sorb_button = sorb_button_suggested_path();\n var button = check_button(sorb_button);\n \n if(button==\"enabled\")\n {\n Log.Message(\"button in correct state\") \n \n click_sorb_button(\"suggested\"); \n \n var sorb_page_heading_path = get_sorb_heading_path();\n var heading = sorb_page_heading_path.contentText;\n Log.Message(heading)\n \n if(heading==\"Skip or Boost\\n(based on Suggested schedule)\")\n {\n Log.Message(\"SORB page exists on 7 day review\")\n } \n else Log.Warning(\"Test Failed - SORB Button Validation - Coventry maintenance testing review period boundaries\" + \" - SORB page was not displayed after clicking button\" )\n \n //Cancel and go to next review period check\n cancel_pending_sorb_treatment();\n } \n if(button==\"disabled\")\n {\n Log.Warning(\"Test Failed - SORB Button Validation - Coventry maintenance testing review period boundaries\")\n } \n//---------------override for invalid 6-1 day review periods\n var result_set = new Array();\n\n for (i=6; i>0; i--)\n {\n override_review(i);\n if(button==\"enabled\")\n {\n Log.Message(\"button in correct state\") \n \n click_sorb_button(\"suggested\"); \n \n var actual_err_mess = get_sorb_button_error_message();\n var expected_err_mess = (\"The review period must be 7 days or greater to create Skip or Boost schedules.\"); \n var results = test_data_individual_step(actual_err_mess,expected_err_mess,\"Coventry maintenance testing review period boundaries checking \" + i + \" day review\"); \n \n WaitSeconds(1);\n result_set.push(results)\n } \n if(button==\"disabled\")\n {\n Log.Warning(\"Test Failed - SORB Button Validation - Coventry maintenance testing review period boundaries\")\n } \n \n var INRstar = INRstar_base()\n INRstar.Panel(3).Panel(1).Panel(0).Button(0).TextNode(0).Click();\n \n if(button==\"disabled\")\n {\n Log.Warning(\"Test Failed - SORB Button Validation - Coventry maintenance testing review period boundaries, button was not enabled\")\n }\n } \n \n //Validate all the result sets are true\n var results = results_checker_are_true(result_set); \n \n //Pass in the final result\n results_checker(results,'SORB Button Validation - Coventry maintenance testing review period boundaries');\n \n Log_Off();\n}",
"function test_service_chargeback_retired_service() {}",
"function defineServiceTest(i) {\n let cd = \"BJ00\" + i;\n let name = \"测试服务\";\n let desc = \"测试\";\n let defType = \"type001\";\n let github = \"xxxx3\";\n let definition = \"xxxx1\";\n\n service.defineService(wallet, cd, name, desc, defType, definition, github, 20000000000, 4300000)\n .then(function (val) {\n console.log('val', val);\n }, function (error) {\n console.log('error', error);\n });\n\n}",
"function test_verify_smart_mgmt_orchest_template() {}",
"function orderDetails() {\n var resourceHelper = require('~/cartridge/scripts/util/resource');\n var orderNo = request.httpParameterMap.OrderNo.stringValue; // eslint-disable-line no-undef\n var order = OrderMgr.searchOrder('orderNo = {0}', orderNo);\n var dueAmount = order.getTotalGrossPrice().value - (order.custom.apexxPaidAmount || 0.0);\n var paidAmount = order.custom.apexxPaidAmount || 0.0;\n var authAmount = order.totalGrossPrice.value;\n var captureAmount = order.totalGrossPrice.value - order.custom.apexxCaptureAmount || 0.0;\n var transactionHistory = order.custom.apexxTransactionHistory || '[]';\n var paymentInstruments = order.getPaymentInstruments()[0];\n var orderReasonMessage = !(paymentInstruments.custom.apexxReasonCode) ? 'Success' : paymentInstruments.custom.apexxReasonCode;\n var transType = order.custom.apexxTransactionType?order.custom.apexxTransactionType.toUpperCase():\"\";\n var transStatus = order.custom.apexxTransactionStatus?order.custom.apexxTransactionStatus.toUpperCase():\"\";\n var canCapture;\n var canRefund;\n var canCancel;\n \n if((transType == 'AUTH' || transType == 'CAPTURE') && (transStatus == 'AUTHORISED' || transStatus == 'PARTIAL_CAPTURE' || transStatus == 'PROCESSING' || transStatus == 'CAPTURED') && (authAmount !== paidAmount) ){\n \tvar canCapture = \"canCapture\";\n }\n if((transType == 'PAYMENT' && transStatus == 'COMPLETED') || (transType == 'CAPTURE' && transStatus == 'COMPLETED') || (paidAmount > 0 && dueAmount < order.getTotalGrossPrice().getValue())){\n \tvar canRefund = \"canRefund\";\n }\n if(transType == \"AUTH\" && transStatus == 'AUTHORISED' ){\n \t\n \tvar canCancel = \"canCancel\";\n }\n var grossAmount = (order.custom.apexxPaidAmount) ? order.totalGrossPrice.value - order.custom.apexxPaidAmount : order.totalGrossPrice.value\n // var canCapture = \"canCapture\"; \n transactionHistory = sortHistory(transactionHistory);\n var r = require('~/cartridge/scripts/util/response');\n //return r.renderJSON(order.custom.apexxCaptureAmount);\n \n ISML.renderTemplate('application/orderdetails', {\n resourceHelper: resourceHelper,\n utils: utils,\n order: order,\n transactionHistory: transactionHistory,// eslint-disable-line no-undef\n dueAmount: dueAmount.toFixed(2),// eslint-disable-line no-undef\n paidAmount: paidAmount.toFixed(2),// eslint-disable-line no-undef\n authAmount: authAmount.toFixed(2),// eslint-disable-line no-undef\n captureAmount: captureAmount.toFixed(2),// eslint-disable-line no-undef\n orderReasonMessage:orderReasonMessage,// eslint-disable-line no-undef\n canCapture:canCapture,// eslint-disable-line no-undef\n canRefund:canRefund,// eslint-disable-line no-undef\n canCancel:canCancel// eslint-disable-line no-undef\n });\n}",
"function test_retire_on_date_for_multiple_service() {}",
"function test_service_bundle_vms() {}",
"function test_crosshair_op_azone_ec2() {}",
"function s()\n{\ntry{\n Log.AppendFolder(\"s\");\n InitializationEnviornment.initiliaze();\n AppLoginLogout.login();\n \n Log.AppendFolder(\"PlaceReservationOrder.placeMixROrder\");\n var groupNm=defaultGroupName; \n var keyWordNm =\"Reservations\";\n var packageNm =\"Minimum Payment Required Reservation 2\";\n var subPakNm =\"Individual\";\n var qtyT = 1;\n var dateD =CommonCalender.getTodaysDate();\n var keyWordNm1 = \"Reservations\"\n var packageNM1 = \"No Payment Required Reservation 1\"\n var subPakNm1 =\"Individual\";\n\n selectGroupForReservation(groupNm,keyWordNm,packageNm,subPakNm,qtyT,dateD);\n \n addNewTicket(keyWordNm1,packageNm1,subPakNm1,qtyT,dateD);\n \n finilizeOrder();\n aqUtils.Delay(3000);\n clickConvertToReservation();\n aqUtils.Delay(4000); \n \n verifyPrefixColorNonReservation(packageNM1);\n verifyPrefixGreenColorReservation(packageNm); \n \n var expectedSettlemtnttotal = orderDetailsTotal.Caption;\n var paymentTypeBal=WrapperFunction.getTextValue(orderDetailsMinimumPayment);\n paymentTypeBal= aqString.Replace(paymentTypeBal,\"$\",\"\");\n applyAmount(\"MinimumPaymentExact\",paymentTypeBal);\n \n Log.Message(\"Complete the order\");\n WrapperFunction.settlementCompleteOrder();\n aqUtils.Delay(3000);\n validateTicket(\"Don't Validate\"); \n var expectedT= (expectedSettlemtnttotal.split('$')[1]).trim();\n var temp = cnf_orderDetailsTotal.Caption;\n var cnf_Ord = (temp.split('$')[1]).trim();\n temp = orderDetailsTotal.Caption ;\n var ord_details = (temp.split('$')[1]).trim();\n var total = parseFloat(cnf_Ord) + parseFloat(ord_details);\n //verifyOrderDetailsStoreOrderId(expectedSettlemtnttotal);\n if( total == expectedT){\n Log.Message(\"Total is matching\");\n }\n else{\n merlinLogError(\"Total is not matching\");\n Log.Message(\"Actual Total\",total);\n Log.Message(\"Expected Total\",expectedSettlemtnttotal); \n } \n var orderId = cnf_orderID.Caption;\n if (orderId == null){\n merlinLogError(\"Order id is not present\");\n } \n var reservationOrderID= (orderId.split('#')[1]).trim();\n ReservationOrderInfo.prototype.ResID = reservationOrderID; \n \n selectReservationRecordToCancelReservation(groupNm);\n aqUtils.Delay(3000); \n if(alertCancelReservation.Exists){\n Button.clickOnButton(alertCancelReservationYes); \n WrapperFunction.setTextValue(refundReservationConfReasontext,\"Test Cancel and refund amount\");\n Button.clickOnButton(refundReservationConfOK); \n aqUtils.Delay(3000); \n var cancelStatus = false;\n var cC = orderinfoResDataGrid.wColumnCount;\n var rC = 0;\n rC = orderinfoResDataGrid.wRowCount;\n for ( rowC = 0 ; rowC < rC ; rowC++){\n var displayDt = orderinfoResDataGrid.wValue(rowC ,6);\n if (displayDt == \"Cancelled\"){ \n cancelStatus = true;\n break; \n }else{\n cancelStatus = false;\n }\n } \n if(cancelStatus){\n Log.Message(\"The Reservation details are correctly reflected to the cancellation status\");\n }else{\n merlinLogError(\"The Reservation details are not correctly reflected to the cancellation status\");\n }\n resOrderInfoClosebutton.Click(); \n }\n else{\n merlinLogError(\"Pop-up is not displayed asking user to confirm about cancel the order\");\n return;\n } \n \n AppLoginLogout.logout(); \n } catch (e) {\n\t merlinLogError(\"Oops! There's some glitch in the script: \" + e.message);\t \n }\n finally { \n\t Log.PopLogFolder();\n } \n}",
"function MvGuardianshiporder(TestName,exestatus)\n{\n \n//Controller for executing or skipping the feature\nif (equal(exestatus,true)) {\n\n//var objData = Data.getData(TestName,\"MedicalCare\");\nvar tcDesc = Data.getData(TestName,\"MedicalCare\",\"TC_DESC\");\nLog.Checkpoint(\"Start Guardianship order for \"+tcDesc ,\"The flow is started\");\n\t//Start of the feature \n\t\n\t\n\t vProcess = Sys.Process(\"iMDSoft.Metavision\");\n\n\t// Patient Details and defaults\n\t var ms = 6000;\n var HelpStr = \"Delaying test run for \" + ms + \" milliseconds, To add Guardianship order.\";\n aqUtils.Delay (ms, HelpStr);\n \n\texestatus = mvObjects.selectMenuOption(exestatus,\"Add Progress Notes\", \"Allied Health Notes\", \"Social Work Notes\", \"Guardianship Order\");\n\t// Wait for screen to appear\n\texestatus = mvObjects.waitForObject(vProcess, \"WPFObject(\\\"lblFreeText_1\\\")\", 120,exestatus);\n\t\t// ** Fill in the Patient details\n\tLog.Message(\"*** enter Guardianship order form data ***\");\n\t//var OrderExpires = objData(\"OrderExpires\").Value;\n\tvar Relationship = Data.getData(TestName,\"MedicalCare\",\"Relationship\");\n\tvar Name = Data.getData(TestName,\"MedicalCare\",\"Name\");\n\tvar Contact_HmC1 = Data.getData(TestName,\"MedicalCare\",\"Contact_HmC1\");\n\tvar Contact_HmC2 = Data.getData(TestName,\"MedicalCare\",\"Contact_HmC2\");\n\tvar Contact_Bus = Data.getData(TestName,\"MedicalCare\",\"Contact_Bus\");\n\tvar Action_Order = Data.getData(TestName,\"MedicalCare\",\"Action_Order\");\n var Req_Order = Data.getData(TestName,\"MedicalCare\",\"Req_Order\");\n \n \t exestatus = mvObjects.selectComboItem(vProcess, \"WPFObject(\\\"cboTextCombo_1\\\")\",Relationship,exestatus);\n\t exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_1\\\")\",Name,exestatus);\n\t exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_2\\\")\",Contact_HmC1,exestatus);\n\t exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_3\\\")\",Contact_HmC2,exestatus);\n\t exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_4\\\")\",Contact_Bus,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_5\\\")\",Action_Order,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"chkTrue_1\\\")\",Req_Order,exestatus);\n\n // Get the save time value\n\tvar timeSavedValue = mvObjects.getObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"mvtFormTime\\\")\", \"Value\",exestatus); \n\t//timeSavedValue = aqString.Replace(timeSavedValue, \":00\", \"\", false);\n\t//timeSavedValue = aqString.Replace(timeSavedValue, \"0\", \"\", false);\n timeSavedValue = timeSavedValue.OleValue\n\tLog.Checkpoint(\"Guardianship order Saved Time: \"+ timeSavedValue);\n\t\n\t\t// save the form data\n\texestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"cmdApply\\\")\",exestatus);\n // to proceed with pop up\n \n var MsgForm = vProcess.Find(\"Name\", \"WinFormsObject(\\\"ImdFormBase\\\")\", 1000);\n \n if (MsgForm.Exists)\n {\n // iMDSoft_Metavision.ImdFormBase.WinFormsObject(\"Buttons\").WinFormsObject(\"Yes\").Click();\n exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WinFormsObject(\\\"Yes\\\")\",exestatus);\n }\n \n\n\t// wait for the form to save.. maybe this object if below don't work -> WPFObject(\"sessionscontrol\") \n\texestatus = mvObjects.waitForObject(vProcess, \"WPFObject(\\\"cmdNewSessionText\\\")\", 120,exestatus);\n //Get the form saved time and date\n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"sessionscontrol\\\")\",exestatus);\n var savedUservalue = mvObjects.getObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"TextEdit\\\", \\\"\\\", 1)\", \"Text\",exestatus);\n \n\t// Click Refresh\n\texestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"cmdRefresh\\\")\",exestatus); \n\n \n\t// close the form \n\texestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"cmdCancel\\\")\",exestatus);\n\texestatus = mvObjects.waitForObjectNotVisible(vProcess, \"WPFObject(\\\"cmdCancel\\\")\", 120,exestatus);\n\t//Validation part open form again\n exestatus = mvObjects.selectMenuOption(exestatus,\"Add Progress Notes\", \"Allied Health Notes\", \"Social Work Notes\", \"Guardianship order\");\n\t// Wait for screen to appear\n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"cmdCancelNewSessionText\\\")\",exestatus);\n //exestatus = mvObjects.waitForObject(vprocess,\"WPFObject(\\\"sessionscontrol\\\")\",120,exestatus);\n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"sessionscontrol\\\")\",exestatus); \n\n var documentedUserValue = mvObjects.getObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"TextEdit\\\", \\\"\\\", 1)\", \"Text\",exestatus); \n \n if(aqString.Compare(savedUservalue,documentedUserValue,false) ==0)\n {\n Log.Checkpoint(\"Saved by user details are matching\");\n }\n else\n {\n Log.Error(\"Saved by user details are not matched\");\n exestatus =false;\n }\n\t//exestatus = mvObjects.waitForObject(vProcess, \"WPFObject(\\\"lblFreeText_1\\\")\", 120,exestatus);\n //exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"dtpDate_1\\\")\", \"Text\", OrderExpires, \"OrderExpires\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_1\\\")\", \"Text\", Relationship, \"Relationship\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_1\\\")\", \"Text\", Name, \"Name\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_2\\\")\", \"Text\", Contact_HmC1, \"Contact_HmC1\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_3\\\")\", \"Text\", Contact_HmC2, \"Contact_HmC2\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_4\\\")\", \"Text\", Contact_Bus, \"Contact_Bus\",exestatus); \n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_5\\\")\", \"Text\", Action_Order, \"Action_Order\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"chkTrue_1\\\")\", \"Text\", Req_Order, \"Req_Order\",exestatus);\n\t// close the form \n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"sessionscontrol\\\")\",exestatus);\n\texestatus = mvObjects.buttonClick(vProcess, \"FullName\", \"*WPFObject(\\\"HwndSource: frmMain\\\", \\\"\\\").WPFObject(\\\"frmMain\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"ucFormBuilder_FBForm\\\").WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"MainGrid\\\").WPFObject(\\\"BottomGrid\\\").WPFObject(\\\"FormActionStackPanel\\\").WPFObject(\\\"cmdCancel\\\")\",exestatus);\n\texestatus = mvObjects.waitForObjectNotVisible(vProcess, \"WPFObject(\\\"cmdCancel\\\")\", 120,exestatus);\n \n \n // Click on Progress Notes tab (so can get Add progress notes details)\n exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"TabItem\\\", \\\"\\\", 10)\",exestatus);\n exestatus = mvObjects.progressnotes(timeSavedValue,\"Guardianship order\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_1\\\")\", \"Text\", Relationship, \"Relationship\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_1\\\")\", \"Text\", Name, \"Name\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_2\\\")\", \"Text\", Contact_HmC1, \"Contact_HmC1\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_3\\\")\", \"Text\", Contact_HmC2, \"Contact_HmC2\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_4\\\")\", \"Text\", Contact_Bus, \"Contact_Bus\",exestatus); \n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_5\\\")\", \"Text\", Action_Order, \"Action_Order\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"chkTrue_1\\\")\", \"Text\", Req_Order, \"Req_Order\",exestatus);\n\t// close the form \n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"sessionscontrol\\\")\",exestatus);\n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"sessionscontrol\\\")\",exestatus);\n\texestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"cmdCancel\\\")\",exestatus);\n\texestatus = mvObjects.waitForObjectNotVisible(vProcess, \"WPFObject(\\\"cmdCancel\\\")\", 120,exestatus);\n \n \n \n \n \n \n //var objData = Data.getData(TestName,\"Patient\");\n //var newPatientMRN = objData(\"MRN\").Value;\n \n if (equal(exestatus,true)) {\n\t \t Log.Checkpoint(\" Guardianship order to is successful\");\n Log.Checkpoint(\"End Guardianship order\",\"The flow is completed\");\n }\n }\n else {\n Log.Message(\"Skipped Guardianship order\",\"The feature is skipped since the execution status is set as '\"+exestatus+\"'\"); \n \n }\n return exestatus;\n \n}",
"assertDetails() {\r\n get('#cart-items > div > div > div._3YFXD._1pBtV > div._269qX.tsLLl._22yST._3bq8v > div:nth-child(2) > div > div > div > div:nth-child(2) > div:nth-child(1) > div > div._3YFXD._2Ib50 > div._269qX._1TSBW.I2ppM > div:nth-child(1) > a').should('contain', 'Canon LS-88Hi III Calculator Pink');\r\n get('#cart-items > div > div > div._3YFXD._1pBtV > div._269qX.tsLLl._22yST._3bq8v > div:nth-child(2) > div > div > div > div:nth-child(2) > div:nth-child(1) > div > div._3YFXD._2Ib50 > div._269qX._1TSBW.I2ppM > div._10UXS > div > span > span').should('contain', 'Product Code: OFM8015945');\r\n get('#txt-AddToCartQty-OFM8015945').should('have.value', '1');\r\n get('#cart-items > div > div > div._3YFXD._1pBtV > div._269qX.tsLLl._22yST._3bq8v > div:nth-child(2) > div > div > div > div:nth-child(2) > div:nth-child(1) > div > div._3YFXD._2Ib50 > div._269qX._3LJO1._1Axt_ > div').should('contain', '198.00');\r\n\r\n get('#cart-items > div > div > div._3YFXD._1pBtV > div._269qX.tsLLl._22yST._3bq8v > div:nth-child(2) > div > div > div > div:nth-child(3) > div:nth-child(1) > div > div._3YFXD._2Ib50 > div._269qX._1TSBW.I2ppM > div:nth-child(1) > a').should('contain', 'Canon LS-88Hi III Calculator. Purple.');\r\n get('#cart-items > div > div > div._3YFXD._1pBtV > div._269qX.tsLLl._22yST._3bq8v > div:nth-child(2) > div > div > div > div:nth-child(3) > div:nth-child(1) > div > div._3YFXD._2Ib50 > div._269qX._1TSBW.I2ppM > div._10UXS > div > span > span').should('contain', 'Product Code: OFM8015949');\r\n get('#txt-AddToCartQty-OFM8015949').should('have.value', '1');\r\n get('#cart-items > div > div > div._3YFXD._1pBtV > div._269qX.tsLLl._22yST._3bq8v > div:nth-child(2) > div > div > div > div:nth-child(3) > div:nth-child(1) > div > div._3YFXD._2Ib50 > div._269qX._3LJO1._1Axt_ > div').should('contain', '198.00');\r\n }",
"async placeOrder(stub, args) {\n\n //check args length should be 11\n if (args.length != 11) {\n console.info(`Argument length should be 11 with the order example: \n {\n orderer_id: \"trader12\",\n organization: \"Trader\",\n order_id: \"order122\",\n product_name: \"Wheat\",\n product_quantity: \"100\",\n unit : \"Kg\",\n quality : \"Pure\",\n price : \"2000\",\n order_date: \"10/02/2020\",\n seller_id: \"seller12\",\n traderBank_id: \"HBL Bank\"\n }`);\n\n throw new Error(`Argument length should be 11 with the order example: \n {\n orderer_id: \"trader12\",\n organization: \"Trader\",\n order_id: \"order122\",\n product_name: \"Wheat\",\n product_quantity: \"100\",\n unit : \"Kg\",\n quality : \"Pure\",\n price : \"2000\",\n order_date: \"10/02/2020\",\n seller_id: \"seller12\",\n traderBank_id: \"HBL Bank\"\n }`);\n }\n\n // check the org\n if (args[1] != 'Trader' && args[1] != 'Buyer' && args[1] != 'Seller') {\n throw new Error('Invalid Organization must be Seller or Trader or Buyer');\n }\n\n // check the orderer existence\n // let ordererBytes = await stub.getPrivateData((args[1].charAt(0).toLowerCase() + args[1].slice(1))+'_users', args[0]);\n let ordererBytes = await stub.getState(args[0]);\n if (!ordererBytes || ordererBytes.length == 0) {\n throw new Error(`Orderer with this id ${args[0]} not exist`);\n }\n\n let orderBytes = await stub.getState(args[2]);\n if (orderBytes && orderBytes.length != 0) {\n throw new Error('already exist');\n }\n\n // check the trader existence\n if (args[1] === 'Trader') {\n // let sellerBytes = await stub.getPrivateData('seller_users', args[6]);\n let sellerBytes = await stub.getState(args[9]);\n if (!sellerBytes || sellerBytes.length == 0) {\n throw new Error(`User with this id ${args[6]} not exist`);\n }\n }\n else if (args[1] === 'Buyer') {\n // let sellerBytes = await stub.getPrivateData('trader_users', args[6]);\n let sellerBytes = await stub.getState(args[9]);\n if (!sellerBytes || sellerBytes.length == 0) {\n throw new Error(`User with this id ${args[6]} not exist`);\n }\n }\n else if (args[1] === 'Seller') {\n // let sellerBytes = await stub.getPrivateData('trader_users', args[6]);\n let sellerBytes = await stub.getState(args[9]);\n if (!sellerBytes || sellerBytes.length == 0) {\n throw new Error(`User with this id ${args[6]} not exist`);\n }\n }\n else {\n throw new Error(`Member of ${args[1]} are not allowed to perform this action`);\n }\n\n // newOrder\n let newOrder = {};\n\n newOrder.product_order_id = args[2];\n newOrder.product_name = args[3];\n newOrder.product_quantity = args[4];\n newOrder.unit = args[5];\n newOrder.quality = args[6];\n newOrder.price = args[7];\n newOrder.order_date = args[8];\n newOrder.Orderer = args[0];\n newOrder.Seller = args[9];\n newOrder.buyerBank = args[10];\n newOrder.status = 'pending';\n\n await stub.putState(args[2], Buffer.from(JSON.stringify(newOrder)));\n }",
"function setupStartCase12() {\n console.log(\"setupStartCase12\");\n\n if (String($scope.OrderType).trim().toLocaleLowerCase() == \"assembly\") {\n //todo line3946-3970\n console.log(\"setupStartCase12 subassembly\", $scope.subAssembly);\n for (var i = 0; i < $scope.subAssembly.length;i++){\n if (String($scope.subAssembly[i]['woStatus']).trim().toLowerCase() != \"completed\") {\n $(\"#alertBoxContent\").text(\"Unable to proceed due to dependent Work Order is not completed.\");\n $('#alertBox').modal('show');\n //alert(\"Unable to proceed due to dependent Work Order is not completed.\");\n break;\n }\n }\n // setupStartCase15();\n } else {\n setupStartCase15();\n }\n\n }",
"function MvOrderingPRNIndication(TestName,exestatus)\n{\n \n//Controller for executing or skipping the feature\nif (equal(exestatus,true)) {\nvar tcDesc = Data.getData(TestName,\"Medications\",\"TC_DESC\");\nLog.Checkpoint(\"Start OrderingPRNIndication for the patient \"+tcDesc ,\"The flow is started\");\n\n//Start of the feature \nvProcess = Sys.Process(\"iMDSoft.Metavision\");\n \nvar drug = Data.getData(TestName,\"Medications\",\"drug\");\nvar template=Data.getData(TestName,\"Medications\",\"template\");\nvar medicaltype=Data.getData(TestName,\"Medications\",\"medicaltype\");\nvar drug_quantity=Data.getData(TestName,\"Medications\",\"drug_quantity\");\nvar PRNIndication = Data.getData(TestName,\"Medications\",\"PRNIndication\");\nvar Password = Data.getData(TestName,\"Navigation\",\"Password\");\n\n//OrderingPRNIndication\nexestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"TabItem\\\"),\\\"\\\"\\,11\",exestatus);\n//Click on Prescribe \nexestatus = mvObjects.buttonClick(vProcess,\"FullName\", \"*WPFObject(\\\"CustomWrapPanel\\\", \\\"\\\", 1).WPFObject(\\\"ImdButton\\\", \\\"\\\",1)\",exestatus);\n\naqUtils.Delay(10000);\n\n//Enter details in Order form\nexestatus = mvObjects.SearchSelectItem(vProcess, \"WPFObject(\\\"FindComboBoxEdit\\\")\",5,2,drug,2,exestatus);\nexestatus = mvObjects.selectToggleItem(vProcess,\"Text\",template,exestatus);\nexestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"PRNToggleButton\\\")\",exestatus);\nexestatus = mvObjects.Fullnametext(vProcess,\"*.WPFObject(\\\"Row1_Group\\\").WPFObject(\\\"LayoutItem\\\", \\\"\\\", 2).WPFObject(\\\"ContentControl\\\", \\\"\\\", 1).WPFObject(\\\"FrequencyView\\\", \\\"\\\", 1).WPFObject(\\\"Frequency_Group\\\").WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"Frequency_Row1\\\").WPFObject(\\\"LayoutItem\\\", \\\"\\\", 2).WPFObject(\\\"Border\\\", \\\"\\\", 1).WPFObject(\\\"TextEdit\\\", \\\"\\\", 1)\",PRNIndication,exestatus);\n//Frequency\nexestatus = mvObjects.wildcardfullname(vProcess, \"*WPFObject(\\\"Frequency_Row2\\\").WPFObject(\\\"LayoutItem\\\", \\\"\\\", 2).WPFObject(\\\"ComboBoxEdit\\\", \\\"\\\", 1).WPFObject(\\\"ButtonContainer\\\", \\\"\\\", 1).WPFObject(\\\"PART_Item\\\")\",\"ComboBoxEditItem\", medicaltype,exestatus);\n\n//Enter Medication Quantity\nexestatus = mvObjects.Fullnametext(vProcess,\"*WPFObject(\\\"LayoutGroup\\\", \\\"\\\", 2).WPFObject(\\\"ContentControl\\\", \\\"\\\", 1).WPFObject(\\\"GridMedications\\\").WPFObject(\\\"DVGridMedications\\\").WPFObject(\\\"view\\\").WPFObject(\\\"HierarchyPanel\\\", \\\"\\\", 1).WPFObject(\\\"GridRow\\\", \\\"\\\", 1).WPFObject(\\\"BandedViewContentSelector\\\", \\\"\\\", 1).WPFObject(\\\"GridCellContentPresenter\\\", \\\"\\\", 4).WPFObject(\\\"TextEdit\\\", \\\"\\\", 1)\",drug_quantity,exestatus);\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"Button\\\", \\\"Save & Close\\\",1)\",exestatus);\n\n//Click on Signow\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"cmdSign\\\")\",exestatus);\n\n//Click on Signnow in Signature Review\n\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WinFormsObject(\\\"cmdSignNow\\\")\",exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"PasswordBoxEdit\\ ,\\\"\\\"\\,1)\", Password,exestatus);\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"Button\\\" , \\\"OK\\\",1)\",exestatus);\n \n if (equal(exestatus,true)) {\n Log.Checkpoint(\" successfully OrderingPRNIndication\");\n Log.Checkpoint(\"End OrderingPRNIndication\",\"The flow is completed\");\n }\n }\n else {\n Log.Message(\"Skipped OrderingPRNIndication\",\"The feature is skipped since the execution status is set as '\"+exestatus+\"'\"); \n \n }\n return exestatus;\n \n}",
"function gaStep3(order) {\n gaAddProducs(order);\n ga('ec:setAction', 'checkout', {\n step: 3,\n });\n gaDimensions();\n ga('send', 'event', 'Flow Checkout', 'Customer Information');\n }",
"function cmdConfirm_ClickCase10() {\n console.log(\"cmdConfirm_ClickCase10\");\n console.log(\"setupStartCase12\");\n if (String($scope.OrderType).trim().toLocaleLowerCase() == \"assembly\") {\n //todo line3946-3970\n\n\n\n\n console.log(\"setupStartCase12 subassembly\", $scope.subAssembly);\n\n if(config.AllowMultipleOperator){\n if (config.AssemblyCheckAtLastOnly) { //Multiple Operator S5 v3.1 line:7100\n var promiseArray1 = [];\n promiseArray1.push(\n $http.post(config.baseUrlApi + 'HMLVTS/cmdConfirm_ClickCase10', {\n 'WOID': $scope.selectedWOIDData['woid']\n })\n );\n\n $q.all(promiseArray1).then(function (response) {\n console.log(\"cmdConfirm_ClickCase10\", response);\n\n if (response.length != 0) {\n if (response[0].data.success) {\n if (response[0].data.result.length != 0) {\n\n $scope.LastProcOpSeq = response[0].data.result[0]['lastProcOpSeq'];\n if ($scope.ProcOpSeq >= $scope.LastProcOpSeq) {\n cmdConfirm_ClickCase12();\n } else {\n cmdConfirm_ClickCase15();\n }\n } else {\n cmdConfirm_ClickCase15();\n }\n } else {\n\n alert(\"ERROR:cmdConfirm_ClickCase10\");\n }\n } else {\n cmdConfirm_ClickCase15();\n }\n\n });\n\n }\n } else {\n for (var i = 0; i < $scope.subAssembly.length; i++) {\n if (String($scope.subAssembly[i]['woStatus']).tirm().toLowerCase() != \"completed\") {\n cmdConfirm_ClickCase60();\n }\n }\n\n cmdConfirm_ClickCase15();\n }\n\n } else {\n cmdConfirm_ClickCase15();\n }\n\n }",
"function test_provision_request_info() {}",
"function tc_treatment_plan_add_first_manual_treatment_plan()\n{\n try\n {\n var test_title = 'Treatment Plan - Add first manual treatment plan'\n login('cl3@regression','INRstar_5','Shared');\n add_patient('Regression', 'Add_manual_tp', 'M', 'Shared'); \n add_treatment_plan('W','Manual','','Shared','');\n \n result_set = new Array();\n \n //Check the confirmation banner is displayed\n var result_set_1 = banner_checker('The patient\\'s dosing method is currently set to : Manual Dosing')\n result_set.push(result_set_1);\n \n //Check the audit for adding the tp\n var result_set_2 = display_top_patient_audit('Add Treatment Plan Details');\n result_set.push(result_set_2);\n \n //Validate all the results sets are true\n var results = results_checker_are_true(result_set); \n Log.Message(results);\n \n //Pass in the result\n results_checker(results,test_title); \n \n Log_Off(); \n } \n catch(e)\n {\n Log.Warning('Test \"' + test_title + '\" FAILED Exception Occured = ' + e);\n Log_Off();\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
store tweet in local localStorage | function saveTweetsOnStorage(tweets){
localStorage.setItem('tweets',JSON.stringify(tweets));
//showTweets();
} | [
"function tweetSave(tweet) {\n var tweets = getTweetsFromLocalStorage();\n\n //Add the tweet/s to the array(list)\n tweets.push(tweet);\n\n // Convert tweet array into string\n localStorage.setItem(\"tweets\", JSON.stringify(tweets));\n}",
"function addTweetsToLocalStorage(tweet) {\n let tweets = getTweetsFromLocalStorage();\n\n\n tweets.push(tweet);\n\n localStorage.setItem('tweets', JSON.stringify( tweets ) );\n\n \n}",
"function addTweetLocalStorage(tweet) {\n let tweets;\n\n tweets = checkTweetsLocalStorage();\n tweets.push(tweet);\n localStorage.setItem('tweets', JSON.stringify(tweets));\n}",
"function addTweetLocalStorage(tweet){\n let tweets = getFromStorage();\n\n tweets.push(tweet);\n\n localStorage.setItem('tweets', JSON.stringify(tweets))\n}",
"function addTweetLocalStorage(tweet) {\n let tweets\n tweets = getLocalStorageTweets(tweet)\n \n // Add new tweet\n tweets.push(tweet)\n\n // String to array (object)\n localStorage.setItem('tweets', JSON.stringify(tweets))\n}",
"function agregarTweetLocalStorage(tweet){\n\n let tweets;\n //muestra los tweets en local storage\n tweets = obtenerTweetsLocalStorage();\n //Añadir el nuevo tweet\n tweets.push(tweet);\n //Convertir de arreglo a string para local storage\n //en local storage solo acepta cadenas de textos, string, no imagenes o objetos\n localStorage.setItem('tweets', JSON.stringify(tweets));\n\n \n }",
"function addTweetLocalStorage(tweet) {\n let tweets;\n tweets = obtainTweetsLocalStorage();\n // Add new tweets\n tweets.push(tweet);\n\n // Convers string to array local storage\n localStorage.setItem('tweets', JSON.stringify(tweets));\n}",
"function addTweetLocalStorage(tweet) {\r\n let tweets = getTweetsFromStorage();\r\n \r\n //Add the tweet into the Array\r\n tweets.push(tweet);\r\n \r\n // Convert tweet array into String\r\n localStorage.setItem('tweets', JSON.stringify( tweets ) );\r\n\r\n}",
"function agregarTweetLocalStorage(tweet) {\n let tweets;\n tweets = obtenerTweetsLocalStorage();\n //Añadimos el nuevo tweet\n tweets.push(tweet);\n //Convertir de String a Arreglo para Local Storage\n localStorage.setItem('tweets', JSON.stringify(tweets));\n // //Agregar a Local Storage\n // localStorage.setItem('tweets', tweet);\n}",
"function addTweetLocalStorage(tweet) {\n let tweets;\n\n tweets = getTweetLocalstorage();\n\n tweets.push(tweet);\n //REMBER localstorage just can get strings\n localStorage.setItem('tweets', JSON.stringify(tweets));\n}",
"function agregarTweetLocalStorage(tweet) {\n let tweets;\n tweets = obtenerTweetsLocalStorage();\n // Añadir el nuevo tweet\n tweets.push(tweet);\n // Convertir de string a arreglo para local storage\n localStorage.setItem('tweets', JSON.stringify(tweets) );\n}",
"function agregarTweetLocalStorage(tweet){\r\n let tweets;\r\n tweets = obtenerTweetsLocalStorage();\r\n //Añadir el nuevo tweet\r\n tweets.push(tweet);\r\n //Convertir de string a arreglo para local Storage\r\n localStorage.setItem(\"tweets\", JSON.stringify(tweets));\r\n}",
"function agregarTweetLocalStorage(tweet) {\n let tweets;\n tweets = obtenerTweetsLocalStorage();\n tweets.push(tweet);\n //convertir de strinf a arreglo para local Storage\n console.log(JSON.stringify(tweets));\n localStorage.setItem(\"tweets\", JSON.stringify(tweets));\n //agregar tweet a localstorage\n // localStorage.setItem('tweets',tweet);\n}",
"function addTweetstoLocalStorage(tweet){\n\n let tweets = getTweetsFromStorage();\n\n //Adding the tweet into the array\n tweets.push(tweet);\n\n //Add the tweet into the array\n localStorage.setItem('tweets', JSON.stringify(tweets));\n\n}",
"function agregarTweetLocalStorage(tweet){\n let tweets;\n\n tweets = obtenerTweetsLocalStorage();\n\n //añadir el nuevo tweet al arreglo\n tweets.push(tweet);\n\n //convertir de string a arreglo para local storage (ya que reescribe lo que hay)\n localStorage.setItem('tweets',JSON.stringify(tweets));\n\n}",
"function addtweet(tweet){\n let tweets= gettweet();\n tweets.push(tweet); \n localStorage.setItem('tweets', JSON.stringify(tweets));\n}",
"function addTweetLocaleStorage(tweet){\n let tweets = getTweetsFromStorage();\n\n //Add the tweets into the array\n tweets.push(tweet);\n\n //Convert array into String\n localStorage.setItem('tweets', JSON.stringify( tweets ));\n}",
"function agregarTareaLocalStorage(tarea) {\r\n let tareas;\r\n\r\n //Obtener Local Storage\r\n tareas = obtenerLocalStorage();\r\n\r\n //Añadir el tweet\r\n tareas.push(tarea);\r\n\r\n //Convertir de string a arreglo para localStorage\r\n localStorage.setItem('tareas', JSON.stringify(tareas));\r\n}",
"function delateTweetLocalStorage(tweet){\n let tweets, tweetCancellato\n //Elimina la x dal tweet\n tweetCencellato = tweet.substring(0, tweet.length - 1)\n\n tweets = ottenereTweetLocalStorage()\n\n tweets.forEach(function(tweet, index){\n if(tweetCencellato === tweet){\n tweets.splice(index, 1)\n }\n })\n\n localStorage.setItem('tweets', JSON.stringify(tweets))\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine whether the given properties match those of a `ConfluencePageConfigurationProperty` | function CfnDataSource_ConfluencePageConfigurationPropertyValidator(properties) {
if (!cdk.canInspect(properties)) {
return cdk.VALIDATION_SUCCESS;
}
const errors = new cdk.ValidationResults();
if (typeof properties !== 'object') {
errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));
}
errors.collect(cdk.propertyValidator('pageFieldMappings', cdk.listValidator(CfnDataSource_ConfluencePageToIndexFieldMappingPropertyValidator))(properties.pageFieldMappings));
return errors.wrap('supplied properties not correct for "ConfluencePageConfigurationProperty"');
} | [
"function CfnDataSource_ConfluenceConfigurationPropertyValidator(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('attachmentConfiguration', CfnDataSource_ConfluenceAttachmentConfigurationPropertyValidator)(properties.attachmentConfiguration));\n errors.collect(cdk.propertyValidator('blogConfiguration', CfnDataSource_ConfluenceBlogConfigurationPropertyValidator)(properties.blogConfiguration));\n errors.collect(cdk.propertyValidator('exclusionPatterns', cdk.listValidator(cdk.validateString))(properties.exclusionPatterns));\n errors.collect(cdk.propertyValidator('inclusionPatterns', cdk.listValidator(cdk.validateString))(properties.inclusionPatterns));\n errors.collect(cdk.propertyValidator('pageConfiguration', CfnDataSource_ConfluencePageConfigurationPropertyValidator)(properties.pageConfiguration));\n errors.collect(cdk.propertyValidator('secretArn', cdk.requiredValidator)(properties.secretArn));\n errors.collect(cdk.propertyValidator('secretArn', cdk.validateString)(properties.secretArn));\n errors.collect(cdk.propertyValidator('serverUrl', cdk.requiredValidator)(properties.serverUrl));\n errors.collect(cdk.propertyValidator('serverUrl', cdk.validateString)(properties.serverUrl));\n errors.collect(cdk.propertyValidator('spaceConfiguration', CfnDataSource_ConfluenceSpaceConfigurationPropertyValidator)(properties.spaceConfiguration));\n errors.collect(cdk.propertyValidator('version', cdk.requiredValidator)(properties.version));\n errors.collect(cdk.propertyValidator('version', cdk.validateString)(properties.version));\n errors.collect(cdk.propertyValidator('vpcConfiguration', CfnDataSource_DataSourceVpcConfigurationPropertyValidator)(properties.vpcConfiguration));\n return errors.wrap('supplied properties not correct for \"ConfluenceConfigurationProperty\"');\n}",
"function CfnDataSource_ConfluenceBlogConfigurationPropertyValidator(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('blogFieldMappings', cdk.listValidator(CfnDataSource_ConfluenceBlogToIndexFieldMappingPropertyValidator))(properties.blogFieldMappings));\n return errors.wrap('supplied properties not correct for \"ConfluenceBlogConfigurationProperty\"');\n}",
"hasProperty(aProperty){\n for(let i = 0; i < this._properties.length; i++){\n let prop = this._properties[i];\n if(aProperty.matches(prop)){\n return true;\n }\n }\n return false;\n }",
"function containsAllowedProps(properties) {\n if (properties === null || (typeof properties === 'undefined' ? 'undefined' : _typeof(properties)) !== 'object') {\n return false;\n }\n return Object.entries(properties).some(function (property) {\n var key = property[0];\n var value = property[1];\n if (typeof value === 'string') {\n return key === 'style' || key === 'src' || key === 'href';\n } else if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && key === 'attributes') {\n return 'class' in properties.attributes;\n }\n });\n}",
"function CfnDataSource_ConfluenceAttachmentConfigurationPropertyValidator(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('attachmentFieldMappings', cdk.listValidator(CfnDataSource_ConfluenceAttachmentToIndexFieldMappingPropertyValidator))(properties.attachmentFieldMappings));\n errors.collect(cdk.propertyValidator('crawlAttachments', cdk.validateBoolean)(properties.crawlAttachments));\n return errors.wrap('supplied properties not correct for \"ConfluenceAttachmentConfigurationProperty\"');\n}",
"function hasSamePropertiesValue(properties1, properties2) {\n for (var property in properties1) {\n if (properties1.hasOwnProperty(property)) {\n if (properties1[property] !== properties2[property]) return false;\n }\n }\n\n return true;\n }",
"function CfnAccountAuditConfiguration_AuditCheckConfigurationPropertyValidator(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('enabled', cdk.validateBoolean)(properties.enabled));\n return errors.wrap('supplied properties not correct for \"AuditCheckConfigurationProperty\"');\n}",
"function CfnDataSource_ConfluenceSpaceConfigurationPropertyValidator(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('crawlArchivedSpaces', cdk.validateBoolean)(properties.crawlArchivedSpaces));\n errors.collect(cdk.propertyValidator('crawlPersonalSpaces', cdk.validateBoolean)(properties.crawlPersonalSpaces));\n errors.collect(cdk.propertyValidator('excludeSpaces', cdk.listValidator(cdk.validateString))(properties.excludeSpaces));\n errors.collect(cdk.propertyValidator('includeSpaces', cdk.listValidator(cdk.validateString))(properties.includeSpaces));\n errors.collect(cdk.propertyValidator('spaceFieldMappings', cdk.listValidator(CfnDataSource_ConfluenceSpaceToIndexFieldMappingPropertyValidator))(properties.spaceFieldMappings));\n return errors.wrap('supplied properties not correct for \"ConfluenceSpaceConfigurationProperty\"');\n}",
"function matches(property) {\n var property = original[property];\n return location.indexOf(property) !== -1;\n }",
"function CfnDataSource_WebCrawlerAuthenticationConfigurationPropertyValidator(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('basicAuthentication', cdk.listValidator(CfnDataSource_WebCrawlerBasicAuthenticationPropertyValidator))(properties.basicAuthentication));\n return errors.wrap('supplied properties not correct for \"WebCrawlerAuthenticationConfigurationProperty\"');\n}",
"function CfnDataSource_WebCrawlerConfigurationPropertyValidator(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('authenticationConfiguration', CfnDataSource_WebCrawlerAuthenticationConfigurationPropertyValidator)(properties.authenticationConfiguration));\n errors.collect(cdk.propertyValidator('crawlDepth', cdk.validateNumber)(properties.crawlDepth));\n errors.collect(cdk.propertyValidator('maxContentSizePerPageInMegaBytes', cdk.validateNumber)(properties.maxContentSizePerPageInMegaBytes));\n errors.collect(cdk.propertyValidator('maxLinksPerPage', cdk.validateNumber)(properties.maxLinksPerPage));\n errors.collect(cdk.propertyValidator('maxUrlsPerMinuteCrawlRate', cdk.validateNumber)(properties.maxUrlsPerMinuteCrawlRate));\n errors.collect(cdk.propertyValidator('proxyConfiguration', CfnDataSource_ProxyConfigurationPropertyValidator)(properties.proxyConfiguration));\n errors.collect(cdk.propertyValidator('urlExclusionPatterns', cdk.listValidator(cdk.validateString))(properties.urlExclusionPatterns));\n errors.collect(cdk.propertyValidator('urlInclusionPatterns', cdk.listValidator(cdk.validateString))(properties.urlInclusionPatterns));\n errors.collect(cdk.propertyValidator('urls', cdk.requiredValidator)(properties.urls));\n errors.collect(cdk.propertyValidator('urls', CfnDataSource_WebCrawlerUrlsPropertyValidator)(properties.urls));\n return errors.wrap('supplied properties not correct for \"WebCrawlerConfigurationProperty\"');\n}",
"function CfnAnomalyDetector_ConfigurationPropertyValidator(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('excludedTimeRanges', cdk.listValidator(CfnAnomalyDetector_RangePropertyValidator))(properties.excludedTimeRanges));\n errors.collect(cdk.propertyValidator('metricTimeZone', cdk.validateString)(properties.metricTimeZone));\n return errors.wrap('supplied properties not correct for \"ConfigurationProperty\"');\n}",
"function matches(property, config, model) {\n\t\treturn listVerdict(Object.keys(config), function(key) {\n\t\t\treturn operation(key, model, property, config[key]);\n\t\t});\n\t}",
"function CfnDataSource_WorkDocsConfigurationPropertyValidator(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('crawlComments', cdk.validateBoolean)(properties.crawlComments));\n errors.collect(cdk.propertyValidator('exclusionPatterns', cdk.listValidator(cdk.validateString))(properties.exclusionPatterns));\n errors.collect(cdk.propertyValidator('fieldMappings', cdk.listValidator(CfnDataSource_DataSourceToIndexFieldMappingPropertyValidator))(properties.fieldMappings));\n errors.collect(cdk.propertyValidator('inclusionPatterns', cdk.listValidator(cdk.validateString))(properties.inclusionPatterns));\n errors.collect(cdk.propertyValidator('organizationId', cdk.requiredValidator)(properties.organizationId));\n errors.collect(cdk.propertyValidator('organizationId', cdk.validateString)(properties.organizationId));\n errors.collect(cdk.propertyValidator('useChangeLog', cdk.validateBoolean)(properties.useChangeLog));\n return errors.wrap('supplied properties not correct for \"WorkDocsConfigurationProperty\"');\n}",
"function CfnWebhook_WebhookAuthConfigurationPropertyValidator(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('allowedIpRange', cdk.validateString)(properties.allowedIpRange));\n errors.collect(cdk.propertyValidator('secretToken', cdk.validateString)(properties.secretToken));\n return errors.wrap('supplied properties not correct for \"WebhookAuthConfigurationProperty\"');\n}",
"function validateProperties(props) {\n let validProps = getProperties();\n for (let i in props) {\n if (!validProps.includes(props[i])) {\n return false;\n }\n }\n return true;\n}",
"shouldUpdate(changedProperties) {\n changedProperties.forEach((oldValue, propName) => {\n console.log(`${propName} changed. oldValue: ${oldValue}`);\n });\n return changedProperties.has('prop1');\n }",
"function matches(property, config, model) {\n\t\t\treturn listVerdict(Object.keys(config), function(key) {\n\t\t\t\treturn operation(key, model, property, config[key]);\n\t\t\t});\n\t\t}",
"function checkSameProps(properties, qParams, model) {\n var result = INCLUDE;\n\n _.each(properties, function(property) {\n if (_.has(qParams, property) && qParams[property] !== model.get(property)) {\n result = EXCLUDE;\n }\n });\n\n return result;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
save the changes from the modal and posted to the table in the global variable if not saved the global variable will keep the records prechanges in the modal | function confirm_changes(){
"use strict"
//current_data_set; // contains all the records
//record_changed_dict; // contains the records changed with the modal
} | [
"function ModalStatusSave() {\n //console.log(\"=== ModalStatusSave =========\");\n\n // put values in el_body\n let el_body = document.getElementById(\"id_mod_status_body\")\n //const tblName = get_attr_from_el(el_body, \"data-table\")\n const data_ppk = get_attr_from_el(el_body, \"data-ppk\")\n const data_field = get_attr_from_el(el_body, \"data-field\")\n const field_is_confirmed = (get_attr_from_el(el_body, \"data-confirmed\", false) === \"true\")\n const status_value = get_attr_from_el_int(el_body, \"data-value\")\n\n //console.log(\"el_body: \", el_body);\n //console.log(\"field_is_confirmed: \", field_is_confirmed);\n //console.log(\"data_field: \", data_field);\n\n const data_pk = get_attr_from_el(el_body, \"data-pk\")\n let tr_changed = document.getElementById(data_pk)\n\n const id_dict = get_iddict_from_element(el_body);\n // period_datefirst and period_datelast necessary for check_emplhour_overlap PR2020-07-22\n let upload_dict = {id: id_dict,\n //period_datefirst: selected_period.period_datefirst,\n //period_datelast: selected_period.period_datelast\n }\n\n //console.log(\"---------------status_value: \", status_value);\n //console.log(\"---------------data_field: \", data_field);\n //console.log(\"---------------field_is_confirmed: \", field_is_confirmed, typeof field_is_confirmed);\n let status_dict = {}, confirmstart_dict = null, confirmend_dict = null;\n if(data_field === \"confirmstart\"){\n confirmstart_dict = {\"value\": field_is_confirmed, \"update\": true};\n if (field_is_confirmed) {\n status_dict = {\"value\": 2, \"remove\": true, \"update\": true} // STATUS_004_START_CONFIRMED = 2\n //console.log(\"confirmstart field_is_confirmed \", status_dict);\n } else {\n status_dict = {\"value\": 2, \"update\": true} // STATUS_004_START_CONFIRMED = 2\n //console.log(\"confirmstart field_is_NOT confirmed \", status_dict);\n }\n } else if(data_field === \"confirmend\"){\n confirmend_dict = {\"value\": field_is_confirmed, \"update\": true};\n if (field_is_confirmed) {\n status_dict = {\"value\": 4, \"remove\": true, \"update\": true} // STATUS_016_END_CONFIRMED = 4\n //console.log(\"confirmend field_is_confirmed \", status_dict);\n } else {\n status_dict = {\"value\": 4, \"update\": true} // STATUS_016_END_CONFIRMED = 4\n //console.log(\"confirmend field_is_NOT_confirmed \", status_dict);\n }\n } else if(data_field === \"status\"){\n if(status_value >= 8){\n status_dict = {\"value\": 8, \"remove\": true, \"update\": true} // STATUS_032_LOCKED = 8\n //console.log(\"status status_value >= 8 \", status_dict);\n } else {\n status_dict = {\"value\": 8, \"update\": true} // STATUS_032_LOCKED = 8\n //console.log(\"status status_value < 8 \", status_dict);\n }\n }\n //console.log(\"---------------status_dict: \", status_dict);\n upload_dict[\"status\"] = status_dict\n if(!!confirmstart_dict){\n upload_dict[\"confirmstart\"] = confirmstart_dict\n }\n if(!!confirmend_dict){\n upload_dict[\"confirmend\"] = confirmend_dict\n }\n\n $(\"#id_mod_status\").modal(\"hide\");\n\n if(!!upload_dict) {\n //console.log( \"upload_dict\", upload_dict);\n let parameters = {\"upload\": JSON.stringify(upload_dict)};\n\n let response = \"\";\n $.ajax({\n type: \"POST\",\n url: url_emplhour_upload,\n data: parameters,\n dataType:'json',\n success: function (response) {\n //console.log( \"response\");\n //console.log( response);\n\n if (\"item_update\" in response) {\n let item_dict =response[\"item_update\"]\n //const tblName = get_dict_value (item_dict, [\"id\", \"table\"], \"\")\n\n UpdateTblRow(tr_changed, item_dict)\n }\n },\n error: function (xhr, msg) {\n console.log(msg + '\\n' + xhr.responseText);\n }\n });\n } // if(!!new_item)\n } // ModalStatusSave",
"function saveInitData() {\n var note = {};\n note.dv = $scope.recod.dv;\n note.dvten = $scope.recod.dvten || '';\n note.dvdiachi = $scope.recod.dvdiachi || '';\n note.dvsdt = $scope.recod.dvsdt || '';\n note.dveil = $scope.recod.dveil || '';\n if ($scope.status == 'M')\n {\n note.action = 'update';\n note.dvnew = note.dv;\n note.dv = $scope.gridApi.selection.getSelectedRows()[0].dv;\n }\n else note.action = 'create';\n return note;\n }",
"function MCREY_Save(btn_clicked) {\n console.log(\" ----- MCREY_save ----\", btn_clicked);\n console.log( \"mod_MCREY_dict: \", mod_MCREY_dict);\n\n // mode = 'create, 'publish', 'lock', 'edit' (with el_input)\n const mode = mod_MCREY_dict.mode;\n //console.log( \"mode: \", mode);\n\n if(!!permit_dict.permit_crud){\n let upload_changes = false;\n let upload_dict = {table: 'examyear', country_pk: mod_MCREY_dict.country_id};\n if(btn_clicked === \"undo\"){\n\n //console.log( \"btn_clicked undo: \", btn_clicked);\n upload_dict.examyear_pk = mod_MCREY_dict.id;\n upload_dict.mapid = mod_MCREY_dict.mapid;\n if(mod_MCREY_dict.locked){\n upload_dict.locked = false;\n upload_changes = true;\n } else if(mod_MCREY_dict.published){\n upload_dict.published = false;\n upload_changes = true;\n } else if(!mod_MCREY_dict.is_addnew){\n // delete exam year\n // TODO open confirm modal when delete\n upload_dict.mode = \"delete\";\n upload_changes = true;\n }\n } else {\n if (mode === \"create\") {\n upload_dict.mode = \"create\";\n upload_dict.examyear_code = mod_MCREY_dict.examyear_code;\n } else if(mod_MCREY_dict.is_delete) {\n // handled by mod confirm\n //upload_dict.examyear_pk = mod_MCREY_dict.id;\n //upload_dict.mapid = mod_MCREY_dict.mapid;\n //upload_dict.mode = \"delete\";\n } else {\n upload_dict.examyear_pk = mod_MCREY_dict.id;\n upload_dict.mapid = mod_MCREY_dict.mapid;\n upload_dict.mode = \"update\";\n if(!mod_MCREY_dict.published){\n upload_dict.published = true;\n } else if(!mod_MCREY_dict.locked){\n upload_dict.locked = true;\n }\n }\n upload_changes = true\n };\n if(upload_changes){\n const url_str = urls.url_examyear_upload\n el_MCREY_loader.classList.remove(cls_visible_hide);\n UploadChanges(upload_dict, url_str);\n el_MCREY_btn_save.disabled = true;\n }\n }\n } // MCREY_Save",
"function MUD_Save() {\n console.log(\"=== MUD_Save === \");\n\n const new_idnumber = (el_MUD_idnumber.value) ? el_MUD_idnumber.value : null;\n const new_cribnumber = (el_MUD_cribnumber.value) ? el_MUD_cribnumber.value : null;\n const new_bankname = (el_MUD_bankname.value) ? el_MUD_bankname.value : null;\n const new_bankaccount = (el_MUD_bankaccount.value) ? el_MUD_bankaccount.value : null;\n const new_beneficiary = (el_MUD_beneficiary.value) ? el_MUD_beneficiary.value : null;\n\n const upload_dict = {\n user_id: mod_MUD_dict.user_id,\n userdata_id: mod_MUD_dict.userdata_id\n };\n if(new_idnumber !== mod_MUD_dict.idnumber ){\n upload_dict.idnumber = new_idnumber;\n };\n if(new_cribnumber !== mod_MUD_dict.cribnumber ){\n upload_dict.cribnumber = new_cribnumber\n };\n if(new_bankname !== mod_MUD_dict.bankname ){\n upload_dict.bankname = new_bankname\n };\n if(new_bankaccount !== mod_MUD_dict.bankaccount ){\n upload_dict.bankaccount = new_bankaccount\n };\n if(new_beneficiary !== mod_MUD_dict.beneficiary ){\n upload_dict.beneficiary = new_beneficiary\n };\n\n if (!isEmpty(upload_dict)){\n UploadChanges(upload_dict, urls.url_userdata_upload);\n };\n\n $(\"#id_mod_userdata\").modal(\"hide\");\n}",
"function ModConfirmSave() {\n console.log(\" --- ModConfirmSave --- \");\n console.log(\"mod_dict: \", mod_dict);\n let close_modal_with_timout = false;\n\n el_confirm_msg_container.innerHTML = null;\n el_confirm_loader.classList.remove(cls_hide);\n el_confirm_btn_save.classList.add(cls_hide);\n el_confirm_btn_cancel.innerText = loc.Close;\n\n let upload_dict = {\n table: mod_dict.table,\n mode: \"delete\",\n published_pk: mod_dict.published_pk\n };\n UploadChanges(upload_dict, urls.url_exampaper_upload);\n\n const tblRow = document.getElementById(mod_dict.map_id)\n ShowClassWithTimeout(tblRow, \"tsa_tr_error\")\n\n // hide modal\n $(\"#id_mod_confirm\").modal(\"hide\");\n\n }",
"function MExemptionYear_Save(mode) {\n console.log(\"=== MExemptionYear_Save =========\");\n // mode = 'save' or 'delete'\n if (permit_dict.permit_crud && permit_dict.requsr_same_school){\n\n// --- get selected_pk\n const tr_selected = b_get_element_by_data_value(el_MExemptionYear_tblBody_select, \"selected\", \"1\")\n const selected_exemption_examyear_int = (mode === \"delete\") ? 0 : get_attr_from_el_int(tr_selected, \"data-pk\");\n console.log( \"tr_selected\", tr_selected);\n console.log( \"selected_exemption_examyear_int\", selected_exemption_examyear_int);\n\n const upload_dict = {\n table: \"studsubj\",\n mode: \"update\",\n exemption_year: (selected_exemption_examyear_int) ? selected_exemption_examyear_int : null,\n student_pk: mod_MSELEX_dict.student_pk,\n studsubj_pk: mod_MSELEX_dict.studsubj_pk,\n };\n\n console.log( \"upload_dict\", upload_dict);\n\n // update field before upload\n const update_dict = {exemption_year: (selected_exemption_examyear_int) ? selected_exemption_examyear_int : null}\n UpdateField(mod_MSELEX_dict.el_input, update_dict, mod_MSELEX_dict.tobedeleted, mod_MSELEX_dict.st_tobedeleted);\n\n UploadChanges(upload_dict, urls.url_studsubj_single_update);\n };\n\n// hide modal\n $(\"#id_mod_select_exemptionyear\").modal(\"hide\");\n\n } // MExemptionYear_Save",
"function MLINKSTUD_save() {\n console.log(\"===== MLINKSTUD_save =====\");\n\n if (permit_dict.permit_crud && permit_dict.requsr_same_school) {\n\n const url_str = urls.url_student_enter_exemptions;\n const upload_dict = {mode: \"enter\",\n table: \"student\"};\n UploadChanges(upload_dict, url_str);\n };\n\n $(\"#id_mod_link_students\").modal(\"hide\");\n\n }",
"function saveAccountChanges() { // save button clicked in modal\r\n\teditAccount();\r\n}",
"function cargarModalAuditor(){\n\n //mostrar modal\n $('#modalAuditor').modal({'show':true, backdrop: 'static', keyboard: false});\n\n $('#modalAuditor #accion').val(\"insert\");\n //limpiar formulario\n document.getElementById('formAuditor').reset();\n\n //DESCARGAR GRID\n $.jgrid.gridUnload(\"gridProcesosDesignados\");\n $.jgrid.gridUnload(\"gridColaboradores\");\n\n\n }",
"function handleModalAccept() {\r\n var newBook = getNewBookValsFromModal();\r\n insertNewBook(newBook.id, newBook.title, newBook.author, newBook.subject, newBook.photoURL, newBook.vendorURL, newBook.favorite);\r\n window.location.reload(false);\r\n storeBook(newBook.title, newBook.author, newBook.photoURL, newBook.subject, newBook.vendorURL, newBook.favorite);\r\n hideAddBookModal();\r\n}",
"function saveTableData() {\n $(regTable).on('click', 'input[id=\"saveButton\"]', function (event) {\n $(this).parents('tr').find('td.editableColumns').each(function () {\n $(this).prop('contenteditable', false);\n });\n $(this).hide();\n $(\"#deleteButton\").show();\n $(\"#editButton\").show();\n $(\"#cancelButton\").hide();\n\n });\n }",
"function ModConfirmSave() {\n console.log(\" --- ModConfirmSave --- \");\n console.log(\"mod_dict: \", mod_dict);\n\n mod_dict.dont_hide_modal = mod_dict.is_test;\n if (permit_dict.permit_submit_exam && permit_dict.requsr_same_school) {\n\n console.log(\"mod_dict.mode: \", mod_dict.mode);\n add_or_remove_class(el_confirm_loader, cls_hide, false);\n let upload_dict = null, url_str = null;\n if (mod_dict.mode === \"copy_scores\"){\n upload_dict = {mode: (mod_dict.is_test) ? \"is_test\" : \"update\"};\n url_str = urls.url_copy_wolf_scores;\n\n } else if (mod_dict.mode === \"undo_submitted\"){\n upload_dict = { table: \"grades\",\n page: 'page_wolf',\n mode: mod_dict.mode,\n grade_pk: mod_dict.grade_pk,\n examyear_pk: mod_dict.examyear_pk,\n subject_pk: mod_dict.subject_pk,\n student_pk: mod_dict.student_pk,\n ce_exam_published: null,\n return_grades_with_exam: true\n };\n url_str = urls.url_grade_upload;\n mod_dict.dont_hide_modal = false;\n };\n\n console.log(\"url_str: \", url_str);\n console.log(\"upload_dict: \", upload_dict);\n UploadChanges(upload_dict, url_str);\n };\n// --- hide modal\n if (!mod_dict.dont_hide_modal){\n $(\"#id_mod_confirm\").modal(\"hide\");\n };\n } // ModConfirmSave",
"function MPUBORD_Save () {\n console.log(\"=== MPUBORD_Save =====\") ;\n\n if (permit_dict.permit_submit_orderlist) {\n mod_MPUBORD_dict.step += 1;\n\n const upload_dict = {\n table: \"orderlist\",\n now_arr: get_now_arr()\n };\n\n\n if (mod_MPUBORD_dict.step === 1){\n UploadChanges(upload_dict, urls.url_orderlist_request_verifcode);\n } else if (mod_MPUBORD_dict.step === 3){\n\n upload_dict.mode = \"submit_save\";\n upload_dict.verificationcode = el_MPUBORD_input_verifcode.value\n upload_dict.verificationkey = mod_MPUBORD_dict.verificationkey;\n\n upload_dict.mode = \"submit_save\";\n\n upload_dict.send_email = !!el_MPUBORD_send_email.checked;\n\n UploadChanges(upload_dict, urls.url_orderlist_publish);\n };\n MPUBORD_SetInfoboxesAndBtns() ;\n } ;\n }",
"function ModConfirmSave() {\n console.log(\" --- ModConfirmSave --- \");\n console.log(\"mod_dict: \", mod_dict);\n let close_modal_with_timout = false;\n\n if ([\"prelim_orderlist\", \"orderlist_per_school\"].includes(mod_dict.mode)){\n let href = null;\n if (mod_dict.mode === \"orderlist_per_school\"){\n href = urls.orderlist_per_school_download_url;\n } else if (mod_dict.mode === \"prelim_orderlist\"){\n const el_id_MCONF_select = document.getElementById(\"id_MCONF_select\")\n const href_str = (el_id_MCONF_select.value) ? el_id_MCONF_select.value : \"-\"\n href = urls.url_orderlist_download.replace(\"-\", href_str);\n };\n const el_modconfirm_link = document.getElementById(\"id_modconfirm_link\");\n el_modconfirm_link.href = href;\n el_modconfirm_link.click();\n // show loader\n el_confirm_loader.classList.remove(cls_visible_hide)\n //close_modal_with_timout = true;\n $(\"#id_mod_confirm\").modal(\"hide\");\n\n } else if ([\"delete_envelopbundle\", \"delete_enveloplabel\", \"delete_envelopitem\"].includes(mod_dict.mode)) {\n if (permit_dict.permit_crud){\n const is_bundle = (mod_dict.mode === \"delete_envelopbundle\");\n const is_label = (mod_dict.mode === \"delete_enveloplabel\");\n let upload_dict = {\n table: mod_dict.table,\n mode: \"delete\",\n pk_int: mod_dict.pk_int\n };\n\n const url_str = (is_bundle) ? urls.url_envelopbundle_upload :\n (is_label) ? urls.url_enveloplabel_upload : urls.url_envelopitem_upload;\n UploadChanges(upload_dict, url_str);\n\n const tblRow = document.getElementById(mod_dict.map_id)\n ShowClassWithTimeout(tblRow, \"tsa_tr_error\")\n };\n $(\"#id_mod_confirm\").modal(\"hide\");\n\n } else if (mod_dict.mode === \"download\") {\n\n const upload_dict = {\n envelopsubject_pk_list: [mod_dict.envelopsubject_pk],\n sel_layout: \"all\"\n };\n\n //console.log(\"upload_dict\", upload_dict)\n // convert dict to json and add as parameter in link\n const upload_str = JSON.stringify(upload_dict);\n const href_str = urls.url_envelop_print.replace(\"-\", upload_str);\n console.log(\"href_str\", href_str)\n\n const el_modconfirm_link = document.getElementById(\"id_modconfirm_link\");\n el_modconfirm_link.href = href_str;\n //console.log(\"el_modconfirm_link\", el_modconfirm_link)\n\n el_modconfirm_link.click();\n\n // --- hide modal\n if(close_modal_with_timout) {\n // close modal after 5 seconds\n setTimeout(function (){ $(\"#id_mod_confirm\").modal(\"hide\") }, 5000);\n } else {\n $(\"#id_mod_confirm\").modal(\"hide\");\n //console.log(\"close_modal_with_timout\", close_modal_with_timout)\n };\n };\n }",
"function save_change_remark(){\n var info_remark = {};\n jQuery('#list_remarked td p').each(function(){\n var t = {};\n t['id'] = jQuery(this).attr(\"id\");\n t['vn'] = jQuery(this).attr(\"vn\");\n t['en'] = jQuery(this).attr(\"en\");\n info_remark[jQuery(this).attr(\"id\")] = t; \n });\n list_remark_room[r_r_id] = info_remark;\n \n jQuery('#popup_add_remark_room').bPopup().close();\n show_remarked();\n }",
"function ModConfirmSave() {\n console.log(\" --- ModConfirmSave --- \");\n console.log(\"mod_dict: \", mod_dict);\n\n let close_modal = false;\n\n if (mod_dict.mode === \"validate_subj_composition\"){\n // --- upload changes\n const upload_dict = {\n student_pk: mod_dict.student_pk,\n subj_dispensation: mod_dict.new_subj_dispensation\n };\n UploadChanges(upload_dict, urls.url_validate_subj_composition);\n close_modal = true;\n\n } else if (mod_dict.mode === \"delete_cluster\"){\n MCL_delete_cluster(mod_MCL_dict.sel_cluster_dict);\n close_modal = true;\n\n // - enable save btn\n if (el_MCL_btn_save){el_MCL_btn_save.disabled = false};\n\n } else if ([\"prelim_ex1\", \"prelim_ex4\"].includes(mod_dict.mode)){\n const el_modconfirm_link = document.getElementById(\"id_modconfirm_link\");\n if (el_modconfirm_link) {\n\n const href_str = (mod_dict.mode === \"prelim_ex4\") ? urls.url_download_ex4 : urls.url_download_ex1;\n el_modconfirm_link.setAttribute(\"href\", href_str);\n el_modconfirm_link.click();\n\n // show loader\n el_confirm_loader.classList.remove(cls_visible_hide)\n // close modal after 5 seconds\n //setTimeout(function (){ $(\"#id_mod_confirm\").modal(\"hide\") }, 5000);\n close_modal = true;\n };\n } else if ([\"has_exemption\", \"has_sr\", \"has_reex\", \"has_reex03\"].includes(mod_dict.mode)){\n\n // --- change icon, before uploading\n // don't, because of validation on server side\n // add_or_remove_class(mod_dict.el_input, \"tickmark_1_2\", new_value, \"tickmark_0_0\");\n// --- upload changes\n const upload_dict = {\n student_pk: mod_dict.stud_pk,\n studsubj_pk: mod_dict.studsubj_pk\n };\n upload_dict[mod_dict.fldName] = mod_dict.new_value;\n UploadChanges(upload_dict, urls.url_studsubj_single_update);\n\n close_modal = true;\n\n } else if ([\"is_extra_nocount\", \"is_extra_counts\", \"is_thumbrule\"].includes(mod_dict.mode)){\n\n // --- change icon, before uploading\n // when validation on server side fails, the old value is reset by RefreshDataRowItem PR2022-05-27\n // updated_studsubj_rows must contain ie err_fields: ['has_reex']\n add_or_remove_class(mod_dict.el_input, \"tickmark_1_2\", mod_dict.new_value, \"tickmark_0_0\");\n\n// --- upload changes\n const upload_dict = {\n student_pk: mod_dict.data_dict.stud_id,\n studsubj_pk: mod_dict.data_dict.studsubj_id\n };\n upload_dict[mod_dict.mode] = mod_dict.new_value;\n UploadChanges(upload_dict, urls.url_studsubj_single_update);\n close_modal = true;\n };\n\n// --- hide modal\n if(close_modal) {\n $(\"#id_mod_confirm\").modal(\"hide\");\n }\n } // ModConfirmSave",
"function ModConfirmSave() {\n console.log(\" --- ModConfirmSave --- \");\n console.log(\" mod_dict: \", mod_dict);\n\n let close_modal = false, skip_uploadchanges = false, url_str = null;\n const upload_dict = {mode: mod_dict.mode, mapid: mod_dict.mapid};\n\n if ([\"prelim_excomp\", \"payment_form\", \"download_invoice\"].includes(mod_dict.mode)){\n const el_modconfirm_link = document.getElementById(\"id_modconfirm_link\");\n if (el_modconfirm_link) {\n skip_uploadchanges = true;\n\n const href_str = (mod_dict.mode === \"payment_form\") ? urls.url_download_paymentform :\n (mod_dict.mode === \"download_invoice\") ? urls.url_download_invoice :\n urls.url_download_excomp;\n el_modconfirm_link.setAttribute(\"href\", href_str);\n el_modconfirm_link.click();\n\n // show loader\n el_confirm_loader.classList.remove(cls_visible_hide)\n\n // close modal after 5 seconds\n //setTimeout(function (){ $(\"#id_mod_confirm\").modal(\"hide\") }, 5000);\n close_modal = true;\n };\n };\n\n// --- Upload changes\n if (!skip_uploadchanges){\n UploadChanges(upload_dict, url_str);\n };\n\n// --- hide modal\n if(close_modal) {\n $(\"#id_mod_confirm\").modal(\"hide\");\n };\n }",
"function applyToTableAndAjaxEdit(r, rowindex, id, selected_button) {\n //if we confirm edit(r = true) call ajax and save changes into DB\n if (r == true) {\n\n //get data from modal's inputs\n //student_name = $('#editModal #student-label').html();\n //exam_name = $('#editModal #exam-label').html();\n pass_date = $('#editModal #birth-date-input').val();\n mark = $('#mark-number-input').val();\n\n if (validate(pass_date, 'edit')) {\n //hide modal\n $('#editModal').modal('hide');\n\n //edit table row\n var tdate = table.cell(rowindex, 2);\n tdate.data(pass_date).draw();\n var tmark = table.cell(rowindex, 3);\n tmark.data(mark).draw();\n\n $.ajax({\n url: selected_button.data('url'),\n type: 'post',\n dataType: 'json',\n data: {id: id, date: pass_date, mark: mark}\n\n }).done(function (response) {\n\n }).fail(function (jqXHR, textStatus, errorThrown) {\n alert('Error : ' + errorThrown);\n });\n\n }\n\n }\n }",
"function pmfAutosave() {\n var ed = window.tinyMCE.activeEditor;\n if (ed.isDirty()) {\n var formData = {};\n formData.revision_id = $('#revision_id').attr('value');\n formData.record_id = $('#record_id').attr('value');\n formData.csrf = $('[name=\"csrf\"]').attr('value');\n formData.openQuestionId = $('#openQuestionId').attr('value');\n formData.question = $('#question').attr('value');\n formData.answer = ed.getContent();\n formData.keywords = $('#keywords').attr('value');\n formData.tags = $('#tags').attr('value');\n formData.author = $('#author').attr('value');\n formData.email = $('#email').attr('value');\n formData.lang = $('#lang').attr('value');\n formData.solution_id = $('#solution_id').attr('value');\n formData.active = $('input:checked:[name=\"active\"]').attr('value');\n formData.sticky = $('#sticky').attr('value');\n formData.comment = $('#comment').attr('value');\n formData.grouppermission = $('[name=\"grouppermission\"]').attr('value');\n formData.userpermission = $('[name=\"userpermission\"]').attr('value');\n formData.restricted_users = $('[name=\"restricted_users\"]').attr('value');\n formData.dateActualize = $('#dateActualize').attr('value');\n formData.dateKeep = $('#dateKeep').attr('value');\n formData.dateCustomize = $('#dateCustomize').attr('value');\n formData.date = $('#date').attr('value');\n\n $.ajax({\n url: pmfAutosaveAction(),\n type: 'POST',\n data: formData,\n success: function (r) {\n var resp = $.parseJSON(r);\n\n $('#saving_data_indicator').html(resp.msg);\n\n ed.isNotDirty = true;\n\n $('#record_id').attr('value', resp.record_id);\n $('#revision_id').attr('value', resp.revision_id);\n /* XXX update more places on the page according to the new saved data */\n }\n });\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
console.log data got from promiseFunction | function printDataPromise() {
promiseFunction().then(data => {
console.log(data);
});
} | [
"function printDataPromise() {\n let p = promiseFunction();\n p.then(function(beta){\n console.log(beta);\n });\n}",
"async function printDataAsyncAwait() {\n const data = await promiseFunction();\n console.log(data);\n}",
"async function printDataAsyncAwait() {\n let p = promiseFunction();\n const beta = await p;\n console.log(beta);\n}",
"function GNPSdata() {\n\t\t\t\t\t\t\treturn new Promise(res=>{\n\t\t\t\t\t\t\t\tlet dataFromDB = \"{}\"; // Data from DB\n\t\t\t\t\t\t\t\tres(dataFromDB);\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}",
"function usFunction(value) {\r\n console.log(value);\r\n}//promise function used for setTimeout",
"async function fetchingData () {\n const datosFetching = await getDatos(); \n console.log(datosFetching); \n }",
"function getDataFromServer() {\n const lastData = getRequestPromise();\n return lastData;\n}",
"function getUserData() {\n userData((err, data) => {\n if(err) {\n console.log('ERROR:', err);\n return;\n }\n return console.log(data.response);\n });\n}",
"async function getAsyncData(){\n const res = await resolveafter3Sec();\n console.log(res); \n}",
"async function grabData() {\n // Including selected instance to ensure we can grab\n // current queueables on load.\n return await eel.dashboard_queue_function_information(activeInstance())();\n }",
"async function showDataWithAsync(title) {\n var data = await getMovieWithPromises(title);\n console.log(data);\n}",
"async function processShowResponse() {\n gPaymentResponse = await gShowPromise;\n print(JSON.stringify(gPaymentResponse, undefined, 2));\n}",
"async function awaitFetchData() {\n let returnedData = await fetchData();\n console.log(returnedData);\n}",
"async function getGrades() { // async returns a promise\n try {\n console.log('We are in async function');\n const getGra = await grades1; // getGra will hold the array which was returned from grades1 promise\n console.log(getGra);\n const getInfo = await getGra1(getGra[2]); // getInfor now is a string returned by getGra1 function\n console.log(getInfo);\n /*If at here we return the getInfo like: \"return getInfo;\", and outside of function, we want to print\n this by using: \"console.log(getGrades())\" ==> it doesn't work correctly because all promises is running\n in the backgournd, and getInfo hasn't got the result already, so return command will return nothing,==>\n \"console.log(getGrades())\" can not print out the actual value. Therefore, we have to wait untill the getinfo\n receives the result from the promise. We can do by using getGrades().then() */\n console.log('We are end-in async function');\n let a = 5;\n let b = 6;\n console.log(a+b);\n\n return getGra;\n } catch(err){\n console.log(err);\n }\n }",
"async function p() {\n requestNumbers().then(function(data){\n returnedResults.push(data);\n })\n}",
"getObjData() {\n console.log(\"Getting object data..\");\n\n // Atualiza o Local Storage com os dados do local storage antigo e com as novas linhas da tabela\n this.app.getObject(this.objId).then((model) => {\n model\n .getHyperCubeData(\"/qHyperCubeDef\", [{\n qTop: 0,\n qLeft: 0,\n qWidth: this.visQtFields,\n qHeight: this.visQtRows,\n }, ])\n .then((data) => {\n let rows = data[0].qMatrix;\n\n rows.forEach((hyperCubeData) => {\n let updated = { qText: 0 };\n hyperCubeData.push(updated);\n });\n var savedItens = this.localStorage;\n if (savedItens) {\n // Junta cada um dos que já estavam salvos ao resultado da seleção\n savedItens.forEach((item) => {\n rows.push(item);\n });\n }\n let jsonData = JSON.stringify(rows);\n\n this.localStorage = rows;\n });\n });\n\n // return new Promise((resolve, reject) => {\n // resolve(\"Data Fetched and Local Storage Updated\");\n // reject(Error);\n // });\n }",
"function AsyncData() {}",
"function promiseLog(message) {\n return value => {\n console.log(message);\n return value;\n }\n}",
"function getData() {\n var defered = q.defer();\n connection.query(sqlStatement, defered.makeNodeResolver());\n return defered.promise;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process the token if valid, otherwise throws an error | function processTokenCallback(kc, token) {
if (kc.debug) {
console.info('[SSI.KEYCLOAK] Processing Token');
}
try {
setTokenIfValid(kc, token);
} catch (e) {
return kc.onAuthError(e);
}
return kc.onAuthSuccess();
} | [
"validateToken(token) {\n return true;\n }",
"ensureValidToken () {\n if (this.isValid()) {\n return\n }\n\n throw new Error(`Invalid JWT. Looks like the token is neither signed nor encrypted. Received token: ${this.value}`)\n }",
"async validateToken () {\n\t\tif (!this.request.user || this.userByNR) { return; }\n\t\tif (\n\t\t\tthis.userClass &&\n\t\t\ttypeof this.request.user.validateTokenPayload === 'function'\n\t\t) {\n\t\t\tconst reason = this.request.user.validateTokenPayload(this.payload);\n\t\t\tif (reason) {\n\t\t\t\tthrow this.errorHandler.error('tokenExpired', { reason });\n\t\t\t}\n\t\t}\n\t}",
"function invalidToken() {\n throw new Error(`Invalid token: \"${encodedToken}\"`);\n }",
"function validateToken(token) {\n console.log('validate token func');\n jsonwebtoken.verify(token, PRIV_KEY, (err, decoded) => {\n if (err) {\n ``;\n console.log(err, 'we had an error in validate token');\n } else {\n console.log(decoded, 'decoded token');\n }\n });\n}",
"async verifyToken () {\n\t\tif (!this.token) { return; }\n\t\ttry {\n\t\t\tthis.payload = this.tokenHandler.verify(this.token);\n\t\t}\n\t\tcatch (error) {\n\t\t\tconst message = typeof error === 'object' ? error.message : error;\n\t\t\tthrow this.errorHandler.error('tokenInvalid', { reason: message });\n\t\t}\n\t}",
"function errorMessageToken(token, error) {\n if (token === \"\") {\n error.textContent = Content.errorMessage('req');\n displayErrorMessage(error);\n return true;\n } else if (!validateToken(token)) {\n error.textContent = Content.errorMessage('valid', text.localize('verification token'));\n displayErrorMessage(error);\n return true;\n }\n hideErrorMessage(error);\n return false;\n }",
"function verifyToken( ) {\n\n }",
"function checkToken (token) {\n return true;\n }",
"function checkToken (token) {\n return true\n }",
"function validateToken(req, res, next) {\n req.token = req.params.token;\n storage.getCallUrlData(req.token, function(err, urlData) {\n if (res.serverError(err)) return;\n if (urlData === null) {\n sendError(res, 404, errors.INVALID_TOKEN, \"Token not found.\");\n return;\n }\n req.callUrlData = urlData;\n next();\n });\n }",
"tokenIsValid(token) { \n try {\n jwt.verify(token, jwtSecret);\n return true\n } catch (error) {\n tokenList = tokenList.filter(item => item !== token);\n return false\n }\n }",
"function checkCurrentToken() {\n try {\n let token = getCurrentToken();\n let claims = JSON.parse(atob(token.split('.')[1]));\n\n if (token) {\n if ((token ? claims.exp : 0) > Date.now()) {\n handleValidToken(claims);\n } else {\n handleExpiredToken();\n }\n } else {\n handleNoToken();\n }\n } catch (err) {\n handleNoToken();\n }\n }",
"function validate() {\n // Define the data object and include the needed parameters.\n let data = { Token: token };\n // Make the validate API call and assign a callback function.\n authService.Validate(data).then(validateCallback);\n}",
"function validateToken() {\n return __awaiter(this, void 0, void 0, function () {\n var resp;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, needle_1.default('get', 'https://id.twitch.tv/oauth2/validate', null, {\n headers: {\n Authorization: \"OAuth \" + apiData.value.accessToken,\n },\n })];\n case 1:\n resp = _a.sent();\n if (resp.statusCode !== 200) {\n throw new Error(JSON.stringify(resp.body));\n // Do we need to retry here?\n }\n return [2 /*return*/, resp.body];\n }\n });\n });\n}",
"function handleTokenCallback(token) {\n logTestOutput(JSON.stringify(token, null, 2));\n if (token.TokenId || token.CvvToken) {\n if (token.TokenId) {\n document.getElementById(\"token\").value = token.TokenId;\n } else {\n document.getElementById(\"cvv-token\").value = token.CvvToken;\n }\n document.getElementById(\"persist\").value = document.getElementById(\"persist\").checked;\n document.getElementById(\"payment-form\").submit();\n } else {\n logTestOutput(\"The value received does not contain a valid Token\");\n event.preventDefault();\n }\n setLoader(false);\n}",
"function tokenValidation(token) {\n const creation_Date = parseInt(token.split(' ')[1]);\n return new Date().getTime() - creation_Date < 600000\n}",
"async function isTokenValid(token) {\n try {\n const config = { headers: { \"x-auth-token\": token } };\n // console.log('Token from AuthState :',state.Token);\n // console.log('config from AuthState',config);\n const TokenResp = await axios.post(\"/api/v4/valid\", null, config);\n dispatch({ type: VALID_TOKEN, payload: TokenResp.data.user, auth: true });\n } catch (err) {\n dispatch({\n type: USER_ERROR,\n payload: err.response.data.msg,\n auth: false,\n });\n }\n }",
"function verifyToken(){\n \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return an array of lines wrapping the given text to the given width. This splits on whitespace. Single tokens longer than `width` are not broken up. | function textwrap(s, width) {
var words = s.trim().split(/\s+/);
var lines = [];
var line = '';
words.forEach(function (w) {
var newLength = line.length + w.length;
if (line.length > 0)
newLength += 1;
if (newLength > width) {
lines.push(line);
line = '';
}
if (line.length > 0)
line += ' ';
line += w;
});
lines.push(line);
return lines;
} | [
"function breakParagraphToFitWidth(text, width, widthMeasure) {\n var lines = [];\n var tokens = tokenize(text);\n var curLine = \"\";\n var i = 0;\n var nextToken;\n while (nextToken || i < tokens.length) {\n if (typeof nextToken === \"undefined\" || nextToken === null) {\n nextToken = tokens[i++];\n }\n var brokenToken = breakNextTokenToFitInWidth(curLine, nextToken, width, widthMeasure);\n\n var canAdd = brokenToken[0];\n var leftOver = brokenToken[1];\n\n if (canAdd !== null) {\n curLine += canAdd;\n }\n nextToken = leftOver;\n if (leftOver) {\n lines.push(curLine);\n curLine = \"\";\n }\n }\n if (curLine) {\n lines.push(curLine);\n }\n return lines;\n }",
"function lineToRows(text, width) {\n const rows = [];\n let row = [];\n let wordsCount = 0;\n text.split(' ').forEach((word) => {\n if (wordsCount + (word.length + 1) > width) {\n /**\n * Push the number of whitespace left after the existing current\n * and the terminal space. We need to do this, coz we at times\n * have whitespace when the upcoming word may break into next\n * lines\n */\n row.push(new Array(width - wordsCount + 1).join(' '));\n /**\n * Push the existing row to the rows\n */\n rows.push(row.join(' '));\n /**\n * Row is empty now\n */\n row = [];\n /**\n * Row has zero words\n */\n wordsCount = 0;\n }\n /**\n * Increase the words count + 1. The extra one is for the\n * whitspace between the words\n */\n wordsCount += word.length + 1;\n /**\n * Collect word inside the row\n */\n row.push(word);\n });\n /**\n * Handle the orphan row\n */\n if (row.length) {\n rows.push(row.join(' '));\n }\n return rows;\n}",
"function getLines(ctx, text, maxWidth) {\n var words = text.split(\" \");\n var lines = [];\n var currentLine = words[0];\n\n for (var i = 1; i < words.length; i++) {\n var word = words[i];\n var width = ctx.measureText(currentLine + \" \" + word).width;\n if (width < maxWidth) {\n currentLine += \" \" + word;\n } else {\n lines.push(currentLine);\n currentLine = word;\n }\n }\n lines.push(currentLine);\n return lines;\n}",
"function CharWrapByFontWidth(textToWrap, font, pixelWidth)\n{\n var lines = new Array();\n var buffer = \"\";\n var nextLine = false;\n var c = 0;\n \n while (c < textToWrap.length)\n {\n buffer = \"\";\n nextLine = false;\n while (!nextLine && c < textToWrap.length)\n {\n if ((font.getStringWidth(buffer + textToWrap.charAt(c)) <= pixelWidth && textToWrap.charAt(c) != '\\n') || buffer == \"\")\n {\n buffer += textToWrap.charAt(c);\n c++;\n }\n else\n {\n nextLine = true;\n if (textToWrap.charAt(c) == '\\n')\n {\n c++;\n }\n }\n }\n lines.push(buffer);\n }\n \n return lines;\n}",
"function breakTextToFitWidth(text, width, widthMeasure) {\n var ret = [];\n var paragraphs = text.split(\"\\n\");\n for (var i = 0, len = paragraphs.length; i < len; i++) {\n var paragraph = paragraphs[i];\n if (paragraph !== null) {\n ret = ret.concat(breakParagraphToFitWidth(paragraph, width, widthMeasure));\n } else {\n ret.push(\"\");\n }\n }\n return ret;\n }",
"function wrapTextIntoLines(context, text, maxLength) {\n var words = text.split(\" \");\n var currentWordIndex = 0;\n var lines = [];\n\n while (currentWordIndex < words.length) {\n var currentLine = words[currentWordIndex++];\n while (context.measureText(currentLine + \" \"\n + words[currentWordIndex + 1]).width\n < maxLength && currentWordIndex < words.length) {\n currentLine += \" \" + words[currentWordIndex++];\n }\n lines.push(currentLine);\n }\n\n return lines;\n}",
"wrapText(str, lineLength, commentToken='//') {\n if (str.length > lineLength) {\n // Find first break before lineLimit\n let breakIndex;\n for (let i = lineLength; breakIndex === undefined; i--) {\n if (str[i] === ' ') {\n breakIndex = i;\n } else if (i === 0) {\n // If no break is found, just break it off at lineLength\n breakIndex = lineLength;\n }\n }\n\n return [\n str.slice(0, breakIndex),\n ...this.wrapText(\n commentToken + str.slice(breakIndex), lineLength, commentToken)\n ];\n } else {\n return [str];\n }\n }",
"function _splitIntoLine(aText, aMaxWidth,textLines) {\n var words = (aText || \"\").split(\" \");\n var currWord = \"\";\n var currlineText = \"\";\n var currlinePx = 0;\n for (var i = 0; i < words.length; i++) {\n currWord = words[i];\n currlinePx = ctx.measureText(currlineText + currWord).width;\n if (currlinePx < aMaxWidth) {\n currlineText += \" \" + currWord;\n } else {\n textLines.push(currlineText);\n currlineText = currWord;\n }\n if (i === words.length-1) {\n textLines.push(currlineText);\n break;\n }\n }// for\n return textLines;\n }",
"wrapText(text, wordWrapWidth) {\n // Greedy wrapping algorithm that will wrap words as the line grows longer\n // than its horizontal bounds.\n let lines = text.split(/\\r?\\n/g);\n let allLines = [];\n let realNewlines = [];\n for (let i = 0; i < lines.length; i++) {\n let resultLines = [];\n let result = '';\n let spaceLeft = wordWrapWidth;\n let words = lines[i].split(' ');\n for (let j = 0; j < words.length; j++) {\n let wordWidth = this._context.measureText(words[j]).width;\n let wordWidthWithSpace = wordWidth + this._context.measureText(' ').width;\n if (j === 0 || wordWidthWithSpace > spaceLeft) {\n // Skip printing the newline if it's the first word of the line that is\n // greater than the word wrap width.\n if (j > 0) {\n resultLines.push(result);\n result = '';\n }\n result += words[j];\n spaceLeft = wordWrapWidth - wordWidth;\n }\n else {\n spaceLeft -= wordWidthWithSpace;\n result += ' ' + words[j];\n }\n }\n\n if (result) {\n resultLines.push(result);\n result = '';\n }\n\n allLines = allLines.concat(resultLines);\n\n if (i < lines.length - 1) {\n realNewlines.push(allLines.length);\n }\n }\n\n return {l: allLines, n: realNewlines};\n }",
"split(raw, width) {\n let res = [\"\"];\n let current = 0;\n raw.split(/\\n/g).forEach((text) => {\n let length = 0;\n res[++current] = \"\";\n if (text.length < width) {\n res[current] = text;\n return;\n }\n // firefox does not support lookbehinds; we are using a private area in the unicode range\n let split = text.replace(AsciiEngine.SEPARATOR_REGEXP, \"$1\\uea01\").split(/\\uea01/g);\n for (let string of split) {\n if (length + string.length <= width) {\n length += string.length;\n res[current] += string;\n } else {\n res[++current] = string;\n length = string.length;\n }\n }\n });\n\n return res.slice(1);\n }",
"explodeWord(text, width, maxNumLines, charWidth) {\n setDummyContext();\n let i;\n let left = text;\n let right = '';\n let lastChar;\n let result = [];\n\n if (textHelper.isNumber(maxNumLines) && maxNumLines <= 1) {\n return [text];\n }\n\n const maxNumChars = Math.ceil(width / charWidth);\n const num = Math.min(text.length, maxNumChars);\n\n for (i = num; i > 0; i--) {\n left = text.substring(0, i);\n lastChar = text.substring(i - 1, i);\n // When remainder is added to a new line there is a chance of breaking at a space\n if (lastChar === ' ') {\n left = text.substring(0, i - 1);\n } else {\n left += defaultHyphen;\n }\n right = text.substring(i);\n if (textHelper.measureTextWidth(left) <= width) {\n break;\n }\n }\n if ((!i && !left) || textHelper.measureTextWidth(left) > width) {\n left = text.substring(0, 1);\n right = text.substring(1);\n }\n\n result.push(left);\n if (!right) {\n return result;\n }\n\n if (textHelper.measureTextWidth(right) > width) {\n right = textHelper.explodeWord(right, width, maxNumLines - 1, charWidth);\n result = result.concat(right);\n } else {\n result.push(right);\n }\n // Remove any spaces added by the remainder\n return result.filter((item) => item.trim() !== '');\n }",
"get lines () {\n var words = this.words;\n if ( this.desired_line_count == 1 ) {\n return [ words.join(' ') ];\n }\n\n var width;\n var lines;\n var index;\n const max = this.max_width;\n const longest_word = this.min_width;\n const est_min = Math.floor( max / ( this.desired_line_count + 1 ) );\n const min = longest_word > est_min ? longest_word : est_min;\n for ( width = min; width <= max; width++ ) {\n // console.log(width);\n lines = [''];\n for ( index = 0; index < words.length; index++ ) {\n var new_length;\n var last_line = lines.length - 1; // index of last line\n\n if ( lines[last_line].length > 0 ) {\n new_length = lines[last_line].length + 1 + words[index].length;\n } else {\n new_length = words[index].length;\n }\n\n // If line would become too long then add new line\n if ( new_length > width ) {\n lines.push('');\n last_line++;\n }\n\n if ( lines[last_line].length > 0 ) {\n lines[last_line] = [lines[last_line], words[index]].join(' ');\n } else {\n lines[last_line] = words[index];\n }\n }\n if ( lines.length <= this.desired_line_count ) {\n return lines;\n }\n }\n }",
"function splitByWidth(content, properties, textWidthMeasurer, maxWidth, maxNumLines, truncator) {\n // Default truncator returns string as-is\n truncator = truncator ? truncator : function (properties, maxWidth) { return properties.text; };\n var result = [];\n var words = split(content);\n var usedWidth = 0;\n var wordsInLine = [];\n for (var _i = 0, words_2 = words; _i < words_2.length; _i++) {\n var word = words_2[_i];\n // Last line? Just add whatever is left\n if ((maxNumLines > 0) && (result.length >= maxNumLines - 1)) {\n wordsInLine.push(word);\n continue;\n }\n // Determine width if we add this word\n // Account for SPACE we will add when joining...\n var wordWidth = wordsInLine.length === 0\n ? getWidth(word, properties, textWidthMeasurer)\n : getWidth(SPACE + word, properties, textWidthMeasurer);\n // If width would exceed max width,\n // then push used words and start new split result\n if (usedWidth + wordWidth > maxWidth) {\n // Word alone exceeds max width, just add it.\n if (wordsInLine.length === 0) {\n result.push(truncate(word, properties, truncator, maxWidth));\n usedWidth = 0;\n wordsInLine = [];\n continue;\n }\n result.push(truncate(wordsInLine.join(SPACE), properties, truncator, maxWidth));\n usedWidth = 0;\n wordsInLine = [];\n }\n // ...otherwise, add word and continue\n wordsInLine.push(word);\n usedWidth += wordWidth;\n }\n // Push remaining words onto result (if any)\n if (wordsInLine && wordsInLine.length) {\n result.push(truncate(wordsInLine.join(SPACE), properties, truncator, maxWidth));\n }\n return result;\n }",
"function splitByWidth(content, properties, textWidthMeasurer, maxWidth, maxNumLines, truncator) {\n // Default truncator returns string as-is\n truncator = truncator ? truncator : function (properties, maxWidth) { return properties.text; };\n var result = [];\n var words = split(content);\n var usedWidth = 0;\n var wordsInLine = [];\n for (var _i = 0, words_2 = words; _i < words_2.length; _i++) {\n var word = words_2[_i];\n // Last line? Just add whatever is left\n if ((maxNumLines > 0) && (result.length >= maxNumLines - 1)) {\n wordsInLine.push(word);\n continue;\n }\n // Determine width if we add this word\n // Account for SPACE we will add when joining...\n var wordWidth = wordsInLine.length === 0\n ? getWidth(word, properties, textWidthMeasurer)\n : getWidth(SPACE + word, properties, textWidthMeasurer);\n // If width would exceed max width,\n // then push used words and start new split result\n if (usedWidth + wordWidth > maxWidth) {\n // Word alone exceeds max width, just add it.\n if (wordsInLine.length === 0) {\n result.push(truncate(word, properties, truncator, maxWidth));\n usedWidth = 0;\n wordsInLine = [];\n continue;\n }\n result.push(truncate(wordsInLine.join(SPACE), properties, truncator, maxWidth));\n usedWidth = 0;\n wordsInLine = [];\n }\n // ...otherwise, add word and continue\n wordsInLine.push(word);\n usedWidth += wordWidth;\n }\n // Push remaining words onto result (if any)\n if (!_.isEmpty(wordsInLine)) {\n result.push(truncate(wordsInLine.join(SPACE), properties, truncator, maxWidth));\n }\n return result;\n }",
"function breakLinesEntry(text, width, font) {\n var descriptors = toTextDescriptors(text, font);\n\n if (isStringArray(text)) {\n return breakLines(descriptors, width);\n }\n\n if (isTextDescriptorArray(text)) {\n return breakLines(descriptors, width);\n }\n\n return breakLines(descriptors, width)[0];\n}",
"function CharWrapByStrLen(textToWrap, charsPerLine)\n{\n var lines = new Array();\n var buffer = \"\";\n var c = 0;\n \n while (c < textToWrap.length)\n {\n buffer = \"\";\n while ((buffer.length < charsPerLine && c < textToWrap.length && textToWrap.charAt(c) != '\\n') || buffer == \"\")\n {\n buffer += textToWrap.charAt(c);\n c++;\n }\n if (textToWrap.charAt(c) == '\\n')\n {\n c++;\n }\n lines.push(buffer);\n }\n \n return lines;\n}",
"chunk (str, width) {\n const chunks = []\n let chunk\n let ansiDiff\n let index\n let noAnsi\n let attempts = 0\n while (str && ++attempts <= 999) {\n noAnsi = this.utils.stripAnsi(str)\n index = noAnsi.length <= width ? width : this.lastIndexOfRegex(noAnsi, this.split, width)\n if (index < 1) index = Math.max(width, 1)\n // TODO this ain't cutting it for ansi reconstitution\n chunk = str.slice(0, index).trim()\n ansiDiff = chunk.length - this.utils.stripAnsi(chunk).length\n if (ansiDiff > 0) {\n index += ansiDiff\n chunk = str.slice(0, index).trim()\n }\n chunks.push(chunk)\n // prep for next iteration\n str = str.slice(index)\n }\n return chunks\n }",
"function breakNextTokenToFitInWidth(curLine, nextToken, width, widthMeasure) {\n if (isBlank(nextToken)) {\n return [nextToken, null];\n }\n if (widthMeasure(curLine + nextToken) <= width) {\n return [nextToken, null];\n }\n if (!isBlank(curLine)) {\n return [null, nextToken];\n }\n var i = 0;\n while (i < nextToken.length) {\n if (widthMeasure(curLine + nextToken[i] + \"-\") <= width) {\n curLine += nextToken[i++];\n } else {\n break;\n }\n }\n var append = \"-\";\n if (isBlank(curLine) && i === 0) {\n i = 1;\n append = \"\";\n }\n return [nextToken.substring(0, i) + append, nextToken.substring(i)];\n }",
"function WordWrapByFontWidth(textToWrap, font, pixelWidth)\n{\n var lines = new Array();\n var wordBuffer = \"\";\n var wsBuffer = \"\";\n var c = 0;\n \n lines[0] = \"\";\n \n // Process the entire string\n while (c < textToWrap.length)\n {\n // Grab a word and trailing whitespaces\n if (textToWrap.charAt(c) == '\\n')\n {\n // Special catering for linefeeds\n wordBuffer = '\\n';\n c++;\n }\n while (textToWrap.charAt(c) != ' ' && textToWrap.charAt(c) != '\\t' && textToWrap.charAt(c) != '\\n' && c < textToWrap.length)\n {\n wordBuffer += textToWrap.charAt(c);\n c++;\n }\n wsBuffer = \"\";\n while ((textToWrap.charAt(c) == ' ' || textToWrap.charAt(c) == '\\t') && c < textToWrap.length)\n {\n wsBuffer += textToWrap.charAt(c);\n c++;\n }\n \n // Add the word to the lines\n while (wordBuffer != \"\")\n {\n if (wordBuffer == '\\n')\n {\n // More special linefeed catering\n lines.push(\"\");\n wordBuffer = \"\";\n }\n else\n {\n // The wrapping condition!!!\n if (font.getStringWidth(lines[lines.length - 1] + wordBuffer) <= pixelWidth)\n {\n lines[lines.length - 1] += wordBuffer;\n wordBuffer = \"\";\n }\n else\n {\n // If the line is already empty, fit as much of the word as we can\n if (lines[lines.length - 1] == \"\")\n {\n // Test the word and line char by char\n while (wordBuffer != \"\")\n {\n if (font.getStringWidth(lines[lines.length - 1] + wordBuffer.charAt(0)) <= pixelWidth)\n {\n lines[lines.length - 1] += wordBuffer.charAt(0);\n wordBuffer = wordBuffer.slice(1);\n }\n else\n {\n lines[lines.length] = \"\";\n }\n }\n \n }\n else\n {\n // Get over it and try the next line\n lines[lines.length] = \"\";\n }\n }\n }\n }\n // Add that whitespace... if it fits\n if (font.getStringWidth(lines[lines.length - 1] + wsBuffer) <= pixelWidth)\n {\n lines[lines.length - 1] += wsBuffer;\n }\n else\n {\n lines[lines.length] = \"\";\n }\n }\n \n return lines;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set note element click handle by id | function setNoteClickHandle(id) {
try {
var noteElm = getNoteElementById(id);
if (!noteElm) {
window.TextSelection.jsError("setNoteClickHandle undefined");
return;
}
noteElm.addEventListener("click", function () {
var noteId = noteElm.getAttribute("id");
if (noteId !== undefined) {
window.TextSelection.noteClicked(parseInt(noteId));
}
});
} catch (e) {
window.TextSelection.jsError("setNoteClickHandle\n" + e);
}
} | [
"function handleNoteClick (e) {\n \n}",
"function clickOnNote(){\n $(\".noteheader\").click(function () {\n if(!editMode){\n //update active note\n activeNote=$(this).attr(\"id\");\n //fill text area\n $(\"textarea\").val($(this).find(\".text\").text());\n showHide([\"#notePad\",\"#AllNotes\"],[\"#notes\",\"#AddNote\",\"#Edit\",\"#Done\"]);\n $(\"textarea\").focus();\n }\n });\n\n }",
"function openNote() {\n // get the handle of the clicked element\n var $selectedNote = ($(this)).parent();\n var id = getNoteId($selectedNote);\n selectNote(id);\n}",
"function clickonNote(){\r\n $('.noteheader').click(function(){\r\n if(!editMode){\r\n \r\n //update activeNote variable\r\n activeNote = $(this).attr('id');\r\n \r\n //fill textarea\r\n $('textarea').val($(this).find('.text').text());\r\n showHide(['#notePad','#allNote'], ['#addNote','#notes','#edit','#done']);\r\n $(\"textarea\").focus();\r\n }\r\n \r\n \r\n });\r\n }",
"function clickonnote(){\n \n $(\".noteheader\").click(function(){\n \n if(!editmode){\n //update activemode variable to id of the clicked note\n activenote = $(this).attr(\"id\");\n \n //fill text area\n \n $(\"textarea\").val($(this).find('.text').text());\n showhide([\"#notepad\",\"#allnotes\"],[\"#notes\",\"#addnote\",\"#edit\",\"#done\"]);\n $(\"textarea\").focus(); \n \n \n \n \n \n \n }\n \n \n \n \n });\n \n \n \n \n}",
"function noteClicked(){\n\t\t\t$(\".noteContainer\").click(function(){\n\t\t\t\t\n\t\t\t\tif(!editMode){\n\t\t\t\t\t\n\t\t\t\t\t//set the activeNote id to the id of the clicked note\n\t\t\t\t\tactiveNote = $(this).attr(\"id\");\n\t\t\t\t\t\n\t\t\t\t\t//set the content of the text area to the content of the clicked note\n\t\t\t\t\t$(\"textarea\").val($(this).find(\".noteSection\").text());\n\t\t\t\t\tshowHideElements([\"#notePad\",\"#allnotes\"],[\"#addnote\", \"#notes\", \"#edit\", \"#done\"]);\n\t\t\t\t\t$(\"textarea\").focus();\t\n\t\t\t\t\t$(\"#successalertContent\").text('You can now edit your note!');\n\t\t\t\t\t$(\"#successalert\").fadeIn();\n\t\t\t\t\t}\n\t\t\t\t\n\t\t\t\t});\n\t\t}",
"function handleClick() {\n // (21) tap into props.onDelete to trigger the function DeleteNote(id)\n // (28) pass in the props.id (index) to know which one to delete in onDelete\n props.onDelete(props.id);\n }",
"function setNextNoteID(id) {\n\tlet mainDiv = document.getElementById(\"main\");\n\tmainDiv.getElementsByTagName('div')[1].id = id; // Store ID in hidden Div in main\n}",
"function handleClick(newId){\n var currentx = lastClicked[0];\n var currenty = lastClicked[2];\n var newx = newId[0];\n var newy = newId[2];\n walk(currentx,currenty,newx,newy)\n}",
"function clickToEdit() {\n jQuery(\"#sheet\").on('click', \".notesCanvas\", function() {\n console.log(\"ID\", this.id);\n if (playOption === \"stop\") editMeasure(this.id);\n })\n}",
"function createCanvasNote(id){\n html.interface.screen.wrapper.prepend('<div id=\"'+id+'\" class=\"noteWrapper\"><div class=\"noteBar\"><img class=\"closeNote\" src=\"Images/close.png\" /><img class=\"swapRight\" src=\"Images/right.png\" /><img class=\"swapLeft\" src=\"Images/left.png\" /><div class=\"noteTitle\">Title</div></div><div class=\"wordwrap notes\">'+notes[id].body+'</div></div>');\n var notepad = html.interface.screen.wrapper.find('#'+id);\n notepad.hide();\n notepad.draggable({\n scroll: false,\n drag: function(event, ui){\n var x = parseInt(ui.position.left) + parseInt(html.interface.screen.wrapper.find('#'+id).css('width'),10) / 2;\n var y = parseInt(ui.position.top) + parseInt(html.interface.screen.wrapper.find('#'+id).css('height'),10) / 2;\n notes[id].x = x;\n notes[id].y = y;\n if (notes[id].atomNote === true){\n $setUIValue.setValue({\n noteMovement:{\n publish: { id: id, x: x, y: y } \n }\n });\n }\n },\n containment: html.interface.screen.appContainer\n });\n // Close Note Handler //\n notepad.find('img.closeNote').on('click',function(){\n showCanvasNote(id,false);\n $setUIValue.setValue({\n noteVisibility:{\n value: false,\n other: html.notes.other.table.find('#'+id)\n }\n });\n if (notes[id].atomNote === true) {\n var x = parseInt(html.interface.screen.wrapper.find('#'+id).css('left'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('width'),10) / 2;\n var y = parseInt(html.interface.screen.wrapper.find('#'+id).css('top'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('height'),10) / 2;\n notes[id].x = x;\n notes[id].y = y;\n $setUIValue.setValue({\n noteVisibility:{\n publish: {id:id, visible: false, x: x, y: y, color: notes[id].color}\n }\n });\n }\n });\n notepad.find('img.swapRight').on('click',function(){\n \n var nextID = undefined;\n \n // Find Next Note //\n var table = {\n first: jQuery('#'+html.notes.other.tableID+' tr:first'),\n last: jQuery('#'+html.notes.other.tableID+' tr:last'),\n current: html.notes.other.table.find('#'+id),\n next: html.notes.other.table.find('#'+id).closest('tr').next('tr')\n };\n \n if (table.next.length > 0) nextID = table.next[0].id;\n else nextID = table.first[0].id;\n\n // Hide Current Note //\n $setUIValue.setValue({\n noteVisibility:{\n value: false,\n other: html.notes.other.table.find('#'+id)\n }\n });\n if (notes[id].atomNote === true) {\n var x = parseInt(html.interface.screen.wrapper.find('#'+id).css('left'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('width'),10) / 2;\n var y = parseInt(html.interface.screen.wrapper.find('#'+id).css('top'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('height'),10) / 2;\n notes[id].x = x;\n notes[id].y = y;\n $setUIValue.setValue({\n noteVisibility:{\n publish: {id:id, visible: false, x: x, y: y, color: notes[id].color}\n }\n });\n }\n showCanvasNote(id,false);\n \n // Show Next Note //\n $setUIValue.setValue({\n noteVisibility:{\n value: true,\n other: html.notes.other.table.find('#'+nextID)\n }\n });\n if (notes[nextID].atomNote === true) {\n var x = parseInt(html.interface.screen.wrapper.find('#'+nextID).css('left'),10) + parseInt(html.interface.screen.wrapper.find('#'+nextID).css('width'),10) / 2;\n var y = parseInt(html.interface.screen.wrapper.find('#'+nextID).css('top'),10) + parseInt(html.interface.screen.wrapper.find('#'+nextID).css('height'),10) / 2;\n notes[nextID].x = x;\n notes[nextID].y = y;\n $setUIValue.setValue({\n noteVisibility:{\n publish: {id:nextID, visible: true, x: x, y: y, color: notes[nextID].color}\n }\n });\n }\n showCanvasNote(nextID,true);\n });\n notepad.find('img.swapLeft').on('click',function(){\n \n var nextID = undefined;\n \n // Find Next Note //\n var table = {\n first: jQuery('#'+html.notes.other.tableID+' tr:first'),\n last: jQuery('#'+html.notes.other.tableID+' tr:last'),\n current: html.notes.other.table.find('#'+id),\n prev: html.notes.other.table.find('#'+id).closest('tr').prev('tr')\n };\n \n if (table.prev.length > 0) nextID = table.prev[0].id;\n else nextID = table.last[0].id;\n\n // Hide Current Note //\n $setUIValue.setValue({\n noteVisibility:{\n value: false,\n other: html.notes.other.table.find('#'+id)\n }\n });\n if (notes[id].atomNote === true) {\n var x = parseInt(html.interface.screen.wrapper.find('#'+id).css('left'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('width'),10) / 2;\n var y = parseInt(html.interface.screen.wrapper.find('#'+id).css('top'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('height'),10) / 2;\n notes[id].x = x;\n notes[id].y = y;\n $setUIValue.setValue({\n noteVisibility:{\n publish: {id:id, visible: false, x: x, y: y, color: notes[id].color}\n }\n });\n }\n showCanvasNote(id,false);\n \n // Show Next Note //\n $setUIValue.setValue({\n noteVisibility:{\n value: true,\n other: html.notes.other.table.find('#'+nextID)\n }\n });\n if (notes[nextID].atomNote === true) {\n var x = parseInt(html.interface.screen.wrapper.find('#'+nextID).css('left'),10) + parseInt(html.interface.screen.wrapper.find('#'+nextID).css('width'),10) / 2;\n var y = parseInt(html.interface.screen.wrapper.find('#'+nextID).css('top'),10) + parseInt(html.interface.screen.wrapper.find('#'+nextID).css('height'),10) / 2;\n notes[nextID].x = x;\n notes[nextID].y = y;\n $setUIValue.setValue({\n noteVisibility:{\n publish: {id:nextID, visible: true, x: x, y: y, color: notes[nextID].color}\n }\n });\n }\n showCanvasNote(nextID,true);\n \n });\n }",
"function addExploreHandler(id){\n $('#'+id+'').on('click', exploreHere);\n }",
"function addInFocusHandler(note){\n note.addEventListener('click', function(){\n var newLocation = note.querySelector('a').href\n if(window.location.href.split('#').includes(note.id)) return false\n window.location = newLocation\n })\n note.addEventListener('click', function(){\n if(!note.querySelector('.new-entry-bottom-container')){\n note.append(buildEditMenu())\n addCloseEvent()\n }\n })\n}",
"function handleElementClickFtn(action, element, index) {\n if(action === 'selected' || action === 'deselected') {\n objInst.notesHeader.notify(action, { 'elem': element, 'idx' : index });\n } \n }",
"setSelectedNote(state, { _id }) {\n state.selectedNoteId = _id;\n }",
"_handleTap(e) {\n this.swatchId = e.path[0].getAttribute(\"id\");\n this.swatchName = e.path[0].getAttribute(\"title\");\n this.$.modal.openModal(e.path[0]);\n }",
"clickDownOnEntity(id) {\r\n\r\n // Pass on event to all plugins\r\n this.passEvent(\"clickDownOnEntity\", id)\r\n\r\n }",
"newNote() {\n this.onSelect({ id: '' })\n }",
"set id(id) {\n if (this.#el) this.#el.id = id;\n else this.#id = id;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Funzione eseguita ad ogni frame se il giocatore risulta "shielded" Gestisce il contatore e, quando questo arriva a 0, rimuove tale stato tramite lowerShield() | function shieldFrame()
{
if(shieldCooldown > 0)
{
shieldCooldown--;
document.getElementById("shieldMessage").style.visibility = "visible";
document.getElementById("shieldCounter").firstChild.nodeValue = shieldCooldown;
return;
}
if(shieldCooldown == 0)
{
lowerShield();
document.getElementById("shieldMessage").style.visibility = "hidden";
}
} | [
"function raise(){\n clearTimeout(shield.coolDown);\n shield.dropped = false;\n}",
"function collidesShield(){\r\nif (player.x < shield.x + shield.w &&\r\n\tplayer.x + player.w > shield.x &&\r\n\tplayer.y < shield.y + shield.h &&\r\n\tplayer.y + player.h > shield.y) {\r\n\tgetshield();\r\n\t}\r\n}",
"function shield(){\n shieldSelected=true;\n console.log(\"entering function\")\n enemYAttack=true;\n playerPickShield=true;\n}",
"function hungerDrain () {\r\n if (hungerBar.w > 0) {\r\n hungerBar.w -= hungerBar.speed;\r\n } else if (hungerBar.w <= 0) {\r\n stopGame();\r\n }\r\n}",
"function showerEffect(ctx){\n \n if(flow===false){\n flow=true;\n showerX+=2;\n }\n else{\n flow=false;\n showerX-=2;\n } \n}",
"function armorShield(unit){\n\t// create shield, and pass in parameters for a gray-blue-colored gradient level:\n var newShield = new shield(unit,\n\t\t\t\t\t\t\t230, 230, 230, // inner RGB\n\t\t\t\t\t\t\t100, 100, 140); // outer RGB\n \n // this shield's health (starts at 100 for\n\t//\tanimation sake, but depletes at twice\n\t//\tthe normal speed. Essentially, this shield\n\t//\thas the equivalent of 50 health.\n newShield.health = 100;\n\t\n\t// upon action, this shield should display that the\n\t//\tdamage was absorbed\n\tnewShield.actionText = \"Absorbed\";\n \n // calculate damage absorbtion: if damaged, then return the\n // amount of damage to be applied to the player\n newShield.absorb = function(object){\n this.health -= 2*object.damage; // deplete this shield's health (twice normal)\n\t\t\n\t\t// adjust the timer (in this case, it just indicates the shield's health):\n\t\tthis.timer = this.health;\n\t\tif(this.timer < 0)\n\t\t\tthis.timer = 0;\n\t\t\n var overflow = 0; // overflow (how much damage was not absorbed)\n if(this.health <=0){\n // adjust overflow appropriately\n overflow = 0 - Math.ceil(this.health / 2);\n // destroy this sheild (resets unit to default shield)\n this.destroy();\n }\n\t\t// return the overflow damaged\n return overflow;\n }\n \n\t// emblem that represents this shield\n\tnewShield.drawEmblem = function(ctx){\n\t\tdrawArmorShieldIcon(ctx);\n //ctx.font = \"9pt Arial\";\n //ctx.fillStyle = \"#FFFF00\";\n\t\t//ctx.globalAlpha = 0.6;\n\t\t//var text = \"\" + this.health + \"%\";\n\t\t//var xOffset = ctx.measureText(text).width / 2;\n //ctx.fillText(text, 0-xOffset, 4);\n\t}\n\t\n return newShield;\n}",
"function Shield() {\n var shieldPrice = 500;// initial price\n /**\n * accessor and mutator to the variable price of the shield\n * @param {number} p the price of the shield\n * @return the current price of the shield\n */ \n this.getShieldPrice = function() {\n return shieldPrice;\n };// end accessor\n this.setShieldPrice = function(p) {\n shieldPrice = p;\n };// end mutator \n /**\n * triggered when the shield upgrade is bought in the shop \n */\n this.shieldBuy = function() {\n if(character.getMoney()>=shieldPrice) {\n if(confirm(\"Est tu sure?\")) {\n var temp = character.getShieldUpgrade() + 1;\n character.setShieldUpgrade(temp); \n temp = character.getMoney() - shieldPrice; \n character.setMoney(temp);\n shieldPrice = parseInt(shieldPrice) + parseInt(500);// the price goes up\n document.getElementById(\"moneySound\").load();\n document.getElementById(\"moneySound\").play();\n }\n }\n else\n alert(\"Tu n'as pas assez d'argent!\");// <- could let the shop guy say it instead?\n };// end shieldBuy\n /**\n * Determines whether the user evades the monster's attack upon giving a wrong answer \n * @return whether the hit was evaded or not\n */\n this.isEvaded = function() {\n var temp1 = Math.random();\n var temp2 = 0.5-0.5*Math.pow(0.5, character.getShieldUpgrade());\n //alert(temp1 + \" < \" + temp2);\n if(temp1<temp2)\n return true;// P(s) = 0.5 - 0.5^(s+1), where P represents the probability of an evasion, and s represent the level of the shield upgrade\n else\n return false;\n };// end shield \n}// end constructor",
"function rechargeShield() {\n\tvar tempID = setInterval(function() {\n\t\tif(displayedShield < maxShield) {\n\t\t\tif(!Pause) {\n\t\t\t\tcurrentShield = ++displayedShield;\n\t\t\t\tupdateShieldDisplay();\n\n\t\t\t\tif(displayedShield == 50) {\n\t\t\t\t\tshieldActive = true;\n\t\t\t\t\tplayer.activateShield();\n\t\t\t\t}\n\t\t\t}\n\t\t} else clearInterval(tempID);\n\t}, 10);\n\n\tupdateShieldDisplay();\n}",
"function hit_shield_up_check() {\n if (shield_up_active) {\n if (shield_up_x <= 70 && shield_up_x + 40 >= 50) {\n if (rocket_y + 20 > shield_up_y - 10 && rocket_y < shield_up_y + 40) {\n shield_up_active = false;\n shield_level++;\n }\n }\n }\n}",
"hitShield(bullet, shield){\n bullet.disableBody(true, true);\n console.log('hit shine');\n\n}",
"block() {\n if (this.type == \"sword\") {\n this.angle = 0;\n this.player.blocking = true;\n this.damage = 0;\n this.setTexture(\"shield\");\n }\n }",
"function runShieldBearer(){\n\n// redraw the gameWindow\nupdate();\ndraw();\n\n}",
"function playerShieldRecover() {\n player.shieldColor = player.shieldHealthyColor;\n}",
"function violence() {\n if (keys[68]) { //D button\n if (thor.health == 100) {\n if (thor.lightningFrameCount >= thor.lightningFrameLimit\n /*&& lightning.positions.length < thor.maxLightningCount*/\n ) {\n // fire lightning! But only if enough frames have elapsed and there aren't already too many on screen\n var directions = [\n [0, -1],\n [-1, 0],\n [0, 1],\n [1, 0]\n ];\n var lightningStartXPos, lightningStartYPos;\n if (thor.isPointing == 1) { // up\n lightningStartXPos = thor.xPos + (thor.dispSize - lightning.size) / 2;\n lightningStartYPos = thor.yPos - lightning.size;\n } else if (thor.isPointing == 2) { // left\n lightningStartXPos = thor.xPos - lightning.size;\n lightningStartYPos = thor.yPos + (thor.dispSize - lightning.size) / 2;\n } else if (thor.isPointing == 3) { // down\n lightningStartXPos = thor.xPos + (thor.dispSize - lightning.size) / 2;\n lightningStartYPos = thor.yPos + thor.dispSize;\n } else if (thor.isPointing == 4) { // right\n lightningStartXPos = thor.xPos + thor.dispSize;\n lightningStartYPos = thor.yPos + (thor.dispSize - lightning.size) / 2;\n }\n lightning.positions.push({\n xPos: lightningStartXPos,\n yPos: lightningStartYPos,\n width: lightning.size,\n height: lightning.size,\n direction: directions[thor.isPointing - 1]\n });\n // remove oldest lightning bolt from screen if there are now too many\n if (lightning.positions.length > thor.maxLightningCount) {\n lightning.positions.shift();\n }\n thor.lightningFrameCount = 0; // reset count\n }\n } else {\n // hit with sword\n if (thor.swordFrameCount >= thor.swordFrameLimit) {\n console.log(\"feel my sword, you annoying bunch of pixels!\")\n for (var i = 0; i < thor.currentTile.enemies.filter(enemy => enemy.alive).length; i++) {\n var enemy = thor.currentTile.enemies.filter(enemy => enemy.alive)[i];\n // hit detection for sword - needs Thor pointing in the same direction as the enemy!\n if (hitDetection(thor, [enemy], 20, thor.isPointing)) {\n enemy.health--;\n enemy.hasBeenHit = true;\n console.log(enemy.id + \" health now \" + enemy.health);\n if (enemy.health <= 0) {\n enemy.alive = false;\n }\n }\n }\n thor.swordFrameCount = 0;\n }\n }\n }\n}",
"updateShield(change){\n this.shield = this.shield + change;\n }",
"function increaseShieldLife(value)\r\n{\r\n shieldbar.width += value;\r\n if(shieldbar.active = false)\r\n {\r\n shieldbar.active = true;\r\n }\r\n}",
"woundState() {\n const damage = this.data.data.damage;\n if(damage == 0) return 0;\n // Wound slots are 4 wide, so divide by 4, floor the result\n return Math.floor((damage-1)/4);\n }",
"function player_shielding(play_i)\n{\n // Check if the player can shield\n if (players_list[play_i].shield) \n {\n // Check if the c is pressed\n if (canvas_surface.keys && canvas_surface.keys[67]) \n {\n // Make the shield visible\n shield_list[0].visible = true;\n\n // Update the shield's speed\n shield_list[0].update_speed();\n\n // Redraw the shield\n shield_list[0].update_movement();\n }\n else\n {\n // Make the shield not visible\n shield_list[0].visible = false;\n }\n }\n}",
"recharge(){\n\t\t// maximum shield\n\t\tif(this.shield == this.shieldMax) return;\n\n\t\tif(this.rechargeTime == 0 && this.shield < this.shieldMax){\n\t\t\tthis.shield++;\n\t\t} else{\n\t\t\tthis.rechargeTime--;\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
finds a UIVeri5 spec definition by a given Jasmine suite description i.e. given the description of one of the suites in a spec file, find the information for that file. | function _getSpecDetails(suite){
return specs.filter(function (suiteDetails) {
return suiteDetails.fullName === suite.description;
})[0];
} | [
"function getSpecName() {\n let spec = _.last(specs);\n let suite = _.last(suites);\n if (spec) {\n return spec.fullName;\n } else if (suite) {\n return suite.description;\n }\n throw new Error('Not currently in a spec or a suite');\n}",
"static findSpecs (projectRoot, specPattern) {\n debug('finding specs for project %s', projectRoot)\n la(check.unemptyString(projectRoot), 'missing project path', projectRoot)\n la(check.maybe.unemptyString(specPattern), 'invalid spec pattern', specPattern)\n\n // if we have a spec pattern\n if (specPattern) {\n // then normalize to create an absolute\n // file path from projectRoot\n // ie: **/* turns into /Users/bmann/dev/project/**/*\n specPattern = path.resolve(projectRoot, specPattern)\n debug('full spec pattern \"%s\"', specPattern)\n }\n\n return new Project(projectRoot)\n .getConfig()\n // TODO: handle wild card pattern or spec filename\n .then((cfg) => {\n return specsUtil.find(cfg, specPattern)\n }).then(R.prop('integration'))\n .then(R.map(R.prop('name')))\n }",
"function findDefinition()\r\n{\r\n var editor = newEditor();\r\n editor.assignActiveEditor();\r\n var restr = editor.selText();\r\n if(!restr)\r\n return;\r\n\r\n\r\n var ram;\r\n var aram;\r\n var proper;\r\n var actual;\r\n\r\n var strLen = restr.length;\r\n\r\n // RAM equates specific\r\n if(restr.charAt(0) == 'a')\r\n {\r\n aram = restr;\r\n ram = aram.substring(1);\r\n }\r\n else\r\n {\r\n aram = \"a{0}\".format(restr);\r\n ram = restr;\r\n }\r\n\r\n // Function label specific\r\n if(restr.charAt(strLen-1) == ':')\r\n {\r\n proper = restr;\r\n actual = aram.substring(0,strLen-1);\r\n }\r\n else\r\n {\r\n proper = \"{0}:\".format(restr,\":\");\r\n actual = restr;\r\n }\r\n\r\n\r\n restr = \"(^(({0})|({1}))[\\\\s]equ)|(^(({2})|({3}))\\\\b)\".format(aram, ram, proper, actual);\r\n var data = findInAllFiles(editor, restr);\r\n\r\n var result = print(data, true);\r\n showResult(result);\r\n}",
"showSuiteExpectations(suite) {\n console.log('Suite info:');\n console.log(suite);\n }",
"function mochaBDD(pat,suite) {\n const tests = {}\n const res = [...includes]\n for(const i of glob(pat,{cwd:root,ignore})) {\n const ext = path.extname(i)\n if (ext !== \".js\")\n continue\n const file = path.join(root,i)\n const contents = fs.readFileSync(file,\"utf-8\")\n const result = {file, contents}\n test262Parser.parseFile(result)\n if (result.attrs.negative && result.attrs.negative.phase === \"early\")\n continue\n const dirs = []\n for(let j = i; (j = path.dirname(j)) !== \".\";)\n dirs.unshift(path.basename(j))\n \n let dir = tests\n for(const j of dirs)\n dir = dir[j] || (dir[j] = {});\n (dir.$ || (dir.$ = [])).push(result)\n }\n function walkDirs(obj,name) {\n res.push(`describe(\"${name}\",function() {`)\n for(const i in obj)\n if (i !== \"$\")\n walkDirs(obj[i],i)\n if (obj.$) {\n for(const i of obj.$) {\n const descr = !process.env.TEST262_NO_DESCR\n && i.attrs.description || path.basename(i.file,\".js\")\n if (!process.env.TEST262_NO_STRICT)\n if (i.attrs.flags.raw || i.attrs.flags.noStrict)\n continue\n res.push(`it(\"${trim(descr).replace(/\"/g,\"\\\\\\\"\")}\",\n function(${i.async ? \"$DONE\" : \"\"}) {`)\n if (process.env.TEST262_NO_STRICT && i.attrs.strictOnly)\n res.push(`\"use strict;\"`)\n if (!process.env.TEST262_NO_DESCR) {\n res.push(\"/*\")\n res.push(JSON.stringify(i.attrs,(i) => i !== \"description\" && i !== \"info\" && i,2))\n res.push(`PATH:${path.relative(test262Root,i.file)}`)\n res.push(i.copyright)\n res.push(i.attrs.info)\n res.push(\"*/\")\n }\n res.push(i.contents)\n res.push(`})/*${path.basename(i.file,\".js\")}*/`)\n }\n }\n res.push(`})/*${name}*/`)\n }\n walkDirs(tests,`test262 ${suite}`)\n console.log(`generated test262 suite ${suite} at ${dst}`)\n fs.writeFileSync(path.join(dst,suite+\".js\"),res.join(\"\\n\"))\n}",
"function findTestByNameId(name, id) {\n $('.test').each(function() {\n var t = $(this);\n\n if (t.find('.test-name').text().trim() == name && t.attr('extentid') == id) {\n $('.analysis > .test-view').click();\n\n t.click();\n return;\n }\n });\n}",
"function\nDeviceDefFindByDescription(InDeviceDefDescription)\n{\n var i;\n for (i = 0; i < MainDeviceDefs.length; i++) {\n if ( MainDeviceDefs[i].description == InDeviceDefDescription ) {\n return MainDeviceDefs[i];\n }\n }\n return null;\n}",
"getSpecByName(name) {\n return this.state.specs.find((s, i) => {\n if (s.Name === name) {\n return s;\n }\n return null;\n });\n }",
"function getSpecifications(){\n\t\n\tvar specificationsArray = [] \t//we gather the captured elements in this array\n\n\tvar xpathToSpecElements = '//body/div[1]/table/tbody/tr'\t\t//xpath to the tr of the first table\n\tvar trNodesXPath = document.evaluate(xpathToSpecElements, document, null, XPathResult.ANY_TYPE, null);\n\tvar trNodes = trNodesXPath.iterateNext();\n\n\tvar loopCount = 1 ;\n\twhile (trNodes){\t//loop while there tr found in the table\n\t\t// We first captur the Name element of the specification\n\t\tvar xpathTdName = '//body/div[1]/table/tbody/tr['+loopCount+']/td[1]'\t//loopcount keep trac of the current tr so we can identify the td\n\t\tvar tdNameXPath = document.evaluate(xpathTdName, document, null, XPathResult.ANY_TYPE, null);\n\t\tvar tdName = tdNameXPath.iterateNext();\t\n\t\tvar tdNameText = tdName.textContent;\n\n\t\t// captur the Value element of the specification\n\t\tvar xpathTdValue = '//body/div[1]/table/tbody/tr['+loopCount+']/td[2]'\n\t\tvar tdValueXPath = document.evaluate(xpathTdValue, document, null, XPathResult.ANY_TYPE, null);\n\t\tvar tdValue = tdValueXPath.iterateNext();\n\t\tvar tdValueText = tdValue.textContent;\n\n\t\tvar specificationTd = {name:tdNameText, value: tdValueText} // constructing the JSON from the captured name and value\n\n\t specificationsArray.push(specificationTd); //add the current tr element to our specificationArray\n\n\t loopCount++;\n\t trNodes = trNodesXPath.iterateNext(); // iterate to the next tr\n\t}\n\treturn specificationsArray;\n}",
"function findTests() {\n var diskPath;\n // Find the actual file-system path of our tests directory...\n for (var uriKey in packaging.options.resources) {\n if (!/^.+-wmsy-tests$/.test(uriKey))\n continue;\n\n diskPath = packaging.options.resources[uriKey];\n break;\n }\n if (!diskPath)\n throw new Error(\"Unable to locate unit test directory\");\n\n console.log(\"listing files in\", diskPath);\n var files = file.list(diskPath);\n var test_files = [];\n for (var i = 0; i < files.length; i++) {\n var name = files[i];\n if (/^test-.*\\.js$/.test(name)) {\n console.log(\" found test\", name);\n test_files.push(name);\n }\n }\n return {\n dir: diskPath,\n tests: test_files,\n };\n}",
"findExpectations(testId, method, url, body = undefined) {\n const test = this.tests[testId];\n if (!test) return null;\n return test.find(expectation => expectation.matches(method, url, body));\n }",
"description(description) {\n const suite = suites.get(this);\n suite.description = description;\n return this;\n }",
"function actualSuiteFile(suiteKey) {\n var suiteFile = \"\";\n if (suiteKey in e2eSuites) {\n suiteFile = './tests/e2e/suites/' + e2eSuites[suiteKey] + '.js';\n } else {\n suiteFile = './tests/e2e/suites/' + suiteKey + '.js';\n }\n return suiteFile;\n}",
"function getCurrentSpecPath() {\n if (!jasmine || !jasmine.currentSpec || !jasmine.currentSuite) {\n return null;\n }\n var currentSuite = jasmine.currentSuite;\n var suites = [];\n while (currentSuite && currentSuite !== jasmine.getEnv().topSuite()) {\n suites.push(currentSuite);\n currentSuite = currentSuite.parentSuite;\n }\n var descriptions = suites.reverse().map(function (x) { return x.description; });\n descriptions.push(jasmine.currentSpec.description);\n return descriptions.map(function (x) { return x.replace(/[^a-z0-9 -/]/gi, \"\"); }).join(\"/\");\n }",
"function matchSpecs(kernelInfo, specs) {\n if (!specs) {\n return [];\n }\n let matches = [];\n let reLang = null;\n let reName = null;\n if (kernelInfo.kernel_spec.language) {\n reLang = new RegExp(kernelInfo.kernel_spec.language);\n }\n if (kernelInfo.kernel_spec.display_name) {\n reName = new RegExp(kernelInfo.kernel_spec.display_name);\n }\n for (let key of Object.keys(specs.kernelspecs)) {\n let spec = specs.kernelspecs[key];\n let match = false;\n if (reLang) {\n match = reLang.test(spec.language);\n }\n if (!match && reName) {\n match = reName.test(spec.display_name);\n }\n if (match) {\n matches.push(spec);\n continue;\n }\n }\n return matches;\n }",
"function findSuitableDescHandler(basePath, cb) {\n const commonFiles = ['FILES.BBS', 'DESCRIPT.ION'];\n\n async.eachSeries(\n commonFiles,\n (fileName, nextFileName) => {\n loadDescHandler(paths.join(basePath, fileName), (err, handler) => {\n if (!err && handler) {\n return cb(null, handler);\n }\n return nextFileName(null);\n });\n },\n () => {\n return cb(Errors.DoesNotExist('No suitable description handler available'));\n }\n );\n}",
"get(descriptor, kind = 'default') {\n const found = this.find(descriptor, kind);\n if (!found) {\n let files = this.entries.map(e => e.file)\n .filter((value, index, array) => array.indexOf(value) === index);\n let msg = `Failed to find name for ${string_format_1.StringFormat.formatName(descriptor)} of kind \"${kind}\". `\n + `Searched in ${files.length} files.`;\n throw new Error(msg);\n }\n return found;\n }",
"function where(fn) {\n\n if (typeof fn != 'function') {\n throw new Error('where(param) expected param should be a function');\n }\n \n var fnBody = fn.toString().replace(/\\s*function[^\\(]*[\\(][^\\)]*[\\)][^\\{]*{/,'')\n .replace(/[\\}]$/, '');\n var values = parseFnBody(fnBody);\n var labels = values[0];\n \n /**\n * {labels} array is toString'd so the values became param symbols in the new Function.\n * {fnBody} is what's left of the original function, mainly the expectation.\n */\n var fnTest = new Function(labels.toString(), fnBody);\n var failedCount = 0;\n var trace = '\\n [' + labels.join(PAD) + '] : ';\n \n /*\n * 1.x.x - jasmine.getEnv().currentSpec\n * 2.x.x - .currentSpec is no longer exposed (leaking state) so use a shim for it with \n * the v2 .result property\n */\n\n var currentSpec = jasmine.getEnv().currentSpec || { result : {} };\n var result = /* jasmine 2.x.x. */ currentSpec.result || \n /* jasmine 1.x.x. */ currentSpec.results_;\n\n var item, message;\n \n for (var i = 1; i < values.length; ++i) {\n \n message = MESSAGE;\n \n fnTest.apply(currentSpec, values[i]);\n\n // TODO - extract method, perhaps...\n \n // collect any failed expectations \n if (result.failedExpectations && result.failedExpectations.length) {\n \n /*\n * jasmine 2.x.x.\n */\n \n if (failedCount < result.failedExpectations.length) {\n failedCount += 1;\n item = result.failedExpectations[failedCount - 1];\n message = item.message;\n item.message = trace + '\\n [' + values[i].join(PAD) + '] (' + message + ')';\n }\n \n } else if (result.items_) {\n \n /*\n * jasmine 1.x.x.\n */\n \n item = result.items_[result.items_.length - 1];\n \n if (item && !item.passed_) {\n failedCount += 1;\n message = item.message;\n item.message = trace + '\\n [' + values[i].join(PAD) + '] (' + message + ')';\n }\n }\n \n } \n \n // use these in further assertions \n return values;\n }",
"function getSuiteData (suite) {\n var suiteData = {\n description : suite.description,\n durationSec : 0,\n specs: [],\n suites: [],\n passed: true\n },\n specs = suite.specs(),\n suites = suite.suites(),\n i, ilen;\n\n // Loop over all the Suite's Specs\n for (i = 0, ilen = specs.length; i < ilen; ++i) {\n suiteData.specs[i] = {\n description : specs[i].description,\n durationSec : specs[i].durationSec,\n passed : specs[i].results().passedCount === specs[i].results().totalCount,\n results : specs[i].results()\n };\n suiteData.passed = !suiteData.specs[i].passed ? false : suiteData.passed;\n suiteData.durationSec += suiteData.specs[i].durationSec;\n }\n\n // Loop over all the Suite's sub-Suites\n for (i = 0, ilen = suites.length; i < ilen; ++i) {\n suiteData.suites[i] = getSuiteData(suites[i]); //< recursive population\n suiteData.passed = !suiteData.suites[i].passed ? false : suiteData.passed;\n suiteData.durationSec += suiteData.suites[i].durationSec;\n }\n\n // Rounding duration numbers to 3 decimal digits\n suiteData.durationSec = round(suiteData.durationSec, 4);\n\n return suiteData;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
When the element tree has been changed, we need to wire up any event handlers in order to intercept Hammer and DOM events. | onDidChangeElementTree()/*: void*/ {
if (this.elementTree) {
for (let evt of this.DOM_EVENTS.split(" ")) {
this[_elementTree].addEventListener(evt, (e)=>this.emit("DOMEvent", e), true);
}
//this[_hammer] = new Hammer(this[_elementTree], {domEvents: true});
this[_hammer] = new Hammer.Manager(this[_elementTree], {
recognizers: this.HAMMER_RECOGNIZERS,
domEvents: true
});
this[_hammer].on(this.HAMMER_EVENTS, (e)=>this.emit("hammerEvent", e));
if (this.renderElement) {
addTreeToElement.call(this);
}
}
} | [
"attach() {\r\n if (this.rootElement) {\r\n Object.keys(this.handlers).forEach(\r\n event => this.rootElement.addEventListener(event, this.handlers[event])\r\n );\r\n }\r\n }",
"registerDomEvents() {/*To be overridden in sub class as needed*/}",
"function treeSyncEventHandler() {\n //re-add a handler to the tree's nodeClicked event\n $tree.UmbracoTreeAPI().addEventHandler(\"nodeClicked\", nodeClickHandler);\n }",
"function updateonchange()\r\n{\r\n document.addEventListener(\"DOMNodeInserted\", nodechanged, false);\r\n ////document.addEventListener(\"DOMSubtreeModified\", subtreemodified, false);\r\n document.addEventListener(\"DOMAttrModified\", attrmodified, false);\r\n}",
"function handleDomChanges() {\n\t\n\t//console.log(\"function handleDomChanges\");\n\t\n\t//Remove the listener before changing\n\t$(this).off();\n\n\t//Modify contents of Holding\n\t//20150107 CB added libInfoLink for library info links\n\tlibInfoLink();\t\n\t\n\t//20150819 CB displaying more holdings info instead of hidden behind lightbox\t\n\tholdingsandlightbox();\t\n\t\n\t//Add note to Show More items that it is loading; this will disappear when items load b/c Primo already hides that row after items load\n\t/*$(\".EXLLocationViewAllLink\").click(function() {\n\t\t$(this).append(' Loading...');\n\t});\t*/\n\n\t//Modify all items in this Holding that was just changed in the DOM.\n\tif ($(this).find(\".EXLLocationTableActions\").length) {\t\t\n\t\tmodifyItems();\n\t}\n\t\n\t//Resume listening (if there are more items, RTA changes, Primo OTB changes\n\t$(this).on(\"DOMSubtreeModified propertychange\", handleDomChanges);\n\n\t//Remove the Loading Wheel\n\t$(this).parents(\".EXLLocationList\").find(\".HVD_LoadingWheel\").remove();\n}",
"_handleContentElementChanged(contentElement, previous) {\n }",
"elementUpdated() {\n this.model.trigger('el:change');\n }",
"onWillChangeElementTree()/*: void*/ {\n if (this.elementTree && this.renderElement) {\n removeTreeFromElement.call(this);\n }\n }",
"function inspectorSelectionChangeListener() {\n if ($0.__keyPolymer__) {\n window.dispatchEvent(new CustomEvent(window[NAMESPACE].getNamespacedEventName('inspected-element-changed'), {\n detail: {\n key: $0.__keyPolymer__\n }\n }));\n }\n}",
"setupIntersectionHandler() {\n this.intersectEmitter.on('intersect', (element) => {\n const receivers = this.elementStore.getReceiversForElement(element);\n receivers.forEach(receiver => this.updateDom(receiver));\n });\n }",
"function HandleDOM_Change () {\n\t\t} //end HandleDom_change()",
"function bindEvents() {}",
"function handleDomEvent () {\n\t\tthis._ractive.binding.handleChange();\n\t}",
"function _attachEvents()\n {\n window.parent.jQuery.PercContentPreSubmitHandlers.addHandler(_preSubmitHandler);\n $(\"input[name='perc-poll-answer-type']\").on(\"click\",function(){\n var inputType = $(this).attr(\"value\") == \"single\"?\"radio\":\"checkbox\";\n self.answerControl.changeAnswerType(inputType);\n });\n // Provides auto-fill functionality for the name box, after being sanitized to\n // replace \"_\" and \" \" with -, and drop all other non-alphanumerics\n $.perc_textAutoFill($('#perc-content-edit-pollTitle'),$('#perc-content-edit-pollUniqueName'),$.perc_autoFillTextFilters.IDNAMECDATA);\n $.perc_filterField($('#perc-content-edit-pollUniqueName'), $.perc_autoFillTextFilters.IDNAMECDATA); \n }",
"function handleDomEvent () {\n\t \tthis._ractive.binding.handleChange();\n\t }",
"registerDomEvents() {\n\t\tgetComponentElementById(this,\"DataListSearchInput\").on(\"keyup\", function() {\n\t\t\tlet search_text = getComponentElementById(this,\"DataListSearchInput\").val();\n\t\t\tsetTimeout(function() {\n\t\t\t\tif (search_text == getComponentElementById(this,\"DataListSearchInput\").val()) {\n\t\t\t\t\tgetComponentElementById(this,\"DataList\").html(\"\");\n\t\t\t\t\tthis.current_page_array = [];\n\t\t\t\t\tthis.current_list_offset = 0;\n\t\t\t\t\tthis.loadPage();\n\t\t\t\t}\n\t\t\t}.bind(this),500);\n\t\t}.bind(this));\n\t\tgetComponentElementById(this,\"btnResetSearch\").on(\"click\", function() {\n\t\t\tgetComponentElementById(this,\"DataListSearchInput\").val(\"\");\n\t\t\tgetComponentElementById(this,\"DataList\").html(\"\");\n\t\t\tthis.current_page_array = [];\n\t\t\tthis.current_list_offset = 0;\n\t\t\tthis.loadPage();\n\t\t}.bind(this));\n\t\tgetComponentElementById(this,\"DataListMoreButton\").on(\"click\", function() {\n\t\t\tthis.current_list_offset += this.list_offset_increment;\n\t\t\tthis.loadPage();\n\t\t}.bind(this));\n\t\tthis.handleOnClassEvent(\"click\",\"data_list_item_\"+this.getUid(),\"_row_item_\",\"on_item_clicked\");\n\t}",
"setEventListeners() {\n $('body').on('click','[data-open-pane]',this.onOpenPane);\n $('body').on('click','.pane__item, .tutorial__menu-item',this.onPaneMenuItemClick);\n $('body').on('click', '[data-skip-to-page]',this.onSkipToPageClick.bind(this));\n $('body').on('click activate','[data-close]',this.onCloseClick);\n this.$container.on('resize',this.setViewPortSize.bind(this));\n this.app.on('load:book',this.onBookLoaded.bind(this));\n this.settings.on('change:letterboxing',this.onLetterboxSettingsChange.bind(this));\n this.settings.on('change:leftHandMode',this.onLeftHandModeSettingsChange.bind(this));\n }",
"_bindEvents()\n {\n \n }",
"function handleDomEvent () {\n\tthis._ractive.binding.handleChange();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ToggleConnection: Toggles between Quit Session and Connect | function ToggleConnection()
{
if(false == g_bConnected)
{
//
// Establish Connection
//
RCConnect();
g_bConnected = true;
//...ConnectionId.innerText = L_QUITSESSION;
}
else
{
//
// Disconnect
//
RCDisconnect();
g_bConnected = false;
//..ConnectionId.innerText = L_CONNECT;
}
return;
} | [
"function ToggleConnection()\n{\n\tTraceFunctEnter(\"ToggleConnection\");\n\tif(false == g_bConnected)\n\t{\n\t\t//\n\t\t// Establish Connection\n\t\t//\n\t\tRCConnect();\n\t\tg_bConnected = true;\n\t}\n\telse\n\t{\n\t\t//\n\t\t// Disconnect\n\t\t//\n\t\tRCDisconnect();\n\t\tg_bConnected = false;\n\t}\n\t\n\tTraceFunctLeave();\n\treturn;\n}",
"connectionToggle() {\n if (this.connected) {\n this.disconnect();\n } else {\n connect(this);\n }\n }",
"function toggleConnection() {\n if(boolCanToggle)\n {\n ipcRenderer.send('toggle-connection', boolConnect);\n boolCanToggle = false;\n btnConnect.addClass(\"disabled\");\n boolConnect = !boolConnect;\n }\n }",
"toggleConnection(callback = undefined) {\n\t\tif (this._connected) {\n\t\t\tthis.closeConnection();\n\t\t} else {\n\t\t\tthis.openConnection(callback);\n\t\t}\n\t}",
"ConnectToggle(){\n if(!this.CheckIfConnected(true)){\n this.Disconnect();\n return false;\n }\n this.Connect();\n return true;\n }",
"function disconnectConnection() {\n View.confirm(getMessage(\"disconnectConnection\"), function (button) {\n if (button == 'yes') {\n tcConnectController.disconnect();\n }\n });\n}",
"function toggleConnectionType(newConnectionName) {\r\n var newConnection;\r\n connection.close();\r\n\r\n if (newConnectionName === \"websocket\") {\r\n newConnection = WebsocketConnection();\r\n } else {\r\n newConnection = LongPollConnection();\r\n }\r\n\r\n newConnection.onmessage = connection.onmessage;\r\n\r\n return newConnection;\r\n}",
"setReconnect( id, toggle ) {\n this._reconnect[ id ] = toggle ? true : false;\n }",
"setConnectionStatus() {}",
"function setConnButtonState(enabled) {\n if (enabled) {\n document.getElementById(\"clientConnectButton\").innerHTML = \"Disconnect\";\n } else {\n document.getElementById(\"clientConnectButton\").innerHTML = \"Connect\";\n }\n}",
"function toggleSwitch(deviceTopicName){\n client.publish(deviceTopicName, 'TOGGLE');\n console.log(`TOGGLE ENVIADO PARA ${deviceTopicName}`);\n}",
"toggleNodeConnection(from, to) {\n\t\tif (this.edgeConnecting(from, to)) {\n\t\t\tthis.disconnectNodes(from, to);\n\t\t} else {\n\t\t\tthis.connectNodes(from, to);\n\t\t}\n\t}",
"function toggleBackendConnectionStatus(connected) {\n globalSettings.connected = connected;\n sdWS.send(JSON.stringify({ event: 'setGlobalSettings', context: connectSocketData.pluginUUID, payload: globalSettings }));\n}",
"function ConnectionState() {\n this.connected = true;\n}",
"function endConnection(){\t\n\tisConnected = false;\n\tchangeButtonToNOTListening();\n\tdictate.cancel();\n}",
"handleToggleOpen(open) {\n this.toggledOpen = open\n // connect/disconnect websocket or something\n }",
"function toggleSession()\n{\n\t// Invert session active state.\n\tsessionActive = !sessionActive;\n\n\t// If session is inactive; save the current dataset.\n\tif (!sessionActive) dataset.overwrite(); drawTimer();\n}",
"function toggleStream() {\n if (mode === 'started') {\n socket.emit('stopStream');\n mode = 'stopped';\n $('#toggle-button').text('Start Streaming');\n $('#displaying').html('Search again or hit <b style=\"color: #EC971F; text-shadow: 0 0 5px #fff;\">Start Streaming</b> to continue the stream.');\n $('#clear-button').show();\n $('#twitter-bird2').hide();\n\n }\n else {\n socket.emit('startStream');\n mode = 'started';\n $('#toggle-button').text('Stop Streaming');\n $('#twitter-bird2').show();\n $('#clear-button').hide();\n\n }\n}",
"function disconnecting( connection ) {\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reorder component price input index. | function reorderRow() {
pricingWrapper.find('.pricing-item').each(function (index) {
// reorder index of inputs pricing
$(this).find('input[name],select[name]').each(function () {
const pattern = new RegExp("pricing[([0-9]*\\)?]", "i");
const attributeName = $(this).attr('name').replace(pattern, 'pricing[' + index + ']');
$(this).attr('name', attributeName);
});
$(this).find('.row-packaging').each(function (indexPackaging) {
$(this).find('input[name],select[name]').each(function () {
const pattern = new RegExp("\\[packaging\\][([0-9]*\\)?]", "i");
const attributeName = $(this).attr('name').replace(pattern, '[packaging][' + indexPackaging + ']');
$(this).attr('name', attributeName);
});
});
$(this).find('.row-surcharge').each(function (indexSurcharge) {
$(this).find('input[name]').each(function () {
const pattern = new RegExp("\\[surcharges\\][([0-9]*\\)?]", "i");
const attributeName = $(this).attr('name').replace(pattern, '[surcharges][' + indexSurcharge + ']');
$(this).attr('name', attributeName);
});
});
});
} | [
"function inputReorder(id) {\n\t\treturn (\n\t\t\t<div>\n\t\t\t\t<input type='number' onChange={(e) => setReorderNumber(e.target.value)} value={reorderNumber} />\n\t\t\t\t<button onClick={() => reorderItem(id)}>Enter Index</button>\n\t\t\t</div>\n\t\t);\n\t}",
"resetReorder() {\n this.$element.removeData('oldIndex');\n }",
"reorderOptionValue(state, { newIndex, oldIndex }) {\n const movedValue = state.optionForm.data.values.splice(oldIndex, 1)[0];\n state.optionForm.data.values.splice(newIndex, 0, movedValue);\n }",
"function handleSortArray() {\n const priceValue = document.querySelector(\"#price\");\n if (priceValue.selectedIndex == 0) {\n sort(products);\n } else {\n sort(productsFiltered);\n }\n}",
"function updateIndex() {\n var items = $('.sortable').find('li');\n items.each(function(i) {\n $(this).attr('data-order',i + 1);\n });\n }",
"function updateIndex() {\n var i,\n orders = $scope.orders.filter(function (n) { return n; }),\n max = orders.length;\n for (i = 0; i < max; i++) {\n orders[i].index = i;\n }\n $scope.orders = orders;\n }",
"orderChangedHandler(id, index) {\n\t\tlet orderInput = getById(`${id}Order${index}`);\n this.order[index] = orderInput.value;\n\t}",
"function updateOrder() {\n orderPoly = orderPolySlider.value();\n initOperands();\n}",
"function changeQuantityByTyping(evt, input, index) {\n if(isNaN(input.value)) {\n\t\tvar splitArray = input.value.split('');\n\t\tsplitArray.pop();\n\t\tinput.value = splitArray.join('');\n\t} else {\n\t\tif (input.value < 1) input.value = 1;\n\t\tif (input.value > 10) input.value = 10;\n\t\tappData.selectedItems[index].quantity = Number(input.value);\n\t\tappData.selectedItems[index].cost = Number((appData.selectedItems[index].quantity * appData.selectedItems[index].price).toFixed(2));\n\t\tupdateCartAmount();\n\t}\n}",
"function sortAllOfTheProductsAscendantlyBasedOnTheNewPrices() {\n\n}",
"function updatePriceByProduct(productPrice, index){\n\n // We will target the div area that we want to fill with the new price by\n // targeting its class, \"item-subtotal\". We will use a flexible \"index\"\n // so that we will be able to update each product based upon its location\n // in the list of items.\n var actualPrice = document.getElementsByClassName('item-subtotal')[index];\n\n // Finally, we will replace the content (initially \"$0\") with the new\n // \"productPrice\" generated in the \"getPriceByProduct\" function.\n actualPrice.innerHTML = \"$\" + productPrice;\n}",
"function addOrderId() {\n $('div.sortable-row').each(function (index) {\n $(this).find('.order-id').first().val(index + 1);\n });\n }",
"function updatePrice(idx) {\n var newPrice = parseInt($('#updatePrice').val(), 10)\n if (!newPrice) return;\n gBooks[idx].price = newPrice\n}",
"resetIndex() {\n this.sortableItems.forEach((sortableItem, index) => {\n sortableItem.index = index;\n });\n }",
"getNewListOrder() {\n return this.tmpDragItems.map(item => {\n return item.index;\n });\n }",
"function moveUpDown(sType,oModule,iIndex)\n{\n\tvar aFieldIds = Array('hidtax_row_no','productName','subproduct_ids','hdnProductId','comment','qty','listPrice','discount_type','discount_percentage','discount_amount','tax1_percentage','hidden_tax1_percentage','popup_tax_row','tax2_percentage','hidden_tax2_percentage','lineItemType');\n\tvar aFieldIds = aFieldIds.concat(moreInfoFields);\n\tvar aContentIds = Array('qtyInStock','netPrice','subprod_names');\n\tvar aOnClickHandlerIds = Array('searchIcon');\n\n\tiIndex = eval(iIndex) + 1;\n\tvar oTable = document.getElementById('proTab');\n\tiMax = oTable.rows.length;\n\tiSwapIndex = 1;\n\tif(sType == 'UP') {\n\t\tfor(iCount=iIndex-2;iCount>=1;iCount--)\n\t\t{\n\t\t\tif(document.getElementById(\"row\"+iCount))\n\t\t\t{\n\t\t\t\tif(document.getElementById(\"row\"+iCount).style.display != 'none' && document.getElementById('deleted'+iCount).value == 0)\n\t\t\t\t{\n\t\t\t\t\tiSwapIndex = iCount+1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor(iCount=iIndex;iCount<=iMax-2;iCount++)\n\t\t{\n\t\t\tif(document.getElementById(\"row\"+iCount) && document.getElementById(\"row\"+iCount).style.display != 'none' && document.getElementById('deleted'+iCount).value == 0)\n\t\t\t{\n\t\t\t\tiSwapIndex = iCount;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tiSwapIndex += 1;\n\t}\n\n\tvar oCurTr = oTable.rows[iIndex];\n\tvar oSwapRow = oTable.rows[iSwapIndex];\n\n\tiMaxCols = oCurTr.cells.length;\n\tiIndex -= 1;\n\tiSwapIndex -= 1;\n\tiCheckIndex = 0;\n\tiSwapCheckIndex = 0;\n\tfor(j=0;j<=2;j++)\n\t{\n\t\tif(eval('document.getElementById(\\'frmEditView\\').discount'+iIndex+'['+j+']'))\n\t\t{\n\t\t\tsFormElement = eval('document.getElementById(\\'frmEditView\\').discount'+iIndex+'['+j+']');\n\t\t\tif(sFormElement.checked)\n\t\t\t{\n\t\t\t\tiCheckIndex = j;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tfor(j=0;j<=2;j++)\n\t{\n\t\tif(eval('document.getElementById(\\'frmEditView\\').discount'+iSwapIndex+'['+j+']'))\n\t\t{\n\t\t\tsFormElement = eval('document.getElementById(\\'frmEditView\\').discount'+iSwapIndex+'['+j+']');\n\t\t\tif(sFormElement.checked)\n\t\t\t{\n\t\t\t\tiSwapCheckIndex = j;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tif(eval('document.getElementById(\\'frmEditView\\').discount'+iIndex+'['+iSwapCheckIndex+']'))\n\t{\n\t\toElement = eval('document.getElementById(\\'frmEditView\\').discount'+iIndex+'['+iSwapCheckIndex+']');\n\t\toElement.checked = true;\n\t}\n\tif(eval('document.getElementById(\\'frmEditView\\').discount'+iSwapIndex+'['+iCheckIndex+']'))\n\t{\n\t\toSwapElement = eval('document.getElementById(\\'frmEditView\\').discount'+iSwapIndex+'['+iCheckIndex+']');\n\t\toSwapElement.checked = true;\n\t}\n\n\tiMaxElement = aFieldIds.length;\n\tfor(iCt=0;iCt<iMaxElement;iCt++)\n\t{\n\t\tsId = aFieldIds[iCt] + iIndex;\n\t\tsSwapId = aFieldIds[iCt] + iSwapIndex;\n\t\tif(document.getElementById(sId) && document.getElementById(sSwapId))\n\t\t{\n\t\t\tsTemp = document.getElementById(sId).value;\n\t\t\tdocument.getElementById(sId).value = document.getElementById(sSwapId).value;\n\t\t\tdocument.getElementById(sSwapId).value = sTemp;\n\t\t}\n\t\tsId = 'jscal_field_' + aFieldIds[iCt] + iIndex;\n\t\tsSwapId = 'jscal_field_'+ aFieldIds[iCt] + iSwapIndex;\n\t\tif(document.getElementById(sId) && document.getElementById(sSwapId))\n\t\t{\n\t\t\tsTemp = document.getElementById(sId).value;\n\t\t\tdocument.getElementById(sId).value = document.getElementById(sSwapId).value;\n\t\t\tdocument.getElementById(sSwapId).value = sTemp;\n\t\t}\n\t\tsId = aFieldIds[iCt] + iIndex + '_display';\n\t\tsSwapId = aFieldIds[iCt] + iSwapIndex + '_display';\n\t\tif(document.getElementById(sId) && document.getElementById(sSwapId))\n\t\t{\n\t\t\tsTemp = document.getElementById(sId).value;\n\t\t\tdocument.getElementById(sId).value = document.getElementById(sSwapId).value;\n\t\t\tdocument.getElementById(sSwapId).value = sTemp;\n\t\t\tsId = aFieldIds[iCt] + iIndex + '_type';\n\t\t\tsSwapId = aFieldIds[iCt] + iSwapIndex + '_type';\n\t\t\tsTemp = document.getElementById(sId).value;\n\t\t\tdocument.getElementById(sId).value = document.getElementById(sSwapId).value;\n\t\t\tdocument.getElementById(sSwapId).value = sTemp;\n\t\t}\n\t\t//oCurTr.cells[iCt].innerHTML;\n\t}\n\tiMaxElement = aContentIds.length;\n\tfor(iCt=0;iCt<iMaxElement;iCt++)\n\t{\n\t\tsId = aContentIds[iCt] + iIndex;\n\t\tsSwapId = aContentIds[iCt] + iSwapIndex;\n\t\tif(document.getElementById(sId) && document.getElementById(sSwapId))\n\t\t{\n\t\t\tsTemp = document.getElementById(sId).innerHTML;\n\t\t\tdocument.getElementById(sId).innerHTML = document.getElementById(sSwapId).innerHTML;\n\t\t\tdocument.getElementById(sSwapId).innerHTML = sTemp;\n\t\t}\n\t}\n\tiMaxElement = aOnClickHandlerIds.length;\n\tfor(iCt=0;iCt<iMaxElement;iCt++)\n\t{\n\t\tsId = aOnClickHandlerIds[iCt] + iIndex;\n\t\tsSwapId = aOnClickHandlerIds[iCt] + iSwapIndex;\n\t\tif(document.getElementById(sId) && document.getElementById(sSwapId))\n\t\t{\n\t\t\tsTemp = document.getElementById(sId).onclick;\n\t\t\tdocument.getElementById(sId).onclick = document.getElementById(sSwapId).onclick;\n\t\t\tdocument.getElementById(sSwapId).onclick = sTemp;\n\t\t\t\n\t\t\tsTemp = document.getElementById(sId).src;\n\t\t\tdocument.getElementById(sId).src = document.getElementById(sSwapId).src;\n\t\t\tdocument.getElementById(sSwapId).src = sTemp;\n\t\t\t\n\t\t\tsTemp = document.getElementById(sId).title;\n\t\t\tdocument.getElementById(sId).title = document.getElementById(sSwapId).title;\n\t\t\tdocument.getElementById(sSwapId).title = sTemp;\n\t\t}\n\t}\n\t//FindDuplicate(); \n\tsettotalnoofrows();\n\tcalcTotal();\n\t\n\tloadTaxes_Ajax(iIndex);\n\tloadTaxes_Ajax(iSwapIndex);\n\tcallTaxCalc(iIndex);\n\tcallTaxCalc(iSwapIndex);\n\tsetDiscount(this,iIndex);\n\tsetDiscount(this,iSwapIndex);\n\tsId = 'tax1_percentage' + iIndex;\n\tsTaxRowId = 'hidtax_row_no' + iIndex;\n\tif(document.getElementById(sTaxRowId))\n\t{\n\t\tif(!(iTaxVal = document.getElementById(sTaxRowId).value))\n\t\t\tiTaxVal = 0;\n\t\t//calcCurrentTax(sId,iIndex,iTaxVal);\n\t}\n\n\tsSwapId = 'tax1_percentage' + iSwapIndex;\n\tsSwapTaxRowId = 'hidtax_row_no' + iSwapIndex;\n\tif(document.getElementById(sSwapTaxRowId))\n\t{\n\t\tif(!(iSwapTaxVal = document.getElementById(sSwapTaxRowId).value))\n\t\t\tiSwapTaxVal = 0;\n\t\t//calcCurrentTax(sSwapId,iSwapIndex,iSwapTaxVal);\n\t}\n\tcalcTotal();\n}",
"function sortPrice() {\n if (lastSort == 0) {\n lastSort = 1;\n } else {\n lastSort = 0;\n }\n\n switch (lastSort) {\n case 0:\n multiSort(mymodel.rows, {\n Total: 'desc'\n });\n break;\n case 1:\n multiSort(mymodel.rows, {\n Total: 'asc'\n });\n break;\n }\n //say(\"Despues de ordenar\");\n //console.table(mymodel.rows);\n draw();\n\n}",
"function updatePriceByProduct(productPrice, index){\n //select the current item\n var currentProduct = document.getElementsByClassName('total-individual-price')[index];\n // update the price\n currentProduct.innerHTML = productPrice;\n}",
"function getSortable(price) {\n if (price < 0) {\n console.log(`Do not support negative prices '${price}'`);\n } else if (price > 99999999) {\n console.log(`Do not support too big prices '${price}'`);\n }\n let n = price * 100; // to centimes\n n = n + ''; // to string\n const i = n.indexOf('.');\n if (i >= 0) {\n n = n.substring(0, i); // strip fractional part if exist\n }\n return pad(n, 10); // up to 99'999'999.99 francs\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function assigns the chosen number to a square if correct, or removes a life if incorrect | function updateSquare() {
// If a square and a number are both selected
if (selectedSquare && selectedNumber) {
// Assign the chosen number to the chosen square
selectedSquare.textContent = selectedNumber.textContent;
// If the number matches the number in the solution key
if (checkIfCorrect(selectedSquare)){
// Deselect the selected square and number selector
selectedSquare.classList.remove("selected");
selectedNumber.classList.remove("selected");
// Clear any selected variables
selectedNumber = null;
selectedSquare = null;
// Check if the game board is completed
if (checkGridComplete()) {
gameOver();
}
} else { // Check if the number does not match the solution key
// Disallow selecting new numbers for half a second
noSelect = true;
// Turn the selected square dark with red text
selectedSquare.classList.add("incorrect");
// Run after half a second
setTimeout(function() {
// Take 1 from lives
lives --;
// If user runs out of lives
if (lives === 0) {
gameOver();
} else { // If there are lives remaining
// Update the remaining lives section with current lives
id("lives").textContent = "Remaining Lives: " + lives;
// Allow number and square selection
noSelect = false;
}
// Restore square and number color and remove selected from both
selectedSquare.classList.remove("incorrect");
selectedSquare.classList.remove("selected");
selectedNumber.classList.remove("selected");
// Clear the text in tiles and selected variables
selectedSquare.textContent = "";
selectedSquare = null;
selectedNumber = null;
}, 500);
}
}
} | [
"function setSquare(thisSquare) {\n var currSquare = \"square\" + thisSquare;\n var colPlace = new Array(0,0,0,0,0,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4);\n var colBasis = colPlace[thisSquare] * 15;\n var newNum;\n do {\n newNum = colBasis + getNewNum() + 1;\n }\n while (usedNums[newNum]);\n usedNums[newNum] = true;\n\t\t var nodes = document.getElementById(currSquare);\n\t\t var oldNode = nodes.childNodes[0];\n\t \t var newNode = document.createTextNode(newNum);\n\t \t nodes.replaceChild(newNode,oldNode);\n}",
"function correctSquare() {\n let random = Math.floor(Math.random() * colors.length);\n return colors[random];\n}",
"function resetSelection(){\r\n\tvar y,x,i;\r\n\r\n\tfor (y=0;y < squares.length; y++){\r\n\t\tfor (x=0;x < squares.length; x++){\r\n\t\t\tif (squares[x][y].tile === 1 || squares[x][y].tile === 2){squares[x][y].piece = 32;}\r\n\t\t\tif (squares[x][y].tile === 3){squares[x][y].piece = 50;}\r\n\t\t}\r\n\t}\r\n\tfor (i=0;i<pieces.length;i++){\r\n\t\tif (pieces[i].isTaken === false){squares[pieces[i].x][pieces[i].y].piece = i;}\r\n\t}\r\n}",
"function rmPiece(board,round){\n if(board.rows[round].code[3] != 0){\n board.rows[round].code[3] = 0;\n }else if(board.rows[round].code[2] != 0){\n board.rows[round].code[2] = 0;\n }else if(board.rows[round].code[1] != 0){\n board.rows[round].code[1] = 0;\n }else if (board.rows[round].code[0] != 0){\n board.rows[round].code[0] = 0;\n }else {\n console.log(\"Error : Tout est déjà effacé\");\n }\n }",
"function removePiece(piece, square) {\n for (let pieceIndex = 0; pieceIndex < pieceList[piece]; pieceIndex++) {\n if (pieceList.pieces[piece * 10 + pieceIndex] == square) {\n var capturedIndex = pieceIndex;\n break;\n }\n }\n \n pieceList[piece]--;\n pieceList.pieces[piece * 10 + capturedIndex] = pieceList.pieces[piece * 10 + pieceList[piece]]; \n }",
"function randomSquare() {\n // clearing all squares first to be sure there are no moles\n square.forEach(moleClass => {\n moleClass.classList.remove('mole')\n })\n // getting our random number using math.floor to make sure its always under 9\n let randomNum = square[Math.floor(Math.random() * 9)];\n randomNum.classList.add('mole');\n\n // storing the position id of the mole so that we can check if the user clicks on it\n molePoisiton = randomNum.id;\n}",
"removeSquareFromBoard(x, y) {\n\t\tvar square = new Empty(\"empty\")\n\t\tthis.board[x][y] = square;\n\t\tupdateSquareHTML(square, x, y);\t\n\t}",
"function decreaseDifficulty() {\n if (Math.random() < 0.5) {\n if (row > 5 || col > 5) {\n if (row === col) {\n --row;\n } else {\n --col;\n }\n }\n } else {\n if (tilesTobeClicked > 3) {\n --tilesTobeClicked;\n }\n }\n }",
"function deselectSquare() {\n selectedSquare = false;\n}",
"function SetSquareNumber(x, y){\r\n\tif(selectNumber != 0){\r\n\t\tallSquares[x][y].value = selectNumber;\r\n\t}\r\n}",
"function newGrid() {\n\tvar numSquares = parseInt(prompt(\"Enter number of squares between 1-64: \", 32));\n\tif (numSquares > 0 && numSquares <= 64){\n\t\t$('.square').unbind();\n\t\tclean();\n\t\tmakeGrid(numSquares);\n\t}\telse {\n\t\talert(\"Sorry, please pick a number in the defined range\");\n\t\t$('.square').unbind();\n\t\tclean();\n\t\tmakeGrid(32);\n\t}\n}",
"function computerTurn() {\n //Double check it's computer's turn\n if (document.getElementById(\"game-turn\").innerHTML === \"Computer's\") {\n //Find a free square\n //Declare array for squares\n let squareArray = [];\n\n //Squares with active O or X will not be added to the array\n //Loop through squares from 1-9.\n for (let i = 1; i <= 9; i++) {\n if (document.getElementById(`square-${i}`).innerHTML === ''){\n squareArray.push(i);\n }\n }\n //Check if all squares are full or not\n if (squareArray.length < 1 && !winner) {\n //If no winner, reset game and increment draw-score\n setTimeout(() => {resetSquares();}, 1000);\n setScoreboard(false);\n\n //Show draw colour\n drawAnimation();\n\n //Draw message\n modalBox(\"Draw\");\n } else {\n //Assign a free square based on difficulty level\n let chosenSquare = (hardMode) ? computerSquareHard(squareArray) : computerSquareEasy(squareArray);\n\n //Wait 0.75 seconds then add X to the square\n setTimeout(() => {setSquare(chosenSquare, \"X\");}, 750);\n }\n } else {\n console.log(\"Error, It's not the computer's turn?\");\n }\n}",
"function computerTurn() {\n var chosenSquare;\n if (findWinningChoice('box-filled-2') != false) {\n chosenSquare = findWinningChoice('box-filled-2');\n chosenSquare.classList.add('box-filled-2');\n } else if (findWinningChoice('box-filled-1') != false) {\n chosenSquare = findWinningChoice('box-filled-1');\n chosenSquare.classList.add('box-filled-2');\n } else {\n var emptySquares = getEmptyBoxes();\n chosenSquare = emptySquares[Math.floor(Math.random() * emptySquares.length)];\n chosenSquare.classList.add('box-filled-2');\n }\n checkForWin('player2');\n}",
"function attack() {\n if (remainingSquares.includes(4)) {\n randomNum = 4;\n } else if (squaresFilled < 6) {\n randomNum = getRandom(outsideSquares.length);\n randomNum = outsideSquares[randomNum];\n } else {\n randomNum = getRandom(remainingSquares.length);\n randomNum = remainingSquares[randomNum];\n }\n }",
"removeSquare(square){\n\t\tif (square.type == \"player\"){\n\t\t\tif (square.killer in this.players){\n\t\t\t\tthis.players[square.killer].score += 1; // add 1 to the score of the killer\n\t\t\t}\n\t\t\tdelete this.players[square.id];\n\t\t} else if (square.type == \"enemy\"){\n\t\t\tif (square.killer in this.players){\n\t\t\t\tthis.players[square.killer].score += 1; // add 1 to the score of the killer\n\t\t\t}\n\t\t\tthis.enemies_number -= 1;\n\t\t} else if (square.type == \"box\"){\n\t\t\tthis.boxes_number -= 1;\n\t\t} else if (square.type == \"obstacle\"){\n\t\t\tthis.obstacles_number -= 1;\n\t\t}\n\t\t// remove the square from squares list\n\t\tvar index=this.squares.indexOf(square);\n\t\tif(index!=-1){\n\t\t\tthis.squares.splice(index,1);\n\t\t}\n\t}",
"function squareFree(square) {\n return (document.getElementById(`square-${square}`).innerHTML === '') ? true : false ;\n}",
"function reset() {\n let newSize = prompt(\"Please enter number of squares per side\", \"e.g. 64\");\n\n // If user clicks cancel\n if (newSize === null) {\n return;\n }\n\n if (isNaN(newSize)) {\n\n alert(\"That's not a number!\");\n return;\n\n } else if (newSize <= 0) {\n\n alert(\"Cannot be less than or equal to zero!\");\n return;\n }\n\n size = parseInt(newSize);\n \n // Remove all the old items from the grid\n while(divGrid.firstChild) {\n divGrid.removeChild(divGrid.firstChild);\n }\n\n drawGrid();\n}",
"function cleanSquare(rowNum, colNum) {\n\tvar canvas = getCanvas();\n\n\tcanvas.beginPath();\n\tcanvas.rect(100*colNum + 5, 100*rowNum + 5, 90, 90);\n\tcanvas.fillStyle = 'white';\n\tcanvas.fill();\n}",
"function randomNumber(){\n \n console.log(\"**Called Function randomNumber**\");\n var randomNum = Math.floor(Math.random() * 9 + 1);\n var zone = \"#\" + randomNum;\n var r;\n var c;\n var id;\n \n switch(zone){\n case \"#1\":\n r = 0;\n c = 0;\n id = \"#r\" + r + \"c\" + c;\n break;\n case \"#2\":\n r = 0;\n c = 1;\n id = \"#r\" + r + \"c\" + c;\n break;\n case \"#3\":\n r = 0;\n c = 2;\n id = \"#r\" + r + \"c\" + c;\n break;\n case \"#4\":\n r = 1;\n c = 0;\n id = \"#r\" + r + \"c\" + c;\n break;\n case \"#5\":\n r = 1;\n c = 1;\n id = \"#r\" + r + \"c\" + c;\n break;\n case \"#6\":\n r = 1;\n c = 2;\n id = \"#r\" + r + \"c\" + c;\n break;\n case \"#7\":\n r = 2;\n c = 0;\n id = \"#r\" + r + \"c\" + c;\n break;\n case \"#8\":\n r = 2;\n c = 1;\n id = \"#r\" + r + \"c\" + c;\n break;\n case \"#9\":\n r = 2;\n c = 2;\n id = \"#r\" + r + \"c\" + c;\n break;\n }\n \n console.log(\"randomNumber is: \" + randomNum);\n console.log(\"'r' is: \" + r + \" and 'c' is: \" + c);\n console.log(\"'id' is: \" + id);\n \n if(game.board[r][c] === \" \"){\n \n game.arr = [r, c, id];\n console.log(\"Space is availible\");\n console.log(\"Updating game.arr...\");\n console.log(\"Exiting randomNumber function\");\n console.log(\"!!-----------------------!!\");\n \n } else {\n console.log(\"Space not availible, choosing another number\");\n randomNumber();\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Runs the card.getImageSource() method for each card in the player's hand, then returns an array of these strings. | getHandImages(){
let handImageSources = [];
this.hand.forEach(element => handImageSources.push(element.getImageSource()));
return handImageSources;
} | [
"getCards(imgPath){\n const suitMap = {\n 0: 'S',\n 1: 'H',\n 2: 'C',\n 3: 'D'\n }\n let allImages = []\n for (let i = 0; i < this.hand.length; i++){\n if (this.hand[i] === 0){\n allImages.push('Purple.png')\n continue\n }\n let suit = Math.floor(this.hand[i] / 13);\n let number = this.hand[i] % 13;\n if (number === 0){\n number = 13\n suit = suit - 1\n }\n allImages.push(imgPath + String(number) + suitMap[suit]+'.png')\n }\n return allImages\n }",
"function generateImageSources() {\n\n // Create empty array\n var imageSources = [];\n\n // for loop to run 6 times\n for (var imageCounter = 1; imageCounter <=6; imageCounter++) {\n // Create new image source using string and imageCounter as number\n var imageSource = \"images/cards/plant-\" + imageCounter + \".jpg\";\n\n // Push to imageSources array twice (can do this using for loop too!)\n imageSources.push(imageSource);\n imageSources.push(imageSource);\n }\n\n // Return the full array\n return imageSources;\n}",
"function readMyCards() {\n // Get my cards\n var cards = document.getElementsByClassName('you-player')[0];\n var card1 = cards.getElementsByClassName('card')[0],\n card2 = cards.getElementsByClassName('card')[1];\n\n // Convert each of my cards to string\n var card1String = face[card1.children[0].innerText] + ' of ' + suit[card1.children[1].innerText];\n var card2String = face[card2.children[0].innerText] + ' of ' + suit[card2.children[1].innerText];\n\n return 'Cards in hand are ' + card1String + ' and ' + card2String;\n}",
"function getSuitedCards() {\n var allSuitedCards = [];\n for (var row = 0; row < cards.length; row++) {\n var isConsecutive = false;\n var consecStart;\n var consecEnd;\n \n for (var column = row + 1; column < cards.length; column++) { // all suited hands are located in the upper right half of the grid\n var handText = cards[row] + cards[column] + \"s\";\n var handObject = handDictionary[handText];\n\n if (handObject.isSelected) {\n if (isConsecutive) {\n consecEnd = column;\n }\n else {\n isConsecutive = true;\n consecStart = column;\n consecEnd = consecStart;\n }\n\t\t\t\tif (column == cards.length - 1) {\n\t\t\t\t allSuitedCards.push(getConsecCards(row, consecStart, consecEnd, \"s\"));\n\t\t\t\t}\n }\n else {\n if (isConsecutive) {\n isConsecutive = false;\n allSuitedCards.push(getConsecCards(row, consecStart, consecEnd, \"s\"));\n }\n }\n }\n }\n return allSuitedCards.join(\",\");\n}",
"function showHand(playerCards) {\n for (var i = 0; i < playerCards.length; i++) {\n console.log('showHand: ', playerCards[i]);\n }\n}",
"function getCribCards(hand, heldCards)\r\n{\r\n var sendToCrib = [];\r\n for (var i = 0; i < 6; i++)\r\n {\r\n if (GlobalHelpers.arrayContainsCard(heldCards, hand[i]))\r\n {\r\n continue;\r\n }\r\n else\r\n {\r\n sendToCrib.push(hand[i]);\r\n }\r\n }\r\n return sendToCrib;\r\n}",
"function get_selected_cards() {\n return get_card_names(player_hand.querySelectorAll('.selected'));\n}",
"function prepareCardImages() {\n var excludeCards = [148, 151, 152, 164, 167, 168, 180, 183, 184, 196, 199]; //exclude non-standard playing cards in the unicode bank\n for (var i = 0; i < 63; i++) {\n if (excludeCards.indexOf((137 + i)) < 0) {\n cardImages.push('' + cardUnicodePrefix + (137 + i));\n }\n }\n console.log(\"Prepared card images!\"); \n}",
"function loadImages() {\n\t\t\n\t\tvar prefix = ['h', 'd', 's', 'c'],\n\t\t\tpath = document.URL + \"_/images/cards/\",\n\t\t\tsize = {\n\t\t\t\twidth: 72,\n\t\t\t\theight: 96\n\t\t\t},\n\t\t\tdeck = [],\n\t\t\ti, l = 13,\n\t\t\tcount = 0,\n\t\t\tlength = 52;\n\n\t\tfor (i = 0; i < l; i++) {\n\t\t\tfor (var u = 0; u < 4; u++) {\n\n\t\t\t\tvar img = new Image(size.width, size.height),\n\t\t\t\t\tlabel = prefix[u] + (i + 1),\n\t\t\t\t\tsrc = path + label + '.png';\n\t\t\t\tdeck.push({\n\t\t\t\t\tlabel: label,\n\t\t\t\t\timg: img\n\t\t\t\t});\n\t\t\t\tdeck[count].img.src = src;\n\t\t\t\tdeck[count].img.onload = loaded;\n\t\t\t\tcount++;\n\n\t\t\t}\n\t\t}\n\n\t\tfunction loaded() {\n\t\t\tlength--;\n\t\t\tif (length == 0) event.dispatch('IMG_LOADED', {\n\t\t\t\tdeck: deck\n\t\t\t});\n\t\t}\n\n\t}",
"function getHandValue(){\r\n\tfor (var i = 0; i < cards.length; i++) {\r\n\t\thandValue(i);\r\n\t}\r\n}",
"function collectImagesInfo(){\n var imagesAddresses = [];\n \n $slots.each(function(el){\n $this = $(this);\n var img = {};\n if(!$this.hasClass('filled')){\n img.html = $(\"<div class=\\\"player__img--blank\\\"></div>\"); \n }else{\n img.img = $this.children().attr(\"src\");\n img.class = \"player__img\";\n } \n imagesAddresses.push(img);\n });\n return imagesAddresses;\n }",
"function displayCards() {\n\t\tfor (let t of table){\n\t\t\t// console.log(table);\n\t\t\tfor (let c of t[1].cards){\n\t\t\t\tt[0].innerHTML += c.image;\n\t\t\t}\n\t\t}\n\t}",
"function getCardItems($) {\n\t// Find all the items that containg Card Image: OR Card Image Iframe:\n\t\n\tvar bbItems = jQuery(tweak_bb.page_id + \" > \" +tweak_bb.row_element).children(\".details\").children('.vtbegenerated').filter(\n\t function( index ) {\n\t if ( $(this).filter(\":contains('Card Image:')\").length==1 ) {\n\t return true;\n\t } \n\t if ( $(this).filter(\":contains('Card Image Iframe:')\").length==1 ) {\n\t return true;\n\t } \n\t return false;\n\t } );\n\t \n\tvar cards = extractCardsFromContent( bbItems);\n\t\n\treturn cards;\n}",
"function getImageSources() {\n var ids = [\n '0001', '0002', '0003', '0004', '0005', '0006', '0007',\n '0008', '0009', '0010', '0011', '0012', '0013', '0014'\n ];\n return ids.map(function(name){\n return 'http://localhost:8000/images/' + name + '.JPG';\n })\n}",
"function convert_selected_cards_to_hand(){\n var selected_cards = [];\n var cards = game_instance.get_cards();\n for(var i = 0; i < cards.length; i++){\n if($('.card_' + i).hasClass('selected')){\n selected_cards.push(cards[i].get_card_number());\n }\n }\n return selected_cards;\n }",
"function generateCards() {\n const randImages = pickRandom(images[kind], difficulty.variety);\n const shuffledImages = shuffle([...randImages, ...randImages]);\n const cards = shuffledImages.map((image) => createCard(image));\n return cards;\n }",
"getHandCards() {\n\t\treturn this.mPlayerHand;\n\t}",
"function Card_getCard() {\n\treturn new Array(this.identifier, this.suit);\n}",
"getSelectedCards() {\r\n\t \tvar result = new Array();\r\n\t \tvar i = 0;\r\n\t \tvar c;\r\n\t \tfor (i=0; i<this.faceUp.length; i++) {\r\n\t \t\tc = this.faceUp[i];\r\n\t \t\tif (c.selected)\r\n\t \t\t\tresult.push(c);\r\n\t \t}\r\n\t \treturn result;\r\n\t }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
refeshes container1 to display tweets. This is where the magic happens. clears container1, from last (newest) to first (oldest) posts html divs for each tweet takes an optional string argument to post tweets from that user only | function refresh(nn){
var $body = $('.container1'); //clears container1
$body.html('');
nn = nn || streams.home;
var index = nn.length - 1;
while(index >= 0){
var tweet = nn[index];
var $tweet = $('<div class="tweetDiv ' + tweet.user + '"></div>');
var eachFullTweetHTML = ''
+ '<a class ="user" onclick = "filterUsername(\'' + tweet.user +'\')">@' + tweet.user + ': ' + '</a>'
+ '<div class = "message">' + tweet.message + '</div>'
+ '<div class = "time">' + timeFormat(tweet.created_at) + '</div>';
$tweet.html(eachFullTweetHTML);
$tweet.appendTo($body);
index -= 1;
}
} | [
"function renderTweets(tweets) {\n const tweetLog = $('.tweets-container');\n tweetLog.empty()\n //prepend to render ontop of old tweets....append would be for bottom\n for(let tweet in tweets) {\n tweetLog.prepend(createTweetElement(tweets[tweet]));\n }\n }",
"function renderTweets(tweets) {\n $('#tweets-container').empty();\n $('.counter').text('140');\n for (tweet in tweets){\n var tweetData = tweets[tweet];\n var $tweet = createTweetElement(tweetData);\n $('#tweets-container').prepend($tweet);\n }\n}",
"function renderTweets(tweets) {\n $(\"#new-section\").empty();\n tweets.forEach(function(tweet) {\n $('#new-section').prepend(createTweetElement(tweet));\n });\n }",
"function renderTweets(tweets) {\n $('.new-tweet textarea').val('');\n $('.counter').text('140');\n for (i = 0; i < tweets.length; i++) {\n const article = createTweetElement(tweets[i]);\n $('.tweets').prepend(article);\n }\n }",
"function renderTweets(tweets) {\n $('#tweets1').html('');\n for (tweet in tweets) {\n let $newTweet = createTweetElement(tweets[tweet]);\n $('#tweets1').prepend($newTweet);\n }\n}",
"function addTweetsToContainer(tweets){\n\n for (var index in tweets){\n $('#tweets-container').append(createTweetItem(tweets[index], index));\n }\n\n // animate overlay\n if ($('.floating-box').hasClass('hidden')){\n showTweets();\n }\n\n if (previousTweetsContainerHeight) {\n $('.floating-box-content').animate({scrollTop: previousTweetsContainerHeight}, 500);\n }\n}",
"function renderTweets(tweets) {\n let temp = \"\";\n for(let i = 0; i < tweets.length; i++){\n temp = createTweetElement(tweets[i]);\n $('#tweets-container').prepend(temp);\n }\n }",
"function renderTweets(tweets) {\n for (let i = 0; i < tweets.length; i++) {\n let $currentTweet = createTweetElement(tweets[i]);\n $(\"#mainContainer\").append($currentTweet);\n }\n }",
"function renderTweets(tweet) {\n tweet.forEach(tweet => {\n let twtHTML = createTweetElement(tweet);\n $(\"#tweets-container\").prepend(twtHTML)\n });\n }",
"function renderTweets(tweet) {\n\n tweet.forEach(function(num, index) {\n let currentTweet = createTweetElement(num);\n $('#tweets-container').prepend(currentTweet);\n });\n}",
"function displayTweets() {\r\n\r\n if (tweets == null) {\r\n setTimeout(displayTweets, 20);\r\n return;\r\n }\r\n\r\n // Dynamically generate rows of tweets\r\n var fullString = \"\";\r\n for (var i = 0; i < tweets.statuses.length; i++) {\r\n fullString += makeRow(tweets,i);\r\n }\r\n $(\"#tweets\").html(fullString);\r\n\r\n}",
"function renderTweets(data) {\n let $tweetContainer = $('#tweets-container')\n $tweetContainer.empty();\n for (tweet of data) {\n $tweetContainer.append(createTweetElement(tweet));\n }\n}",
"function clearTweets() {\n $tweetContainer.empty();\n}",
"function addTweets(arrTweets) {\r\n\t// body...\r\n\t/*\r\n\tHTML structure to be used to add tweets\r\n\t<div class=\"tweet retweeted\">\r\n \t<div class=\"tweetHeader\"><div class=\"date\"></div><div class=\"RT\"></div></div>\r\n \t<div class=\"tweetText\"></div>\r\n </div>\r\n */\r\n\r\n $(\".tweetsHolder\").html('')\r\n\r\n var tweetText, tweetDateTime, isRT;\r\n\r\n var numberOfTweets = arrTweets.length;\r\n var currTweet;\r\n\r\n var strHTML;\r\n\r\n var strHTML1 = '<div class=\"tweet';\r\n var strRTClass;\r\n var strHTML2 = '\">'\r\n var strHeaderHTML = '<div class=\"tweetHeader\"><div ';\r\n var strHeaderHTML1a = 'theotherdateinfo=\"'\r\n var strHeaderHTML1b = '\" class=\"date\">'\r\n var strHeaderHTML2;\r\n var strHTML3 = '</div></div><div class=\"tweetText\">';\r\n var strHTML4 = '</div>'\r\n var rtUser;\r\n var mediaURLInText, mediaURLToUse, mediaLinkHTML;\r\n var strReadableDateTimeInfo;\r\n\r\n for (var i=0; i<numberOfTweets; i++)\r\n {\r\n \t\t// strHTML = strHTML1;\r\n\t\tstrRTClass = '';\r\n\t\trtUser = '';\r\n\t\tstrHeaderHTML2 = '';\r\n\r\n \t\tcurrTweet = arrTweets[i];\r\n\r\n \t\ttweetDateTime = getDateTime(currTweet.created_at);\r\n \t\tshortDate = normalizeDate(tweetDateTime.date);\r\n \t\tstrReadableDateTimeInfo = getReadableDateTime(tweetDateTime);\r\n\r\n \t\tisRT = (currTweet.retweeted_status === undefined) ? false : true\r\n\r\n \t\tif(isRT)\r\n \t\t{\r\n\t\t\t//if tweet is a retweet do the following \t\t\r\n\t\t\trtUser = '@' + currTweet.retweeted_status.user.screen_name;\r\n \t\t\ttweetText = currTweet.retweeted_status.text;\r\n\t \t\tstrRTClass = ' retweeted'\r\n\t \t\tstrHeaderHTML2 = '</div><div class=\"RT\">';\t \t\t\r\n \t\t}\r\n \t\telse\r\n \t\t{\r\n \t\t\ttweetText = currTweet.text;\t\t\r\n \t\t}\r\n\r\n \t\t//the twitter data contains media information here >> currTweet.entities.media[0].url\r\n \t\t//it will be present in the tweetText. this needs to be replaced with an actual link. \r\n\r\n \t\tif (currTweet.entities.media.length > 0)\r\n \t\t{\r\n \t\t\t//if tweet contains media\r\n \t\t\tmediaURLInText = currTweet.entities.media[0].url;\r\n \t\t\tmediaURLToUse = currTweet.entities.media[0].media_url;\r\n \t\t\tmediaLinkHTML = '<a href=\"'+ mediaURLToUse + '\" target=\"_blank\">media</a>'\r\n \t\t\ttweetText = tweetText.replace(mediaURLInText, mediaLinkHTML);\r\n \t\t}\r\n \t\telse if (currTweet.entities.urls.length > 0)\r\n \t\t{\r\n \t\t\tmediaURLInText = currTweet.entities.urls[0].url;\r\n \t\t\tmediaURLToUse = currTweet.entities.urls[0].expanded_url;\r\n \t\t\tmediaLinkHTML = '<a href=\"'+ mediaURLToUse + '\" target=\"_blank\">media</a>'\r\n \t\t\ttweetText = tweetText.replace(mediaURLInText, mediaLinkHTML);\t\r\n \t\t}\r\n\r\n\r\n \t\tstrHTML = strHTML1 + strRTClass + strHTML2 + strHeaderHTML + strHeaderHTML1a + strReadableDateTimeInfo + strHeaderHTML1b + shortDate + strHeaderHTML2 + rtUser + strHTML3 + tweetText + strHTML4;\r\n\r\n \t\t$(\".tweetsHolder\").append(strHTML);\r\n }\r\n\r\n}",
"function loadTweets () {\n\n $.getJSON( \"/tweets/\", function (data) {\n //Empties the container and re-renders with new tweets.\n $( \"#tweets-container\" ).empty()\n renderTweets(data.sort( function(a,b){\n return b.created_at - a.created_at;\n }));\n\n });\n\n }",
"function renderTweets(tweets) {\n\n // 4a. Render each 'tweet' with each using 'createTweetElement' \n // 4b. Add each 'tweet' to beginning of 'tweets'\n $.each(tweets, function(index, tweet) {\n var tweet_html = createTweetElement(tweet);\n $('.tweets').prepend(tweet_html);\n });\n }",
"function twitterCallback2(twitters) {\n var statusHTML = [];\n for (var i=0; i<twitters.length; i++) {\n // fetch tweet information\n var tweet = {\n username: twitters[i].user.screen_name,\n uname : twitters[i].user.name,\n imageurl: twitters[i].user.profile_image_url,\n location: twitters[i].location,\n entities: twitters[i].entities,\n pic : getTweetPic(twitters[i].entities)\n };\n var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\\:\\/\\/[^\"\\s\\<\\>]*[^.,;'\">\\:\\s\\<\\>\\)\\]\\!])/g, function(url) {\n return '<a href=\"'+url+'\">'+url+'</a>';\n }).replace(/\\B@([_a-z0-9]+)/ig, function(reply) {\n return reply.charAt(0)+'<a href=\"http://twitter.com/'+reply.substring(1)+'\">'+reply.substring(1)+'</a>';\n });\n statusHTML.push('<div class=\"tileItem tweetBlock\">'+ '<div class=\"intro\"><img src=\"'+tweet.imageurl+'\"/><span class=\"name\">' + tweet.uname + '</span><span class=\"sname\">@' + tweet.username + '</span></div><div class=\"tweet\"><span>' + status+'</span> <a class=\"time\" href=\"http://twitter.com/'+tweet.username+'/statuses/'+twitters[i].id_str+'\">'+relative_time(twitters[i].created_at)+'</a></div>');\n if (tweet.pic)\n statusHTML.push('<a href=\"' + tweet.pic + '\"' + 'class=\"pic\"><img class=\"interactive\" src=\"'+tweet.pic+'\"/>' + '</a></div>');\n else\n statusHTML.push('</div>');\n };\n var oldHtml = document.getElementById('gridHolder').innerHTML;\n document.getElementById('gridHolder').innerHTML = oldHtml + statusHTML.join('');\n document.getElementById('spinner').style.display = 'none';\n}",
"function publishNewTweet () {\n document.querySelector(\"form\").reset();\n document.querySelector(\".counter\").innerHTML = 140;\n $.getJSON(\"/tweets/\", function(data) {\n var $happy = createTweetElement(data.slice(-1)[0]);\n $('.freshtweets').prepend($happy);\n })\n }",
"function renderTweets(tweetArray) {\n tweetArray.forEach( function(tweetObject) {\n let $tweet = createTweetElement(tweetObject);\n $('#tweets-container').prepend($tweet); // appends it to front\n $(\"time.timeago\").timeago();\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
=================================================================== from functions/threads/ThreadLocalSet.java =================================================================== Needed early: Builtin Needed late: ArcThreadLocal | function ThreadLocalSet() {
} | [
"function SetThreadLocal() {\r\n}",
"function NewThreadLocal() {\r\n}",
"function ThreadLocalGet() {\r\n}",
"enterDataThreadLocalClause(ctx) {\n\t}",
"function h$gc(t) {\n if(h$currentThread !== null) throw \"h$gc: GC can only be run when no thread is running\";\n ;\n var start = Date.now();\n h$resetRegisters();\n h$resetResultVars();\n h$gcMark = 5-h$gcMark;\n var i;\n \n for(i=h$extensibleRetentionRoots.length-1;i>=0;i--) {\n var a = h$extensibleRetentionRoots[i]();\n h$follow(a, a.length-1);\n }\n ;\n if(t !== null) h$markThread(t);\n var nt, runnable = h$threads.iter();\n while((nt = runnable()) !== null) h$markThread(nt);\n var iter = h$blocked.iter();\n while((nt = iter.next()) !== null) {\n if(!(nt.blockedOn instanceof h$MVar) || (nt.stack && nt.stack[nt.sp] === h$unboxFFIResult)) {\n h$markThread(nt);\n }\n }\n ;\n iter = h$extraRoots.iter();\n while((nt = iter.next()) !== null) h$follow(nt.root);\n // now we've marked all the regular Haskell data, continue marking\n // weak references and everything retained by DOM retainers\n h$markRetained();\n // now all running threads and threads blocked on something that's\n // not an MVar operation have been marked, including other threads\n // they reference through their ThreadId\n // clean up threads waiting on unreachable MVars:\n // throw an exception to a thread (which brings it back\n // to life), then scan it. Killing one thread might be enough\n // since the killed thread could make other threads reachable again.\n var killedThread;\n while(killedThread = h$finalizeMVars()) {\n h$markThread(killedThread);\n h$markRetained();\n }\n // mark all blocked threads\n iter = h$blocked.iter();\n while((nt = iter.next()) !== null) h$markThread(nt);\n // and their weak references etc\n h$markRetained();\n // now everything has been marked, bring out your dead references\n // run finalizers for all weak references with unreachable keys\n var finalizers = h$finalizeWeaks();\n h$clearWeaks();\n for(i=0;i<finalizers.length;i++) {\n var fin = finalizers[i].finalizer;\n if(fin !== null && !((typeof fin.m === 'number' && (fin.m & 3) === mark) || (typeof fin.m === 'object' && ((fin.m.m & 3) === mark)))) h$follow(fin);\n }\n h$markRetained();\n h$clearWeaks();\n h$scannedWeaks = [];\n h$finalizeDom(); // remove all unreachable DOM retainers\n h$finalizeCAFs(); // restore all unreachable CAFs to unevaluated state\n var now = Date.now();\n h$lastGc = now;\n}",
"function h$gcQuick(t) {\n if(h$currentThread !== null) throw \"h$gcQuick: GC can only run when no thread is running\";\n h$resetRegisters();\n h$resetResultVars();\n var i;\n if(t !== null) { // reset specified threads\n if(t instanceof h$Thread) { // only thread t\n h$resetThread(t);\n } else { // assume it's an array\n for(var i=0;i<t.length;i++) h$resetThread(t[i]);\n }\n } else { // all threads, h$currentThread assumed unused\n var nt, runnable = h$threads.iter();\n while((nt = runnable()) !== null) h$resetThread(nt);\n var iter = h$blocked.iter();\n while((nt = iter.next()) !== null) h$resetThread(nt);\n }\n}",
"enterGtuidSet(ctx) {\n\t}",
"function setLocal(local)\n{\n isLocal = local;\n}",
"function unix_tcsetattr() { unix_ll(\"unix_tcsetattr\", arguments); }",
"function h$resetThread(t) {\n\n\n\n var stack = t.stack;\n var sp = t.sp;\n if(stack.length - sp > sp && stack.length > 100) {\n t.stack = t.stack.slice(0,sp+1);\n } else {\n for(var i=sp+1;i<stack.length;i++) {\n stack[i] = null;\n }\n }\n ;\n}",
"function FSet() {}",
"set threadRootId(aValue) {\n this._logger.debug(\"threadRootId[set]\");\n this._threadRootId = aValue;\n }",
"static set() {this.count = SemaphoreLimit;}",
"function h$resetThread(t) {\n var stack = t.stack;\n if(!stack) return;\n var sp = t.sp;\n if(stack.length - sp > sp && stack.length > 100) {\n t.stack = t.stack.slice(0,sp+1);\n } else {\n for(var i=sp+1;i<stack.length;i++) {\n stack[i] = null;\n }\n }\n ;\n}",
"function h$resetThread(t) {\n var stack = t.stack;\n var sp = t.sp;\n if(stack.length - sp > sp && stack.length > 100) {\n t.stack = t.stack.slice(0,sp+1);\n } else {\n for(var i=sp+1;i<stack.length;i++) {\n stack[i] = null;\n }\n }\n ;\n}",
"function ParallelRunnerEnv() {}",
"newTSO() {\n const tid = ++this.lastTid;\n let promise_resolve, promise_reject;\n const ret_promise = new Promise((resolve, reject) => {\n promise_resolve = resolve;\n promise_reject = reject;\n });\n this.tsos.set(\n tid,\n Object.seal({\n addr: -1, // TSO struct address in Wasm memory\n ret: 0, // returned object address in Wasm memory\n retError: undefined,\n rstat: -1, // thread status\n ffiRet: undefined, // FFI returned value\n ffiRetType: undefined, // FFI returned value type\n ffiRetErr: undefined, // FFI returned error\n returnPromise: ret_promise,\n promise_resolve: promise_resolve, // Settle the promise used by user\n promise_reject: promise_reject\n })\n );\n return tid;\n }",
"set(name,value,global){if(global===void 0){global=false;}if(global){// Global set is equivalent to setting in all groups. Simulate this\n// by destroying any undos currently scheduled for this name,\n// and adding an undo with the *new* value (in case it later gets\n// locally reset within this environment).\nfor(let i=0;i<this.undefStack.length;i++){delete this.undefStack[i][name];}if(this.undefStack.length>0){this.undefStack[this.undefStack.length-1][name]=value;}}else{// Undo this set at end of this group (possibly to `undefined`),\n// unless an undo is already in place, in which case that older\n// value is the correct one.\nconst top=this.undefStack[this.undefStack.length-1];if(top&&!top.hasOwnProperty(name)){top[name]=this.current[name];}}this.current[name]=value;}",
"function TokenSet(){\r\n\tSet.call(this); // just call set constructor\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Callback for when the user says the identity is wrong. | identityWrong() {
this.identityReset();
this.setState({ flow: LOGIN_FLOW.GotoRegister });
} | [
"function partyIDmissing(){\n $ionicPopup.alert({\n title: 'Error',\n template: 'Something went wrong, please try to \"Invite Yotme Users\" again'\n }).then(function(){\n $ionicHistory.goBack();\n });\n }",
"function _authError() {\n next('Invalid User ID/Password');\n }",
"function onLogInFailure() {\n clearHeaderUI();\n\n renderLogOutUI();\n\n alert(AUTH_STRINGS['sign-in-failure']);\n}",
"function onLogInFailure() {\n // No UI change\n}",
"function failure(error) {\n console.log(error);\n registerResult(false, \"User Already Exists\");\n }",
"function isOidValid(req, res, next) {\n\tconst id = req.params.user_id;\n\tif (!id) {\n\t\treturn next();\n\t}\n\tif (id.includes(\"-\") && id.length > 30 && req.oid !== id) {\n\t\t// likely oid format\n\t\treturn res\n\t\t\t.status(400)\n\t\t\t.send(\"User ID specified does not match authorized user.\");\n\t}\n\treturn next();\n}",
"authMailboxFailure (evt, data) {\n if (data.errorMessage.toLowerCase().indexOf('user') === 0) {\n return { user: true, data: null }\n } else {\n // Really log wha we're getting here to try and resolve issue #2\n console.error('[AUTH ERR]', data)\n console.error(data.errorString)\n console.error(data.errorStack)\n reporter.reportError('[AUTH ERR]' + data.errorString)\n return { data: data, user: false }\n }\n }",
"function validateIdentifyEvent(event){assert(event.anonymousId||event.userId,'You must pass either an \"anonymousId\" or a \"userId\".');}",
"function onUserLoginError( result )\r\n{\r\n debug( 'user-login-error: ' + JSON.stringify( result ) );\r\n}",
"function signInError(response) {\r\n\terror(response, \"sign-in-errors\");\r\n}",
"function errorByAuthentication() {\n next('Invalid username or password');\n }",
"function createUserErrorCallback(response) {\n alert(\"Unable to create user.\");\n kony.application.dismissLoadingScreen();\n}",
"checkIdentity(identity) {\n if (!identity.validate()) {\n throw Error('Identity is not valid. Provide valid one or generate new one.');\n }\n }",
"onInvalid() {\n }",
"function ProfileFailedCallback(error_object, userContext, methodName) {\n alert(\"Profile service failed with message: \" +\n\t error_object.get_message());\n}",
"function handleLoginErr(err) {\n $(\"#alert .msg\").text(err.responseJSON);\n $(\"#alert\").fadeIn(500);\n }",
"ensureNotSelf(request, response, next) {\r\n if (request.user && request.params.id && request.user.id === request.params.id) {\r\n request.flash(\r\n 'errorMessage',\r\n 'Modify your data through profile'\r\n );\r\n return response.redirect('/users/me');\r\n }\r\n\r\n next();\r\n }",
"function checkNickname(nick) {\n transmit.sendEventWithCallback('receiverNickname', nick, (error) => { // Async callback with server's validation response\n // If response is undefined, we're good - hide the modal\n if (error === null) {\n receiverDetails.nickname = nick;\n frontendUI.hideNicknameModal();\n frontendUI.showNotificationBanner(\"Set nickname: \" + receiverDetails.nickname, false, false);\n return;\n }\n frontendUI.showNicknameModal();\n // If response is anything else, there's been an error\n alert(\"Setting nickname has been encountered an error: \" + error);\n return error;\n });\n}",
"function cmisLoginFail() {\n login.loginFail();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Signal start of an incomplete line. | onLineStart() { } | [
"function takeEmptyLine() {\n\t\tnewBlock = true\n\t}",
"extendToLineStart() {\n if (isNullOrUndefined(this.start)) {\n return;\n }\n this.end.moveToLineStartInternal(this, true);\n this.upDownSelectionLength = this.end.location.x;\n this.fireSelectionChanged(true);\n }",
"checkLineComplete() {\n checkLineCompleteHelper(this);\n }",
"ensureSkippedLine() {\n this.ensureNewLine();\n if (!this._previousLineIsBlank) {\n this._writeNewLine();\n }\n }",
"isAtBeginningOfLine() {\n return this.getBufferPosition().column === 0;\n }",
"moveToBeginningOfLine() {\n this.setBufferPosition([this.getBufferRow(), 0]);\n }",
"navigateLineStart() {\n this.selection.moveCursorLineStart();\n this.clearSelection();\n }",
"removeToLineStart() {\n if (this.selection.isEmpty())\n this.selection.selectLineStart();\n if (this.selection.isEmpty())\n this.selection.selectLeft();\n this.session.remove(this.getSelectionRange());\n this.clearSelection();\n }",
"function eatAtLeast1EmptyLines(state) {\n var linesEaten = 0;\n while (state.text.length > 0) {\n var nextLine = peekLine(state);\n if ($.trim(nextLine).length === 0) {\n cutLine(state);\n linesEaten += 1;\n }\n else {\n break;\n }\n }\n if (linesEaten === 0) {\n state.error = 'Missing empty line.';\n }\n }",
"moveToLineStart() {\n if (isNullOrUndefined(this.start)) {\n return;\n }\n this.updateBackwardSelection();\n this.start.moveToLineStartInternal(this, false);\n this.end.setPositionInternal(this.start);\n this.upDownSelectionLength = this.start.location.x;\n this.fireSelectionChanged(true);\n }",
"extendToNextLine() {\n if (isNullOrUndefined(this.start)) {\n return;\n }\n this.end.moveToNextLine(this.upDownSelectionLength);\n this.fireSelectionChanged(true);\n }",
"unvoidLine() {\r\n\t\treturn null\r\n\t}",
"function set_beginLine(n) {\n jbNS.beginLine[jbNS.columns_config[1] - 1] = n;\n }",
"onLineEnd() { }",
"isSelectionOnFirstLine() {\n return this.getLineIndex(this.start) === 0;\n }",
"ignoreLine() {\n this._ignoredLine = true;\n }",
"resetToFileStart() {\n this.linesRead = 0\n this.nextByteToRead = 0\n this.chunkLines = []\n this.updateHasMoreChunks()\n this.updateHasMoreLines()\n }",
"moveToEndOfLine() {\n this.setBufferPosition([this.getBufferRow(), Infinity]);\n }",
"function uploadPartialLine() {\n uploadLine();\n points = points.slice(points.length - 1);\n drawing_timeout_id = setTimeout(uploadPartialLine, drawing_upload_interval);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update PLC html table and show it. | function updateTable() {
// Check if plcs finished loading
for (var i = 0; i < g_plcs.length; ++i) {
if (g_plcs[i].err) {
moduleStatus("Error querying table");
return false;
}
if (g_plcs[i].ready != READY_ALL) return false;
}
$("#detail-table-body").html("");
for (var i = 0; i < g_plcs.length; ++i) {
var row_name = "detail-table-row-" + i;
$("#detail-table-body").append("<tr id = '" + row_name + "'>");
$("#" + row_name).append("<td>" + g_plcs[i].name + "</td>");
for (var j = 0; j < 6; ++j)
$("#" + row_name).append("<td data-toggle='tooltip' data-placement='top' title='" + g_plcs[i].ai[j].name + "'>" + g_plcs[i].ai[j].val + "</td>");
for (var j = 0; j < 6; ++j)
$("#" + row_name).append("<td data-toggle='tooltip' data-placement='top' title='" + g_plcs[i].di[j].name + "'>" + g_plcs[i].di[j].val + "</td>");
for (var j = 0; j < 6; ++j) {
do_val = g_plcs[i].do[j].val ? "ON" : "OFF";
do_class = "btn do-button " + (g_plcs[i].do[j].val ? "btn-success" : "btn-secondary");
do_txt = "<button data-do-index = " + j + " data-plc-index = " + i + " data-do-value = " + g_plcs[i].do[j].val + " type = 'button' class = '" + do_class + "'>" + do_val + "</button>";
$("#" + row_name).append("<td data-toggle='tooltip' data-placement='top' title='" + g_plcs[i].do[j].name + "'>" + do_txt + "</td>");
}
conf_val = g_plcs[i].confirmation ? "Pend" : "OK";
conf_class = "btn " + (g_plcs[i].confirmation ? "btn-warning" : "btn-info")
$("#" + row_name).append("<td><button type = 'button' class = '" + conf_class + "'>" + conf_val + "</button></td>");
$("#" + row_name).append("<td><button data-plc-index = " + i + " type = 'button' class = 'send-button btn btn-light'> Enviar </button></td>");
}
$('[data-toggle="tooltip"]').tooltip({trigger : 'hover'});
moduleStatus("Table query OK");
} | [
"function updatePinConfigTableData() {\n\n println(\"Update Pin Configuration Data.\")\n\n var pinconfigtypes = getHTMLValue(\"pinconfigtypes\");\n\n if(pinconfigtypes != \"Please Select\") {\n\n let tableData = ''\n tableData += '<br><br><table class=\"table table-striped\">\\\n <thead>\\\n <tr>\\\n <th>ID</th>\\\n <th>NAME</th>\\\n <th>PIN</th>\\\n <th>STATUS</th>\\\n <th>INIT</th>\\\n <th>MIN-MAX</th>\\\n <th>CONF-CNG</th>\\\n </tr>\\\n </thead>\\\n <tbody>'\n\n for(eachkey in currentDevicePinConfigData) {\n let eachPinData = currentDevicePinConfigData[eachkey]\n\n if(eachPinData['TYPE'] == pinconfigtypes) {\n \n tableData += '<tr>\\\n <td>'+eachPinData[\"ID\"]+'</td>\\\n <td>'+eachPinData[\"NAME\"]+'</td>\\\n <td>'+eachPinData[\"PIN\"]+'</td>\\\n <td>'+eachPinData[\"STATUS\"]+'</td>\\\n <td>'+eachPinData[\"INITVALUE\"]+'</td>\\\n <td>'+eachPinData[\"MINVALUE\"] + ' - ' + eachPinData[\"MAXVALUE\"]+'</td>\\\n <td>'+eachPinData[\"CONFACTOR\"] + ' - ' + eachPinData[\"CNGFACTOR\"]+'</td>\\\n </tr>'\n }\n }\n\n tableData += '</tbody></table>'\n\n\n setHTML(\"pinconfigtableview\",tableData)\n\n }\n\n \n\n}",
"function updateDisplayTables()\n{\n //refresh the memory display\n _MemoryTable.innerHTML = \"\";\n _MemoryTable.appendChild(memoryToTable());\n\n //refresh CPU display\n _CpuTable.innerHTML = \"\";\n _CpuTable.appendChild(cpuToTable());\n\n //old way shows current thread pcb\n //refresh pcbTable\n// _PcbTable.innerHTML = \"\";\n// _PcbTable.appendChild(pcbToTable());\n\n //new way shows ready queue\n _PcbTable.innerHTML = \"\";\n _PcbTable.appendChild(readyQueueToTable());\n}",
"function displayPLCTable(){\n hiddenTable();\n $('#PLC-table').removeClass('hidden');\n // Reset Switch (new & edit) to create new\n $('#switch-PLC input')[0].checked = false;\n changeModePLC();\n\n}",
"function updateTable() {\n var keys = Object.keys(tableTrack.addedTables);\n var tableView = $(\"#added_tables\");\n if (keys.length === 0) {\n tableView.html(\"\");\n return false;\n }\n\n tableView.html(\"<tr>\" +\n \"<th>Number of seats</th>\" +\n \"<th>Number of tables</th>\" +\n \"</tr>\");\n\n for (var i = 0; i < keys.length; i++) {\n var row = \"<tr><td> \" + keys[i] + \" </td>\";\n row += \"<td> \" + tableTrack.addedTables[keys[i]] + \" </td></tr>\"\n tableView.append(row);\n }\n }",
"function refreshTables() {\n\n\t\t$(\"#biomatcher-data-table\").html(\"<table id='biomatcher-data-table' class='table table-striped'><tr><th>Subject ID</th><th>Oligo Name</th><th>Oligo Seq</th><th>Mismatch Tolerance</th><th>Hit Coordinates</th></tr></table>\");\n\t}",
"function renderUpdateCyphrPage() {\n showCyphrUpdatePage();\n allocateUpdateValues();\n}",
"updatePage() {\r\n\t\tvar htmlString = '';\r\n\r\n\t\tfor ( var key in this.data ) {\r\n\t\t\thtmlString = htmlString + '<li>' + this.data[key] + '</li>';\r\n\t\t}\r\n\r\n\t\tthis._dataEl.innerHTML = htmlString;\r\n\t}",
"function updatePlcs() {\n\tmoduleStatus(\"Querying table\");\n\n\t$.post(\"modules/post.php\", {\n\t\t\tmodule: \"tabla_plcs\",\n\t\t\toperation: \"get\",\n\t\t\tformat: \"array\",\n\t\t},\n\t\tfunction(data, status) {\n\n\t\t\tvar json_data = jQuery.parseJSON(data);\n\t\t\tg_data = json_data;\n\n\t\t\tvar err = json_data.error;\n\n\t\t\tdetailStatus(err);\n\t\t\tif (!plcOk(err))\n\t\t\t\treturn;\n\n\t\t\tvar ids = json_data.ids;\n\t\t\tif (!ids)\n\t\t\t\treturn;\n\n\t\t\tvar names = json_data.names;\n\t\t\tif (!names)\n\t\t\t\treturn;\n\n\t\t\tg_plcs = Array();\n\n\t\t\tfor (var i = 0; i < ids.length; ++i) {\n\t\t\t\tg_plcs.push({\n\t\t\t\t\tid: ids[i],\n\t\t\t\t\tname: names[i],\n\t\t\t\t\tdi: [],\n\t\t\t\t\tai: [],\n\t\t\t\t\tdo: [],\n\t\t\t\t\tconfirmation: 0,\n\t\t\t\t\terr: false,\n\t\t\t\t\tready: 0\n\t\t\t\t});\n\t\t\t\tfor (var j = 0; j < 6; j++) {\n\t\t\t\t\tg_plcs[i].ai.push({\n\t\t\t\t\t\tval: 0,\n\t\t\t\t\t\tname: \"\"\n\t\t\t\t\t});\n\t\t\t\t\tg_plcs[i].di.push({\n\t\t\t\t\t\tval: 0,\n\t\t\t\t\t\tname: \"\"\n\t\t\t\t\t});\n\t\t\t\t\tg_plcs[i].do.push({\n\t\t\t\t\t\tval: 0,\n\t\t\t\t\t\tname: \"\"\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tgetIO();\n\t\t});\n}",
"function update() {\n\t\t// Delete all child elements.\n\t\tsongDataTable.empty();\n\t\t// Defines HTML rows for the table.\n\t\tsongDataTable.append(\"<tr> <th>#</th> <th>Pitch</th> <th>Frequency (Hz)</th> <th>Action</th> </tr>\");\n\t\tfor (let i = 0; i < songContainer.data.src.length; i++) {\n\t\t\tif (i === (songContainer.data.src.length - 1)) {\n\t\t\t\t// Make the last note red.\n\t\t\t\tsongDataTable.append(fillHTMLTableRow(i + 1, `<span style='font-weight: bold; color: red;'>${ProgramNotes.getPitch(songContainer.data.src[i])}</span>`, songContainer.data.src[i]));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tsongDataTable.append(fillHTMLTableRow(i + 1, getPitchSelectionTableHTML(i + 1, ProgramNotes.getPitch(songContainer.data.src[i])), songContainer.data.src[i]));\n\t\t}\n\t\t// -1 for ending note.\n\t\tsongContainer.size = songContainer.data.src.length - 1;\n\t\t// Update the text.\n\t\tattrSongSize.text(songContainer.size);\n\t\tattrLastEditDate.text(songContainer.attributes.lastEdit);\n\t\t// Reinstantiate the event which checks when a add/remove button is clicked on a specific row. This must be done every time the table is updated to\n\t\t// keep the javascript insync with the DOM.\n\t\t// CHECK IF A ADD/REMOVE BUTTON ON A TABLE WAS CLICKED\n\t\t$(\"button\").click((e) => {\n\t\t\tlet element;\n\t\t\t// We must check if the <i> part of the button is being clicked.\n\t\t\tif ($(e.target).is(\"i\")) {\n\t\t\t\telement = $(e.target).parent().data('command');\n\t\t\t} else {\n\t\t\t\telement = $(e.target).data('command');\n\t\t\t}\n\t\t\tif (element === undefined) return;\n\t\t\tif (element.split(\",\")[0] === \"add\") {\n\t\t\t\tlet index = Number(element.split(\",\")[1]);\n\t\t\t\tsongContainer.data.src.insert(index, songContainer.data.src[index-1]);\n\t\t\t\tupdateLastEdit();\n\t\t\t\tupdate();\n\t\t\t} else if (element.split(\",\")[0] === \"rem\") {\n\t\t\t\tlet index = Number(element.split(\",\")[1]);\n\t\t\t\tif (songContainer.size === 1) { // End Note + Song Note\n\t\t\t\t\talert(\"You cannot remove your last note!\\nEither edit this note or add more!\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsongContainer.data.src.splice(index - 1, 1);\n\t\t\t\tupdateLastEdit();\n\t\t\t\tupdate();\n\t\t\t} else {\n\t\t\t\tdebug(\"ERROR: Found data-command tag but not a proper command.\");\n\t\t\t}\n\t\t});\n\t\t// GET WHEN A ELEMENT IS CHANGED USING THE DROPDOWN BOX AND UPDATE THE SONG OBJECT.\n\t\t$(\"select\").change((e) => {\n\t\t\t// Ensure that the select tag we are opening is to be edited.\n\t\t\tif ($(e.target).data(\"command\").split(\",\")[0] === \"edit\") {\n\t\t\t\t// Replace the index in the songContainer notes list with the new note the user selected.\n\t\t\t\tsongContainer.data.src[Number($(e.target).data(\"command\").split(\",\")[1]) - 1] = Object.values(ProgramNotes)[Object.keys(ProgramNotes).indexOf($(e.target).val())];\n\t\t\t\t//saveSongObject();\n\t\t\t\tupdateLastEdit();\n\t\t\t\tupdate(); // Refresh the table.\n\t\t\t}\n\t\t});\n\t\t// Update font sizes.\n\t\tsongDataTable.css(\"font-size\", fontSizes[fontSizeIndex]);\n\t\t$(\"select\").css(\"font-size\", fontSizes[fontSizeIndex]);\n\t\tsetTheme();\n\t\tdebug(\"Finished updating table\");\n\t}",
"function load_patchmaster_table(patches, master_list){\n\n //build the combobox\n group_list = collect_groups(master_list);\n let combo_box = create_combo_box();\n\n //get the unassigned products\n unassigned_products = collect_unassigned_products(patches, master_list);\n alphabetize(unassigned_products);\n\n //build the patchmaster table\n let patchmaster_table = \"<table class='pm'>\\n\";\n patchmaster_table += \"<tHead><td class='pm-header'>> PRODUCT</td><td class='pm-header'>> RESPONSIBLE GROUP</td></tHead>\\n\";\n for(let i=0; i<unassigned_products.length; i++){\n patchmaster_table += \"<tr class='pm-table'><td class='pm-data'>\" + unassigned_products[i].split(\",\")[0] + \"</td>\"\n patchmaster_table += \"<td>\" + combo_box.replace(new RegExp(\"replace_me\", \"g\"), \"\" + i);\n }\n patchmaster_table += \"</table>\\n\";\n patchmaster_table += \"<br/><table><tr><td class='pm-button'><button class='pm-table' onclick='create_new_master()'>> SAVE</button></td>\"\n patchmaster_table += \"<td class='pm-button'><button class='pm-table' onclick='location.reload()'>> CANCEL</button></td></tr>\\n\";\n\n //write table to page\n document.getElementById(\"div-body\").innerHTML = patchmaster_table;\n}",
"function populatePage(){\n clearRecordTables();\n forEachMember(tables, function(table, tip){\n serverData[tip].forEach(displayRecord, tip); //'tip' will be accessible as 'this'\n });\n displayAporturi();\n displayCumuli();\n datatitlu.text(serverData.zi.Data);\n displayTotals();\n showHide(logoutButton, serverData.loggedin);\n countDataRows();\n}",
"function updateTable() {\r\n\tvar req = new XMLHttpRequest(); \r\n\tvar url = \"http://flip2.engr.oregonstate.edu:\" + port + \"/select-table\";\r\n\treq.open(\"GET\", url, false); \r\n\t\treq.addEventListener('load',function(){\r\n\t\t\t//If the request status is valid, update the table\r\n\t\t\tif(req.status >= 200 && req.status < 400){\r\n\t\t\t\t//Parse the JSON response\r\n\t\t\t\tvar response = JSON.parse(req.responseText); \r\n\t\t\t\t\r\n\t\t\t\t//Delete old table contents\r\n\t\t\t\tdeleteTableContents(\"workouts\");\r\n\t\t\t\t\r\n\t\t\t\t//Add new table contents;\r\n\t\t\t\taddTableContents(\"workouts\", response);\r\n\t\t\t} \r\n\t\t\t//If the request status isn't valid, display an error message with the request status\r\n\t\t\telse {\r\n\t\t\t\tconsole.log(\"Error in network request: \" + req.statusText);\r\n\t\t\t}});\t\r\n\treq.send(null); //no need to send additional data\r\n}",
"_updateOutput() {\n if (this.$output.length) {\n var html = '';\n var data = this.rrule.all(function(date, index) {\n return index < 15;\n });\n\n html += '<table><tbody>';\n data.forEach(function(item, index) {\n var parts = item.toString().split(' ');\n\n html += '<tr><td>' + (index + 1) + '</td>';\n\n parts.forEach(function(part) {\n html += '<td>' + part + '</td>';\n });\n\n html += '</tr>';\n })\n html += '</tbody></table>';\n\n this.$output.html(html);\n }\n }",
"function redrawSummaryTransTable()\n {\n document.getElementById(panelName + \"_TransSummaryTableModule\").innerHTML = transSummaryTable.toHTML();\n }",
"function showLeaderboardRefresh(){\n viewLeaderboard();\n if(leaderboard){\n document.getElementById(\"table\").innerHTML = leaderboard;\n } else {\n resetTable();\n }\n}",
"function renderWatchTable() {\n var watchingTbodyEl = $(\"#watching tbody\");\n watchingTbodyEl.text(\"\"); // Clear watching table\n\n if (watchList.length === 0) {\n // Show message in table body saying \"You're not currently watching any currencies.\"\n watchingTbodyEl.html(\n \"<tr class='table-empty-msg'><td>You're not currently watching any currencies.</td></tr>\");\n return;\n }\n\n // Show message saying \"updating watch list\"\n watchingTbodyEl.html(\n \"<tr class='table-empty-msg'><td>Updating prices...</td></tr>\");\n\n var symList = \"\";\n for (var i = 0; i < watchList.length; i++) {\n symList += watchList[i].symbol;\n if (i !== watchList.length-1) {\n symList += \",\"\n }\n }\n\n // Submit an API request to get the most recent price for all watched currencies and draw\n // table rows with these prices\n $.ajax({\n url: `https://min-api.cryptocompare.com/data/pricemulti?fsyms=${symList}&tsyms=USD`,\n method: \"GET\"\n }).then(function(response) {\n watchingTbodyEl.html(\"\");\n for (var i = 0; i < watchList.length; i++) {\n var newTableRow = $(\"<tr>\");\n var symbol = watchList[i].symbol;\n newTableRow.attr(\"data-crypto-id\", watchList[i].id);\n newTableRow.append($(\"<td>\").text(symbol), $(\"<td>\").text(watchList[i].name),\n $(\"<td>\").text(response[symbol].USD));\n watchingTbodyEl.append(newTableRow);\n }\n });\n\n watchingTbodyEl.click(function (event) {\n var target = $(event.target);\n if (target.prop(\"tagName\").toLowerCase() === \"td\") {\n showChartArea(event);\n }\n });\n }",
"function tableReset() {\n ipcRenderer.send('app:debug', \"Resetting whois result table\");\n $('#swTdDomain').attr('href', \"#\");\n $('#swTdDomain').text('n/a');\n\n $('#swTdUpdate').text('n/a');\n $('#swTdRegistrar').text('n/a');\n $('#swTdCreation').text('n/a');\n $('#swTdCompany').text('n/a');\n $('#swTdExpiry').text('n/a');\n}",
"function refreshCorpusTable() {\n $('#corpus-table').css('display', 'table-row');\n var inputExtension = $('[name=\"input-extension\"]').val();\n var outputExtension = $('[name=\"output-extension\"]').val();\n $.ajax({ url: '/?action=buildEngine&do=corpus-table&input-extension=' + inputExtension + '&output-extension=' + outputExtension,\n method: 'get',\n dataType: 'text',\n success: function(remoteData) {\n $(\"#corpus-table-content\").html(remoteData);\n refreshConfig();\n }});\n}",
"function refreshMainTable(data){\n document.getElementById(\"ap_name\").innerHTML = data.monitor_info.essid;\n document.getElementById(\"ap_usage\").innerHTML = \"⬆\"+getUsage(data)[0].toFixed(2)+\" ⬇\"+getUsage(data)[1].toFixed(2);\n document.getElementById(\"ap_mac\").innerHTML = data.monitor_info.mac;\n document.getElementById(\"ap_channel\").innerHTML = data.monitor_info.channel;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This static method is used exclusively to produce type signature objects for use by macro definitions in macrolib. Specifically, it lets us specify which clauses a macro expects its lambda to have. | TypeSignature(clauses) {
return { pattern: "lambda", innerType: Lambda, clauses };
} | [
"\"\"() {\n\t\t\tObject.keys(this).forEach((key) => {\n\t\t\t\tif (key) {\n\t\t\t\t\tlet fn = this[key][0];\n\t\t\t\t\tlet typeSignature = this[key][1];\n\t\t\t\t\t/*\n\t\t\t\t\t\tOf course, the mandatory first argument of all macro\n\t\t\t\t\t\tfunctions is section, so we have to convert the above\n\t\t\t\t\t\tto use a contract that's amenable to this requirement.\n\t\t\t\t\t*/\n\t\t\t\t\tMacros.add(key, (_, ...rest) => fn(...rest), typeSignature);\n\t\t\t\t}\n\t\t\t});\n\t\t}",
"static lambda(...parameterNames) {\n return CodeBlock.empty()\n .add('(%L) => {\\n', parameterNames.join(', '))\n .indent()\n .addTrailer(CodeBlock.empty()\n .unindent()\n .add('}'));\n }",
"function macro() {\n\t\tvar resolve = function (identifier) {\n\t\t\ttry { return eval(identifier); } catch (e) {}\n\t\t};\n\t\treturn function (closure) {\n\t\t\treturn mandox(closure, resolve);\n\t\t};\n\t}",
"function makeClosure(names, body, env) {\n // TODO step 1: use your own makeClosure here\n return {\n type: 'closure',\n num: closureCounter++,\n names: names,\n body: body,\n env: env,\n toString: function() {\n return \"Lambda\"\n }\n };\n }",
"function defineFunctionBuilders({\n type, htmlBuilder, mathmlBuilder,\n}) {\n defineFunction({\n type,\n names: [],\n props: {numArgs: 0},\n handler() { throw new Error('Should never be called.'); },\n htmlBuilder,\n mathmlBuilder,\n });\n}",
"function makeClosure(names, body, env) {\n return {\n names: names,\n body: body,\n type: 'closure',\n env: env,\n num: cCounter++,\n toString: function() {\n return \"Lambda\"\n }\n };\n }",
"function AnonymousTypes() {}",
"function defineFunctionBuilders({type, htmlBuilder, mathmlBuilder}) {\n defineFunction({type, names: [], props: {numArgs: 0},\n handler() { throw new Error('Should never be called.'); },htmlBuilder});\n}",
"function buildTypeFunction(buildModule, tlSchema) {\r\n const methodName = tlSchema.method\r\n // Start creating the body of the new Type function\r\n let body =\r\n '\\tvar self = arguments.callee;\\n' +\r\n '\\tvar callback = options.callback;\\n' +\r\n '\\tvar channel = options.channel;\\n' +\r\n '\\tif (!channel) {\\n' +\r\n '\\t\\tvar msg = \\'The \\\\\\'channel\\\\\\' option is missing, it\\\\\\'s mandatory\\';\\n' +\r\n '\\t\\tself.logger.error(msg);\\n' +\r\n '\\t\\tif(callback) {\\n' +\r\n '\\t\\t\\tcallback(new TypeError(msg));\\n' +\r\n '\\t\\t}\\n' +\r\n '\\t\\treturn;\\n' +\r\n '\\t}\\n'\r\n body +=\r\n '\\tvar reqPayload = new self.Type(options)\\n' +\r\n // '\\tdebugger\\n' +\r\n '\\tchannel.callMethod(reqPayload, callback)\\n'\r\n // '\\tchannel.request(reqPayload).then(e => callback(null, e), callback);\\n'\r\n logger.debug('Body for %s type function:', methodName)\r\n logger.debug(`\\n${ body}`)\r\n // Create the new Type function\r\n const typeFunction = new Function('options', body)\r\n typeFunction._name = methodName\r\n typeFunction.requireTypeFromBuffer = ConstructorBuilder.requireTypeFromBuffer\r\n // Create the function payload class re-calling TypeBuilder constructor.\r\n typeFunction.Type = new ConstructorBuilder(buildModule, tlSchema, true).getType()\r\n typeFunction.logger = getLogger(`${buildModule }.${ methodName}`)\r\n return typeFunction\r\n}",
"function spitMacros(){\n return _STAR_macros_STAR.length==0 ?\n \"{}\" :\n std.wrapStr(std.seq(_STAR_macros_STAR).map(function([k,v]){\n return [std.quoteStr(`${k}`), \":\", std.quoteStr(v)].join(\"\");\n }).join(\",\\n\"), \"{\\n\", \"}\\n\");\n }",
"function xformDef(defSym, lambdaEx)\n{\n return function (e) {\n\tvar op = e.getOp();\n\tvar args = e.getArgs();\n\tif (op === defSym) {\n\t args = e.getArgs();\n\t return applyLambda(lambdaEx, args);\n\t}\n\telse {\n\t return e;\n\t}\n };\n}",
"_compile_lambda(x, e, s, f, next) {\n if (x.length() < 3)\n throw new Scheme._Error(\"Invalid lambda: \" + x.to_write());\n var vars = x.cdr.car;\n var body = x.cdr.cdr;\n // Handle internal defines\n var tbody = Compiler.transform_internal_define(body);\n if (Scheme.isPair(tbody) && Scheme.isSymbol(tbody.car) &&\n tbody.car.name == \"letrec*\") {\n // The body has internal defines.\n // Expand letrec* macro\n var cbody = Scheme.Interpreter.expand(tbody);\n }\n else {\n // The body has no internal defines.\n // Just wrap the list with begin \n var cbody = new Scheme.Pair(Scheme.Sym(\"begin\"), x.cdr.cdr);\n }\n var dotpos = this.find_dot_pos(vars);\n var proper = this.dotted2proper(vars);\n var free = this.find_free(cbody, proper.to_set(), f); //free variables\n var sets = this.find_sets(cbody, proper.to_set()); //local variables\n var do_body = this.compile(cbody, [proper.to_set(), free], sets.set_union(s.set_intersect(free)), f.set_union(proper.to_set()), [\"return\"]);\n var do_close = [\"close\",\n free.size(),\n this.make_boxes(sets, proper, do_body),\n next,\n dotpos];\n return this.collect_free(free, e, do_close);\n }",
"function defineFunctionBuilders(_ref2) {\n var {\n type,\n htmlBuilder,\n mathmlBuilder\n } = _ref2;\n defineFunction({\n type,\n names: [],\n props: {\n numArgs: 0\n },\n\n handler() {\n throw new Error('Should never be called.');\n },\n\n htmlBuilder,\n mathmlBuilder\n });\n}",
"function defineFunctionBuilders(_ref2){let type=_ref2.type,htmlBuilder=_ref2.htmlBuilder,mathmlBuilder=_ref2.mathmlBuilder;defineFunction({type,names:[],props:{numArgs:0},handler(){throw new Error('Should never be called.');},htmlBuilder,mathmlBuilder});}// Since the corresponding buildHTML/buildMathML function expects a",
"static lambda(parameters = new Map(), returnType) {\n return new Lambda(parameters, returnType);\n }",
"static lambda2(parameters = [], returnType) {\n return new Lambda(new Map(parameters), returnType);\n }",
"function shouldAddParamTypesMetadata(node){switch(node.kind){case 245/* ClassDeclaration */:case 214/* ClassExpression */:return ts.getFirstConstructorWithBody(node)!==undefined;case 161/* MethodDeclaration */:case 163/* GetAccessor */:case 164/* SetAccessor */:return true;}return false;}",
"function emitLambda(parameters, body) {\n\t\t\tvar code = ['function(', parameters.join(', '), ') {'];\n\t\t\t\n\t\t\tvar withOpen = [];\n\t\t\tvar withClose = [];\n\t\t\tvar resolveStack = [];\n\t\t\t\n\t\t\t// If any of the parameters of the lambda expression is a \n\t\t\t// transparent identifier, put a with statement around the\n\t\t\t// body of the lambda so that its members are in scope. Do this\n\t\t\t// \"recursively\" if necessary.\n\t\t\tfor (var i = 0; i < parameters.length; i++) {\n\t\t\t\tif (isTransparentIdentifier(parameters[i])) {\n\t\t\t\t\tresolveStack.push(parameters[i]);\n\t\t\t\t\tdo {\n\t\t\t\t\t\tvar topOfStack = resolveStack.pop();\n\t\t\t\t\t\twithOpen.push('with (', topOfStack, ') {');\n\t\t\t\t\t\twithClose.push('}');\n\t\t\t\t\t\tvar child = transparentIdentifiers[topOfStack];\n\t\t\t\t\t\tif (transparentIdentifiers[topOfStack].length > 0) {\n\t\t\t\t\t\t\tresolveStack.push(child[0]);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t} while (true);\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tcode = code.concat(withOpen);\n\t\t\tcode.push(body);\n\t\t\tcode = code.concat(withClose);\t\t\t\n\t\t\tcode.push('}');\n\t\t\treturn code.join('');\n\t\t}",
"function TypedLambdaVisitor() {\n antlr4.tree.ParseTreeVisitor.call(this);\n return this;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine whether the given properties match those of a `ProvisionedThroughputProperty` | function CfnSimpleTable_ProvisionedThroughputPropertyValidator(properties) {
if (!cdk.canInspect(properties)) {
return cdk.VALIDATION_SUCCESS;
}
const errors = new cdk.ValidationResults();
errors.collect(cdk.propertyValidator('readCapacityUnits', cdk.validateNumber)(properties.readCapacityUnits));
errors.collect(cdk.propertyValidator('writeCapacityUnits', cdk.requiredValidator)(properties.writeCapacityUnits));
errors.collect(cdk.propertyValidator('writeCapacityUnits', cdk.validateNumber)(properties.writeCapacityUnits));
return errors.wrap('supplied properties not correct for "ProvisionedThroughputProperty"');
} | [
"function CfnTable_ProvisionedThroughputPropertyValidator(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('readCapacityUnits', cdk.requiredValidator)(properties.readCapacityUnits));\n errors.collect(cdk.propertyValidator('readCapacityUnits', cdk.validateNumber)(properties.readCapacityUnits));\n errors.collect(cdk.propertyValidator('writeCapacityUnits', cdk.requiredValidator)(properties.writeCapacityUnits));\n errors.collect(cdk.propertyValidator('writeCapacityUnits', cdk.validateNumber)(properties.writeCapacityUnits));\n return errors.wrap('supplied properties not correct for \"ProvisionedThroughputProperty\"');\n}",
"function TableResource_ProvisionedThroughputPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n errors.collect(cdk.propertyValidator('readCapacityUnits', cdk.requiredValidator)(properties.readCapacityUnits));\n errors.collect(cdk.propertyValidator('readCapacityUnits', cdk.validateNumber)(properties.readCapacityUnits));\n errors.collect(cdk.propertyValidator('writeCapacityUnits', cdk.requiredValidator)(properties.writeCapacityUnits));\n errors.collect(cdk.propertyValidator('writeCapacityUnits', cdk.validateNumber)(properties.writeCapacityUnits));\n return errors.wrap('supplied properties not correct for \"ProvisionedThroughputProperty\"');\n }",
"function CfnSimpleTable_ProvisionedThroughputPropertyValidator(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('readCapacityUnits', cdk.validateNumber)(properties.readCapacityUnits));\n errors.collect(cdk.propertyValidator('writeCapacityUnits', cdk.requiredValidator)(properties.writeCapacityUnits));\n errors.collect(cdk.propertyValidator('writeCapacityUnits', cdk.validateNumber)(properties.writeCapacityUnits));\n return errors.wrap('supplied properties not correct for \"ProvisionedThroughputProperty\"');\n}",
"function CfnTable_ProvisionedThroughputPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n errors.collect(cdk.propertyValidator('readCapacityUnits', cdk.requiredValidator)(properties.readCapacityUnits));\n errors.collect(cdk.propertyValidator('readCapacityUnits', cdk.validateNumber)(properties.readCapacityUnits));\n errors.collect(cdk.propertyValidator('writeCapacityUnits', cdk.requiredValidator)(properties.writeCapacityUnits));\n errors.collect(cdk.propertyValidator('writeCapacityUnits', cdk.validateNumber)(properties.writeCapacityUnits));\n return errors.wrap('supplied properties not correct for \"ProvisionedThroughputProperty\"');\n}",
"hasProperty(aProperty){\n for(let i = 0; i < this._properties.length; i++){\n let prop = this._properties[i];\n if(aProperty.matches(prop)){\n return true;\n }\n }\n return false;\n }",
"function CfnGlobalTable_WriteProvisionedThroughputSettingsPropertyValidator(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('writeCapacityAutoScalingSettings', CfnGlobalTable_CapacityAutoScalingSettingsPropertyValidator)(properties.writeCapacityAutoScalingSettings));\n return errors.wrap('supplied properties not correct for \"WriteProvisionedThroughputSettingsProperty\"');\n}",
"function CfnGlobalTable_ReadProvisionedThroughputSettingsPropertyValidator(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('readCapacityAutoScalingSettings', CfnGlobalTable_CapacityAutoScalingSettingsPropertyValidator)(properties.readCapacityAutoScalingSettings));\n errors.collect(cdk.propertyValidator('readCapacityUnits', cdk.validateNumber)(properties.readCapacityUnits));\n return errors.wrap('supplied properties not correct for \"ReadProvisionedThroughputSettingsProperty\"');\n}",
"function hasProperties(actual, expected) {\n for (var k in expected) {\n var v = expected[k];\n if (!(k in actual))\n return false;\n if (Object(v) === v) {\n if (!hasProperties(actual[k], v))\n return false;\n } else {\n if (actual[k] !== v)\n return false;\n }\n }\n return true;\n}",
"has(target,prop){\n return ['age','name','job'].includes(prop);\n }",
"function validateProperties(props) {\n let validProps = getProperties();\n for (let i in props) {\n if (!validProps.includes(props[i])) {\n return false;\n }\n }\n return true;\n}",
"function tableResourceProvisionedThroughputPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n TableResource_ProvisionedThroughputPropertyValidator(properties).assertSuccess();\n return {\n ReadCapacityUnits: cdk.numberToCloudFormation(properties.readCapacityUnits),\n WriteCapacityUnits: cdk.numberToCloudFormation(properties.writeCapacityUnits),\n };\n }",
"function containsAllowedProps(properties) {\n if (properties === null || (typeof properties === 'undefined' ? 'undefined' : _typeof(properties)) !== 'object') {\n return false;\n }\n return Object.entries(properties).some(function (property) {\n var key = property[0];\n var value = property[1];\n if (typeof value === 'string') {\n return key === 'style' || key === 'src' || key === 'href';\n } else if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && key === 'attributes') {\n return 'class' in properties.attributes;\n }\n });\n}",
"shouldUpdate(changedProperties) {\n changedProperties.forEach((oldValue, propName) => {\n console.log(`${propName} changed. oldValue: ${oldValue}`);\n });\n return changedProperties.has('prop1');\n }",
"function checkSameProps(properties, qParams, model) {\n var result = INCLUDE;\n\n _.each(properties, function(property) {\n if (_.has(qParams, property) && qParams[property] !== model.get(property)) {\n result = EXCLUDE;\n }\n });\n\n return result;\n }",
"function propertiesEquals(objA, objB, properties) {\n var i, property;\n\n for (i = 0; i < properties.length; i++) {\n property = properties[i];\n\n if (!equals(objA[property], objB[property])) {\n return false;\n }\n }\n\n return true;\n}",
"function check_properties(search_specs, possible_keys) {\n for (let spec in search_specs) {\n if (!possible_keys.includes(spec)) {\n throw [`no property '${spec}' for given type`];\n }\n }\n}",
"function CfnRule_MatchPropertyValidator(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('httpMatch', cdk.requiredValidator)(properties.httpMatch));\n errors.collect(cdk.propertyValidator('httpMatch', CfnRule_HttpMatchPropertyValidator)(properties.httpMatch));\n return errors.wrap('supplied properties not correct for \"MatchProperty\"');\n}",
"function cfnTableProvisionedThroughputPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnTable_ProvisionedThroughputPropertyValidator(properties).assertSuccess();\n return {\n ReadCapacityUnits: cdk.numberToCloudFormation(properties.readCapacityUnits),\n WriteCapacityUnits: cdk.numberToCloudFormation(properties.writeCapacityUnits),\n };\n}",
"function TermIs(term, listOfProperties) {\n\tvar hits = 0;\n\n\tfor (var i = 0; i < listOfProperties.length; i++) {\n\t\tif (term.pos.hasOwnProperty(listOfProperties[i]))\n\t\t\thits++;\n\t}\n\n\tif (hits === listOfProperties.length)\n\t\treturn true;\n\n\treturn false;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates the lookup items. Items must be an array which has a length property. The item must be an object with the following properties. Name Path AllowNavigation | function createLookupItems(items) {
var TMPL_UL = '<ul class="ds-nav-lu-results-ul">';
var TMPL_BACK_ITEM = '<li class="ds-nav-lu-results-li"> <strong class="ds-nav-lu-results-li-item"><a href="#" class="ds-nav-lu-results-li-item-back"> <i class="fa fa-level-up"></i> </a></strong></li>';
var TMPL_ITEM = '<li class="ds-nav-lu-results-li"> <i class="fa fa-folder ds-nav-lu-results-li-item-foldericon"></i> <a href="#" class="ds-nav-lu-results-li-item-name" data-children="{Count}" data-path="{Path}">{NAME}</a></li>';
var TMPL_NAV = '<strong class="ds-nav-lu-results-li-item"><a href="#" class="ds-nav-lu-results-li-item-navigate"> <i class="fa fa-chevron-circle-right"></i> </a></strong>';
var ul = $(TMPL_UL);
//Create the back button
var li_back = $(TMPL_BACK_ITEM);
//Append it
$(ul).append(li_back);
for (var i = 0 ; i < items.length; i++) {
var item = items[i];
var _path = item.Path;
var _name = item.Name;
var _allowNavigation = item.AllowNavigation;
//Create the list item
var li_item = $(TMPL_ITEM.replace("{Count}", items.length).replace("{Path}", _path).replace("{NAME}", _name));
if (_allowNavigation == true) {
//create the navigation
var li_nav = $(TMPL_NAV);
//append it to the li
$(li_item).append(li_nav);
}
//Append the li_item to the ul
$(ul).append(li_item);
}
return $(ul);
} | [
"setupItems() {\n\t\tthis.items = {};\n\t\tObject.keys(ITEMS.default).forEach((item) => {\n\t\t\tthis.items[item] = new Item(ITEMS.default[item]);\n\t\t});\n\t}",
"function createSelectDataLookupObj(items) {\n\n var lookupObj = {};\n\n for (var i = items.length; i--;) {\n var type = items[i];\n lookupObj[type.Value] = type.Label;\n }\n\n return lookupObj;\n }",
"function buildItems() {\n itemMap = new ItemMap();\n}",
"function createItem(item) {\n\tvar location = item.location;\n\n\tvar options = {};\n\n\tbsService.loadMetadata(location, options, function itemData(err, metadataAndMetametaData){\n\t\t//To make metadata easier to use via js, first unwrap it (it's initially wrapped for cross-compatibility with C#)\n\t\tvar unwrappedMetadata = BSUtils.unwrap(metadataAndMetametaData.metadata);\n\t\tvar itemDetails = unwrappedMetadata;\n\n\t\ttry {\n\t\t\tvar product = new laptop(itemDetails);\n\t\t\tappendLaptop(product);\t// Adds product to view\n\t\t\tsessionStorage.setItem('working_items', JSON.stringify([...working_items])); // Store for the session so we don't lose it as user changes pages\n\t\t}\n\t\tcatch(e){\n\t\t\tconsole.log(e.stack);\n\t\t}\n\t});\n}",
"function createNavigationItem(){\n\tORACLE_SERVICE_CLOUD.extension_loader.load(appName , appVersion).then(function(extensionProvider){\n\t\textensionProvider.registerUserInterfaceExtension(function(IUserInterfaceContext){\n\t\t\tIUserInterfaceContext.getNavigationSetContext().then(function(INavigationSetContext){\n\t\t\t\t//From Navigation Set Context the code can get an existing Id. we are not using an existing id in this sample code.\n\t\t\t\tINavigationSetContext.getNavigationItem('id').then(function(INavigationItem){\n\t\t\t\t\t\n\t\t\t\t\t//Setting a label for the parent item.\n\t\t\t\t\tINavigationItem.setLabel(navigationItemLabel);\n\n\t\t\t\t\t//Creating a child item.\n\t\t\t\t\tvar childNavigationItem1 = INavigationItem.createChildItem();\n\n\t\t\t\t\t//Setting a label to the child item.\n\t\t\t\t\tchildNavigationItem1.setLabel(childLabel);\n\n\t\t\t\t\t//Handling an action to call the popup function that is defined later in this code.\n\t\t\t\t\tchildNavigationItem1.setHandler(function(INavigationItem)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tMyPopUp();\t\t\t\t\t\t\t\n\t\t\t\t\t\t});\n\n\t\t\t\t\t//Don't forget to add the child to the parent item created early in this code.\n\t\t\t\t\tINavigationItem.addChildItem(childNavigationItem1);\n\t\t\t\t\tINavigationItem.render();\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t});\n\t\t});\n}",
"function setupItems()\n{\n itemGloves = new Item(\"Gloves\", gloves);\n itemArray.push(itemGloves);\n itemRedHerring = new Item(\"Red Herring\", redherring);\n itemArray.push(itemRedHerring);\n itemFlowers = new Item(\"Flowers\", null);\n itemArray.push(itemFlowers);\n itemPerfume = new Item(\"Perfume\", null);\n itemArray.push(itemPerfume);\n itemBroom = new Item(\"Broom\", null);\n itemArray.push(itemBroom);\n itemWand = new Item(\"Magic Wand\", null);\n itemArray.push(itemWand);\n}",
"function createLinkDetailItems() {\n MobileCRM.UI.EntityForm.requestObject(function (entityForm) {\n /// Get detail view with name 'Custom Items'\n var detailView = entityForm.getDetailView(\"Items\");\n if (detailView) {\n // if items with name 'linkHrefItem' and 'linkRefItem' exist, remove them\n var ind1 = detailView.getItemIndex(\"linkHrefItem\");\n if (ind1 && ind1 > -1) {\n detailView.removeItem(ind1);\n var linkHrefItem = new MobileCRM.UI.DetailViewItems.LinkItem();\n linkHrefItem.name = \"linkHrefItem\";\n linkHrefItem.label = \"Web\";\n linkHrefItem.value = \"Google\";\n // Handle click on this link item and open google page outside of application in default browser.\n detailView.registerClickHandler(linkHrefItem, function (itemName) {\n if (itemName === linkHrefItem.name)\n MobileCRM.Platform.openUrl(\"http://wwww.google.com\");\n });\n detailView.insertItem(linkHrefItem, -1);\n }\n var ind2 = detailView.getItemIndex(\"linkRefItem\");\n if (ind2 && ind2 > -1) {\n detailView.removeItem(ind2);\n var linkRefItem = new MobileCRM.UI.DetailViewItems.LinkItem();\n linkRefItem.name = \"linkRefItem\";\n linkRefItem.label = \"Reference\";\n // Set value to null or any valid MobileCRM.Reference object\n // If value is 'null' reference, then displayed value is 'Click To Select...'\n // Otherwise 'primaryName' of MobileCRM.Reference will be displayed.\n linkRefItem.value = undefined; // new MobileCRM.Reference(null, null, null);\n detailView.registerClickHandler(linkRefItem, function (itemName, detailView) {\n if (itemName === linkRefItem.name) {\n MobileCRM.bridge.alert(\"You clicked on \" + itemName);\n /// HINTS: Here you can implement own custom logic similar to lookup, or open record using reference\n var refValue = linkRefItem.value;\n if (refValue)\n MobileCRM.UI.FormManager.showEditDialog(refValue.entityName, refValue.id);\n }\n });\n detailView.insertItem(linkRefItem, -1);\n }\n }\n else\n MobileCRM.bridge.alert(\"View 'Items' is not defined\");\n }, MobileCRM.bridge.alert, null);\n}",
"function createItem() {\n vm.learningPath = datacontext.createLearningItem();\n }",
"function assignLookup() {\n var count = 0;\n vm.customPropertyList.forEach(function(val) {\n if (val.PropertyType == 2) {\n val.lookupList = lookupArray[count];\n count++;\n }\n })\n }",
"function generatePrimaryNav(label, url, items = false) {\n // Create listItem element\n var listItem = document.createElement('Li');\n\n // console.log(items);\n\n // TODO: do this in for loop? Maybe have function that takes properties object and adds all of them.\n // Could then be used for primary and submenu items\n listItem.setAttribute('class', 'navitem primary');\n listItem.setAttribute('role', 'menuitem');\n listItem.setAttribute('tabindex', '0');\n\n var a = document.createElement('a');\n a.setAttribute('href', url);\n a.appendChild(document.createTextNode(label));\n\n listItem.appendChild(a);\n\n\n // console.log('new listItem: ' + listItem);\n\n // If there are submenu items, generate the html for that and add it to listItem\n if (items && items.length > 0) {\n\n // Add the aria-haspopup class to the primary listItem\n listItem.setAttribute('aria-haspopup', true);\n\n // Generate image element for chevron\n var chevron = document.createElement('img');\n chevron.setAttribute('src', '../images/chevron.svg');\n chevron.setAttribute('class', 'chevron');\n chevron.setAttribute('alt', 'chevron');\n\n // Add chevron to list item\n listItem.appendChild(chevron);\n\n // Generate the submenu ul element and append it to the primary listItem\n listItem.appendChild(returnSubNav(items));\n }\n\n // console.log(listItem);\n return listItem;\n}",
"@wire(getNavigationMenuItems, { \n menuName: '$menuName',\n publishedState: '$publishedState'\n })\n wiredMenuItems({error, data}) {\n if (data && !this.isLoaded) {\n this.menuItems = data.map((item, index) => {\n return {\n target: item.Target,\n id: index,\n label: item.Label,\n defaultListViewId: item.DefaultListViewId,\n type: item.Type,\n accessRestriction: item.AccessRestriction\n }\n }).filter(item => {\n // Only show \"Public\" items if guest user\n return item.accessRestriction === \"None\"\n || (item.accessRestriction === \"LoginRequired\" && !isGuestUser);\n });\n this.error = undefined;\n this.isLoaded = true;\n } else if (error) {\n this.error = error;\n this.menuItems = [];\n this.isLoaded = true;\n console.log(`Navigation menu error: ${JSON.stringify(this.error)}`);\n }\n }",
"initItem(item) {\n if (!item || typeof(item)!==\"object\") item = {};\n return item;\n }",
"constructor(_items = []) {\n this._items = _items;\n }",
"function mkItems() {\n var ht = {};\n var truth = function() { return true; };\n\n var self = {\n lookup: function(keys, cb) {\n if (typeof(keys) == 'string') {\n keys = [keys];\n }\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n if (cb(key, ht[key]) == false) {\n break;\n }\n }\n\n cb(null);\n },\n update: function(k, cb) {\n ht[k] = cb(k, ht[k]);\n cb(null);\n },\n remove: function(k, cb) {\n var prev = ht[k];\n delete ht[k];\n cb(k, prev);\n cb(null);\n },\n reset: function(cb) { ht = {}; cb(null); },\n range: function(startKey,\n startInclusion,\n endKey,\n endInclusion,\n cb) {\n var startPredicate =\n startKey ?\n (startInclusion ?\n (function(k) { return k >= startKey }) :\n (function(k) { return k > startKey })) :\n truth;\n\n var endPredicate =\n endKey ?\n (endInclusion ?\n (function(k) { return k <= endKey }) :\n (function(k) { return k < endKey })) :\n truth;\n\n for (var k in ht) {\n if (startPredicate(k) && endPredicate(k)) {\n if (cb(k, ht[k]) == false) {\n break;\n }\n }\n }\n\n cb(null);\n }\n };\n\n return self;\n}",
"function createItem(item, position) {}",
"getItems(callback){\n if(Object.keys(this.items).length != this.item.length){\n for (let item of Object.keys(this.item)) {\n ItemModelManage.getInstance().getItem((itemModel) => {\n this.items[item] = itemModel\n \n if(Object.keys(this.items).length == Object.keys(this.item).length){\n \n callback(this.items)\n }\n\n }, this.item[item])\n }\n }else{\n callback(this.items)\n }\n }",
"function parseNavItem (item) {\n if (item.route === req.path) {\n item.isActive = true;\n }\n\n // replace object by array structure\n var childArray = [];\n for (var child in item.children) {\n var subItem = parseNavItem( item.children[ child ] );\n if (subItem.isActive || subItem.hasActiveChildren) {\n item.hasActiveChildren = true;\n }\n // check if user can access item\n if (userHasAccess(subItem)) {\n childArray.push(subItem);\n }\n }\n // sort by _w\n childArray.sort(function (a, b) { return a._w - b._w });\n item.children = childArray;\n\n return item;\n }",
"function initItems() {\n if (angular.isDefined($scope.items)) {\n self.fields.items = angular.copy($scope.items);\n } else {\n self.fields.items = angular.copy($scope.itemsGetter({param: self.fields.event.refresh.value}));\n }\n self.fields.initialItems = angular.copy(self.fields.items);\n\n if (self.fields.debug) {\n $log.debug(self.fields.name + \" itAutocomplete: copy option items \" + self.fields.initialItems);\n }\n }",
"build_paths() {\n return {\n items: {\n list: { // Returns a list of items\n method: \"GET\",\n path: \"items\", \n }, \n item: { // Returns a single item with ID %%\n method: \"GET\",\n path: \"items/%%\"\n }, \n item_metadata: { // Returns metadata for item %%\n method: \"GET\",\n path: \"items/%%/metadata\", \n }, \n item_bitstreams: { // Returns available bitstreams for item %%\n method: \"GET\",\n path: \"items/%%/bitstreams\" \n },\n find_by_metadata: { // Returns items based on specified metadata value\n method: \"POST\",\n path: \"items/find-by-metadata-field\"\n } \n },\n query: { \n filtered_items: { // Returns items based on chosen filters\n method: \"GET\",\n path: \"filtered-items\", \n }, \n filtered_collections: { // Returns collections based on chosen filters\n method: \"GET\",\n path: \"filtered-collections\",\n }, \n collection: { // Returns collection with ID %%\n method: \"GET\",\n path: \"filtered-collections/%%\",\n } \n },\n bitstreams: { \n list: { // Returns all bitstreams in DSpace\n method: \"GET\",\n path: \"bitsreams\"\n },\n item: { // Returns an item with bitstream ID %%\n method: \"GET\",\n path: \"bitstreams/{%%}\"\n },\n item_policy: { // Returns the policy for a bitstream with ID %%\n method: \"GET\",\n path: \"bitstreams/%%/policy\"\n },\n content: { // Retrieve content for a bitstream with ID %%\n method: \"GET\",\n path: \"bitstreams/%%/retrieve\"\n }\n },\n schemas: {\n list: { // Returns a list of all schemas\n method: \"GET\",\n path: \"registries/schema\"\n },\n item: { // Returns a metadata schema with schema prefix %%\n method: \"GET\",\n path: \"registries/schema/%%\"\n },\n field: { // Returns a metadata schema with field ID %%\n method: \"GET\",\n path: \"registries/metadata-fields/%%\"\n }\n }\n };\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Match tags in token stream starting at `i` with `pattern`. `pattern` may consist of strings (equality), an array of strings (one of) or null (wildcard). Returns the index of the match or 1 if no match. | indexOfTag(i, ...pattern) {
var fuzz, j, k, ref, ref1;
fuzz = 0;
for (j = k = 0, ref = pattern.length; (0 <= ref ? k < ref : k > ref); j = 0 <= ref ? ++k : --k) {
if (pattern[j] == null) {
continue;
}
if (typeof pattern[j] === 'string') {
pattern[j] = [pattern[j]];
}
if (ref1 = this.tag(i + j + fuzz), indexOf.call(pattern[j], ref1) < 0) {
return -1;
}
}
return i + j + fuzz - 1;
} | [
"indexOfTag(i, ...pattern) {\n var fuzz, j, k, ref, ref1;\n fuzz = 0;\n for (j = k = 0, ref = pattern.length; (0 <= ref ? k < ref : k > ref); j = 0 <= ref ? ++k : --k) {\n if (pattern[j] == null) {\n continue;\n }\n if (typeof pattern[j] === 'string') {\n pattern[j] = [pattern[j]];\n }\n if (ref1 = this.tag(i + j + fuzz), indexOf.call(pattern[j], ref1) < 0) {\n return -1;\n }\n }\n return i + j + fuzz - 1;\n }",
"function match(text, re, i) {\n\tif (i === undefined) { i = 1; }\n\tlet m = text.match(re);\n\treturn (m != null && m.length > i) ? m[i] : null;\n}",
"function findTagMatchIndices(markup) {\n\t\tlet indices = [];\n\t\tlet offset = 0;\n\t\tlet index;\n\t\twhile (markup.search(TAG_REGEX) != -1) {\n\t\t\tindex = markup.search(TAG_REGEX);\n\t\t\toffset += index+1;\n\t\t\tindices.push(offset-1);\n\t\t\tmarkup = markup.substring(index+1, markup.length);\n\t\t}\n\t\treturn indices;\n\t}",
"tag(i) {\n var ref;\n return (ref = this.tokens[i]) != null ? ref[0] : void 0;\n }",
"tag(i) {\r\n\t\t\t\t\tvar ref;\r\n\t\t\t\t\treturn (ref = this.tokens[i]) != null ? ref[0] : void 0;\r\n\t\t\t\t}",
"function _matchArray(\n parseContext,\n matchArray\n )\n{\n for (var i = 0; i < matchArray.length; i++)\n {\n if (_matchText(parseContext, matchArray[i]))\n {\n return i;\n }\n }\n \n // no match\n return null;\n}",
"match_regex(pattern) {\n const match = pattern.exec(this.template.slice(this.index));\n if (!match || match.index !== 0)\n return null;\n return match[0];\n }",
"function getPatternIdx(name){\n let idx = -1\n for(let i = 0; i < patternNames.length; i++){\n let patternName = patternNames[i]\n\n if(patternName === name){\n idx = i\n }\n }\n return idx\n}",
"match(pattern, start) {\n pattern.lastIndex = start;\n const raw = pattern.exec(this.str);\n if (raw !== null) {\n this.matchEnd = pattern.lastIndex;\n return raw[0];\n }\n return null;\n }",
"function dictIndexOf(dictionary, pattern) {\n\tfor (let i = 0; i < dictionary.length; i++) {\n\t\tlet entry = dictionary[i];\n\t\tif (arrayEquals(entry, pattern)) {\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn -1;\n}",
"function stringPatternSearch(text, pattern) {\n let count = 0\n for (let i = 0; i <= text.length - pattern.length; i++) {\n if (text.substring(i, i + pattern.length) === pattern) { \n count++\n }\n }\n\n return count\n}",
"function RVLMatchPattern(/*string*/str, /**string*/pattern)\r\n{\r\n\tvar lastParams = RVL.LastParams;\r\n\treturn MatchPattern(str, pattern, lastParams);\r\n}",
"function getMatchingOpeningToken(tokens, i) {\n if (tokens[i].type === \"softbreak\") {\n return false;\n }\n // non closing blocks, example img\n if (tokens[i].nesting === 0) {\n return tokens[i];\n }\n const level = tokens[i].level;\n const type = tokens[i].type.replace(\"_close\", \"_open\");\n for (;i >= 0; --i) {\n if (tokens[i].type === type && tokens[i].level === level) {\n return tokens[i];\n }\n }\n return false;\n }",
"function matches (string, pattern) {\n if (string . length == 0 || pattern . length == 0) {\n return 0\n }\n let count = matches (string . substring (1), pattern);\n if (string . substring (0, 1) == pattern . substring (0, 1)) {\n if (pattern . length == 1) {\n count ++\n }\n else {\n count += matches (string . substring (1), pattern . substring (1))\n }\n }\n return count\n}",
"function stringPatternSearch(text, pattern) {\n \"use strict\";\n let string = \"\";\n let patternCount = 0;\n\n for (let i = 0; i < text.length; i++) {\n string += text[i];\n if (pattern === string) {\n patternCount++;\n string = \"\";\n string = text[i];\n }\n }\n\n return patternCount;\n}",
"function match(test, reg, i){\n if(typeof reg == 'string'){\n reg = new RegExp(reg, i)\n }\n \n ok(test.match(reg) != null, \"Expected to match \"+reg)\n \n}",
"function stringPatternSearch(text, pattern) {\n count =0;\n for(let i=0; i<text.length; i++){\n for(let j=0; j<pattern.length; j++){\n const patternChar= pattern[j]\n if(patternChar !== text[i+j]){\n break;\n }\n\n if(j === pattern.length-1){\n count ++\n }\n }\n }\n return count\n}",
"function scan_charEqAny(text, bx, pattern )\n{\n let ix = bx;\n let found_char = '';\n let found_index = -1;\n while (ix < text.length)\n {\n const ch1 = text.substr(ix, 1);\n const fx = pattern.indexOf(ch1);\n if (fx >= 0)\n {\n found_index = ix;\n found_char = ch1;\n break;\n }\n ix += 1;\n }\n return { found_index, found_char };\n}",
"function regexIndexes(regex, token) {\n var indexes = [],\n match, tokenLength = token.length\n\n while ((match = regex.exec(token)) != null) {\n indexes.push({\n obj: match[0],\n index: match.index,\n lastIndex: tokenLength - match.index - 1\n })\n }\n return indexes\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The LookupSupportedLocales abstract operation returns the subset of the provided BCP 47 language priority list requestedLocales for which availableLocales has a matching locale when using the BCP 47 Lookup algorithm. Locales appear in the same order in the returned list as in requestedLocales. The following steps are taken: | function /* 9.2.6 */LookupSupportedLocales (availableLocales, requestedLocales) {
var
// 1. Let len be the number of elements in requestedLocales.
len = requestedLocales.length,
// 2. Let subset be a new empty List.
subset = new List(),
// 3. Let k be 0.
k = 0;
// 4. Repeat while k < len
while (k < len) {
var
// a. Let locale be the element of requestedLocales at 0-origined list
// position k.
locale = requestedLocales[k],
// b. Let noExtensionsLocale be the String value that is locale with all
// Unicode locale extension sequences removed.
noExtensionsLocale = String(locale).replace(expUnicodeExSeq, ''),
// c. Let availableLocale be the result of calling the
// BestAvailableLocale abstract operation (defined in 9.2.2) with
// arguments availableLocales and noExtensionsLocale.
availableLocale = BestAvailableLocale(availableLocales, noExtensionsLocale);
// d. If availableLocale is not undefined, then append locale to the end of
// subset.
if (availableLocale !== undefined)
arrPush.call(subset, locale);
// e. Increment k by 1.
k++;
}
var
// 5. Let subsetArray be a new Array object whose elements are the same
// values in the same order as the elements of subset.
subsetArray = arrSlice.call(subset);
// 6. Return subsetArray.
return subsetArray;
} | [
"function /* 9.2.6 */LookupSupportedLocales (availableLocales, requestedLocales) {\n\t var\n\t // 1. Let len be the number of elements in requestedLocales.\n\t len = requestedLocales.length,\n\t // 2. Let subset be a new empty List.\n\t subset = new List(),\n\t // 3. Let k be 0.\n\t k = 0;\n\t\n\t // 4. Repeat while k < len\n\t while (k < len) {\n\t var\n\t // a. Let locale be the element of requestedLocales at 0-origined list\n\t // position k.\n\t locale = requestedLocales[k],\n\t // b. Let noExtensionsLocale be the String value that is locale with all\n\t // Unicode locale extension sequences removed.\n\t noExtensionsLocale = String(locale).replace(expUnicodeExSeq, ''),\n\t // c. Let availableLocale be the result of calling the\n\t // BestAvailableLocale abstract operation (defined in 9.2.2) with\n\t // arguments availableLocales and noExtensionsLocale.\n\t availableLocale = BestAvailableLocale(availableLocales, noExtensionsLocale);\n\t\n\t // d. If availableLocale is not undefined, then append locale to the end of\n\t // subset.\n\t if (availableLocale !== undefined)\n\t arrPush.call(subset, locale);\n\t\n\t // e. Increment k by 1.\n\t k++;\n\t }\n\t\n\t var\n\t // 5. Let subsetArray be a new Array object whose elements are the same\n\t // values in the same order as the elements of subset.\n\t subsetArray = arrSlice.call(subset);\n\t\n\t // 6. Return subsetArray.\n\t return subsetArray;\n\t}",
"function /* 9.2.6 */LookupSupportedLocales(availableLocales, requestedLocales) {\n\t // 1. Let len be the number of elements in requestedLocales.\n\t var len = requestedLocales.length;\n\t // 2. Let subset be a new empty List.\n\t var subset = new List();\n\t // 3. Let k be 0.\n\t var k = 0;\n\t\n\t // 4. Repeat while k < len\n\t while (k < len) {\n\t // a. Let locale be the element of requestedLocales at 0-origined list\n\t // position k.\n\t var locale = requestedLocales[k];\n\t // b. Let noExtensionsLocale be the String value that is locale with all\n\t // Unicode locale extension sequences removed.\n\t var noExtensionsLocale = String(locale).replace(expUnicodeExSeq, '');\n\t // c. Let availableLocale be the result of calling the\n\t // BestAvailableLocale abstract operation (defined in 9.2.2) with\n\t // arguments availableLocales and noExtensionsLocale.\n\t var availableLocale = BestAvailableLocale(availableLocales, noExtensionsLocale);\n\t\n\t // d. If availableLocale is not undefined, then append locale to the end of\n\t // subset.\n\t if (availableLocale !== undefined) arrPush.call(subset, locale);\n\t\n\t // e. Increment k by 1.\n\t k++;\n\t }\n\t\n\t // 5. Let subsetArray be a new Array object whose elements are the same\n\t // values in the same order as the elements of subset.\n\t var subsetArray = arrSlice.call(subset);\n\t\n\t // 6. Return subsetArray.\n\t return subsetArray;\n\t}",
"function /* 9.2.6 */LookupSupportedLocales(availableLocales, requestedLocales) {\n // 1. Let len be the number of elements in requestedLocales.\n var len = requestedLocales.length;\n // 2. Let subset be a new empty List.\n var subset = new List();\n // 3. Let k be 0.\n var k = 0;\n\n // 4. Repeat while k < len\n while (k < len) {\n // a. Let locale be the element of requestedLocales at 0-origined list\n // position k.\n var locale = requestedLocales[k];\n // b. Let noExtensionsLocale be the String value that is locale with all\n // Unicode locale extension sequences removed.\n var noExtensionsLocale = String(locale).replace(expUnicodeExSeq, '');\n // c. Let availableLocale be the result of calling the\n // BestAvailableLocale abstract operation (defined in 9.2.2) with\n // arguments availableLocales and noExtensionsLocale.\n var availableLocale = BestAvailableLocale(availableLocales, noExtensionsLocale);\n\n // d. If availableLocale is not undefined, then append locale to the end of\n // subset.\n if (availableLocale !== undefined) arrPush.call(subset, locale);\n\n // e. Increment k by 1.\n k++;\n }\n\n // 5. Let subsetArray be a new Array object whose elements are the same\n // values in the same order as the elements of subset.\n var subsetArray = arrSlice.call(subset);\n\n // 6. Return subsetArray.\n return subsetArray;\n}",
"function /*9.2.7 */BestFitSupportedLocales (availableLocales, requestedLocales) {\n\t // ###TODO: implement this function as described by the specification###\n\t return LookupSupportedLocales(availableLocales, requestedLocales);\n\t}",
"function /*9.2.7 */BestFitSupportedLocales(availableLocales, requestedLocales) {\n // ###TODO: implement this function as described by the specification###\n return LookupSupportedLocales(availableLocales, requestedLocales);\n}",
"function /*9.2.7 */BestFitSupportedLocales(availableLocales, requestedLocales) {\n\t // ###TODO: implement this function as described by the specification###\n\t return LookupSupportedLocales(availableLocales, requestedLocales);\n\t}",
"function /*9.2.7 */BestFitSupportedLocales (availableLocales, requestedLocales) {\n // ###TODO: implement this function as described by the specification###\n return LookupSupportedLocales(availableLocales, requestedLocales);\n}",
"function negotiateLanguages(requestedLocales, availableLocales) {\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n\n\n var defaultLocale = GetOption(options, 'defaultLocale', 'string');\n var likelySubtags = GetOption(options, 'likelySubtags', 'object', undefined);\n var strategy = GetOption(options, 'strategy', 'string', ['filtering', 'matching', 'lookup'], 'filtering');\n\n if (strategy === 'lookup' && !defaultLocale) {\n throw new Error('defaultLocale cannot be undefined for strategy `lookup`');\n }\n\n var resolvedReqLoc = Array.from(Object(requestedLocales)).map(function (loc) {\n return String(loc);\n });\n var resolvedAvailLoc = Array.from(Object(availableLocales)).map(function (loc) {\n return String(loc);\n });\n\n var supportedLocales = filterMatches(resolvedReqLoc, resolvedAvailLoc, strategy, likelySubtags);\n\n if (strategy === 'lookup') {\n if (supportedLocales.length === 0) {\n supportedLocales.push(defaultLocale);\n }\n } else if (defaultLocale && !supportedLocales.includes(defaultLocale)) {\n supportedLocales.push(defaultLocale);\n }\n return supportedLocales;\n }",
"function /* 9.2.3 */LookupMatcher(availableLocales, requestedLocales) {\n\t // 1. Let i be 0.\n\t var i = 0;\n\n\t // 2. Let len be the number of elements in requestedLocales.\n\t var len = requestedLocales.length;\n\n\t // 3. Let availableLocale be undefined.\n\t var availableLocale = void 0;\n\n\t var locale = void 0,\n\t noExtensionsLocale = void 0;\n\n\t // 4. Repeat while i < len and availableLocale is undefined:\n\t while (i < len && !availableLocale) {\n\t // a. Let locale be the element of requestedLocales at 0-origined list\n\t // position i.\n\t locale = requestedLocales[i];\n\n\t // b. Let noExtensionsLocale be the String value that is locale with all\n\t // Unicode locale extension sequences removed.\n\t noExtensionsLocale = String(locale).replace(expUnicodeExSeq, '');\n\n\t // c. Let availableLocale be the result of calling the\n\t // BestAvailableLocale abstract operation (defined in 9.2.2) with\n\t // arguments availableLocales and noExtensionsLocale.\n\t availableLocale = BestAvailableLocale(availableLocales, noExtensionsLocale);\n\n\t // d. Increase i by 1.\n\t i++;\n\t }\n\n\t // 5. Let result be a new Record.\n\t var result = new Record();\n\n\t // 6. If availableLocale is not undefined, then\n\t if (availableLocale !== undefined) {\n\t // a. Set result.[[locale]] to availableLocale.\n\t result['[[locale]]'] = availableLocale;\n\n\t // b. If locale and noExtensionsLocale are not the same String value, then\n\t if (String(locale) !== String(noExtensionsLocale)) {\n\t // i. Let extension be the String value consisting of the first\n\t // substring of locale that is a Unicode locale extension sequence.\n\t var extension = locale.match(expUnicodeExSeq)[0];\n\n\t // ii. Let extensionIndex be the character position of the initial\n\t // \"-\" of the first Unicode locale extension sequence within locale.\n\t var extensionIndex = locale.indexOf('-u-');\n\n\t // iii. Set result.[[extension]] to extension.\n\t result['[[extension]]'] = extension;\n\n\t // iv. Set result.[[extensionIndex]] to extensionIndex.\n\t result['[[extensionIndex]]'] = extensionIndex;\n\t }\n\t }\n\t // 7. Else\n\t else\n\t // a. Set result.[[locale]] to the value returned by the DefaultLocale abstract\n\t // operation (defined in 6.2.4).\n\t result['[[locale]]'] = DefaultLocale();\n\n\t // 8. Return result\n\t return result;\n\t}",
"function /* 9.2.3 */LookupMatcher (availableLocales, requestedLocales) {\n\t var\n\t // 1. Let i be 0.\n\t i = 0,\n\t\n\t // 2. Let len be the number of elements in requestedLocales.\n\t len = requestedLocales.length,\n\t\n\t // 3. Let availableLocale be undefined.\n\t availableLocale;\n\t\n\t // 4. Repeat while i < len and availableLocale is undefined:\n\t while (i < len && !availableLocale) {\n\t var\n\t // a. Let locale be the element of requestedLocales at 0-origined list\n\t // position i.\n\t locale = requestedLocales[i],\n\t\n\t // b. Let noExtensionsLocale be the String value that is locale with all\n\t // Unicode locale extension sequences removed.\n\t noExtensionsLocale = String(locale).replace(expUnicodeExSeq, ''),\n\t\n\t // c. Let availableLocale be the result of calling the\n\t // BestAvailableLocale abstract operation (defined in 9.2.2) with\n\t // arguments availableLocales and noExtensionsLocale.\n\t availableLocale = BestAvailableLocale(availableLocales, noExtensionsLocale);\n\t\n\t // d. Increase i by 1.\n\t i++;\n\t }\n\t\n\t var\n\t // 5. Let result be a new Record.\n\t result = new Record();\n\t\n\t // 6. If availableLocale is not undefined, then\n\t if (availableLocale !== undefined) {\n\t // a. Set result.[[locale]] to availableLocale.\n\t result['[[locale]]'] = availableLocale;\n\t\n\t // b. If locale and noExtensionsLocale are not the same String value, then\n\t if (String(locale) !== String(noExtensionsLocale)) {\n\t var\n\t // i. Let extension be the String value consisting of the first\n\t // substring of locale that is a Unicode locale extension sequence.\n\t extension = locale.match(expUnicodeExSeq)[0],\n\t\n\t // ii. Let extensionIndex be the character position of the initial\n\t // \"-\" of the first Unicode locale extension sequence within locale.\n\t extensionIndex = locale.indexOf('-u-');\n\t\n\t // iii. Set result.[[extension]] to extension.\n\t result['[[extension]]'] = extension;\n\t\n\t // iv. Set result.[[extensionIndex]] to extensionIndex.\n\t result['[[extensionIndex]]'] = extensionIndex;\n\t }\n\t }\n\t // 7. Else\n\t else\n\t // a. Set result.[[locale]] to the value returned by the DefaultLocale abstract\n\t // operation (defined in 6.2.4).\n\t result['[[locale]]'] = DefaultLocale();\n\t\n\t // 8. Return result\n\t return result;\n\t}",
"function /* 9.2.3 */LookupMatcher(availableLocales, requestedLocales) {\n\t // 1. Let i be 0.\n\t var i = 0;\n\t\n\t // 2. Let len be the number of elements in requestedLocales.\n\t var len = requestedLocales.length;\n\t\n\t // 3. Let availableLocale be undefined.\n\t var availableLocale = void 0;\n\t\n\t var locale = void 0,\n\t noExtensionsLocale = void 0;\n\t\n\t // 4. Repeat while i < len and availableLocale is undefined:\n\t while (i < len && !availableLocale) {\n\t // a. Let locale be the element of requestedLocales at 0-origined list\n\t // position i.\n\t locale = requestedLocales[i];\n\t\n\t // b. Let noExtensionsLocale be the String value that is locale with all\n\t // Unicode locale extension sequences removed.\n\t noExtensionsLocale = String(locale).replace(expUnicodeExSeq, '');\n\t\n\t // c. Let availableLocale be the result of calling the\n\t // BestAvailableLocale abstract operation (defined in 9.2.2) with\n\t // arguments availableLocales and noExtensionsLocale.\n\t availableLocale = BestAvailableLocale(availableLocales, noExtensionsLocale);\n\t\n\t // d. Increase i by 1.\n\t i++;\n\t }\n\t\n\t // 5. Let result be a new Record.\n\t var result = new Record();\n\t\n\t // 6. If availableLocale is not undefined, then\n\t if (availableLocale !== undefined) {\n\t // a. Set result.[[locale]] to availableLocale.\n\t result['[[locale]]'] = availableLocale;\n\t\n\t // b. If locale and noExtensionsLocale are not the same String value, then\n\t if (String(locale) !== String(noExtensionsLocale)) {\n\t // i. Let extension be the String value consisting of the first\n\t // substring of locale that is a Unicode locale extension sequence.\n\t var extension = locale.match(expUnicodeExSeq)[0];\n\t\n\t // ii. Let extensionIndex be the character position of the initial\n\t // \"-\" of the first Unicode locale extension sequence within locale.\n\t var extensionIndex = locale.indexOf('-u-');\n\t\n\t // iii. Set result.[[extension]] to extension.\n\t result['[[extension]]'] = extension;\n\t\n\t // iv. Set result.[[extensionIndex]] to extensionIndex.\n\t result['[[extensionIndex]]'] = extensionIndex;\n\t }\n\t }\n\t // 7. Else\n\t else\n\t // a. Set result.[[locale]] to the value returned by the DefaultLocale abstract\n\t // operation (defined in 6.2.4).\n\t result['[[locale]]'] = DefaultLocale();\n\t\n\t // 8. Return result\n\t return result;\n\t}",
"function /* 9.2.3 */LookupMatcher (availableLocales, requestedLocales) {\n var\n // 1. Let i be 0.\n i = 0,\n\n // 2. Let len be the number of elements in requestedLocales.\n len = requestedLocales.length,\n\n // 3. Let availableLocale be undefined.\n availableLocale;\n\n // 4. Repeat while i < len and availableLocale is undefined:\n while (i < len && !availableLocale) {\n var\n // a. Let locale be the element of requestedLocales at 0-origined list\n // position i.\n locale = requestedLocales[i],\n\n // b. Let noExtensionsLocale be the String value that is locale with all\n // Unicode locale extension sequences removed.\n noExtensionsLocale = String(locale).replace(expUnicodeExSeq, ''),\n\n // c. Let availableLocale be the result of calling the\n // BestAvailableLocale abstract operation (defined in 9.2.2) with\n // arguments availableLocales and noExtensionsLocale.\n availableLocale = BestAvailableLocale(availableLocales, noExtensionsLocale);\n\n // d. Increase i by 1.\n i++;\n }\n\n var\n // 5. Let result be a new Record.\n result = new Record();\n\n // 6. If availableLocale is not undefined, then\n if (availableLocale !== undefined) {\n // a. Set result.[[locale]] to availableLocale.\n result['[[locale]]'] = availableLocale;\n\n // b. If locale and noExtensionsLocale are not the same String value, then\n if (String(locale) !== String(noExtensionsLocale)) {\n var\n // i. Let extension be the String value consisting of the first\n // substring of locale that is a Unicode locale extension sequence.\n extension = locale.match(expUnicodeExSeq)[0],\n\n // ii. Let extensionIndex be the character position of the initial\n // \"-\" of the first Unicode locale extension sequence within locale.\n extensionIndex = locale.indexOf('-u-');\n\n // iii. Set result.[[extension]] to extension.\n result['[[extension]]'] = extension;\n\n // iv. Set result.[[extensionIndex]] to extensionIndex.\n result['[[extensionIndex]]'] = extensionIndex;\n }\n }\n // 7. Else\n else\n // a. Set result.[[locale]] to the value returned by the DefaultLocale abstract\n // operation (defined in 6.2.4).\n result['[[locale]]'] = DefaultLocale();\n\n // 8. Return result\n return result;\n}",
"function /* 9.2.3 */LookupMatcher(availableLocales, requestedLocales) {\n // 1. Let i be 0.\n var i = 0;\n\n // 2. Let len be the number of elements in requestedLocales.\n var len = requestedLocales.length;\n\n // 3. Let availableLocale be undefined.\n var availableLocale = void 0;\n\n var locale = void 0,\n noExtensionsLocale = void 0;\n\n // 4. Repeat while i < len and availableLocale is undefined:\n while (i < len && !availableLocale) {\n // a. Let locale be the element of requestedLocales at 0-origined list\n // position i.\n locale = requestedLocales[i];\n\n // b. Let noExtensionsLocale be the String value that is locale with all\n // Unicode locale extension sequences removed.\n noExtensionsLocale = String(locale).replace(expUnicodeExSeq, '');\n\n // c. Let availableLocale be the result of calling the\n // BestAvailableLocale abstract operation (defined in 9.2.2) with\n // arguments availableLocales and noExtensionsLocale.\n availableLocale = BestAvailableLocale(availableLocales, noExtensionsLocale);\n\n // d. Increase i by 1.\n i++;\n }\n\n // 5. Let result be a new Record.\n var result = new Record();\n\n // 6. If availableLocale is not undefined, then\n if (availableLocale !== undefined) {\n // a. Set result.[[locale]] to availableLocale.\n result['[[locale]]'] = availableLocale;\n\n // b. If locale and noExtensionsLocale are not the same String value, then\n if (String(locale) !== String(noExtensionsLocale)) {\n // i. Let extension be the String value consisting of the first\n // substring of locale that is a Unicode locale extension sequence.\n var extension = locale.match(expUnicodeExSeq)[0];\n\n // ii. Let extensionIndex be the character position of the initial\n // \"-\" of the first Unicode locale extension sequence within locale.\n var extensionIndex = locale.indexOf('-u-');\n\n // iii. Set result.[[extension]] to extension.\n result['[[extension]]'] = extension;\n\n // iv. Set result.[[extensionIndex]] to extensionIndex.\n result['[[extensionIndex]]'] = extensionIndex;\n }\n }\n // 7. Else\n else\n // a. Set result.[[locale]] to the value returned by the DefaultLocale abstract\n // operation (defined in 6.2.4).\n result['[[locale]]'] = DefaultLocale();\n\n // 8. Return result\n return result;\n}",
"function localesToUseFrom(requestedLocales) {\n let supportedLocales = _dataLocales;\n\n let toUse = [];\n for (let i in requestedLocales) {\n let locale = requestedLocales[i];\n if (supportedLocales[locale]) toUse.push(locale);\n\n if (locale.includes('-')) {\n // Full locale ('es-ES'), add fallback to the base ('es')\n let langPart = locale.split('-')[0];\n if (supportedLocales[langPart]) toUse.push(langPart);\n }\n }\n // remove duplicates\n return utilArrayUniq(toUse);\n }",
"function localesToUseFrom(requestedLocales) {\n\t var supportedLocales = _dataLocales;\n\t var toUse = [];\n\n\t for (var i in requestedLocales) {\n\t var locale = requestedLocales[i];\n\t if (supportedLocales[locale]) toUse.push(locale);\n\n\t if (locale.includes('-')) {\n\t // Full locale ('es-ES'), add fallback to the base ('es')\n\t var langPart = locale.split('-')[0];\n\t if (supportedLocales[langPart]) toUse.push(langPart);\n\t }\n\t } // remove duplicates\n\n\n\t return utilArrayUniq(toUse);\n\t }",
"function /* 9.2.4 */BestFitMatcher (availableLocales, requestedLocales) {\n return LookupMatcher(availableLocales, requestedLocales);\n}",
"function /* 9.2.4 */BestFitMatcher(availableLocales, requestedLocales) {\n return LookupMatcher(availableLocales, requestedLocales);\n}",
"function /* 9.2.5 */ResolveLocale(availableLocales, requestedLocales, options, relevantExtensionKeys, localeData) {\n if (availableLocales.length === 0) {\n throw new ReferenceError('No locale data has been provided for this object yet.');\n }\n\n // The following steps are taken:\n // 1. Let matcher be the value of options.[[localeMatcher]].\n var matcher = options['[[localeMatcher]]'];\n\n var r = void 0;\n\n // 2. If matcher is \"lookup\", then\n if (matcher === 'lookup')\n // a. Let r be the result of calling the LookupMatcher abstract operation\n // (defined in 9.2.3) with arguments availableLocales and\n // requestedLocales.\n r = LookupMatcher(availableLocales, requestedLocales);\n\n // 3. Else\n else\n // a. Let r be the result of calling the BestFitMatcher abstract\n // operation (defined in 9.2.4) with arguments availableLocales and\n // requestedLocales.\n r = BestFitMatcher(availableLocales, requestedLocales);\n\n // 4. Let foundLocale be the value of r.[[locale]].\n var foundLocale = r['[[locale]]'];\n\n var extensionSubtags = void 0,\n extensionSubtagsLength = void 0;\n\n // 5. If r has an [[extension]] field, then\n if (hop.call(r, '[[extension]]')) {\n // a. Let extension be the value of r.[[extension]].\n var extension = r['[[extension]]'];\n // b. Let split be the standard built-in function object defined in ES5,\n // 15.5.4.14.\n var split = String.prototype.split;\n // c. Let extensionSubtags be the result of calling the [[Call]] internal\n // method of split with extension as the this value and an argument\n // list containing the single item \"-\".\n extensionSubtags = split.call(extension, '-');\n // d. Let extensionSubtagsLength be the result of calling the [[Get]]\n // internal method of extensionSubtags with argument \"length\".\n extensionSubtagsLength = extensionSubtags.length;\n }\n\n // 6. Let result be a new Record.\n var result = new Record();\n\n // 7. Set result.[[dataLocale]] to foundLocale.\n result['[[dataLocale]]'] = foundLocale;\n\n // 8. Let supportedExtension be \"-u\".\n var supportedExtension = '-u';\n // 9. Let i be 0.\n var i = 0;\n // 10. Let len be the result of calling the [[Get]] internal method of\n // relevantExtensionKeys with argument \"length\".\n var len = relevantExtensionKeys.length;\n\n // 11 Repeat while i < len:\n while (i < len) {\n // a. Let key be the result of calling the [[Get]] internal method of\n // relevantExtensionKeys with argument ToString(i).\n var key = relevantExtensionKeys[i];\n // b. Let foundLocaleData be the result of calling the [[Get]] internal\n // method of localeData with the argument foundLocale.\n var foundLocaleData = localeData[foundLocale];\n // c. Let keyLocaleData be the result of calling the [[Get]] internal\n // method of foundLocaleData with the argument key.\n var keyLocaleData = foundLocaleData[key];\n // d. Let value be the result of calling the [[Get]] internal method of\n // keyLocaleData with argument \"0\".\n var value = keyLocaleData['0'];\n // e. Let supportedExtensionAddition be \"\".\n var supportedExtensionAddition = '';\n // f. Let indexOf be the standard built-in function object defined in\n // ES5, 15.4.4.14.\n var indexOf = arrIndexOf;\n\n // g. If extensionSubtags is not undefined, then\n if (extensionSubtags !== undefined) {\n // i. Let keyPos be the result of calling the [[Call]] internal\n // method of indexOf with extensionSubtags as the this value and\n // an argument list containing the single item key.\n var keyPos = indexOf.call(extensionSubtags, key);\n\n // ii. If keyPos ≠ -1, then\n if (keyPos !== -1) {\n // 1. If keyPos + 1 < extensionSubtagsLength and the length of the\n // result of calling the [[Get]] internal method of\n // extensionSubtags with argument ToString(keyPos +1) is greater\n // than 2, then\n if (keyPos + 1 < extensionSubtagsLength && extensionSubtags[keyPos + 1].length > 2) {\n // a. Let requestedValue be the result of calling the [[Get]]\n // internal method of extensionSubtags with argument\n // ToString(keyPos + 1).\n var requestedValue = extensionSubtags[keyPos + 1];\n // b. Let valuePos be the result of calling the [[Call]]\n // internal method of indexOf with keyLocaleData as the\n // this value and an argument list containing the single\n // item requestedValue.\n var valuePos = indexOf.call(keyLocaleData, requestedValue);\n\n // c. If valuePos ≠ -1, then\n if (valuePos !== -1) {\n // i. Let value be requestedValue.\n value = requestedValue,\n // ii. Let supportedExtensionAddition be the\n // concatenation of \"-\", key, \"-\", and value.\n supportedExtensionAddition = '-' + key + '-' + value;\n }\n }\n // 2. Else\n else {\n // a. Let valuePos be the result of calling the [[Call]]\n // internal method of indexOf with keyLocaleData as the this\n // value and an argument list containing the single item\n // \"true\".\n var _valuePos = indexOf(keyLocaleData, 'true');\n\n // b. If valuePos ≠ -1, then\n if (_valuePos !== -1)\n // i. Let value be \"true\".\n value = 'true';\n }\n }\n }\n // h. If options has a field [[<key>]], then\n if (hop.call(options, '[[' + key + ']]')) {\n // i. Let optionsValue be the value of options.[[<key>]].\n var optionsValue = options['[[' + key + ']]'];\n\n // ii. If the result of calling the [[Call]] internal method of indexOf\n // with keyLocaleData as the this value and an argument list\n // containing the single item optionsValue is not -1, then\n if (indexOf.call(keyLocaleData, optionsValue) !== -1) {\n // 1. If optionsValue is not equal to value, then\n if (optionsValue !== value) {\n // a. Let value be optionsValue.\n value = optionsValue;\n // b. Let supportedExtensionAddition be \"\".\n supportedExtensionAddition = '';\n }\n }\n }\n // i. Set result.[[<key>]] to value.\n result['[[' + key + ']]'] = value;\n\n // j. Append supportedExtensionAddition to supportedExtension.\n supportedExtension += supportedExtensionAddition;\n\n // k. Increase i by 1.\n i++;\n }\n // 12. If the length of supportedExtension is greater than 2, then\n if (supportedExtension.length > 2) {\n // a.\n var privateIndex = foundLocale.indexOf(\"-x-\");\n // b.\n if (privateIndex === -1) {\n // i.\n foundLocale = foundLocale + supportedExtension;\n }\n // c.\n else {\n // i.\n var preExtension = foundLocale.substring(0, privateIndex);\n // ii.\n var postExtension = foundLocale.substring(privateIndex);\n // iii.\n foundLocale = preExtension + supportedExtension + postExtension;\n }\n // d. asserting - skipping\n // e.\n foundLocale = CanonicalizeLanguageTag(foundLocale);\n }\n // 13. Set result.[[locale]] to foundLocale.\n result['[[locale]]'] = foundLocale;\n\n // 14. Return result.\n return result;\n}",
"function /* 9.2.5 */ResolveLocale (availableLocales, requestedLocales, options, relevantExtensionKeys, localeData) {\n if (availableLocales.length === 0) {\n throw new ReferenceError('No locale data has been provided for this object yet.');\n }\n\n // The following steps are taken:\n var\n // 1. Let matcher be the value of options.[[localeMatcher]].\n matcher = options['[[localeMatcher]]'];\n\n // 2. If matcher is \"lookup\", then\n if (matcher === 'lookup')\n var\n // a. Let r be the result of calling the LookupMatcher abstract operation\n // (defined in 9.2.3) with arguments availableLocales and\n // requestedLocales.\n r = LookupMatcher(availableLocales, requestedLocales);\n\n // 3. Else\n else\n var\n // a. Let r be the result of calling the BestFitMatcher abstract\n // operation (defined in 9.2.4) with arguments availableLocales and\n // requestedLocales.\n r = BestFitMatcher(availableLocales, requestedLocales);\n\n var\n // 4. Let foundLocale be the value of r.[[locale]].\n foundLocale = r['[[locale]]'];\n\n // 5. If r has an [[extension]] field, then\n if (hop.call(r, '[[extension]]'))\n var\n // a. Let extension be the value of r.[[extension]].\n extension = r['[[extension]]'],\n // b. Let extensionIndex be the value of r.[[extensionIndex]].\n extensionIndex = r['[[extensionIndex]]'],\n // c. Let split be the standard built-in function object defined in ES5,\n // 15.5.4.14.\n split = String.prototype.split,\n // d. Let extensionSubtags be the result of calling the [[Call]] internal\n // method of split with extension as the this value and an argument\n // list containing the single item \"-\".\n extensionSubtags = split.call(extension, '-'),\n // e. Let extensionSubtagsLength be the result of calling the [[Get]]\n // internal method of extensionSubtags with argument \"length\".\n extensionSubtagsLength = extensionSubtags.length;\n\n var\n // 6. Let result be a new Record.\n result = new Record();\n\n // 7. Set result.[[dataLocale]] to foundLocale.\n result['[[dataLocale]]'] = foundLocale;\n\n var\n // 8. Let supportedExtension be \"-u\".\n supportedExtension = '-u',\n // 9. Let i be 0.\n i = 0,\n // 10. Let len be the result of calling the [[Get]] internal method of\n // relevantExtensionKeys with argument \"length\".\n len = relevantExtensionKeys.length;\n\n // 11 Repeat while i < len:\n while (i < len) {\n var\n // a. Let key be the result of calling the [[Get]] internal method of\n // relevantExtensionKeys with argument ToString(i).\n key = relevantExtensionKeys[i],\n // b. Let foundLocaleData be the result of calling the [[Get]] internal\n // method of localeData with the argument foundLocale.\n foundLocaleData = localeData[foundLocale],\n // c. Let keyLocaleData be the result of calling the [[Get]] internal\n // method of foundLocaleData with the argument key.\n keyLocaleData = foundLocaleData[key],\n // d. Let value be the result of calling the [[Get]] internal method of\n // keyLocaleData with argument \"0\".\n value = keyLocaleData['0'],\n // e. Let supportedExtensionAddition be \"\".\n supportedExtensionAddition = '',\n // f. Let indexOf be the standard built-in function object defined in\n // ES5, 15.4.4.14.\n indexOf = arrIndexOf;\n\n // g. If extensionSubtags is not undefined, then\n if (extensionSubtags !== undefined) {\n var\n // i. Let keyPos be the result of calling the [[Call]] internal\n // method of indexOf with extensionSubtags as the this value and\n // an argument list containing the single item key.\n keyPos = indexOf.call(extensionSubtags, key);\n\n // ii. If keyPos ≠ -1, then\n if (keyPos !== -1) {\n // 1. If keyPos + 1 < extensionSubtagsLength and the length of the\n // result of calling the [[Get]] internal method of\n // extensionSubtags with argument ToString(keyPos +1) is greater\n // than 2, then\n if (keyPos + 1 < extensionSubtagsLength\n && extensionSubtags[keyPos + 1].length > 2) {\n var\n // a. Let requestedValue be the result of calling the [[Get]]\n // internal method of extensionSubtags with argument\n // ToString(keyPos + 1).\n requestedValue = extensionSubtags[keyPos + 1],\n // b. Let valuePos be the result of calling the [[Call]]\n // internal method of indexOf with keyLocaleData as the\n // this value and an argument list containing the single\n // item requestedValue.\n valuePos = indexOf.call(keyLocaleData, requestedValue);\n\n // c. If valuePos ≠ -1, then\n if (valuePos !== -1)\n var\n // i. Let value be requestedValue.\n value = requestedValue,\n // ii. Let supportedExtensionAddition be the\n // concatenation of \"-\", key, \"-\", and value.\n supportedExtensionAddition = '-' + key + '-' + value;\n }\n // 2. Else\n else {\n var\n // a. Let valuePos be the result of calling the [[Call]]\n // internal method of indexOf with keyLocaleData as the this\n // value and an argument list containing the single item\n // \"true\".\n valuePos = indexOf(keyLocaleData, 'true');\n\n // b. If valuePos ≠ -1, then\n if (valuePos !== -1)\n var\n // i. Let value be \"true\".\n value = 'true';\n }\n }\n }\n // h. If options has a field [[<key>]], then\n if (hop.call(options, '[[' + key + ']]')) {\n var\n // i. Let optionsValue be the value of options.[[<key>]].\n optionsValue = options['[[' + key + ']]'];\n\n // ii. If the result of calling the [[Call]] internal method of indexOf\n // with keyLocaleData as the this value and an argument list\n // containing the single item optionsValue is not -1, then\n if (indexOf.call(keyLocaleData, optionsValue) !== -1) {\n // 1. If optionsValue is not equal to value, then\n if (optionsValue !== value) {\n // a. Let value be optionsValue.\n value = optionsValue;\n // b. Let supportedExtensionAddition be \"\".\n supportedExtensionAddition = '';\n }\n }\n }\n // i. Set result.[[<key>]] to value.\n result['[[' + key + ']]'] = value;\n\n // j. Append supportedExtensionAddition to supportedExtension.\n supportedExtension += supportedExtensionAddition;\n\n // k. Increase i by 1.\n i++;\n }\n // 12. If the length of supportedExtension is greater than 2, then\n if (supportedExtension.length > 2) {\n var\n // a. Let preExtension be the substring of foundLocale from position 0,\n // inclusive, to position extensionIndex, exclusive.\n preExtension = foundLocale.substring(0, extensionIndex),\n // b. Let postExtension be the substring of foundLocale from position\n // extensionIndex to the end of the string.\n postExtension = foundLocale.substring(extensionIndex),\n // c. Let foundLocale be the concatenation of preExtension,\n // supportedExtension, and postExtension.\n foundLocale = preExtension + supportedExtension + postExtension;\n }\n // 13. Set result.[[locale]] to foundLocale.\n result['[[locale]]'] = foundLocale;\n\n // 14. Return result.\n return result;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get date id format:yyyyMMdd | function getDateId() {
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth()+1;
var day = date.getDate();
return year+month+day;
} | [
"function genereID(){\nvar ref='DA-';\nvar date = new Date();\n\n // Format de l'ID de la demande d'achat DA-YYMMDD-HHMMSS\n ref+=(String(date.getFullYear())).slice(-2)+(\"0\"+ String(date.getMonth()+1)).slice(-2)+(\"0\" + String(date.getDate())).slice(-2);\n ref+=\"-\"\n ref+=(\"0\"+String(date.getHours())).slice(-2)+(\"0\"+ String(date.getMinutes()+1)).slice(-2)+(\"0\" + String(date.getSeconds())).slice(-2);\n return ref;\n}",
"dailyNoteUid() {\n\t\treturn moment( new Date() ).format( 'MM-DD-YYYY' );\n\t}",
"function getYYYYMMDD (date) {\n let yyyy = date.getFullYear().toString();\n let mm = (date.getMonth()+1).toString();\n let dd = date.getDate().toString();\n return yyyy + '-' + padWithZeroes(mm) + '-' + padWithZeroes(dd);\n }",
"function getDateString(date) {\n return date.getMonth() + \"_\" + date.getDate() + \"_\" + date.getFullYear();\n}",
"function getUniqueId()\n{\n var dateObject = new Date();\n var uniqueId =\n dateObject.getFullYear() + '' +\n dateObject.getMonth() + '' +\n dateObject.getDate() + '' +\n dateObject.getTime();\n\n return uniqueId;\n}",
"toYYYYMMDD(date){\n let month = '' + (date.getMonth() + 1);\n let day = '' + date.getDate();\n let year = date.getFullYear();\n \n if (month.length < 2) \n month = '0' + month;\n if (day.length < 2) \n day = '0' + day;\n\n return [year, month, day].join('-');\n }",
"function getUID(month, year, day){\n if(month == 12){\n month = 0;\n year++;\n }\n monthString = \"\" + month;\n yearString = \"\" + year;\n dayString = \"\" + day;\n\n if(day <= 9) {\n dayString = \"0\" + dayString;\n }\n\n if(month <= 9) {\n monthString = \"0\" + monthString;\n }\n\n return yearString + \"-\" + monthString + \"-\" + dayString;\n}",
"function dateKey(date) {\n const d = new Date(date);\n const year = d.getFullYear();\n var month = d.getMonth() + 1;\n month = month < 10 ? \"0\" + month : month;\n var day = d.getDate();\n day = day < 10 ? \"0\" + day : day;\n return `${year}-${month}-${day}`;\n}",
"function getFormatedDate_DDMMYYYY(date) {\n var year = date.getFullYear();\n var month = (date.getMonth() + 1);\n if (month < 10)\n month = '0' + month;\n var date = date.getDate();\n if (date < 10)\n date = '0' + date;\n\n var formatedDate = date + '-' + month + '-' + year;\n return formatedDate;\n }",
"function date_to_str_1(date_obj) {\n var year = date_obj.getFullYear();\n var month = date_obj.getMonth() + 1;\n var day = date_obj.getDate();\n if (month < 10)\n month = \"0\" + month;\n if (day < 10)\n day = \"0\" + day;\n return [year, month, day].join(\"-\");\n}",
"function createDateStrForDBRequest(date){\n var year = date.getFullYear().toString();\n var tmpMonth = date.getMonth() + 1; \n var month = tmpMonth>9 ? tmpMonth.toString() : ('0'+tmpMonth.toString());\n var tmpDay = date.getDate();\n var day = tmpDay>9 ? date.getDate().toString() : ('0'+tmpDay.toString());\n return year+'-'+month+'-'+day;\n}",
"get dateFormated() {\n var dd = (this.date.getDate() < 10 ? '0' : '') + this.date.getDate();\n var MM = ((this.date.getMonth() + 1) < 10 ? '0' : '') + (this.date.getMonth() + 1);\n var yyyy = this.date.getFullYear();\n return (dd + \"-\" + MM + \"-\" + yyyy);\n }",
"getDateFromID(id) {\n let itineraries = this.props.itineraries;\n for (let x in itineraries) {\n if (itineraries[x]._id === id) {\n return new Date(itineraries[x].date);\n }\n }\n return \"\";\n }",
"function toYYYY_MM_DD(dateObj) {\n return \"\" + dateObj.getFullYear() + \"-\" + padZero((dateObj.getMonth() + 1)) + \"-\" + padZero(dateObj.getDate());\n }",
"function getRunId(txtDate){\n\tvar time = new Date();\n\tvar month = time.getMonth() + 1;\n\tvar date = time.getDate();\n\tvar year = time.getFullYear();\n\tvar dateIndex = month + date + year;\n}",
"static generateDateBasedUuid() {\n return `${uuidv4()}-${dateFormat(new Date(new Date().toLocaleString('es-CO', { timeZone: 'America/Bogota' })), \"yymm\")}`;\n }",
"function originalId(id) {\n if (id.slice(0, 3) == 'mm-') {\n return id.slice(3);\n }\n return id;\n}",
"function createdAt(id) {\n return new Date(parseInt(id.substring(0, 8), 16) * 1000);\n}",
"function toMMDDYYYY(date) {\n var dateString = \"\";\n if (date.getMonth() < 9) {\n dateString += \"0\";\n }\n dateString += date.getMonth() + 1;\n if (date.getDate() < 10) {\n dateString += \"0\";\n }\n dateString += date.getDate();\n dateString += date.getFullYear();\n\n return dateString;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets if the provided structure is a MethodSignatureStructure. | static isMethodSignature(structure) {
return structure.kind === StructureKind_1.StructureKind.MethodSignature;
} | [
"static isCallSignature(structure) {\r\n return structure.kind === StructureKind_1.StructureKind.CallSignature;\r\n }",
"static isSignatured(structure) {\r\n switch (structure.kind) {\r\n case StructureKind_1.StructureKind.Constructor:\r\n case StructureKind_1.StructureKind.ConstructorOverload:\r\n case StructureKind_1.StructureKind.GetAccessor:\r\n case StructureKind_1.StructureKind.Method:\r\n case StructureKind_1.StructureKind.MethodOverload:\r\n case StructureKind_1.StructureKind.SetAccessor:\r\n case StructureKind_1.StructureKind.Function:\r\n case StructureKind_1.StructureKind.FunctionOverload:\r\n case StructureKind_1.StructureKind.CallSignature:\r\n case StructureKind_1.StructureKind.ConstructSignature:\r\n case StructureKind_1.StructureKind.MethodSignature:\r\n return true;\r\n default:\r\n return false;\r\n }\r\n }",
"static isMethod(structure) {\r\n return structure.kind === StructureKind_1.StructureKind.Method;\r\n }",
"static isConstructSignature(structure) {\r\n return structure.kind === StructureKind_1.StructureKind.ConstructSignature;\r\n }",
"static isPropertySignature(structure) {\r\n return structure.kind === StructureKind_1.StructureKind.PropertySignature;\r\n }",
"static isMethodSignature(node) {\r\n return node.getKind() === typescript_1.SyntaxKind.MethodSignature;\r\n }",
"static isParametered(structure) {\r\n switch (structure.kind) {\r\n case StructureKind_1.StructureKind.Constructor:\r\n case StructureKind_1.StructureKind.ConstructorOverload:\r\n case StructureKind_1.StructureKind.GetAccessor:\r\n case StructureKind_1.StructureKind.Method:\r\n case StructureKind_1.StructureKind.MethodOverload:\r\n case StructureKind_1.StructureKind.SetAccessor:\r\n case StructureKind_1.StructureKind.Function:\r\n case StructureKind_1.StructureKind.FunctionOverload:\r\n case StructureKind_1.StructureKind.CallSignature:\r\n case StructureKind_1.StructureKind.ConstructSignature:\r\n case StructureKind_1.StructureKind.MethodSignature:\r\n return true;\r\n default:\r\n return false;\r\n }\r\n }",
"static isReturnTyped(structure) {\r\n switch (structure.kind) {\r\n case StructureKind_1.StructureKind.Constructor:\r\n case StructureKind_1.StructureKind.ConstructorOverload:\r\n case StructureKind_1.StructureKind.GetAccessor:\r\n case StructureKind_1.StructureKind.Method:\r\n case StructureKind_1.StructureKind.MethodOverload:\r\n case StructureKind_1.StructureKind.SetAccessor:\r\n case StructureKind_1.StructureKind.Function:\r\n case StructureKind_1.StructureKind.FunctionOverload:\r\n case StructureKind_1.StructureKind.CallSignature:\r\n case StructureKind_1.StructureKind.ConstructSignature:\r\n case StructureKind_1.StructureKind.IndexSignature:\r\n case StructureKind_1.StructureKind.MethodSignature:\r\n return true;\r\n default:\r\n return false;\r\n }\r\n }",
"static isTypeParametered(structure) {\r\n switch (structure.kind) {\r\n case StructureKind_1.StructureKind.Class:\r\n case StructureKind_1.StructureKind.Constructor:\r\n case StructureKind_1.StructureKind.ConstructorOverload:\r\n case StructureKind_1.StructureKind.GetAccessor:\r\n case StructureKind_1.StructureKind.Method:\r\n case StructureKind_1.StructureKind.MethodOverload:\r\n case StructureKind_1.StructureKind.SetAccessor:\r\n case StructureKind_1.StructureKind.Function:\r\n case StructureKind_1.StructureKind.FunctionOverload:\r\n case StructureKind_1.StructureKind.CallSignature:\r\n case StructureKind_1.StructureKind.ConstructSignature:\r\n case StructureKind_1.StructureKind.Interface:\r\n case StructureKind_1.StructureKind.MethodSignature:\r\n case StructureKind_1.StructureKind.TypeAlias:\r\n return true;\r\n default:\r\n return false;\r\n }\r\n }",
"static isIndexSignature(structure) {\r\n return structure.kind === StructureKind_1.StructureKind.IndexSignature;\r\n }",
"isType(signature) {\n return this.typeHierarchy().includes(signature);\n }",
"function hasSignature() {\n\t\treturn visitFields(Cognito.Forms.model.currentForm, function (field) { return field.get_FieldType().get_Name() === \"Signature\"; });\n\t}",
"static isMethodDeclarationOverload(structure) {\r\n return structure.kind === StructureKind_1.StructureKind.MethodOverload;\r\n }",
"static isParameter(structure) {\r\n return structure.kind === StructureKind_1.StructureKind.Parameter;\r\n }",
"static isTypeParameter(structure) {\r\n return structure.kind === StructureKind_1.StructureKind.TypeParameter;\r\n }",
"static isDecoratable(structure) {\r\n switch (structure.kind) {\r\n case StructureKind_1.StructureKind.Class:\r\n case StructureKind_1.StructureKind.GetAccessor:\r\n case StructureKind_1.StructureKind.Method:\r\n case StructureKind_1.StructureKind.Property:\r\n case StructureKind_1.StructureKind.SetAccessor:\r\n case StructureKind_1.StructureKind.Parameter:\r\n return true;\r\n default:\r\n return false;\r\n }\r\n }",
"static isTypeElementMembered(structure) {\r\n return structure.kind === StructureKind_1.StructureKind.Interface;\r\n }",
"static isCallSignatureDeclaration(node) {\r\n return node.getKind() === typescript_1.SyntaxKind.CallSignature;\r\n }",
"static isQuestionTokenable(structure) {\r\n switch (structure.kind) {\r\n case StructureKind_1.StructureKind.Method:\r\n case StructureKind_1.StructureKind.MethodOverload:\r\n case StructureKind_1.StructureKind.Property:\r\n case StructureKind_1.StructureKind.Parameter:\r\n case StructureKind_1.StructureKind.MethodSignature:\r\n case StructureKind_1.StructureKind.PropertySignature:\r\n return true;\r\n default:\r\n return false;\r\n }\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Time Scale Control set the time scale stopping any scheduled warping although .paused = true yields an effective time scale of zero, this method does not change .paused, because it would be confusing | setEffectiveTimeScale( timeScale ) {
this.timeScale = timeScale;
this._effectiveTimeScale = this.paused ? 0 : timeScale;
return this.stopWarping();
} | [
"setEffectiveTimeScale(timeScale){this.timeScale=timeScale;this._effectiveTimeScale=this.paused?0:timeScale;return this.stopWarping();}",
"setEffectiveTimeScale(timeScale) {\n this.timeScale = timeScale;\n this._effectiveTimeScale = this.paused ? 0 : timeScale;\n return this.stopWarping();\n }",
"setEffectiveTimeScale(timeScale) {\n this.timeScale = timeScale;\n this._effectiveTimeScale = this.paused ? 0 : timeScale;\n return this.stopWarping();\n }",
"setEffectiveTimeScale(timeScale) {\n\t\t\tthis.timeScale = timeScale;\n\t\t\tthis._effectiveTimeScale = this.paused ? 0 : timeScale;\n\t\t\treturn this.stopWarping();\n\t\t}",
"setEffectiveTimeScale( timeScale ) {\n\n\t\t\tthis.timeScale = timeScale;\n\t\t\tthis._effectiveTimeScale = this.paused ? 0 : timeScale;\n\n\t\t\treturn this.stopWarping();\n\n\t\t}",
"function timeScalePause() {\n\tvar startSpeed = 86; /* (document.getElementById(\"range-slider-1\").style.width)/10 */\n\n\t//click anywhere to toggle paused state\n\tvar currentTimeScale = tl.timeScale();\n\tif (currentTimeScale >= 0.5) {\n\t\tTweenMax.to(tl, 1.8, { timeScale: 0 });\n\t\tTweenMax.to(dragBall, 1.8, {\n\t\t\tleft: 0,\n\t\t\tonUpdate: function() {\n\t\t\t\tsliderVal.innerHTML =\n\t\t\t\t\tMath.round(parseInt(dragBall.style.left) * 1.163) + \"%\";\n\t\t\t}\n\t\t});\n\t} else {\n\t\tcurrentTimeScale = 0;\n\t}\n\tif (currentTimeScale < 0.5) {\n\t\tTweenMax.to(tl, 1.8, { timeScale: 1 });\n\t\tTweenMax.to(dragBall, 1.8, {\n\t\t\tleft: startSpeed,\n\t\t\tonUpdate: function() {\n\t\t\t\tsliderVal.innerHTML =\n\t\t\t\t\tMath.round(parseInt(dragBall.style.left) * 1.163) + \"%\";\n\t\t\t}\n\t\t});\n\t} else {\n\t\tcurrentTimeScale = 1;\n\t}\n}",
"set timeScale(pScl) {\n\t\tthis.__Internal__Dont__Modify__.timeScale = Math.max(Validate.type(pScl, \"number\", 0, true), 0);\n\t}",
"scale(timeScale){if(timeScale!==1.0){const times=this.times;for(let i=0,n=times.length;i!==n;++i){times[i]*=timeScale;}}return this;}",
"set timescale(value) {\n if (value <= 0) {\n Logger.getInstance().error('Cannot set engine.timescale to a value of 0 or less than 0.');\n return;\n }\n this._timescale = value;\n }",
"getEffectiveTimeScale(){return this._effectiveTimeScale;}",
"function time_scaled() {\n\n \tvar subDivision = 60;\n \n \ttickMark1 = Math.round( (timeScale / subDivision) * 100 ) / 100;\n \ttickMark2 = 2 * tickMark1;\n \ttickMark3 = 10 * tickMark1;\n \n }",
"scale( timeScale ) {\n\n\t\tif ( timeScale !== 1.0 ) {\n\n\t\t\tconst times = this.times;\n\n\t\t\tfor ( let i = 0, n = times.length; i !== n; ++ i ) {\n\n\t\t\t\ttimes[ i ] *= timeScale;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn this;\n\n\t}",
"scale(timeScale) {\n\t\t\tif (timeScale !== 1.0) {\n\t\t\t\tconst times = this.times;\n\n\t\t\t\tfor (let i = 0, n = times.length; i !== n; ++i) {\n\t\t\t\t\ttimes[i] *= timeScale;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn this;\n\t\t}",
"get timeScale() {\r\n return this._timeScale;\r\n }",
"function togglePause() {\n if (!timerIsPaused)\n timerIsPaused = true;\n else\n timerIsPaused = false;\n} // end-togglePause",
"restoreTimeScales() {\n this[$timeScales].restoreTimeScales();\n }",
"pause (paused)\n {\n this.lerpIntervals.pause(paused);\n }",
"get timeScale() {\n\t\treturn this.__Internal__Dont__Modify__.timeScale;\n\t}",
"pauseTimer() {\n\t\tthis.startPauseTime = Math.round((new Date().getTime() / 1000));\n\t\t// console.log(\"Paused timer at \" + this.startPauseTime);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new AwsConnectionParams object filled with keyvalue pairs serialized as a string. | static fromString(line) {
let map = pip_services3_commons_node_2.StringValueMap.fromString(line);
return new AwsConnectionParams(map);
} | [
"static fromConfig(config) {\n let result = new AwsConnectionParams();\n let credentials = pip_services3_components_node_1.CredentialParams.manyFromConfig(config);\n for (let credential of credentials)\n result.append(credential);\n let connections = pip_services3_components_node_2.ConnectionParams.manyFromConfig(config);\n for (let connection of connections)\n result.append(connection);\n return result;\n }",
"static fromString(line) {\n let map = pip_services3_commons_node_2.StringValueMap.fromString(line);\n return new ConnectionParams(map);\n }",
"static fromTuples(...tuples) {\n let map = pip_services3_commons_node_2.StringValueMap.fromTuplesArray(tuples);\n return new ConnectionParams(map);\n }",
"function toAwsParams(bucket, file) {\n var params = {};\n\n var headers = file.s3.headers || {};\n\n for (var header in headers) {\n if (header === 'x-amz-acl') {\n params.ACL = headers[header];\n } else if (header === 'Content-MD5') {\n params.ContentMD5 = headers[header];\n } else {\n params[pascalCase(header)] = headers[header];\n }\n }\n\n params.Bucket = bucket;\n params.Key = file.s3.path;\n params.Body = file.contents;\n\n return params;\n}",
"function createAws(p) {\r\n var awsConfig = p.awsConfig;\r\n var serviceName = p.serviceName;\r\n var url = p.url;\r\n var route = p.route;\r\n var params = p.params;\r\n\r\n // FIXME\r\n return {\r\n baseUrl: 'http://localhost/' + url, // TODO fix\r\n requestUrl: url, // TODO fix\r\n serviceName: serviceName,\r\n params: params,\r\n restParams: params,\r\n data: psplit.split(params),\r\n reqParams: params,\r\n version: awsConfig.VERSION, // AWS.config.versions, really.\r\n action: route.Action,\r\n accessKey: '1123', // TODO should come from AWS.config\r\n expires: '123412341234', // TODO fix\r\n signature: '12341234', // TODO fix\r\n signatureMethod: '', // TODO fix\r\n signatureVersion: '', // TODO fix\r\n timestamp: 10, // TODO fix\r\n region: (!!awsConfig.region ? awsConfig.region : 'ZN-MOCK-1'),\r\n isRest: (!route.Action),\r\n };\r\n}",
"static mergeConfigs(...configs) {\n let config = pip_services3_commons_node_1.ConfigParams.mergeConfigs(...configs);\n return new AwsConnectionParams(config);\n }",
"function cfnConnectionParameterPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnConnection_ParameterPropertyValidator(properties).assertSuccess();\n return {\n IsValueSecret: cdk.booleanToCloudFormation(properties.isValueSecret),\n Key: cdk.stringToCloudFormation(properties.key),\n Value: cdk.stringToCloudFormation(properties.value),\n };\n}",
"function SignatureParams() {\n this.prefix = \"\";\n }",
"function toParams(rootElement, keyStringElement, valueStringElement) {\n var requestParamsKeys = rootElement.find(keyStringElement).map(function () {\n return $(this).val();\n }).get();\n var requestParamsValues = rootElement.find(valueStringElement).map(function () {\n return $(this).val();\n }).get();\n\n var params = {};\n for (var i = 0; i < requestParamsKeys.length; i++) {\n if (requestParamsKeys[i] === \"\" || requestParamsValues[i] === \"\") {\n continue;\n }\n params[requestParamsKeys[i]] = requestParamsValues[i];\n }\n return $.param(params);\n }",
"constructor(scope, id, props = {}) {\n super(scope, id, { type: CfnPlaybackKeyPair.CFN_RESOURCE_TYPE_NAME, properties: props });\n try {\n jsiiDeprecationWarnings.aws_cdk_lib_aws_ivs_CfnPlaybackKeyPairProps(props);\n }\n catch (error) {\n if (process.env.JSII_DEBUG !== \"1\" && error.name === \"DeprecationError\") {\n Error.captureStackTrace(error, CfnPlaybackKeyPair);\n }\n throw error;\n }\n this.attrArn = cdk.Token.asString(this.getAtt('Arn', cdk.ResolutionTypeHint.STRING));\n this.attrFingerprint = cdk.Token.asString(this.getAtt('Fingerprint', cdk.ResolutionTypeHint.STRING));\n this.name = props.name;\n this.publicKeyMaterial = props.publicKeyMaterial;\n this.tags = new cdk.TagManager(cdk.TagType.STANDARD, \"AWS::IVS::PlaybackKeyPair\", props.tags, { tagPropertyName: 'tags' });\n }",
"static connectionParams() {\n const connectionString = process.env.DB_MYSQL_CONNECTION;\n if (!connectionString) throw new Error('No DB_MYSQL_CONNECTION available');\n\n const dbConfigKeyVal = connectionString.split(';').map(v => v.trim().split('='));\n const dbConfig = dbConfigKeyVal.reduce((config, v) => { config[v[0].toLowerCase()] = v[1]; return config; }, {});\n\n return dbConfig;\n }",
"function Param() {\n\t\tthis.key = \"\";\n\t\tthis.value = \"\";\n\t}",
"function createConnectionRequest() {\n return {\n type : consts.TYPE,\n version : consts.CURRENT_VERSION,\n capabilities : consts.CAPABILITIES\n };\n}",
"static fromString(line) {\n let map = pip_services3_commons_node_2.StringValueMap.fromString(line);\n return new CredentialParams(map);\n }",
"constructor() {\n this.keyPair = ec.genKeyPair()\n }",
"function createEnvVars(s3AccessKeyId, s3SecretAccessKey) {\n return {\n ignoreReturnCode: true,\n silent: false,\n env: {\n 'AWS_ACCESS_KEY_ID': s3AccessKeyId || \"\",\n 'AWS_SECRET_ACCESS_KEY': s3SecretAccessKey || \"\",\n 'AWS_DEFAULT_REGION': 'us-east-1',\n }\n };\n}",
"constructor(scope, id, props) {\n super(scope, id, { type: CfnVPCPeeringConnection.resourceTypeName, properties: props });\n cdk.requireProperty(props, 'peerVpcId', this);\n cdk.requireProperty(props, 'vpcId', this);\n this.vpcPeeringConnectionName = this.ref.toString();\n const tags = props === undefined ? undefined : props.tags;\n this.tags = new cdk.TagManager(cdk.TagType.Standard, \"AWS::EC2::VPCPeeringConnection\", tags);\n }",
"function serializeParams(pretty){\n\t\tvar params = getData('params');\n\t\tvar arr = [];\n\n\t\tfor (var param in params){\n\t\t\tif (pretty) {\n\t\t\t\tarr.push( wrapTag(param, _settings.className.param) + wrapTag('=', _settings.className.equals) + wrapTag(params[param], _settings.className.param) );\n\t\t\t} else {\n\t\t\t\tarr.push( param + '=' + params[param] );\n\t\t\t}\n\t\t}\n\t\treturn arr;\n\t}",
"constructor(scope, id, props) {\n super(scope, id, { type: CfnVPCPeeringConnection.CFN_RESOURCE_TYPE_NAME, properties: props });\n cdk.requireProperty(props, 'peerVpcId', this);\n cdk.requireProperty(props, 'vpcId', this);\n this.peerVpcId = props.peerVpcId;\n this.vpcId = props.vpcId;\n this.peerOwnerId = props.peerOwnerId;\n this.peerRegion = props.peerRegion;\n this.peerRoleArn = props.peerRoleArn;\n this.tags = new cdk.TagManager(cdk.TagType.STANDARD, \"AWS::EC2::VPCPeeringConnection\", props.tags, { tagPropertyName: 'tags' });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tries converting any value to a number. | function anyToNumber(value) {
if (_utils_Type__WEBPACK_IMPORTED_MODULE_3__["isDate"](value)) {
return value.getTime();
}
else if (_utils_Type__WEBPACK_IMPORTED_MODULE_3__["isNumber"](value)) {
return value;
}
else if (_utils_Type__WEBPACK_IMPORTED_MODULE_3__["isString"](value)) {
// Try converting to number (assuming timestamp)
var num = Number(value);
if (!_utils_Type__WEBPACK_IMPORTED_MODULE_3__["isNumber"](num)) {
// Failing
return undefined;
}
else {
return num;
}
}
} | [
"function anyToNumber(value) {\n if (_utils_Type__WEBPACK_IMPORTED_MODULE_3__[\"isDate\"](value)) {\n return value.getTime();\n } else if (_utils_Type__WEBPACK_IMPORTED_MODULE_3__[\"isNumber\"](value)) {\n return value;\n } else if (_utils_Type__WEBPACK_IMPORTED_MODULE_3__[\"isString\"](value)) {\n // Try converting to number (assuming timestamp)\n var num = Number(value);\n\n if (!_utils_Type__WEBPACK_IMPORTED_MODULE_3__[\"isNumber\"](num)) {\n // Failing\n return undefined;\n } else {\n return num;\n }\n }\n }",
"function anyToNumber(value) {\n if (isDate(value)) {\n return value.getTime();\n }\n else if (Type_isNumber(value)) {\n return value;\n }\n else if (isString(value)) {\n // Try converting to number (assuming timestamp)\n var num = Number(value);\n if (!Type_isNumber(num)) {\n // Failing\n return undefined;\n }\n else {\n return num;\n }\n }\n}",
"function validNum(value) {\n return isNaN(Number(value)) ? null : Number(value);\n}",
"function number(value) {\r\n return typeof value === 'number' && !isNaN(value);\r\n }",
"function castNum ( data, alt_data, option_map ) {\n var\n var_type = getVarType( data ),\n solve_num = var_type === '_Number_'\n ? data : var_type === '_String_'\n ? parseFloat( data ) : __undef;\n\n if ( isNaN( solve_num ) ) { return alt_data; }\n\n // Begin process optional constraints\n if ( typeofFn( option_map ) === vMap._object_ ) {\n return checkNumFn( solve_num, alt_data, option_map );\n }\n // . End process optional constraints\n return solve_num;\n }",
"function testNumber(value) {\r\n return (value && value != null && value != \"undefined\") ? value : 0;\r\n }",
"asNumber() {\n this.validate();\n const val = this._captured[this.idx];\n if ((0, type_1.getType)(val) === 'number') {\n return val;\n }\n this.reportIncorrectType('number');\n }",
"function number(value) {\r\n return typeof value === 'number' && !isNaN(value);\r\n}",
"function parseValue (value) {\n if (Number(value).toString() === value) {\n return Number(value)\n }\n return value\n}",
"function strToNumber(value) {\n // Convert strings to numbers\n if (typeof value === 'string' && !isNaN(Number(value) - parseFloat(value))) {\n return Number(value);\n }\n if (typeof value !== 'number') {\n throw new Error(`${value} is not a number`);\n }\n return value;\n}",
"function tryNumber (input) {\n var test = parseInt(input, 10);\n\n if (test.toString() === input) return test;\n else return input;\n}",
"function tryConvert(value, tUnit) {\n\tvar tryNumber = Number(value);\n\tif (isNaN(tryNumber)) {\n\t\t//this is NOT!!!! a valid number we can work with!\n\t\treturn '';\n\t}\n\telse {\n\t\t//this is a valid number (isNaN returned false) we can convert!\n\t\tif (tUnit == 'c') {\n\t\t\tvar convertedNumber = toFahreheit(tryNumber);\n\t\t}\n\t\telse {\n\t\t\tvar convertedNumber = toCelcius(tryNumber);\n\t\t}\n\t\treturn convertedNumber;\n\t}\n}",
"function ToNumber(argument) { // eslint-disable-line no-unused-vars\n\t\treturn Number(argument);\n\t}",
"function resolveNumber(value) {\n if (value % 1 === 0) {\n if (value < Constants.Int64.Min || value > Constants.Int64.Max) {\n // Integers beyond the bounds of Int64 are EDM Double properties.\n return AzureStorage.TableUtilities.EdmType.DOUBLE;\n }\n else if (value < Constants.Int32.Min || value > Constants.Int32.Max) {\n // Integers beyond the bounds of Int32 but within Int64 are EDM Int64 properties.\n if (Utilities.isSafeInteger(value)) {\n return AzureStorage.TableUtilities.EdmType.INT64;\n }\n else {\n // Fallback to EDM String if the value is not a safe integer,\n // that is, it falls outside of range (-2^53 - 1, 2^53 - 1).\n return AzureStorage.TableUtilities.EdmType.STRING;\n }\n }\n else {\n // All other integers are EDM Int32 properties.\n return AzureStorage.TableUtilities.EdmType.INT32;\n }\n }\n else {\n // Non-integer values are EDM Double properties.\n return AzureStorage.TableUtilities.EdmType.DOUBLE;\n }\n}",
"function castInt ( data, alt_data, option_map ) {\n var\n var_type = getVarType( data ),\n solve_num = var_type === '_Number_'\n ? data : var_type === '_String_'\n ? parseFloat( data ) : __undef,\n solve_int;\n\n if ( isNaN( solve_num ) ) { return alt_data; }\n solve_int = makeRoundNumFn( solve_num );\n\n // Begin process optional constraints\n if ( typeofFn( option_map ) === vMap._object_ ) {\n return checkNumFn( solve_int, alt_data, option_map );\n }\n // . End process optional constraints\n return solve_int;\n }",
"function filter_number(value) {\n var m = NUMBER_RE.exec(value);\n if(m == null) throw OptError('Expected a number representative');\n if(m[1]) {\n // The number is in HEX format. Convert into a number, then return it\n return parseInt(m[1], 16);\n } else {\n // The number is in regular- or decimal form. Just run in through\n // the float caster.\n return parseFloat(m[2] || m[3]);\n }\n }",
"function _toNumber(obj) {\n return typeof obj === 'number'\n ? obj\n : Number.NaN;\n }",
"function convertToNumber(id){\n var nr;\n $(id).val(function(i, val){\n nr = Number(val);\n if(Number(val) != nr){\n nr = false;\n }\n });\n return nr;\n}",
"function stringToNum () {\n const x= Number(\"1000\");\n return x;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Example: For inputArray = [2, 4, 1, 0], the output should be arrayMaximalAdjacentDifference(inputArray) = 3. | function arrayMaximalAdjacentDifference(inputArray) {
let arr = [];
for (let i = 0; i < inputArray.length - 1; i++) {
arr.push(Math.abs(inputArray[i] - inputArray[i+1]));
}
arr.sort((a,b) => b > a);
return arr[0];
} | [
"function arrayMaximalAdjacentDifference(inputArray) {\n let maxDiff = 0;\n let currentDiff = 0;\n\n inputArray.forEach(function(item, i) {\n currentDiff = Math.abs(item - inputArray[i + 1]);\n if (currentDiff > maxDiff) {\n maxDiff = currentDiff;\n }\n });\n\n return maxDiff;\n}",
"function arrayMaxAdjacentDiffernce(inputArray){\n\tlet maxDiff = Math.abs(inputArray[0] - inputArray[1])\n\n\tfor (let i = 0; i < inputArray.length; i++){\n\t\tlet absoluteDiff = Math.abs(inputArray[i - 1] - inputArray[i]);\n\t\tmaxDiff = absoluteDiff > maxDiff ? absoluteDiff : maxDiff;\n\n\t}\n\treturn maxDiff;\n}",
"function arrayMaximalAdjacentDifference(arr) {\n return Math.max(...arr.slice(1).map((x, i) => Math.abs(x - arr[i])))\n}",
"function arrayMaximalAdjacentDifference(arr) {\n const diffs = [];\n\n for (let i = 0; i < arr.length - 1; i++) {\n diffs.push(Math.abs(arr[i] - arr[i + 1]));\n }\n\n // return diffs.reduce((max, num) => (num > max ? num : max), diffs[0]);\n return Math.max(...diffs);\n}",
"function arrayMaximalAdjacentDifference(values) {\n let maxAbsoluteDifference = Math.abs(values[1] - values[0])\n for (let index = 0; index < values.length; index++) {\n const absoluteDifference = values[index - 1] - values[index]\n if (absoluteDifference > maxAbsoluteDifference) {\n maxAbsoluteDifference = absoluteDifference\n }\n }\n return maxAbsoluteDifference\n}",
"function maxDifference(arr) {\n let maxDiff = 0;\n\n for (let i = 0; i < arr.length; i++) {\n for (let j = i + 1; j < arr.length; j++) {\n let diff = Math.abs(arr[i] - arr[j]);\n maxDiff = Math.max(maxDiff, diff);\n }\n }\n return maxDiff;\n}",
"function max_difference(arr) {\n let max = -1;\n let temp;\n for (let i = 0; i < arr.length - 1; i++) {\n temp = Math.abs(arr[i] - arr[i+1]);\n max = Math.max(max, temp);\n }\n return max;\n}",
"function adjacentElementsProduct(inputArray) {\n let max = inputArray[0] * inputArray[1];\n for (let i = 1; i < inputArray.length - 1; i++) {\n if (inputArray[i + 1] * inputArray[i] > max) {\n max = inputArray[i + 1] * inputArray[i];\n }\n }\n return max;\n}",
"function diff(inputArray) {\n var outputArray = [];\n for (i =0; i < (inputArray.length - 1); i++) {\n outputArray.push(math.abs(inputArray[i+1] - inputArray[i]));\n }\n return outputArray;\n}",
"function maxDiff(arr) {\n var max = arr[0] - arr[1];\n for (var i = 1; i < arr.length - 1; i++) {\n if (max < arr[i] - arr[i + 1]) {\n max = arr[i] - arr[i + 1];\n }\n }\n return max;\n}",
"function maxAdjacentSum(array) {\n\tvar sum = 0;\n\n\tfor (var i = 0; i < array.length - 1; i++) {\n\t\tvar currentSum = array[i] + array[i+1];\n\n\t\tif (sum < currentSum) {\n\t\t\tsum = currentSum;\n\t\t}\n\t}\n\n\treturn sum;\n}",
"function maxAdjacentSum(array) {\n const maxSum = null;\n\n for(let i = 0; i < array.length - 1; i++) {\n const currentSum = array[i] + array[i+1];\n\n if(currentSum > maxSum || !maxSum) maxSum = currentSum;\n }\n\n return maxSum;\n}",
"function adjacentElementsProduct(inputArray) {\n let maxProduct = inputArray[0] * inputArray[1];\n for(let i = 1; i < inputArray.length; i++) {\n let product = inputArray[i-1] * inputArray[i]\n if(product > maxProduct) {\n maxProduct = product;\n }\n }\n return maxProduct;\n}",
"function findMaxDiff (array){\n\tif (typeof array !== 'object' || typeof array == 'undefined' || array == null || Object.getOwnPropertyNames(array).length === 0) {\n\t\tthrow 'Invalid Input';\n\t} else if (array.length<2) {\n\t\treturn 0;\n\t}\n\tfor (var i=0; i<array.length; i++) {\n\t\tif ( typeof array[i] !== 'number' || array[i]%1 !== 0) {\n\t\t\tthrow 'Invalid Input';\n\t\t}\n\t}\n\tvar diffArray = [];\n\tfor (var i=0; i<array.length-1; i++) {\n\t\tvar diff = array[i]-array[i+1];\n\t\tif (diff<0){\n\t\t\tdiff = -diff;\n\t\t} \n\t\tdiffArray.push(diff);\n\t}\n\tdiffArray.sort(function(a,b){return a-b});\n\tvar max = diffArray[diffArray.length-1];\n\treturn max;\n}",
"function maxDifference(a) {\n let maxDiff = 0;\n\n for (let i = 0; i < a.length; i++) {\n for (let j = 0; j < a.length; j++) {\n if (j !== i && i < j && a[i] < a[j]) {\n let diff = a[j] - a[i];\n if (diff > maxDiff) {\n maxDiff = diff;\n }\n }\n }\n }\n if (maxDiff === 0) {\n maxDiff = -1;\n }\n return maxDiff;\n}",
"function difference(array){\n let biggest = Math.max.apply(null, array);\n let smallest = Math.min.apply(null, array);\n return biggest - smallest;\n}",
"function adjacentElementsProduct(inputArray) {\n let res = 0;\n for (let i = 0; i < inputArray.length-1; i++) {\n let product = inputArray[i]*inputArray[i+1];\n if (product > res) res = product;\n }\n return res;\n}",
"function adjacentElementsProduct(inputArray) {\n let largest = inputArray[0] * inputArray[1]\n for (let i = 0; i < inputArray.length; i++) {\n let j = i + 1\n if (inputArray[i] * inputArray[j] > largest) {\n largest = inputArray[i] * inputArray[j]\n }\n }\n return largest\n}",
"function adjacentElementsProduct(inputArray) {\n \n let maxProduct = inputArray[0]*inputArray[1];\n \n for(let i = 0; i < inputArray.length - 1; i++) {\n if(inputArray[i]*inputArray[i+1] > maxProduct) {\n maxProduct = inputArray[i]*inputArray[++i];\n }\n }\n return maxProduct;\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes all items from Chrome Storage | function clearStorage() {
wordList.empty();
chrome.storage.local.clear(function () {
log('Data removed from storage!');
let error = chrome.runtime.lastError;
if (error) console.error(error);
});
} | [
"async clear() {\n const storagePrefix = this.keyToExtensionLocalStorageKey(\"\");\n const storageEntries = await browser.storage.local.get();\n const keysToRemove = [ ];\n for(const key in storageEntries) {\n if(key.startsWith(storagePrefix)) {\n keysToRemove.push(key);\n }\n }\n await browser.storage.local.remove(keysToRemove);\n }",
"clearAllItems() {\n window.localStorage.clear();\n }",
"clearAllItems () {\n window.localStorage.clear()\n }",
"clearItemsFromStorage() {\n localStorage.removeItem('items');\n }",
"static deleteAllFromLS() {\n localStorage.removeItem(\"items\");\n }",
"function clearStorage(arr) {\n chrome.storage.local.remove(arr)\n }",
"function removeItemsFromLocalStorage(){\n localStorage.clear();\n}",
"function clearLocalStorage() {\n chrome.storage.local.clear(() => {\n console.log('[STORAGE] Cleared all data within this extensions local storage');\n groupList = [];\n var error = chrome.runtime.lastError;\n if (error) {\n console.error(error);\n }\n });\n}",
"function delete_all_elements_from_LS(item) {\r\n localStorage.clear();\r\n}",
"static emptyStorage() {\n chrome.storage.sync.clear();\n }",
"function clearChromeStorage() {\n chrome.storage.sync.clear(function () {\n if (debugMode) {\n console.log('cleared chrome storage');\n }\n });\n}",
"clearAll() {\n localStorage.clear();\n }",
"purge() {\n let dirReader = this.fs.root.createReader();\n dirReader.readEntries(entries => {\n for (let i = 0, entry; entry = entries[i]; ++i) {\n if (entry.isDirectory) {\n entry.removeRecursively(() => {\n }, ChromeStore.errorHandler);\n } else {\n entry.remove(() => {\n }, ChromeStore.errorHandler);\n }\n }\n console.log('Local storage emptied.');\n }, ChromeStore.errorHandler);\n }",
"clearAll () {\n eachStorageType((storageType, isSupported) => {\n if (isSupported) {\n window[storageType].clear()\n }\n })\n }",
"static async wipeAll() {\n let keys = await AsyncStorage.getAllKeys();\n \n async function removeKey(key) {\n await Storage.remove(key);\n }\n \n await Promise.all(keys.map(removeKey));\n }",
"function clearAllAccounts() {\n storage.clearSync();\n}",
"function removeChromeStorage(key){\n chrome.storage.local.remove(key);\n}",
"static clearData() {\n chrome.storage.sync.clear();\n }",
"clear() {\n this.storage.clear();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
end acceptRequest / This function is called when a group join request is accepted | function acceptGroupJoin(feedRequest) {
Parse.Promise.when([
feedRequest.get("group"),
feedRequest.get("fromUser"),
feedRequest.get("toUsers")
]).then(function(group, user, toUsers){
var promises = [];
group.add('joinedUsers', user);
group.remove('pendingUsers', user);
promises.push(group.save());
promises.push(pushNotificationManager.sendGroupRefreshNotification(group.id));
promises.push(pushNotificationManager.sendFeedNotification(toUsers));
promises.push(pushNotificationManager.sendGroupJoinAcceptedNotification(user));
return Parse.Promise.when(promises);
});
} | [
"function acceptJoinRequest() {\n\n console.log('Accept join request');\n\n joinRequest.accept()\n .then(function() {\n console.log('Join request accepted');\n document.getElementById('joinRequest').style.display = 'none';\n })\n .catch(function(err) {\n console.error('Request accept error', err);\n });\n }",
"function acceptGroupInvitation(feedRequest) {\n\n feedRequest.set('type', 'GroupJoin');\n\n Parse.Promise.when([\n feedRequest.get(\"group\"),\n feedRequest.get(\"fromUser\"),\n feedRequest.get(\"toUsers\"),\n feedRequest.save()\n ]).then(function(group, user, toUsers, feedRequestSaved){\n\n var promises = [];\n\n var Feed = Parse.Object.extend(\"Feed\");\n var feedQuery = new Parse.Query(Feed);\n feedQuery.equalTo('churchId', appID);\n feedQuery.equalTo('requestStatus', 'request');\n feedQuery.equalTo('group', group);\n feedQuery.equalTo('type', 'GroupInvitation');\n feedQuery.containsAll('toUsers', toUsers);\n\n promises.push(feedQuery.first());\n\n group.add('joinedUsers', currentUser);\n promises.push(group.save());\n\n promises.push(pushNotificationManager.sendGroupRefreshNotification(group.id));\n promises.push(pushNotificationManager.sendFeedNotification(toUsers));\n promises.push(pushNotificationManager.sendGroupJoinAcceptedNotification(user)); \n return Parse.Promise.when(promises);\n\n }).then(function(oldInvitation){\n\n if (oldInvitation) {\n return oldInvitation.destroy();\n }else{\n return;\n }\n \n });\n\n}",
"static async newGroupRequest(newRequest) {\n\t\tconst masterSite = \"kite\";\n const connection = db.getConnection(); \n const requestType = newRequest.requestType;\n const requestTypeText = newRequest.requestTypeText;\n const requestIsPending = 1;\n const groupUsers = newRequest.sentTo;\n const requestFrom = newRequest.sentBy;\n const groupID = newRequest.groupID;\n\n //Create request and Loop over members\n for(let i = 0; i < groupUsers.length; i++) {\n\t\t\tlet requestTo = groupUsers[i];\n\t\t\tif(requestTo != requestFrom) {\n\t\t\n\t\t\t\t//Step 1: Check if there is already a request \n\t\t\t\tconst queryString = \"SELECT COUNT(*) AS requestCount FROM pending_requests WHERE request_type = ? AND sent_by = ? AND sent_to = ? AND request_is_pending = '1' AND group_id = ?\"\t\t\t\n\t\t\t\tconst insertString = \"INSERT INTO pending_requests (master_site, request_type, request_type_text, request_is_pending, sent_by, sent_to, group_id) VALUES (?, ?, ?, ?, ?, ?, ?)\"\n\n\t\t\t\tconnection.query(queryString, [newRequest.requestType, requestFrom, requestTo, groupID], (err, rows) => {\n\t\t\t\t\tif (!err) {\n\n\t\t\t\t\t\t//Step 2: Insert Record if it is new \n\t\t\t\t\t\tconst existingRequestCount = rows[0].requestCount;\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\tif(existingRequestCount == 0) {\n\t\t\t\t\t\t\tconsole.log(\"MAKEY \" + requestTo + \" \" + existingRequestCount);\n\t\t\t\t\t\t\tconnection.query(insertString, [masterSite, requestType, requestTypeText, requestIsPending, requestFrom, requestTo, groupID], (err, results) => {\n\t\t\t\t\t\t\t\tif (!err) {\n\t\t\t\t\t\t\t\t\tconsole.log(\"You created a new Request with ID \" + results.insertId); \n\t\t\t\t\t\t\t\t} else { \n\t\t\t\t\t\t\t\t\tconsole.log(err)\n\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t}) \t\t\t\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tconsole.log(\"NO MAKEY \" + requestTo + \" \" + existingRequestCount);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(\"Failed to Select Requests: \" + err);\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}\n }\n\t\t\n\t//Function End\n }",
"function joinGroup(request, response, params) {\n var groupname = params.groupname;\n var username = utils.getUser(request);\n var groupExistenceQuery =\n \"SELECT group_id \" + \n \"FROM groups \" + \n \"WHERE group_name='\" + groupname + \"' AND privacy='public'\";\n\n pg.connect(connectionString, function(err, client, done) {\n client.query(groupExistenceQuery, function(err, result) {\n if(err) {\n return utils.respondError(err, response);\n }\n \n var payload = {\n success: false,\n groupId: -1,\n userAlreadyInGroup : false\n }\n \n if (result.rows.length > 0) {\n // Insert the user in the existing group.\n payload.success = true;\n payload.groupId = result.rows[0].group_id;\n insertUserIntoMemberOf(request, response, client, done, \n function(inGroup) {\n done(client);\n payload.userAlreadyInGroup = inGroup;\n utils.respondJSON(response, payload);\n },\n result.rows[0].group_id, username);\n } else {\n utils.respondJSON(response, payload);\n }\n });\n });\n}",
"function requestGroup(user, group, access){\n\nconsole.log(user + group);\n $.ajax({\n url:\"request_group/\", //the end point\n type: \"POST\", //http method\n data : { user:user, group:group }, // data sent with the post\n \n\n // handle success\n success : function(json){\n console.log(\"Success\")\n if (access == 1){\n console.log(\"Success access 1\")\n $('.confirmation').prepend(\n \"<h5> You have joined this group</h5>\")\n }\n\n if (access == 2){\n console.log(\"Success access 2\")\n $('.confirmation').prepend(\n \"<h5> You have requested to join this group</h5>\")\n }\n \n },\n\n // handle non success\n\n error : function(xhr,errmsg,err){\n $('#results').html(\"<div class='alert-box alert radius' data-alert> Failed again steve!\" +errmsg+ \"<a href='#' class='close'>×</a></div>\");\n console.log(xhr.status + \": \" + xhr.responseText)\n\n }\n });\n $(\".join-button\").hide();\n \n}",
"joinTopicOutgoing(request, socket, self){\n console.log(\"Join topic outgoing request received from client\");\n let envelop = new Envelope(request, request.headers.destination, \"request\");\n self.connector.send(envelop)\n .then(()=>{\n self.pendingTopicJoins[request.body.inviteCode] = {socketID: socket.id, publicKey: request.body.invitee.publicKey };\n console.log(\"Join request attempted to be sent successfully\");\n })\n .catch((err)=>{\n console.log(\"Join request failed to be sent: \" + err);\n throw err;\n })\n }",
"function requestToJoinGroup() {\n const reqBody = { message: message }\n axios\n .post(`/api/v1/${modalType}/${modalId}/request`, reqBody)\n .then((res) => {\n makeRequest()\n closeRequestModal()\n })\n .catch((err) => {\n console.log(err)\n })\n }",
"function onPlayerJoinGroup(groupId, peerId) {\n return true;\n}",
"function handleJoin() {\n axios.post('http://localhost:3001/api/groups/join/' + groupname)\n .then((response) =>\n {\n alert(response.data)\n if (response.status === 200) {\n setMember(true)\n } \n }\n )\n }",
"function acceptGroupInvite(req, res) {\n\tconst currentUser = req.body.currentUser;\n\tconst groupID = req.body.groupID;\n\tconst requestID = req.body.requestID;\n\tGroup.acceptGroupInvite(groupID, currentUser, requestID)\n\t\n\tres.json({currentUser: currentUser, groupID: groupID});\n}",
"function onAcceptMembership(data, textStatus, jqXHR) {\n if (data.meta.code == 200) {\n refreshGroupsWhereUserIsMemberOf();\n console.log(\"You accepted the request.\");\n } else {\n alertAPIError(data.meta.message);\n }\n}",
"function joinGroup(groupId){\n if (validateGroupId(groupId)){\n socket.emit(\"JoinGroup\", groupId);\n } else {\n alert(\"Invalid Group Id\");\n }\n}",
"function onLeaveGroup(data, textStatus, jqXHR) {\n if (data.meta.code == 200) {\n refreshGroupsWhereUserIsMemberOf();\n console.log(\"You left the group.\");\n } else {\n alertAPIError(data.meta.message);\n }\n}",
"function handle_request_decision(event, callback, context) {\n let req_id = get_event_property(event, 'request_id', callback);\n let adm_username = get_event_property(event, 'admin_username', callback);\n let adm_passhash = get_event_property(event, 'admin_passhash', callback);\n let group_id = get_event_property(event, 'group_id', callback);\n let decision = get_event_property(event, 'decision', callback);\n\n /*\n *calls a MySQL Procedure to eihether add the user to the group or only\n *delete their request\n */\n let statement = SqlString.format(\n 'CALL request_decision(?, ?, ?, ?, ?);',\n [req_id, adm_username, adm_passhash, group_id, decision]\n );\n\n return handle_statement({statement: statement}, callback, context);\n}",
"join() {\n if (this.ancestor) this.ancestor.dispatchEvent(Events.createRequest(this));\n }",
"handleAddGroup() {\n\t\tthis.fetchGroups();\n\t\tthis.addGroup();\n\t\t//this.fetchGroups();\n\t}",
"function onAddGroup(data, textStatus, jqXHR) {\n if (data.meta.code == 200) {\n refreshGroupsWhereUserIsMemberOf();\n console.log(\"Group created.\");\n } else {\n alertAPIError(data.meta.message);\n }\n}",
"function declineJoinRequest() {\n\n console.log('Decline join request');\n\n joinRequest.decline()\n .then(function() {\n console.log('Join request was declined');\n document.getElementById('joinRequest').style.display = 'none';\n })\n .catch(function(err) {\n console.error('Request decline error', err);\n });\n }",
"function NotifyGroupJoin(obj, bot) {\n // Send Invitation to join group to Pending Members\n obj.pending_members.forEach(pending_member => {\n bot.startPrivateConversationWithPersonId(pending_member.id, function(err, convo) {\n if (err) throw err;\n // Start conversation\n convo.sayFirst(obj.admin_name + ' has invited you to join the ' + obj.group_name + ' lunch group!');\n convo.addQuestion('To accept/decline, please reply yes or no.', [{\n pattern: bot.utterances.yes,\n callback: function(response, convo) {\n HelperService.AddPersonToGroup(pending_member, obj.group_name)\n .then(function(msg) {\n convo.say(msg);\n convo.next('stop');\n })\n .catch(function(error) {\n convo.setVar('error', error);\n convo.gotoThread('error');\n convo.next(error);\n });\n }\n },\n {\n pattern: bot.utterances.no,\n callback: function(response, convo) {\n HelperService.RemovePersonFromGroup(pending_member, obj.group_name)\n .then(function(msg) {\n convo.say(msg);\n convo.next('stop');\n })\n .catch(function(error) {\n convo.setVar('error', error);\n convo.gotoThread('error');\n convo.next(error);\n });\n }\n },\n {\n default: true,\n callback: function(response, convo) {\n // just repeat the question\n convo.gotoThread('default');\n convo.next();\n }\n }\n ], {}, 'default');\n // Error thread\n convo.addMessage({\n text: '\\u274c Oh no I had an error! {{vars.error}}'\n }, 'error');\n });\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make layer div again acc to the array | function updateLayersDiv(){
var node = document.querySelector(".layer-list");
node.innerHTML = '';
for(var i = layersArray.length-1; i>=0; i--){
node.appendChild(layersArray[i].layerIndicatorDiv)
}
} | [
"function layering() {\n\t//get all objectss\n\tlet items = document.getElementsByClassName(\"object\");\n\n\tfor(let j = 0; j < items.length; j++)\n\t{\n\t\t//layer is equal to y coordinate\n\t\t// console.log(items)\n\t\titems[j].style.zIndex = 5;\n\t}\n}",
"createLayerElements(){\n let arr = []\n if(this.state.bubbleLayer){\n for(let i = 0; i < 100; i++){\n arr.push('bubble'+i)\n }\n } else {\n arr = []\n }\n\n return arr;\n }",
"function drawTileList(div,arr){\r\n\t\tclearNodes(div);\r\n\t\tif(arr.length == 0){\r\n\t\t\tvar text = document.createTextNode(\"None (click to add)\");\r\n\t\t\tdiv.appendChild(text);\r\n\t\t}\r\n\t\telse{\r\n\t\t\tfor(var i=0;i<arr.length;i++){\r\n\t\t\t\t//get the tile\r\n\t\t\t\tvar tile = cloneTile(arr[i]);\r\n\t\t\t\ttile.style.float = \"initial\";\r\n\t\t\t\ttile.style.border = \"1px solid white\";\r\n\t\t\t\tdiv.appendChild(tile);\r\n\t\t\t\tif(arr[i] < 10){\r\n\t\t\t\t\tarr[i] = \"0\" + arr[i];\r\n\t\t\t\t}\r\n\t\t\t\tvar text = document.createTextNode(\" (\" + arr[i] + \") \");\r\n\t\t\t\tdiv.appendChild(text);\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"function displayWorld(arr) {\n\tvar htmlString = \"\";\n\tfor(var i = 0; i < arr.length; i++) {\n\t\thtmlString+='<div class=\"row\">';\n\t\tfor(var j = 0; j < arr[i].length; j++) {\n\t\t\tif(arr[i][j]==2) {\n\t\t\t\thtmlString+='<div class=\"brick\"></div>';\n\t\t\t} else if (arr[i][j]==1) {\n\t\t\t\thtmlString+='<div class=\"empty\"><div class=\"dot\"></div></div>';\n\t\t\t} else if (arr[i][j]==0) {\n\t\t\t\thtmlString+='<div class=\"empty\"></div>';\n\t\t\t} else if (arr[i][j]==3) {\n\t\t\t\thtmlString+='<div class=\"cherry\"></div>';\n\t\t\t}\n\t\t}\n\t\thtmlString+='</div>';\n\t}\n\tthis.loop = function(){\n\t\tmoveGhost(ghosts);\n\t}\n\tdocument.getElementById('container').style.width = (arr[0].length)*20+\"px\";\n\tdocument.getElementById('world').innerHTML = htmlString;\n}",
"function render(arr){\n \tvar container = document.getElementsByClassName('outfit-images')[0];\n container.innerHTML = \"\";\n\t\tfor (var i = 0; i < arr.length; i++) {\n\t\t\tvar backgroundImgUrl = arr[i].img;\n\t\t\tvar outfitId = arr[i].id;\n\t\t\tvar makeDiv = document.createElement('div');\n\t\t\tvar outfitContainer = document.getElementsByClassName(\"outfit-images\")[0];\n\n\t\t\tmakeDiv.id = outfitId;\n\t\t\tmakeDiv.className = 'col-sm-2 outfit-image';\n\t\t\toutfitContainer.appendChild(makeDiv);\n\n\t\t\tfunction setBackground(n) {\n\t \t\tdocument.getElementById(n).style.backgroundImage = \"url('\" + backgroundImgUrl + \"')\";\n\t \t}\n\n\t \tsetBackground(outfitId);\n\t\t};\n\t}",
"function render(arr){\n\t\tfor (var i = 0; i < arr.length; i++) {\n\t\t\tvar backgroundImgUrl = arr[i].img;\n\t\t\tvar outfitId = arr[i].id;\n\t\t\tvar makeDiv = document.createElement('div');\n\t\t\tvar outfitContainer = document.getElementsByClassName(\"outfit-images\")[0];\n\n\t\t\tmakeDiv.id = outfitId;\n\t\t\tmakeDiv.className = 'col-sm-2 outfit-image';\n\t\t\toutfitContainer.appendChild(makeDiv);\n\n\t\t\tfunction setBackground(n) {\n\t \t\tdocument.getElementById(n).style.backgroundImage = \"url('\" + backgroundImgUrl + \"')\";\n\t \t}\n\n\t \tsetBackground(outfitId);\n\t\t};\n\t}",
"function createDiv(){\n var wrapDiv = document.getElementById('wrap');\n for (var i = 0; i < tagsObj.length; i++) {\n for (var j = 0; j < tagsObj[i].length; j++) {\n for (var k = 0; k < tagsObj[i][j].length; k++) {\n var tag = tagsObj[i][j][k];\n var div = tag.div;\n wrapDiv.appendChild(div);\n tag.setCoordinates();\n addListener(tag);\n };\n }}\n }",
"generateLayers() {\n // create the canvas container div\n this.canvasDiv = {};\n this.canvasDiv.element = document.createElement('div'); this.canvasDiv.element.setAttribute('style', `width: ${this.width}px; height: ${this.height}px; background: #000000;`);\n this.canvasDiv.element.id = 'domParent';\n document.body.appendChild(this.canvasDiv.element);\n\n // create a tmp div for generating images offscreen\n this.tmpDiv = document.createElement('div');\n this.tmpDiv.setAttribute('style', `width: 50px; height: 50px; position: absolute; left: -99999px`);\n this.tmpDiv.id = 'hidden';\n document.body.appendChild(this.tmpDiv);\n\n // the layers array and id counter\n this.layers = [];\n this.canvasId = 0;\n\n // the layers we are going to generate,\n // defaults to 2d\n const layers = [\n { name: 'background' },\n { name: 'primary' },\n { name: 'character' },\n {\n name: 'object3d',\n type: '3d',\n lightCameraZ: 300\n },\n { name: 'secondary' },\n { name: 'override' },\n { name: 'shadow' },\n {\n name: 'shadow3d',\n type: '3d'\n },\n {\n name: 'shadow3dtexture',\n type: '3d'\n },\n { name: 'mouse' },\n { name: 'hude' },\n { name: 'menu' },\n { name: 'debug' },\n {\n name: 'tmp',\n appendTo: this.tmpDiv\n },\n ];\n\n for (let i = 0; i < layers.length; i++) {\n // get a unique id\n this.canvasId++;\n const id = `canvas-${this.canvasId}`;\n\n const layer = new Layer();\n layer.create(id, layers[i]);\n\n // add 'er to the stack\n this.layers.push(layer);\n }\n\n // get explicit reference to debug layer\n this.debugLayer = this.getLayerByName('debug');\n this.debugKeys = [];\n this.debugText = [];\n\n // primary, secondary, override\n this.primaryLayer = this.getLayerByName('primary');\n this.secondaryLayer = this.getLayerByName('secondary');\n this.overrideLayer = this.getLayerByName('override');\n\n // get reference to shadow layer\n this.shadowLayer = this.getLayerByName('shadow');\n\n // reference to our 3d layers\n this.object3dLayer = this.getLayerByName('object3d');\n this.shadow3dLayer = this.getLayerByName('shadow3d');\n }",
"generateLayers() {\n // create the canvas container div\n this.canvasDiv = {};\n this.canvasDiv.element = document.createElement('div');;\n this.canvasDiv.element.setAttribute('style', `width: ${this.width}px; height: ${this.height}px; background: #000000;`);\n this.canvasDiv.element.id = 'domParent';\n document.body.appendChild(this.canvasDiv.element);\n\n // create a tmp div for generating images offscreen\n this.tmpDiv = document.createElement('div');\n this.tmpDiv.setAttribute('style', `width: 50px; height: 50px; position: absolute; left: -99999px`);\n this.tmpDiv.id = 'hidden';\n document.body.appendChild(this.tmpDiv);\n\n // the layers array and id counter\n this.layers = [];\n this.canvasId = 0;\n\n // the layers we are going to generate,\n // defaults to 2d\n const layers = [\n { name: 'background' },\n { name: 'primary' },\n { name: 'character' },\n {\n name: 'object3d',\n type: '3d',\n lightCameraZ: 300\n },\n { name: 'secondary' },\n { name: 'override' },\n { name: 'shadow' },\n {\n name: 'shadow3d',\n type: '3d'\n },\n {\n name: 'shadow3dtexture',\n type: '3d'\n },\n { name: 'mouse' },\n { name: 'hude' },\n { name: 'menu' },\n { name: 'debug' },\n {\n name: 'tmp',\n appendTo: this.tmpDiv\n },\n ];\n\n for (let i = 0; i < layers.length; i++) {\n // get a unique id\n this.canvasId++;\n const id = `canvas-${this.canvasId}`;\n\n const layer = new Layer();\n layer.create(id, layers[i]);\n\n // add 'er to the stack\n this.layers.push(layer);\n }\n\n // get explicit reference to debug layer\n this.debugLayer = this.getLayerByName('debug');\n this.debugKeys = [];\n this.debugText = [];\n\n // primary, secondary, override\n this.primaryLayer = this.getLayerByName('primary');\n this.secondaryLayer = this.getLayerByName('secondary');\n this.overrideLayer = this.getLayerByName('override');\n\n // get reference to shadow layer\n this.shadowLayer = this.getLayerByName('shadow');\n\n // reference to our 3d layers\n this.object3dLayer = this.getLayerByName('object3d');\n this.shadow3dLayer = this.getLayerByName('shadow3d');\n }",
"buildOverlays() {\n this.components.elements.forEach((elm, index) => this.components.overlays.push(this.overlay(elm, index)));\n this.components.overlays.forEach(overlay => document.body.appendChild(overlay));\n }",
"function makeLayerContainer() {\r\n layerContainer = $(document.createElement('img'))\r\n .attr({\r\n src: currSource\r\n })\r\n .addClass('layerContainer')\r\n .appendTo(root);\r\n\r\n // add manipulation handlers\r\n LADS.Util.makeManipulatable(layerContainer[0], {\r\n onManipulate: function (res) {\r\n var l = layerContainer.offset().left, // TODO might need to update this for web app\r\n t = layerContainer.offset().top,\r\n tx = res.translation.x,\r\n ty = res.translation.y;\r\n\r\n layerContainer.css({\r\n left: (l + tx) + 'px',\r\n top: (t + ty) + 'px'\r\n });\r\n\r\n annotatedImage.viewer.drawer.updateOverlay(layerContainer[0], getLayerRect());\r\n },\r\n onScroll: function (res, pivot) {\r\n var l = layerContainer.offset().left, // TODO might need to update this for web app\r\n t = layerContainer.offset().top,\r\n w = layerContainer.width(),\r\n h = layerContainer.height(),\r\n newW = w * res,\r\n newH = h * res;\r\n\r\n annotatedImage.viewer.drawer.removeOverlay(layerContainer[0]); // remove and re-add to ensure correct positioning if we move artwork\r\n root.append(layerContainer);\r\n\r\n layerContainer.css({\r\n left: (l + (1 - res) * (pivot.x)) + 'px',\r\n top: (t + (1 - res) * (pivot.y)) + 'px',\r\n width: newW + 'px',\r\n height: newH + 'px',\r\n position: 'absolute'\r\n });\r\n\r\n annotatedImage.viewer.drawer.addOverlay(layerContainer[0], getLayerRect());\r\n }\r\n }, false, true);\r\n\r\n //layerContainer.on('mousedown', function () {\r\n // var l = layerContainer.offset().left, // TODO might need to update this for web app\r\n // t = layerContainer.offset().top,\r\n // w = layerContainer.width(),\r\n // h = layerContainer.height();\r\n\r\n // annotatedImage.viewer.drawer.removeOverlay(layerContainer[0]); // remove to ensure correct positioning if artwork is in midst of a move\r\n // root.append(layerContainer);\r\n // layerContainer.css({\r\n // left: l + 'px',\r\n // top: t + 'px',\r\n // width: w + 'px',\r\n // height: h + 'px',\r\n // position: 'absolute'\r\n // });\r\n //});\r\n\r\n \r\n /**\r\n layerContainer.hover(function () {\r\n console.log(\"freezing\");\r\n annotatedImage.freezeArtwork();\r\n }, function () {\r\n console.log(\"unfreezing\");\r\n annotatedImage.unfreezeArtwork();\r\n });\r\n **/\r\n\r\n //Not sure why this is the combo of handlers that works, probably should refine at some point \r\n layerContainer.on(\"mousedown\", function () {\r\n annotatedImage.freezeArtwork();\r\n });\r\n //Mouse up doesn't seem to work...added on click\r\n layerContainer.on(\"mouseup\", function () {\r\n positionChanged = true;\r\n annotatedImage.unfreezeArtwork();\r\n annotatedImage.viewer.drawer.updateOverlay(layerContainer[0], getLayerRect());\r\n });\r\n layerContainer.on(\"click\", function () {\r\n positionChanged = true;\r\n annotatedImage.unfreezeArtwork();\r\n annotatedImage.viewer.drawer.updateOverlay(layerContainer[0], getLayerRect());\r\n });\r\n }",
"buildLayerContainers() {\n\t\tlet layersToAdd = [];\n\t\tfor(const l of Object.keys(this.utage.layerInfo)) {\n\t\t\tlayersToAdd.push(this.utage.layerInfo[l]);\n\t\t}\n\t\tlayersToAdd.push({LayerName: \"bg|loopeffect\", Type: \"Bg\", X: 0, Y: 0, Order: 1})\n\t\tlayersToAdd.sort(compare);\n\t\tlayersToAdd.push({LayerName: \"movie\", Type: \"Bg\", X: 0, Y: 0})\n\t\tlet parentContainer = new PIXI.Container();\n\t\tparentContainer.position.set(this.center.x, this.center.y);\n\t\tparentContainer.pivot.set(this.center.x, this.center.y);\n\t\tthis.pixi.app.stage.addChild(parentContainer);\n\t\tthis.layers[\"bg|mainparent\"] = { container: parentContainer };\n\t\tfor(const l of layersToAdd) {\n\t\t\tthis.layers[l.LayerName] = { info: l };\n\t\t\tlet cont = new PIXI.Container();\n\t\t\tthis.layers[l.LayerName].container = cont;\n\t\t\tparentContainer.addChild(cont);\n\t\t\t//center the position of the container then offset it by the value in the layer info\n\t\t\tlet x = (((baseDimensions.width / 2) + Number(l.X)) * this.resolutionScale);\n\t\t\tlet y = (((baseDimensions.height / 2) - Number(l.Y)) * this.resolutionScale);\n\t\t\tcont.position.set(x, y);\n\t\t\tcont.visible = false;\n\t\t}\n\t\tlet fadeBackCon = new PIXI.Container();\n\t\tlet fadeBackSp = new PIXI.Sprite(this.loader.resources[\"bg|whiteFade\"].texture);\n\t\tfadeBackSp.height = baseDimensions.height * this.resolutionScale;\n\t\tfadeBackSp.width = baseDimensions.width * this.resolutionScale;\n\t\tthis.layers[\"bg|whiteFade\"] = { info: undefined, sprite: fadeBackSp, container: fadeBackCon };\n\t\tfadeBackSp.alpha = 0;\n\t\tfadeBackCon.addChild(fadeBackSp);\n\t\tthis.pixi.app.stage.addChild(fadeBackCon);\n\t\t\n\t\tfunction compare(a, b) {\n\t\t\treturn a.Order - b.Order;\n\t\t}\n\t}",
"buildBackground(width) {\n for (let p = 0; p < 11; p += 1) {\n for (let b = 0; b < 3; b += 1) {\n const newImg = document.createElement('img');\n newImg.classList.add(`pane${p}`);\n newImg.classList.add(`background${b}`);\n newImg.src = (`./assets/back/layer${p}.png`);\n this.mainContainer.appendChild(newImg);\n }\n }\n for (let x = 0; x < 3; x += 1) {\n this.background.push(document.querySelectorAll(`.background${x}`));\n for (let y = 0; y < 11; y += 1) {\n this.newPos[x].push(x * width);\n }\n }\n }",
"drawTiles() {\n \n for (var i = 0; i < this.tiles.length; i++) {\n $(\"#board\").append($('<div class=\"tile hidden ' +this.tiles[i].content + '\" id=' + i + '></div>'));\n\t }\n\t \n }",
"function makeLayers() {\r try {\r if (app.documents.length) {\r var layerColor = [\"Cyan\",\"Magenta\",\"Yellow\",\"Black\"]\r var doc = activeDocument;\r var layers = doc.artLayers;\r var cmyk = [layerA= layers.add(),\r layerB= layers.add(),\r layerC= layers.add(),\r layerD= layers.add()];\r\r if (layerColor) {\r cmyk[0].name = layerColor [3];\r cmyk[0].blendMode = BlendMode.MULTIPLY\r cmyk[1].name = layerColor [2];\r cmyk[1].blendMode = BlendMode.MULTIPLY\r cmyk[2].name = layerColor [1];\r cmyk[2].blendMode = BlendMode.MULTIPLY\r cmyk[3].name = layerColor [0];\r cmyk[3].blendMode = BlendMode.MULTIPLY\r \r }\r \r doc.activeLayer = newLayer;\r }\r } catch (e) { \r }\r}",
"redrawTileArray(arr) {\n for(let i = 0; i < arr.length; i++) {\n let tile = arr[i];\n if(tile == null || tile.image == null)\n continue;\n tile.image = this.add.image(tile.image.x, tile.image.y, tile.letter).setInteractive();\n this.setTileEvents(tile);\n }\n }",
"function displayLayers()\n{\n\t//Clears out old layer images.\n\twhile(document.getElementById(\"myFrame\").contentDocument.getElementById(\"imageDiv\").hasChildNodes() == true)\n\t{\n\t\tdocument.getElementById(\"myFrame\").contentDocument.getElementById(\"imageDiv\").removeChild(document.getElementById(\"myFrame\").contentDocument.getElementById(\"imageDiv\").childNodes[0]);\n\t}\n\t\n\t//Iterates through all selected layers, sets their updated opacity, and displays\n\tvar counter = 0;\n\twhile(counter < currentListOfLayers.length)\n\t{\n\t\tcurrentListOfLayers[counter].align=\"center\";\n\t\tcurrentListOfLayers[counter].width = imageWidth;\n\t\tcurrentListOfLayers[counter].height = imageHeight;\n\t\tcurrentListOfLayers[counter].style.opacity = 1.0/(counter+1) ;//currentListOfLayers.length;\n\t\tdocument.getElementById(\"myFrame\").contentDocument.getElementById(\"imageDiv\").appendChild(currentListOfLayers[counter]);\n\t\tcounter = counter + 1;\n\t}\n\t\n}",
"function bigLeds (){\n for(let i = 0; i < bigLedArray.length; i++){\n var led = document.createElement(\"div\");\n led.className = bigLedArray[i].class;\n led.style.top = bigLedArray[i].top;\n led.style.left = bigLedArray[i].left;\n $(\".border\").prepend(led);\n }\n}",
"function showFrontInDOM() {\r\n $('.frontPoint').remove();\r\n front.all().forEach(function (point, index) {\r\n $('<div/>', {\r\n 'class': 'frontPoint'\r\n }).css('-webkit-transform', 'translate(' + point.x + 'px, ' + point.y + 'px)')\r\n .html(String(index))\r\n .appendTo('.tiles-container');\r\n });\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
handle all the children from the loaded json and attach them to given parent | function handle_children( parent, children ) {
var mat, dst, pos, rot, scl, quat;
for ( var objID in children ) {
// check by id if child has already been handled,
// if not, create new object
var object = result.objects[ objID ];
var objJSON = children[ objID ];
if ( object === undefined ) {
// meshes
if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
if ( objJSON.loading === undefined ) {
var reservedTypes = {
"type": 1, "url": 1, "material": 1,
"position": 1, "rotation": 1, "scale" : 1,
"visible": 1, "children": 1, "userData": 1,
"skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1
};
var loaderParameters = {};
for ( var parType in objJSON ) {
if ( ! ( parType in reservedTypes ) ) {
loaderParameters[ parType ] = objJSON[ parType ];
}
}
material = result.materials[ objJSON.material ];
objJSON.loading = true;
var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ];
// ColladaLoader
if ( loader.options ) {
loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
// UTF8Loader
// OBJLoader
} else {
loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
}
}
} else if ( objJSON.geometry !== undefined ) {
geometry = result.geometries[ objJSON.geometry ];
// geometry already loaded
if ( geometry ) {
var needsTangents = false;
material = result.materials[ objJSON.material ];
needsTangents = material instanceof THREE.ShaderMaterial;
pos = objJSON.position;
rot = objJSON.rotation;
scl = objJSON.scale;
mat = objJSON.matrix;
quat = objJSON.quaternion;
// use materials from the model file
// if there is no material specified in the object
if ( ! objJSON.material ) {
material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
}
// use materials from the model file
// if there is just empty face material
// (must create new material as each model has its own face material)
if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
}
if ( material instanceof THREE.MeshFaceMaterial ) {
for ( var i = 0; i < material.materials.length; i ++ ) {
needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
}
}
if ( needsTangents ) {
geometry.computeTangents();
}
if ( objJSON.skin ) {
object = new THREE.SkinnedMesh( geometry, material );
} else if ( objJSON.morph ) {
object = new THREE.MorphAnimMesh( geometry, material );
if ( objJSON.duration !== undefined ) {
object.duration = objJSON.duration;
}
if ( objJSON.time !== undefined ) {
object.time = objJSON.time;
}
if ( objJSON.mirroredLoop !== undefined ) {
object.mirroredLoop = objJSON.mirroredLoop;
}
if ( material.morphNormals ) {
geometry.computeMorphNormals();
}
} else {
object = new THREE.Mesh( geometry, material );
}
object.name = objID;
if ( mat ) {
object.matrixAutoUpdate = false;
object.matrix.set(
mat[0], mat[1], mat[2], mat[3],
mat[4], mat[5], mat[6], mat[7],
mat[8], mat[9], mat[10], mat[11],
mat[12], mat[13], mat[14], mat[15]
);
} else {
object.position.fromArray( pos );
if ( quat ) {
object.quaternion.fromArray( quat );
} else {
object.rotation.fromArray( rot );
}
object.scale.fromArray( scl );
}
object.visible = objJSON.visible;
object.castShadow = objJSON.castShadow;
object.receiveShadow = objJSON.receiveShadow;
parent.add( object );
result.objects[ objID ] = object;
}
// lights
} else if ( objJSON.type === "AmbientLight" || objJSON.type === "PointLight" ||
objJSON.type === "DirectionalLight" || objJSON.type === "SpotLight" ||
objJSON.type === "HemisphereLight" || objJSON.type === "AreaLight" ) {
var color = objJSON.color;
var intensity = objJSON.intensity;
var distance = objJSON.distance;
var position = objJSON.position;
var rotation = objJSON.rotation;
switch ( objJSON.type ) {
case 'AmbientLight':
light = new THREE.AmbientLight( color );
break;
case 'PointLight':
light = new THREE.PointLight( color, intensity, distance );
light.position.fromArray( position );
break;
case 'DirectionalLight':
light = new THREE.DirectionalLight( color, intensity );
light.position.fromArray( objJSON.direction );
break;
case 'SpotLight':
light = new THREE.SpotLight( color, intensity, distance, 1 );
light.angle = objJSON.angle;
light.position.fromArray( position );
light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
break;
case 'HemisphereLight':
light = new THREE.DirectionalLight( color, intensity, distance );
light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
break;
case 'AreaLight':
light = new THREE.AreaLight(color, intensity);
light.position.fromArray( position );
light.width = objJSON.size;
light.height = objJSON.size_y;
break;
}
parent.add( light );
light.name = objID;
result.lights[ objID ] = light;
result.objects[ objID ] = light;
// cameras
} else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
pos = objJSON.position;
rot = objJSON.rotation;
quat = objJSON.quaternion;
if ( objJSON.type === "PerspectiveCamera" ) {
camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
} else if ( objJSON.type === "OrthographicCamera" ) {
camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
}
camera.name = objID;
camera.position.fromArray( pos );
if ( quat !== undefined ) {
camera.quaternion.fromArray( quat );
} else if ( rot !== undefined ) {
camera.rotation.fromArray( rot );
}
parent.add( camera );
result.cameras[ objID ] = camera;
result.objects[ objID ] = camera;
// pure Object3D
} else {
pos = objJSON.position;
rot = objJSON.rotation;
scl = objJSON.scale;
quat = objJSON.quaternion;
object = new THREE.Object3D();
object.name = objID;
object.position.fromArray( pos );
if ( quat ) {
object.quaternion.fromArray( quat );
} else {
object.rotation.fromArray( rot );
}
object.scale.fromArray( scl );
object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
parent.add( object );
result.objects[ objID ] = object;
result.empties[ objID ] = object;
}
if ( object ) {
if ( objJSON.userData !== undefined ) {
for ( var key in objJSON.userData ) {
var value = objJSON.userData[ key ];
object.userData[ key ] = value;
}
}
if ( objJSON.groups !== undefined ) {
for ( var i = 0; i < objJSON.groups.length; i ++ ) {
var groupID = objJSON.groups[ i ];
if ( result.groups[ groupID ] === undefined ) {
result.groups[ groupID ] = [];
}
result.groups[ groupID ].push( objID );
}
}
}
}
if ( object !== undefined && objJSON.children !== undefined ) {
handle_children( object, objJSON.children );
}
}
} | [
"function handle_children( parent, children ) {\n\n var mat, dst, pos, rot, scl, quat;\n\n for ( var objID in children ) {\n\n // check by id if child has already been handled,\n // if not, create new object\n\n var object = result.objects[ objID ];\n var objJSON = children[ objID ];\n\n if ( object === undefined ) {\n\n // meshes\n\n if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {\n\n if ( objJSON.loading === undefined ) {\n\n var reservedTypes = {\n \"type\": 1, \"url\": 1, \"material\": 1,\n \"position\": 1, \"rotation\": 1, \"scale\" : 1,\n \"visible\": 1, \"children\": 1, \"userData\": 1,\n \"skin\": 1, \"morph\": 1, \"mirroredLoop\": 1, \"duration\": 1\n };\n\n var loaderParameters = {};\n\n for ( var parType in objJSON ) {\n\n if ( ! ( parType in reservedTypes ) ) {\n\n loaderParameters[ parType ] = objJSON[ parType ];\n\n }\n\n }\n\n material = result.materials[ objJSON.material ];\n\n objJSON.loading = true;\n\n var loader = scope.hierarchyHandlers[ objJSON.type ][ \"loaderObject\" ];\n\n // ColladaLoader\n\n if ( loader.options ) {\n\n loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );\n\n // UTF8Loader\n // OBJLoader\n\n } else {\n\n loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );\n\n }\n\n }\n\n } else if ( objJSON.geometry !== undefined ) {\n\n geometry = result.geometries[ objJSON.geometry ];\n\n // geometry already loaded\n\n if ( geometry ) {\n\n var needsTangents = false;\n\n material = result.materials[ objJSON.material ];\n needsTangents = material instanceof THREE.ShaderMaterial;\n\n pos = objJSON.position;\n rot = objJSON.rotation;\n scl = objJSON.scale;\n mat = objJSON.matrix;\n quat = objJSON.quaternion;\n\n // use materials from the model file\n // if there is no material specified in the object\n\n if ( ! objJSON.material ) {\n\n material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );\n\n }\n\n // use materials from the model file\n // if there is just empty face material\n // (must create new material as each model has its own face material)\n\n if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {\n\n material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );\n\n }\n\n if ( material instanceof THREE.MeshFaceMaterial ) {\n\n for ( var i = 0; i < material.materials.length; i ++ ) {\n\n needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );\n\n }\n\n }\n\n if ( needsTangents ) {\n\n geometry.computeTangents();\n\n }\n\n if ( objJSON.skin ) {\n\n object = new THREE.SkinnedMesh( geometry, material );\n\n } else if ( objJSON.morph ) {\n\n object = new THREE.MorphAnimMesh( geometry, material );\n\n if ( objJSON.duration !== undefined ) {\n\n object.duration = objJSON.duration;\n\n }\n\n if ( objJSON.time !== undefined ) {\n\n object.time = objJSON.time;\n\n }\n\n if ( objJSON.mirroredLoop !== undefined ) {\n\n object.mirroredLoop = objJSON.mirroredLoop;\n\n }\n\n if ( material.morphNormals ) {\n\n geometry.computeMorphNormals();\n\n }\n\n } else {\n\n object = new THREE.Mesh( geometry, material );\n\n }\n\n object.name = objID;\n\n if ( mat ) {\n\n object.matrixAutoUpdate = false;\n object.matrix.set(\n mat[0], mat[1], mat[2], mat[3],\n mat[4], mat[5], mat[6], mat[7],\n mat[8], mat[9], mat[10], mat[11],\n mat[12], mat[13], mat[14], mat[15]\n );\n\n } else {\n\n object.position.fromArray( pos );\n\n if ( quat ) {\n\n object.quaternion.fromArray( quat );\n\n } else {\n\n object.rotation.fromArray( rot );\n\n }\n\n object.scale.fromArray( scl );\n\n }\n\n object.visible = objJSON.visible;\n object.castShadow = objJSON.castShadow;\n object.receiveShadow = objJSON.receiveShadow;\n\n parent.add( object );\n\n result.objects[ objID ] = object;\n\n }\n\n // lights\n\n } else if ( objJSON.type === \"DirectionalLight\" || objJSON.type === \"PointLight\" || objJSON.type === \"AmbientLight\" ) {\n\n hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;\n intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;\n\n if ( objJSON.type === \"DirectionalLight\" ) {\n\n pos = objJSON.direction;\n\n light = new THREE.DirectionalLight( hex, intensity );\n light.position.fromArray( pos );\n\n if ( objJSON.target ) {\n\n target_array.push( { \"object\": light, \"targetName\" : objJSON.target } );\n\n // kill existing default target\n // otherwise it gets added to scene when parent gets added\n\n light.target = null;\n\n }\n\n } else if ( objJSON.type === \"PointLight\" ) {\n\n pos = objJSON.position;\n dst = objJSON.distance;\n\n light = new THREE.PointLight( hex, intensity, dst );\n light.position.fromArray( pos );\n\n } else if ( objJSON.type === \"AmbientLight\" ) {\n\n light = new THREE.AmbientLight( hex );\n\n }\n\n parent.add( light );\n\n light.name = objID;\n result.lights[ objID ] = light;\n result.objects[ objID ] = light;\n\n // cameras\n\n } else if ( objJSON.type === \"PerspectiveCamera\" || objJSON.type === \"OrthographicCamera\" ) {\n\n pos = objJSON.position;\n rot = objJSON.rotation;\n quat = objJSON.quaternion;\n\n if ( objJSON.type === \"PerspectiveCamera\" ) {\n\n camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );\n\n } else if ( objJSON.type === \"OrthographicCamera\" ) {\n\n camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );\n\n }\n\n camera.name = objID;\n camera.position.fromArray( pos );\n\n if ( quat !== undefined ) {\n\n camera.quaternion.fromArray( quat );\n\n } else if ( rot !== undefined ) {\n\n camera.rotation.fromArray( rot );\n\n }\n\n parent.add( camera );\n\n result.cameras[ objID ] = camera;\n result.objects[ objID ] = camera;\n\n // pure Object3D\n\n } else {\n\n pos = objJSON.position;\n rot = objJSON.rotation;\n scl = objJSON.scale;\n quat = objJSON.quaternion;\n\n object = new THREE.Object3D();\n object.name = objID;\n object.position.fromArray( pos );\n\n if ( quat ) {\n\n object.quaternion.fromArray( quat );\n\n } else {\n\n object.rotation.fromArray( rot );\n\n }\n\n object.scale.fromArray( scl );\n object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;\n\n parent.add( object );\n\n result.objects[ objID ] = object;\n result.empties[ objID ] = object;\n\n }\n\n if ( object ) {\n\n if ( objJSON.userData !== undefined ) {\n\n for ( var key in objJSON.userData ) {\n\n var value = objJSON.userData[ key ];\n object.userData[ key ] = value;\n\n }\n\n }\n\n if ( objJSON.groups !== undefined ) {\n\n for ( var i = 0; i < objJSON.groups.length; i ++ ) {\n\n var groupID = objJSON.groups[ i ];\n\n if ( result.groups[ groupID ] === undefined ) {\n\n result.groups[ groupID ] = [];\n\n }\n\n result.groups[ groupID ].push( objID );\n\n }\n\n }\n\n }\n\n }\n\n if ( object !== undefined && objJSON.children !== undefined ) {\n\n handle_children( object, objJSON.children );\n\n }\n\n }\n\n }",
"function handle_children(parent, children) {\n\t\tvar mat, dst, pos, rot, scl, quat;\n\n\t\tfor (var objID in children) {\n\t\t\t// check by id if child has already been handled,\n\t\t\t// if not, create new object\n\n\t\t\tif (result.objects[objID] === undefined) {\n\t\t\t\tvar objJSON = children[objID];\n\n\t\t\t\tvar object = null;\n\n\t\t\t\t// meshes\n\n\t\t\t\tif (objJSON.type && objJSON.type in scope.hierarchyHandlerMap) {\n\t\t\t\t\tif (objJSON.loading === undefined) {\n\t\t\t\t\t\tvar reservedTypes = {\n\t\t\t\t\t\t\ttype: 1,\n\t\t\t\t\t\t\turl: 1,\n\t\t\t\t\t\t\tmaterial: 1,\n\t\t\t\t\t\t\tposition: 1,\n\t\t\t\t\t\t\trotation: 1,\n\t\t\t\t\t\t\tscale: 1,\n\t\t\t\t\t\t\tvisible: 1,\n\t\t\t\t\t\t\tchildren: 1,\n\t\t\t\t\t\t\tuserData: 1,\n\t\t\t\t\t\t\tskin: 1,\n\t\t\t\t\t\t\tmorph: 1,\n\t\t\t\t\t\t\tmirroredLoop: 1,\n\t\t\t\t\t\t\tduration: 1\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tvar loaderParameters = {};\n\n\t\t\t\t\t\tfor (var parType in objJSON) {\n\t\t\t\t\t\t\tif (!(parType in reservedTypes)) {\n\t\t\t\t\t\t\t\tloaderParameters[parType] = objJSON[parType];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tmaterial = result.materials[objJSON.material];\n\n\t\t\t\t\t\tobjJSON.loading = true;\n\n\t\t\t\t\t\tvar loader = scope.hierarchyHandlerMap[objJSON.type][\"loaderObject\"];\n\n\t\t\t\t\t\t// ColladaLoader\n\n\t\t\t\t\t\tif (loader.options) {\n\t\t\t\t\t\t\tloader.load(get_url(objJSON.url, data.urlBaseType), create_callback_hierachy(objID, parent, material, objJSON));\n\n\t\t\t\t\t\t\t// UTF8Loader\n\t\t\t\t\t\t\t// OBJLoader\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tloader.load(get_url(objJSON.url, data.urlBaseType), create_callback_hierachy(objID, parent, material, objJSON), loaderParameters);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (objJSON.geometry !== undefined) {\n\t\t\t\t\tgeometry = result.geometries[objJSON.geometry];\n\n\t\t\t\t\t// geometry already loaded\n\n\t\t\t\t\tif (geometry) {\n\t\t\t\t\t\tvar needsTangents = false;\n\n\t\t\t\t\t\tmaterial = result.materials[objJSON.material];\n\t\t\t\t\t\tneedsTangents = material instanceof THREE.ShaderMaterial;\n\n\t\t\t\t\t\tpos = objJSON.position;\n\t\t\t\t\t\trot = objJSON.rotation;\n\t\t\t\t\t\tscl = objJSON.scale;\n\t\t\t\t\t\tmat = objJSON.matrix;\n\t\t\t\t\t\tquat = objJSON.quaternion;\n\n\t\t\t\t\t\t// use materials from the model file\n\t\t\t\t\t\t// if there is no material specified in the object\n\n\t\t\t\t\t\tif (!objJSON.material) {\n\t\t\t\t\t\t\tmaterial = new THREE.MeshFaceMaterial(result.face_materials[objJSON.geometry]);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// use materials from the model file\n\t\t\t\t\t\t// if there is just empty face material\n\t\t\t\t\t\t// (must create new material as each model has its own face material)\n\n\t\t\t\t\t\tif (material instanceof THREE.MeshFaceMaterial && material.materials.length === 0) {\n\t\t\t\t\t\t\tmaterial = new THREE.MeshFaceMaterial(result.face_materials[objJSON.geometry]);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (material instanceof THREE.MeshFaceMaterial) {\n\t\t\t\t\t\t\tfor (var i = 0; i < material.materials.length; i++) {\n\t\t\t\t\t\t\t\tneedsTangents = needsTangents || material.materials[i] instanceof THREE.ShaderMaterial;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (needsTangents) {\n\t\t\t\t\t\t\tgeometry.computeTangents();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (objJSON.skin) {\n\t\t\t\t\t\t\tobject = new THREE.SkinnedMesh(geometry, material);\n\t\t\t\t\t\t} else if (objJSON.morph) {\n\t\t\t\t\t\t\tobject = new THREE.MorphAnimMesh(geometry, material);\n\n\t\t\t\t\t\t\tif (objJSON.duration !== undefined) {\n\t\t\t\t\t\t\t\tobject.duration = objJSON.duration;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (objJSON.time !== undefined) {\n\t\t\t\t\t\t\t\tobject.time = objJSON.time;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (objJSON.mirroredLoop !== undefined) {\n\t\t\t\t\t\t\t\tobject.mirroredLoop = objJSON.mirroredLoop;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (material.morphNormals) {\n\t\t\t\t\t\t\t\tgeometry.computeMorphNormals();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tobject = new THREE.Mesh(geometry, material);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tobject.name = objID;\n\n\t\t\t\t\t\tif (mat) {\n\t\t\t\t\t\t\tobject.matrixAutoUpdate = false;\n\t\t\t\t\t\t\tobject.matrix.set(mat[0], mat[1], mat[2], mat[3], mat[4], mat[5], mat[6], mat[7], mat[8], mat[9], mat[10], mat[11], mat[12], mat[13], mat[14], mat[15]);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tobject.position.set(pos[0], pos[1], pos[2]);\n\n\t\t\t\t\t\t\tif (quat) {\n\t\t\t\t\t\t\t\tobject.quaternion.set(quat[0], quat[1], quat[2], quat[3]);\n\t\t\t\t\t\t\t\tobject.useQuaternion = true;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tobject.rotation.set(rot[0], rot[1], rot[2]);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tobject.scale.set(scl[0], scl[1], scl[2]);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tobject.visible = objJSON.visible;\n\t\t\t\t\t\tobject.castShadow = objJSON.castShadow;\n\t\t\t\t\t\tobject.receiveShadow = objJSON.receiveShadow;\n\n\t\t\t\t\t\tparent.add(object);\n\n\t\t\t\t\t\tresult.objects[objID] = object;\n\t\t\t\t\t}\n\n\t\t\t\t\t// lights\n\t\t\t\t} else if (objJSON.type === \"DirectionalLight\" || objJSON.type === \"PointLight\" || objJSON.type === \"AmbientLight\") {\n\t\t\t\t\thex = objJSON.color !== undefined ? objJSON.color : 0xffffff;\n\t\t\t\t\tintensity = objJSON.intensity !== undefined ? objJSON.intensity : 1;\n\n\t\t\t\t\tif (objJSON.type === \"DirectionalLight\") {\n\t\t\t\t\t\tpos = objJSON.direction;\n\n\t\t\t\t\t\tlight = new THREE.DirectionalLight(hex, intensity);\n\t\t\t\t\t\tlight.position.set(pos[0], pos[1], pos[2]);\n\n\t\t\t\t\t\tif (objJSON.target) {\n\t\t\t\t\t\t\ttarget_array.push({ object: light, targetName: objJSON.target });\n\n\t\t\t\t\t\t\t// kill existing default target\n\t\t\t\t\t\t\t// otherwise it gets added to scene when parent gets added\n\n\t\t\t\t\t\t\tlight.target = null;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (objJSON.type === \"PointLight\") {\n\t\t\t\t\t\tpos = objJSON.position;\n\t\t\t\t\t\tdst = objJSON.distance;\n\n\t\t\t\t\t\tlight = new THREE.PointLight(hex, intensity, dst);\n\t\t\t\t\t\tlight.position.set(pos[0], pos[1], pos[2]);\n\t\t\t\t\t} else if (objJSON.type === \"AmbientLight\") {\n\t\t\t\t\t\tlight = new THREE.AmbientLight(hex);\n\t\t\t\t\t}\n\n\t\t\t\t\tparent.add(light);\n\n\t\t\t\t\tlight.name = objID;\n\t\t\t\t\tresult.lights[objID] = light;\n\t\t\t\t\tresult.objects[objID] = light;\n\n\t\t\t\t\t// cameras\n\t\t\t\t} else if (objJSON.type === \"PerspectiveCamera\" || objJSON.type === \"OrthographicCamera\") {\n\t\t\t\t\tif (objJSON.type === \"PerspectiveCamera\") {\n\t\t\t\t\t\tcamera = new THREE.PerspectiveCamera(objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far);\n\t\t\t\t\t} else if (objJSON.type === \"OrthographicCamera\") {\n\t\t\t\t\t\tcamera = new THREE.OrthographicCamera(objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far);\n\t\t\t\t\t}\n\n\t\t\t\t\tpos = objJSON.position;\n\t\t\t\t\tcamera.position.set(pos[0], pos[1], pos[2]);\n\t\t\t\t\tparent.add(camera);\n\n\t\t\t\t\tcamera.name = objID;\n\t\t\t\t\tresult.cameras[objID] = camera;\n\t\t\t\t\tresult.objects[objID] = camera;\n\n\t\t\t\t\t// pure Object3D\n\t\t\t\t} else {\n\t\t\t\t\tpos = objJSON.position;\n\t\t\t\t\trot = objJSON.rotation;\n\t\t\t\t\tscl = objJSON.scale;\n\t\t\t\t\tquat = objJSON.quaternion;\n\n\t\t\t\t\tobject = new THREE.Object3D();\n\t\t\t\t\tobject.name = objID;\n\t\t\t\t\tobject.position.set(pos[0], pos[1], pos[2]);\n\n\t\t\t\t\tif (quat) {\n\t\t\t\t\t\tobject.quaternion.set(quat[0], quat[1], quat[2], quat[3]);\n\t\t\t\t\t\tobject.useQuaternion = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tobject.rotation.set(rot[0], rot[1], rot[2]);\n\t\t\t\t\t}\n\n\t\t\t\t\tobject.scale.set(scl[0], scl[1], scl[2]);\n\t\t\t\t\tobject.visible = objJSON.visible !== undefined ? objJSON.visible : false;\n\n\t\t\t\t\tparent.add(object);\n\n\t\t\t\t\tresult.objects[objID] = object;\n\t\t\t\t\tresult.empties[objID] = object;\n\t\t\t\t}\n\n\t\t\t\tif (object) {\n\t\t\t\t\tif (objJSON.userData !== undefined) {\n\t\t\t\t\t\tfor (var key in objJSON.userData) {\n\t\t\t\t\t\t\tvar value = objJSON.userData[key];\n\t\t\t\t\t\t\tobject.userData[key] = value;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (objJSON.groups !== undefined) {\n\t\t\t\t\t\tfor (var i = 0; i < objJSON.groups.length; i++) {\n\t\t\t\t\t\t\tvar groupID = objJSON.groups[i];\n\n\t\t\t\t\t\t\tif (result.groups[groupID] === undefined) {\n\t\t\t\t\t\t\t\tresult.groups[groupID] = [];\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tresult.groups[groupID].push(objID);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (objJSON.children !== undefined) {\n\t\t\t\t\t\thandle_children(object, objJSON.children);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"function handle_children( parent, children ) {\n\n\t\tvar mat, dst, pos, rot, scl, quat;\n\n\t\tfor ( var objID in children ) {\n\n\t\t\t// check by id if child has already been handled,\n\t\t\t// if not, create new object\n\n\t\t\tif ( result.objects[ objID ] === undefined ) {\n\n\t\t\t\tvar objJSON = children[ objID ];\n\n\t\t\t\tvar object = null;\n\n\t\t\t\t// meshes\n\n\t\t\t\tif ( objJSON.type && ( objJSON.type in scope.hierarchyHandlerMap ) ) {\n\n\t\t\t\t\tif ( objJSON.loading === undefined ) {\n\n\t\t\t\t\t\tvar reservedTypes = { \"type\": 1, \"url\": 1, \"material\": 1,\n\t\t\t\t\t\t\t\t\t\t\t \"position\": 1, \"rotation\": 1, \"scale\" : 1,\n\t\t\t\t\t\t\t\t\t\t\t \"visible\": 1, \"children\": 1, \"userData\": 1,\n\t\t\t\t\t\t\t\t\t\t\t \"skin\": 1, \"morph\": 1, \"mirroredLoop\": 1, \"duration\": 1 };\n\n\t\t\t\t\t\tvar loaderParameters = {};\n\n\t\t\t\t\t\tfor ( var parType in objJSON ) {\n\n\t\t\t\t\t\t\tif ( ! ( parType in reservedTypes ) ) {\n\n\t\t\t\t\t\t\t\tloaderParameters[ parType ] = objJSON[ parType ];\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tmaterial = result.materials[ objJSON.material ];\n\n\t\t\t\t\t\tobjJSON.loading = true;\n\n\t\t\t\t\t\tvar loader = scope.hierarchyHandlerMap[ objJSON.type ][ \"loaderObject\" ];\n\n\t\t\t\t\t\t// ColladaLoader\n\n\t\t\t\t\t\tif ( loader.options ) {\n\n\t\t\t\t\t\t\tloader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );\n\n\t\t\t\t\t\t// UTF8Loader\n\t\t\t\t\t\t// OBJLoader\n\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\tloader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t} else if ( objJSON.geometry !== undefined ) {\n\n\t\t\t\t\tgeometry = result.geometries[ objJSON.geometry ];\n\n\t\t\t\t\t// geometry already loaded\n\n\t\t\t\t\tif ( geometry ) {\n\n\t\t\t\t\t\tvar needsTangents = false;\n\n\t\t\t\t\t\tmaterial = result.materials[ objJSON.material ];\n\t\t\t\t\t\tneedsTangents = material instanceof THREE.ShaderMaterial;\n\n\t\t\t\t\t\tpos = objJSON.position;\n\t\t\t\t\t\trot = objJSON.rotation;\n\t\t\t\t\t\tscl = objJSON.scale;\n\t\t\t\t\t\tmat = objJSON.matrix;\n\t\t\t\t\t\tquat = objJSON.quaternion;\n\n\t\t\t\t\t\t// use materials from the model file\n\t\t\t\t\t\t// if there is no material specified in the object\n\n\t\t\t\t\t\tif ( ! objJSON.material ) {\n\n\t\t\t\t\t\t\tmaterial = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// use materials from the model file\n\t\t\t\t\t\t// if there is just empty face material\n\t\t\t\t\t\t// (must create new material as each model has its own face material)\n\n\t\t\t\t\t\tif ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {\n\n\t\t\t\t\t\t\tmaterial = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif ( material instanceof THREE.MeshFaceMaterial ) {\n\n\t\t\t\t\t\t\tfor ( var i = 0; i < material.materials.length; i ++ ) {\n\n\t\t\t\t\t\t\t\tneedsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif ( needsTangents ) {\n\n\t\t\t\t\t\t\tgeometry.computeTangents();\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif ( objJSON.skin ) {\n\n\t\t\t\t\t\t\tobject = new THREE.SkinnedMesh( geometry, material );\n\n\t\t\t\t\t\t} else if ( objJSON.morph ) {\n\n\t\t\t\t\t\t\tobject = new THREE.MorphAnimMesh( geometry, material );\n\n\t\t\t\t\t\t\tif ( objJSON.duration !== undefined ) {\n\n\t\t\t\t\t\t\t\tobject.duration = objJSON.duration;\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif ( objJSON.time !== undefined ) {\n\n\t\t\t\t\t\t\t\tobject.time = objJSON.time;\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif ( objJSON.mirroredLoop !== undefined ) {\n\n\t\t\t\t\t\t\t\tobject.mirroredLoop = objJSON.mirroredLoop;\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif ( material.morphNormals ) {\n\n\t\t\t\t\t\t\t\tgeometry.computeMorphNormals();\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\tobject = new THREE.Mesh( geometry, material );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tobject.name = objID;\n\n\t\t\t\t\t\tif ( mat ) {\n\n\t\t\t\t\t\t\tobject.matrixAutoUpdate = false;\n\t\t\t\t\t\t\tobject.matrix.set(\n\t\t\t\t\t\t\t\tmat[0], mat[1], mat[2], mat[3],\n\t\t\t\t\t\t\t\tmat[4], mat[5], mat[6], mat[7],\n\t\t\t\t\t\t\t\tmat[8], mat[9], mat[10], mat[11],\n\t\t\t\t\t\t\t\tmat[12], mat[13], mat[14], mat[15]\n\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\tobject.position.set( pos[0], pos[1], pos[2] );\n\n\t\t\t\t\t\t\tif ( quat ) {\n\n\t\t\t\t\t\t\t\tobject.quaternion.set( quat[0], quat[1], quat[2], quat[3] );\n\t\t\t\t\t\t\t\tobject.useQuaternion = true;\n\n\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\tobject.rotation.set( rot[0], rot[1], rot[2] );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tobject.scale.set( scl[0], scl[1], scl[2] );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tobject.visible = objJSON.visible;\n\t\t\t\t\t\tobject.castShadow = objJSON.castShadow;\n\t\t\t\t\t\tobject.receiveShadow = objJSON.receiveShadow;\n\n\t\t\t\t\t\tparent.add( object );\n\n\t\t\t\t\t\tresult.objects[ objID ] = object;\n\n\t\t\t\t\t}\n\n\t\t\t\t// lights\n\n\t\t\t\t} else if ( objJSON.type === \"DirectionalLight\" || objJSON.type === \"PointLight\" || objJSON.type === \"AmbientLight\" ) {\n\n\t\t\t\t\thex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;\n\t\t\t\t\tintensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;\n\n\t\t\t\t\tif ( objJSON.type === \"DirectionalLight\" ) {\n\n\t\t\t\t\t\tpos = objJSON.direction;\n\n\t\t\t\t\t\tlight = new THREE.DirectionalLight( hex, intensity );\n\t\t\t\t\t\tlight.position.set( pos[0], pos[1], pos[2] );\n\n\t\t\t\t\t\tif ( objJSON.target ) {\n\n\t\t\t\t\t\t\ttarget_array.push( { \"object\": light, \"targetName\" : objJSON.target } );\n\n\t\t\t\t\t\t\t// kill existing default target\n\t\t\t\t\t\t\t// otherwise it gets added to scene when parent gets added\n\n\t\t\t\t\t\t\tlight.target = null;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else if ( objJSON.type === \"PointLight\" ) {\n\n\t\t\t\t\t\tpos = objJSON.position;\n\t\t\t\t\t\tdst = objJSON.distance;\n\n\t\t\t\t\t\tlight = new THREE.PointLight( hex, intensity, dst );\n\t\t\t\t\t\tlight.position.set( pos[0], pos[1], pos[2] );\n\n\t\t\t\t\t} else if ( objJSON.type === \"AmbientLight\" ) {\n\n\t\t\t\t\t\tlight = new THREE.AmbientLight( hex );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tparent.add( light );\n\n\t\t\t\t\tlight.name = objID;\n\t\t\t\t\tresult.lights[ objID ] = light;\n\t\t\t\t\tresult.objects[ objID ] = light;\n\n\t\t\t\t// cameras\n\n\t\t\t\t} else if ( objJSON.type === \"PerspectiveCamera\" || objJSON.type === \"OrthographicCamera\" ) {\n\n\t\t\t\t\tif ( objJSON.type === \"PerspectiveCamera\" ) {\n\n\t\t\t\t\t\tcamera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );\n\n\t\t\t\t\t} else if ( objJSON.type === \"OrthographicCamera\" ) {\n\n\t\t\t\t\t\tcamera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tpos = objJSON.position;\n\t\t\t\t\tcamera.position.set( pos[0], pos[1], pos[2] );\n\t\t\t\t\tparent.add( camera );\n\n\t\t\t\t\tcamera.name = objID;\n\t\t\t\t\tresult.cameras[ objID ] = camera;\n\t\t\t\t\tresult.objects[ objID ] = camera;\n\n\t\t\t\t// pure Object3D\n\n\t\t\t\t} else {\n\n\t\t\t\t\tpos = objJSON.position;\n\t\t\t\t\trot = objJSON.rotation;\n\t\t\t\t\tscl = objJSON.scale;\n\t\t\t\t\tquat = objJSON.quaternion;\n\n\t\t\t\t\tobject = new THREE.Object3D();\n\t\t\t\t\tobject.name = objID;\n\t\t\t\t\tobject.position.set( pos[0], pos[1], pos[2] );\n\n\t\t\t\t\tif ( quat ) {\n\n\t\t\t\t\t\tobject.quaternion.set( quat[0], quat[1], quat[2], quat[3] );\n\t\t\t\t\t\tobject.useQuaternion = true;\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tobject.rotation.set( rot[0], rot[1], rot[2] );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tobject.scale.set( scl[0], scl[1], scl[2] );\n\t\t\t\t\tobject.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;\n\n\t\t\t\t\tparent.add( object );\n\n\t\t\t\t\tresult.objects[ objID ] = object;\n\t\t\t\t\tresult.empties[ objID ] = object;\n\n\t\t\t\t}\n\n\t\t\t\tif ( object ) {\n\n\t\t\t\t\tif ( objJSON.userData !== undefined ) {\n\n\t\t\t\t\t\tfor ( var key in objJSON.userData ) {\n\n\t\t\t\t\t\t\tvar value = objJSON.userData[ key ];\n\t\t\t\t\t\t\tobject.userData[ key ] = value;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( objJSON.groups !== undefined ) {\n\n\t\t\t\t\t\tfor ( var i = 0; i < objJSON.groups.length; i ++ ) {\n\n\t\t\t\t\t\t\tvar groupID = objJSON.groups[ i ];\n\n\t\t\t\t\t\t\tif ( result.groups[ groupID ] === undefined ) {\n\n\t\t\t\t\t\t\t\tresult.groups[ groupID ] = [];\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tresult.groups[ groupID ].push( objID );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( objJSON.children !== undefined ) {\n\n\t\t\t\t\t\thandle_children( object, objJSON.children );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}",
"function handle_children(parent, children) {\r\n\r\n\t\t\t\tvar mat, pos, rot, scl, quat;\r\n\r\n\t\t\t\tfor (var objID in children) {\r\n\r\n\t\t\t\t\t// check by id if child has already been handled,\r\n\t\t\t\t\t// if not, create new object\r\n\r\n\t\t\t\t\tvar object = result.objects[objID];\r\n\t\t\t\t\tvar objJSON = children[objID];\r\n\r\n\t\t\t\t\tif (object === undefined) {\r\n\r\n\t\t\t\t\t\t// meshes\r\n\r\n\t\t\t\t\t\tif (objJSON.type && (objJSON.type in scope.hierarchyHandlers)) {\r\n\r\n\t\t\t\t\t\t\tif (objJSON.loading === undefined) {\r\n\r\n\t\t\t\t\t\t\t\tmaterial = result.materials[objJSON.material];\r\n\r\n\t\t\t\t\t\t\t\tobjJSON.loading = true;\r\n\r\n\t\t\t\t\t\t\t\tvar loader = scope.hierarchyHandlers[objJSON.type][\"loaderObject\"];\r\n\r\n\t\t\t\t\t\t\t\t// ColladaLoader\r\n\r\n\t\t\t\t\t\t\t\tif (loader.options) {\r\n\r\n\t\t\t\t\t\t\t\t\tloader.load(get_url(objJSON.url, data.urlBaseType), create_callback_hierachy(objID, parent, material, objJSON));\r\n\r\n\t\t\t\t\t\t\t\t\t// UTF8Loader\r\n\t\t\t\t\t\t\t\t\t// OBJLoader\r\n\r\n\t\t\t\t\t\t\t\t} else {\r\n\r\n\t\t\t\t\t\t\t\t\tloader.load(get_url(objJSON.url, data.urlBaseType), create_callback_hierachy(objID, parent, material, objJSON));\r\n\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t} else if (objJSON.geometry !== undefined) {\r\n\r\n\t\t\t\t\t\t\tgeometry = result.geometries[objJSON.geometry];\r\n\r\n\t\t\t\t\t\t\t// geometry already loaded\r\n\r\n\t\t\t\t\t\t\tif (geometry) {\r\n\r\n\t\t\t\t\t\t\t\tmaterial = result.materials[objJSON.material];\r\n\r\n\t\t\t\t\t\t\t\tpos = objJSON.position;\r\n\t\t\t\t\t\t\t\trot = objJSON.rotation;\r\n\t\t\t\t\t\t\t\tscl = objJSON.scale;\r\n\t\t\t\t\t\t\t\tmat = objJSON.matrix;\r\n\t\t\t\t\t\t\t\tquat = objJSON.quaternion;\r\n\r\n\t\t\t\t\t\t\t\t// use materials from the model file\r\n\t\t\t\t\t\t\t\t// if there is no material specified in the object\r\n\r\n\t\t\t\t\t\t\t\tif (!objJSON.material) {\r\n\r\n\t\t\t\t\t\t\t\t\tmaterial = new THREE.MultiMaterial(result.face_materials[objJSON.geometry]);\r\n\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t// use materials from the model file\r\n\t\t\t\t\t\t\t\t// if there is just empty face material\r\n\t\t\t\t\t\t\t\t// (must create new material as each model has its own face material)\r\n\r\n\t\t\t\t\t\t\t\tif ((material instanceof THREE.MultiMaterial) && material.materials.length === 0) {\r\n\r\n\t\t\t\t\t\t\t\t\tmaterial = new THREE.MultiMaterial(result.face_materials[objJSON.geometry]);\r\n\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\tif (objJSON.skin) {\r\n\r\n\t\t\t\t\t\t\t\t\tobject = new THREE.SkinnedMesh(geometry, material);\r\n\r\n\t\t\t\t\t\t\t\t} else if (objJSON.morph) {\r\n\r\n\t\t\t\t\t\t\t\t\tobject = new THREE.MorphAnimMesh(geometry, material);\r\n\r\n\t\t\t\t\t\t\t\t\tif (objJSON.duration !== undefined) {\r\n\r\n\t\t\t\t\t\t\t\t\t\tobject.duration = objJSON.duration;\r\n\r\n\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\tif (objJSON.time !== undefined) {\r\n\r\n\t\t\t\t\t\t\t\t\t\tobject.time = objJSON.time;\r\n\r\n\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\tif (objJSON.mirroredLoop !== undefined) {\r\n\r\n\t\t\t\t\t\t\t\t\t\tobject.mirroredLoop = objJSON.mirroredLoop;\r\n\r\n\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\tif (material.morphNormals) {\r\n\r\n\t\t\t\t\t\t\t\t\t\tgeometry.computeMorphNormals();\r\n\r\n\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t} else {\r\n\r\n\t\t\t\t\t\t\t\t\tobject = new THREE.Mesh(geometry, material);\r\n\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\tobject.name = objID;\r\n\r\n\t\t\t\t\t\t\t\tif (mat) {\r\n\r\n\t\t\t\t\t\t\t\t\tobject.matrixAutoUpdate = false;\r\n\t\t\t\t\t\t\t\t\tobject.matrix.set(\r\n\t\t\t\t\t\t\t\t\t\tmat[0], mat[1], mat[2], mat[3],\r\n\t\t\t\t\t\t\t\t\t\tmat[4], mat[5], mat[6], mat[7],\r\n\t\t\t\t\t\t\t\t\t\tmat[8], mat[9], mat[10], mat[11],\r\n\t\t\t\t\t\t\t\t\t\tmat[12], mat[13], mat[14], mat[15]\r\n\t\t\t\t\t\t\t\t\t);\r\n\r\n\t\t\t\t\t\t\t\t} else {\r\n\r\n\t\t\t\t\t\t\t\t\tobject.position.fromArray(pos);\r\n\r\n\t\t\t\t\t\t\t\t\tif (quat) {\r\n\r\n\t\t\t\t\t\t\t\t\t\tobject.quaternion.fromArray(quat);\r\n\r\n\t\t\t\t\t\t\t\t\t} else {\r\n\r\n\t\t\t\t\t\t\t\t\t\tobject.rotation.fromArray(rot);\r\n\r\n\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\tobject.scale.fromArray(scl);\r\n\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\tobject.visible = objJSON.visible;\r\n\t\t\t\t\t\t\t\tobject.castShadow = objJSON.castShadow;\r\n\t\t\t\t\t\t\t\tobject.receiveShadow = objJSON.receiveShadow;\r\n\r\n\t\t\t\t\t\t\t\tparent.add(object);\r\n\r\n\t\t\t\t\t\t\t\tresult.objects[objID] = object;\r\n\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t// lights\r\n\r\n\t\t\t\t\t\t} else if (objJSON.type === \"AmbientLight\" || objJSON.type === \"PointLight\" ||\r\n\t\t\t\t\t\t\tobjJSON.type === \"DirectionalLight\" || objJSON.type === \"SpotLight\" ||\r\n\t\t\t\t\t\t\tobjJSON.type === \"HemisphereLight\") {\r\n\r\n\t\t\t\t\t\t\tvar color = objJSON.color;\r\n\t\t\t\t\t\t\tvar intensity = objJSON.intensity;\r\n\t\t\t\t\t\t\tvar distance = objJSON.distance;\r\n\t\t\t\t\t\t\tvar position = objJSON.position;\r\n\t\t\t\t\t\t\tvar rotation = objJSON.rotation;\r\n\r\n\t\t\t\t\t\t\tswitch (objJSON.type) {\r\n\r\n\t\t\t\t\t\t\t\tcase 'AmbientLight':\r\n\t\t\t\t\t\t\t\t\tlight = new THREE.AmbientLight(color);\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\t\t\t\tcase 'PointLight':\r\n\t\t\t\t\t\t\t\t\tlight = new THREE.PointLight(color, intensity, distance);\r\n\t\t\t\t\t\t\t\t\tlight.position.fromArray(position);\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\t\t\t\tcase 'DirectionalLight':\r\n\t\t\t\t\t\t\t\t\tlight = new THREE.DirectionalLight(color, intensity);\r\n\t\t\t\t\t\t\t\t\tlight.position.fromArray(objJSON.direction);\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\t\t\t\tcase 'SpotLight':\r\n\t\t\t\t\t\t\t\t\tlight = new THREE.SpotLight(color, intensity, distance);\r\n\t\t\t\t\t\t\t\t\tlight.angle = objJSON.angle;\r\n\t\t\t\t\t\t\t\t\tlight.position.fromArray(position);\r\n\t\t\t\t\t\t\t\t\tlight.target.set(position[0], position[1] - distance, position[2]);\r\n\t\t\t\t\t\t\t\t\tlight.target.applyEuler(new THREE.Euler(rotation[0], rotation[1], rotation[2], 'XYZ'));\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\t\t\t\tcase 'HemisphereLight':\r\n\t\t\t\t\t\t\t\t\tlight = new THREE.DirectionalLight(color, intensity, distance);\r\n\t\t\t\t\t\t\t\t\tlight.target.set(position[0], position[1] - distance, position[2]);\r\n\t\t\t\t\t\t\t\t\tlight.target.applyEuler(new THREE.Euler(rotation[0], rotation[1], rotation[2], 'XYZ'));\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tparent.add(light);\r\n\r\n\t\t\t\t\t\t\tlight.name = objID;\r\n\t\t\t\t\t\t\tresult.lights[objID] = light;\r\n\t\t\t\t\t\t\tresult.objects[objID] = light;\r\n\r\n\t\t\t\t\t\t\t// cameras\r\n\r\n\t\t\t\t\t\t} else if (objJSON.type === \"PerspectiveCamera\" || objJSON.type === \"OrthographicCamera\") {\r\n\r\n\t\t\t\t\t\t\tpos = objJSON.position;\r\n\t\t\t\t\t\t\trot = objJSON.rotation;\r\n\t\t\t\t\t\t\tquat = objJSON.quaternion;\r\n\r\n\t\t\t\t\t\t\tif (objJSON.type === \"PerspectiveCamera\") {\r\n\r\n\t\t\t\t\t\t\t\tcamera = new THREE.PerspectiveCamera(objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far);\r\n\r\n\t\t\t\t\t\t\t} else if (objJSON.type === \"OrthographicCamera\") {\r\n\r\n\t\t\t\t\t\t\t\tcamera = new THREE.OrthographicCamera(objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far);\r\n\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tcamera.name = objID;\r\n\t\t\t\t\t\t\tcamera.position.fromArray(pos);\r\n\r\n\t\t\t\t\t\t\tif (quat !== undefined) {\r\n\r\n\t\t\t\t\t\t\t\tcamera.quaternion.fromArray(quat);\r\n\r\n\t\t\t\t\t\t\t} else if (rot !== undefined) {\r\n\r\n\t\t\t\t\t\t\t\tcamera.rotation.fromArray(rot);\r\n\r\n\t\t\t\t\t\t\t} else if (objJSON.target) {\r\n\r\n\t\t\t\t\t\t\t\tcamera.lookAt(new THREE.Vector3().fromArray(objJSON.target));\r\n\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tparent.add(camera);\r\n\r\n\t\t\t\t\t\t\tresult.cameras[objID] = camera;\r\n\t\t\t\t\t\t\tresult.objects[objID] = camera;\r\n\r\n\t\t\t\t\t\t\t// pure Object3D\r\n\r\n\t\t\t\t\t\t} else {\r\n\r\n\t\t\t\t\t\t\tpos = objJSON.position;\r\n\t\t\t\t\t\t\trot = objJSON.rotation;\r\n\t\t\t\t\t\t\tscl = objJSON.scale;\r\n\t\t\t\t\t\t\tquat = objJSON.quaternion;\r\n\r\n\t\t\t\t\t\t\tobject = new THREE.Object3D();\r\n\t\t\t\t\t\t\tobject.name = objID;\r\n\t\t\t\t\t\t\tobject.position.fromArray(pos);\r\n\r\n\t\t\t\t\t\t\tif (quat) {\r\n\r\n\t\t\t\t\t\t\t\tobject.quaternion.fromArray(quat);\r\n\r\n\t\t\t\t\t\t\t} else {\r\n\r\n\t\t\t\t\t\t\t\tobject.rotation.fromArray(rot);\r\n\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tobject.scale.fromArray(scl);\r\n\t\t\t\t\t\t\tobject.visible = (objJSON.visible !== undefined) ? objJSON.visible : false;\r\n\r\n\t\t\t\t\t\t\tparent.add(object);\r\n\r\n\t\t\t\t\t\t\tresult.objects[objID] = object;\r\n\t\t\t\t\t\t\tresult.empties[objID] = object;\r\n\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tif (object) {\r\n\r\n\t\t\t\t\t\t\tif (objJSON.userData !== undefined) {\r\n\r\n\t\t\t\t\t\t\t\tfor (var key in objJSON.userData) {\r\n\r\n\t\t\t\t\t\t\t\t\tvar value = objJSON.userData[key];\r\n\t\t\t\t\t\t\t\t\tobject.userData[key] = value;\r\n\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tif (objJSON.groups !== undefined) {\r\n\r\n\t\t\t\t\t\t\t\tfor (var i = 0; i < objJSON.groups.length; i++) {\r\n\r\n\t\t\t\t\t\t\t\t\tvar groupID = objJSON.groups[i];\r\n\r\n\t\t\t\t\t\t\t\t\tif (result.groups[groupID] === undefined) {\r\n\r\n\t\t\t\t\t\t\t\t\t\tresult.groups[groupID] = [];\r\n\r\n\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\tresult.groups[groupID].push(objID);\r\n\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (object !== undefined && objJSON.children !== undefined) {\r\n\r\n\t\t\t\t\t\thandle_children(object, objJSON.children);\r\n\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t}\r\n\r\n\t\t\t}",
"function handle_children( parent, children ) {\r\n\r\n\t\tvar mat, dst, pos, rot, scl, quat;\r\n\r\n\t\tfor ( var objID in children ) {\r\n\r\n\t\t\t// check by id if child has already been handled,\r\n\t\t\t// if not, create new object\r\n\r\n\t\t\tif ( result.objects[ objID ] === undefined ) {\r\n\r\n\t\t\t\tvar objJSON = children[ objID ];\r\n\r\n\t\t\t\tvar object = null;\r\n\r\n\t\t\t\t// meshes\r\n\r\n\t\t\t\tif ( objJSON.type && ( objJSON.type in scope.hierarchyHandlerMap ) ) {\r\n\r\n\t\t\t\t\tif ( objJSON.loading === undefined ) {\r\n\r\n\t\t\t\t\t\tvar reservedTypes = { \"type\": 1, \"url\": 1, \"material\": 1,\r\n\t\t\t\t\t\t\t\t\t\t\t \"position\": 1, \"rotation\": 1, \"scale\" : 1,\r\n\t\t\t\t\t\t\t\t\t\t\t \"visible\": 1, \"children\": 1, \"properties\": 1,\r\n\t\t\t\t\t\t\t\t\t\t\t \"skin\": 1, \"morph\": 1, \"mirroredLoop\": 1, \"duration\": 1 };\r\n\r\n\t\t\t\t\t\tvar loaderParameters = {};\r\n\r\n\t\t\t\t\t\tfor ( var parType in objJSON ) {\r\n\r\n\t\t\t\t\t\t\tif ( ! ( parType in reservedTypes ) ) {\r\n\r\n\t\t\t\t\t\t\t\tloaderParameters[ parType ] = objJSON[ parType ];\r\n\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tmaterial = result.materials[ objJSON.material ];\r\n\r\n\t\t\t\t\t\tobjJSON.loading = true;\r\n\r\n\t\t\t\t\t\tvar loader = scope.hierarchyHandlerMap[ objJSON.type ][ \"loaderObject\" ];\r\n\r\n\t\t\t\t\t\t// ColladaLoader\r\n\r\n\t\t\t\t\t\tif ( loader.options ) {\r\n\r\n\t\t\t\t\t\t\tloader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );\r\n\r\n\t\t\t\t\t\t// UTF8Loader\r\n\t\t\t\t\t\t// OBJLoader\r\n\r\n\t\t\t\t\t\t} else {\r\n\r\n\t\t\t\t\t\t\tloader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );\r\n\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t} else if ( objJSON.geometry !== undefined ) {\r\n\r\n\t\t\t\t\tgeometry = result.geometries[ objJSON.geometry ];\r\n\r\n\t\t\t\t\t// geometry already loaded\r\n\r\n\t\t\t\t\tif ( geometry ) {\r\n\r\n\t\t\t\t\t\tvar needsTangents = false;\r\n\r\n\t\t\t\t\t\tmaterial = result.materials[ objJSON.material ];\r\n\t\t\t\t\t\tneedsTangents = material instanceof THREE.ShaderMaterial;\r\n\r\n\t\t\t\t\t\tpos = objJSON.position;\r\n\t\t\t\t\t\trot = objJSON.rotation;\r\n\t\t\t\t\t\tscl = objJSON.scale;\r\n\t\t\t\t\t\tmat = objJSON.matrix;\r\n\t\t\t\t\t\tquat = objJSON.quaternion;\r\n\r\n\t\t\t\t\t\t// use materials from the model file\r\n\t\t\t\t\t\t// if there is no material specified in the object\r\n\r\n\t\t\t\t\t\tif ( ! objJSON.material ) {\r\n\r\n\t\t\t\t\t\t\tmaterial = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );\r\n\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t// use materials from the model file\r\n\t\t\t\t\t\t// if there is just empty face material\r\n\t\t\t\t\t\t// (must create new material as each model has its own face material)\r\n\r\n\t\t\t\t\t\tif ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {\r\n\r\n\t\t\t\t\t\t\tmaterial = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );\r\n\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tif ( material instanceof THREE.MeshFaceMaterial ) {\r\n\r\n\t\t\t\t\t\t\tfor ( var i = 0; i < material.materials.length; i ++ ) {\r\n\r\n\t\t\t\t\t\t\t\tneedsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );\r\n\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tif ( needsTangents ) {\r\n\r\n\t\t\t\t\t\t\tgeometry.computeTangents();\r\n\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tif ( objJSON.skin ) {\r\n\r\n\t\t\t\t\t\t\tobject = new THREE.SkinnedMesh( geometry, material );\r\n\r\n\t\t\t\t\t\t} else if ( objJSON.morph ) {\r\n\r\n\t\t\t\t\t\t\tobject = new THREE.MorphAnimMesh( geometry, material );\r\n\r\n\t\t\t\t\t\t\tif ( objJSON.duration !== undefined ) {\r\n\r\n\t\t\t\t\t\t\t\tobject.duration = objJSON.duration;\r\n\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tif ( objJSON.time !== undefined ) {\r\n\r\n\t\t\t\t\t\t\t\tobject.time = objJSON.time;\r\n\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tif ( objJSON.mirroredLoop !== undefined ) {\r\n\r\n\t\t\t\t\t\t\t\tobject.mirroredLoop = objJSON.mirroredLoop;\r\n\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tif ( material.morphNormals ) {\r\n\r\n\t\t\t\t\t\t\t\tgeometry.computeMorphNormals();\r\n\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t} else {\r\n\r\n\t\t\t\t\t\t\tobject = new THREE.Mesh( geometry, material );\r\n\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tobject.name = objID;\r\n\r\n\t\t\t\t\t\tif ( mat ) {\r\n\r\n\t\t\t\t\t\t\tobject.matrixAutoUpdate = false;\r\n\t\t\t\t\t\t\tobject.matrix.set(\r\n\t\t\t\t\t\t\t\tmat[0], mat[1], mat[2], mat[3],\r\n\t\t\t\t\t\t\t\tmat[4], mat[5], mat[6], mat[7],\r\n\t\t\t\t\t\t\t\tmat[8], mat[9], mat[10], mat[11],\r\n\t\t\t\t\t\t\t\tmat[12], mat[13], mat[14], mat[15]\r\n\t\t\t\t\t\t\t);\r\n\r\n\t\t\t\t\t\t} else {\r\n\r\n\t\t\t\t\t\t\tobject.position.set( pos[0], pos[1], pos[2] );\r\n\r\n\t\t\t\t\t\t\tif ( quat ) {\r\n\r\n\t\t\t\t\t\t\t\tobject.quaternion.set( quat[0], quat[1], quat[2], quat[3] );\r\n\t\t\t\t\t\t\t\tobject.useQuaternion = true;\r\n\r\n\t\t\t\t\t\t\t} else {\r\n\r\n\t\t\t\t\t\t\t\tobject.rotation.set( rot[0], rot[1], rot[2] );\r\n\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tobject.scale.set( scl[0], scl[1], scl[2] );\r\n\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tobject.visible = objJSON.visible;\r\n\t\t\t\t\t\tobject.castShadow = objJSON.castShadow;\r\n\t\t\t\t\t\tobject.receiveShadow = objJSON.receiveShadow;\r\n\r\n\t\t\t\t\t\tparent.add( object );\r\n\r\n\t\t\t\t\t\tresult.objects[ objID ] = object;\r\n\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t// lights\r\n\r\n\t\t\t\t} else if ( objJSON.type === \"DirectionalLight\" || objJSON.type === \"PointLight\" || objJSON.type === \"AmbientLight\" ) {\r\n\r\n\t\t\t\t\thex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;\r\n\t\t\t\t\tintensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;\r\n\r\n\t\t\t\t\tif ( objJSON.type === \"DirectionalLight\" ) {\r\n\r\n\t\t\t\t\t\tpos = objJSON.direction;\r\n\r\n\t\t\t\t\t\tlight = new THREE.DirectionalLight( hex, intensity );\r\n\t\t\t\t\t\tlight.position.set( pos[0], pos[1], pos[2] );\r\n\r\n\t\t\t\t\t\tif ( objJSON.target ) {\r\n\r\n\t\t\t\t\t\t\ttarget_array.push( { \"object\": light, \"targetName\" : objJSON.target } );\r\n\r\n\t\t\t\t\t\t\t// kill existing default target\r\n\t\t\t\t\t\t\t// otherwise it gets added to scene when parent gets added\r\n\r\n\t\t\t\t\t\t\tlight.target = null;\r\n\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t} else if ( objJSON.type === \"PointLight\" ) {\r\n\r\n\t\t\t\t\t\tpos = objJSON.position;\r\n\t\t\t\t\t\tdst = objJSON.distance;\r\n\r\n\t\t\t\t\t\tlight = new THREE.PointLight( hex, intensity, dst );\r\n\t\t\t\t\t\tlight.position.set( pos[0], pos[1], pos[2] );\r\n\r\n\t\t\t\t\t} else if ( objJSON.type === \"AmbientLight\" ) {\r\n\r\n\t\t\t\t\t\tlight = new THREE.AmbientLight( hex );\r\n\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tparent.add( light );\r\n\r\n\t\t\t\t\tlight.name = objID;\r\n\t\t\t\t\tresult.lights[ objID ] = light;\r\n\t\t\t\t\tresult.objects[ objID ] = light;\r\n\r\n\t\t\t\t// cameras\r\n\r\n\t\t\t\t} else if ( objJSON.type === \"PerspectiveCamera\" || objJSON.type === \"OrthographicCamera\" ) {\r\n\r\n\t\t\t\t\tif ( objJSON.type === \"PerspectiveCamera\" ) {\r\n\r\n\t\t\t\t\t\tcamera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );\r\n\r\n\t\t\t\t\t} else if ( objJSON.type === \"OrthographicCamera\" ) {\r\n\r\n\t\t\t\t\t\tcamera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );\r\n\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tpos = objJSON.position;\r\n\t\t\t\t\tcamera.position.set( pos[0], pos[1], pos[2] );\r\n\t\t\t\t\tparent.add( camera );\r\n\r\n\t\t\t\t\tcamera.name = objID;\r\n\t\t\t\t\tresult.cameras[ objID ] = camera;\r\n\t\t\t\t\tresult.objects[ objID ] = camera;\r\n\r\n\t\t\t\t// pure Object3D\r\n\r\n\t\t\t\t} else {\r\n\r\n\t\t\t\t\tpos = objJSON.position;\r\n\t\t\t\t\trot = objJSON.rotation;\r\n\t\t\t\t\tscl = objJSON.scale;\r\n\t\t\t\t\tquat = objJSON.quaternion;\r\n\r\n\t\t\t\t\tobject = new THREE.Object3D();\r\n\t\t\t\t\tobject.name = objID;\r\n\t\t\t\t\tobject.position.set( pos[0], pos[1], pos[2] );\r\n\r\n\t\t\t\t\tif ( quat ) {\r\n\r\n\t\t\t\t\t\tobject.quaternion.set( quat[0], quat[1], quat[2], quat[3] );\r\n\t\t\t\t\t\tobject.useQuaternion = true;\r\n\r\n\t\t\t\t\t} else {\r\n\r\n\t\t\t\t\t\tobject.rotation.set( rot[0], rot[1], rot[2] );\r\n\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tobject.scale.set( scl[0], scl[1], scl[2] );\r\n\t\t\t\t\tobject.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;\r\n\r\n\t\t\t\t\tparent.add( object );\r\n\r\n\t\t\t\t\tresult.objects[ objID ] = object;\r\n\t\t\t\t\tresult.empties[ objID ] = object;\r\n\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif ( object ) {\r\n\r\n\t\t\t\t\tif ( objJSON.properties !== undefined ) {\r\n\r\n\t\t\t\t\t\tfor ( var key in objJSON.properties ) {\r\n\r\n\t\t\t\t\t\t\tvar value = objJSON.properties[ key ];\r\n\t\t\t\t\t\t\tobject.properties[ key ] = value;\r\n\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif ( objJSON.groups !== undefined ) {\r\n\r\n\t\t\t\t\t\tfor ( var i = 0; i < objJSON.groups.length; i ++ ) {\r\n\r\n\t\t\t\t\t\t\tvar groupID = objJSON.groups[ i ];\r\n\r\n\t\t\t\t\t\t\tif ( result.groups[ groupID ] === undefined ) {\r\n\r\n\t\t\t\t\t\t\t\tresult.groups[ groupID ] = [];\r\n\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tresult.groups[ groupID ].push( objID );\r\n\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif ( objJSON.children !== undefined ) {\r\n\r\n\t\t\t\t\t\thandle_children( object, objJSON.children );\r\n\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t}\r\n\r\n\t\t\t}\r\n\r\n\t\t}\r\n\r\n\t}",
"_setChildren(item,data){// find all children\nconst children=data.filter(d=>item.id===d.parent);item.children=children;if(0<item.children.length){item.children.forEach(child=>{// recursively call itself\nthis._setChildren(child,data)})}}",
"function loadChildData(rowid) {\n\t\tvar selRec = grid.getModelRecord(rowid);//current parent grid selection\n\t\tgrid.triggerHandler(\"jaduBeforeLoadChild\", [rowid,selRec]);\n\t\tvar selectionChangeFunc = grid.getGridParam('onSelectionChange');\n\t\tif(selectionChangeFunc) {\n\t\t\tselectionChangeFunc(rowid,selRec);\n\t\t}\n\t\tvar children = grid.getGridParam('hasMany');\n\t\tlog.debug(children+' loadChildData '+rowid);\n\t\tif(children && children.length > 0) {\t\t\t\n\t\t\tfor(var i=0; i < children.length; i++){\n\t\t\t\tvar child = children[i];\n\t\t\t\tchild.container.onParentChange({crudIndicator:\"selectionchange\"})\n\t\t\t\tlog.debug(\"selected record: \"+JSON.stringify(selRec));\n\t\t\t\tchild.container.loadDataForParentRecord(selRec,child);\n\t\t\t}\n\t\t}\t\n\t}",
"loadChildTrees() {\n this.set('isLoading', true);\n let promises = [\n this.get('content.files'),\n this.get('content.children')\n ];\n Ember.RSVP.allSettled(promises).then((results) => {\n let childTrees = Ember.A();\n for (let r of results) {\n let array = r.value;\n if (array && array.length) {\n for (let i = 0; i < array.length; i++) {\n let child = array.objectAt(i);\n childTrees.pushObject(child);\n }\n }\n }\n this.set('childTrees', childTrees);\n this.set('isLoading', false);\n });\n }",
"function decorateChildren(parent) {\n parent.children.forEach(c => {\n c.userData.partOfModal = e;\n decorateChildren(c);\n });\n }",
"update_children(){\n let children = this.get_children_objects()\n for (var i = 0; i < children.length; i++) {\n children[i].set_parent_node(this);\n }\n this.notify_fragment_dirty();\n }",
"function setChildren(json, id) {\n\tconsole.log(json[id])\n\tfor (var i in json[id].children) {\n\t\tconsole.log(json[id].children[i])\n\t\t// console.log(json[id].children[i] - 1)\n\t\tjson[id].children[i] = json[json[id].children[i] - 1];\n\t\t// json[id].children[i].parent = json[id];\n\t\tconsole.log(json[id].children[i])\n\t\tif (json[id].children[i].children) {\n\t\t\tsetChildren(json, json[id].children[i].id);\n\t\t}\n\t}\n}",
"setChildrensParent() { \r\n this.children.forEach(childName => { \r\n const childNode = this.nodeMap.get(childName)\r\n if(childNode !== undefined) { \r\n childNode.parent = this.name;\r\n }\r\n })\r\n }",
"function deserialize_children(elem, parent) {\n return flexo.fold_promises(flexo.map(parent.childNodes, function (child) {\n return deserialize(child);\n }), flexo.call.bind(function (child) {\n return child &&\n this.child(child.hasOwnProperty(\"view\") ? child.view : child) || this;\n }), elem);\n }",
"function _build_tree(parent){\n for (let child_elem of parent._elem.children){\n if(child_elem.getAttribute('uuid') === null || child_elem.getAttribute('uuid') in self._children_uuids){\n child_elem.setAttribute('uuid', uuidv4());\n }\n\n let _new;\n if (child_elem.tagName === 'stack') {\n _new = new Group(self, child_elem);\n _build_tree(_new);\n }else if (child_elem.tagName === 'layer') {\n const image_source = other_group._project.get_by_uuid(child_elem.getAttribute('uuid'))._image_elem.src;\n _new = new Layer(image_source, self, child_elem);\n }else{\n console.log(`Warning: unknown tag in stack: ${child_elem.tagName}`);\n continue;\n }\n self._children.push(_new);\n\n self._children_elems.set(child_elem, _new);\n self._children_uuids[_new.uuid] = _new;\n }\n }",
"createChildren(node,data,cache) {\n // Go through each child\n data.forEach((child, index)=>{\n cache.children[index] = cache.children[index] || {};\n // If it's Array we have to build new element\n if (Array.isArray(child)) {\n // Create node at first\n if (cache.node && !cache.children[index].node) {\n cache.children[index] = {\"node\": document.createElement(child[0])};\n cache.node.insertBefore(cache.children[index].node, cache.node.childNodes[index] ? cache.node.childNodes[index] : null);\n }\n // Build children\n JsonMLDriver.build.call(this,cache.node || node, child, cache.children[index]);\n }\n // If it's string we have to create new TextNode\n else if (typeof child === 'string') {\n if (!cache.children[index].node || cache.children[index].node.nodeValue !== child) {\n cache.children[index] = {\"node\": document.createTextNode(child)};\n if (cache.node && cache.node.tagName) {\n cache.node.insertBefore(cache.children[index].node, cache.node.childNodes[index] ? cache.node.childNodes[index] : null);\n }\n else {\n node.insertBefore(cache.children[index].node, cache.node.childNodes[index] ? cache.node.childNodes[index] : null);\n }\n }\n }\n // If it's component we have to setup root node and render it.\n else if(child instanceof Xion) {\n child.node = cache.node || node;\n child.parent = this;\n child.render();\n }\n });\n }",
"buildChildren(reflection, parent) {\n const modules = reflection.getChildrenByKind(index_1.ReflectionKind.SomeModule);\n modules.sort((a, b) => {\n return a.getFullName() < b.getFullName() ? -1 : 1;\n });\n modules.forEach((reflection) => {\n const item = NavigationItem_1.NavigationItem.create(reflection, parent);\n this.includeDedicatedUrls(reflection, item);\n this.buildChildren(reflection, item);\n });\n }",
"function appendToParent(jsonParent, jsonChildName, jsonChildObj) {\n\n // Check if we need a simple object or an array.\n if (jsonParent[jsonChildName] == null) {\n\n // Simple Object\n jsonParent[jsonChildName] = jsonChildObj;\n\n } else if (jsonParent[jsonChildName] instanceof Array) {\n\n // Append to an existing child array.\n var childArr = jsonParent[jsonChildName];\n childArr.push(jsonChildObj);\n\n } else {\n\n // Create a new child array and put the old and new elements in it.\n var oldChild = jsonParent[jsonChildName];\n var childArr = [];\n childArr.push(oldChild);\n childArr.push(jsonChildObj);\n jsonParent[jsonChildName] = childArr;\n\n }\n\n }",
"_add_children(block, block_dict) {\n const rels_list = block.Relationships || [];\n rels_list.forEach((rels) => {\n if (rels.Type === \"CHILD\") {\n block[\"Children\"] = [];\n rels.Ids.forEach((relId) => {\n const kid = block_dict[relId];\n block[\"Children\"].push(kid);\n this._add_children(kid, block_dict);\n });\n }\n });\n }",
"function loadChildren(n) {\n n.loaded = true;\n childrenMap[n.type].forEach(function (childCollection) {\n $.ajax({\n url: n.links[childCollection],\n success: function (collection) {\n n[childCollection] = collection.Items.map(function (item) {\n return new node(item.Name, childCollection, item.Links, n.div);\n })\n },\n error: function (xhr) {\n console.log(xhr.responseText);\n },\n beforeSend: function (xhr) {\n xhr.setRequestHeader('Authorization', 'Basic xxx');\n }\n })\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
! Init all element to usage \param src source of the image \param boundingBox list of boundingBox from the server \param baselines list of baselines from the server | function init(src, boundingBox, baseline) {
var image = new ProcessingImage(src);
var imagePreview = new ProcessingImage(src);
var listRect = new Array();
for (var rect in boundingBox) {
listRect.push(new Rectangle({x:boundingBox[rect].x, y:boundingBox[rect].y, w:boundingBox[rect].width, h: boundingBox[rect].height},boundingBox[rect].idCC, boundingBox[rect].idLine));
}
var boundingBox = new BoundingBox(listRect);
var listBaseline = new Array();
for (var line in baseline) {
listBaseline.push(new Line(baseline[line].idLine, baseline[line].x_begin,baseline[line].y_baseline,baseline[line].x_end));
}
var baseline = new Baseline(listBaseline);
var previewCanvas = new PreviewCanvas(document.getElementById('small_canvas'), imagePreview);
var normalCanvas = new Canvas(document.getElementById('canvas'), image, baseline, boundingBox);
var listCharacter = new ListCharacter();
var controller = new Controller(normalCanvas, previewCanvas, listCharacter);
} | [
"function Baseline(lines) {\n this.lines = lines;\n this.visible = false;\n this.clickMargin = 0.4; //in percent of the image height\n}",
"static imageDataToView() {\n let currentImage = collectedData.current();\n let imgSource = currentImage.imageSource;\n let rectangles = currentImage.rectangle;\n \n if (imgSource != null && imgSource.length > 0) {\n $(\"#image\").empty().css(\"background-image\", `url(\"${imgSource}\")`);\n \n if (rectangles != null && rectangles.length > 0) {\n rectangles.forEach(function(element) {\n DrawingUtils.drawDiv(element);\n }, this);\n }\n }\n }",
"constructor(img = []) {\n\t\tthis.img = img; // Thresholded, sized rank image loaded from hard drive\n\t\tthis.name = \"Placeholder\";\n\t}",
"function displayBoundingBox() {\n\tlet tabIndex = 1;\n\tIMAGEDATA.faces[0].forEach(face => {\n\t\ttabIndex++;\n\t\t$('#js-image-container').append(createBoundingBoxTag(face, tabIndex));\n\t});\n}",
"constructor(img, portion)\n {\n this.img = img;\n this.r = portion;\n }",
"function init(elements, bounds, setInitial) {\n // store elements and current min/max of x,y\n list = elements;\n top = bounds.top;\n left = bounds.left;\n right = bounds.right;\n bottom = bounds.bottom;\n\n // store sorted lists of left, right, top, bottom edges of bounding boxes\n tops = getRepresentations(getTop, list, false);\n lefts = getRepresentations(getLeft, list, false);\n rights = getRepresentations(getRight, list, true);\n bottoms = getRepresentations(getBottom, list, true);\n\n // find index of first non-visible element in each list\n firstTop = bisectLeft(tops, bottom);\n firstLeft = bisectLeft(lefts, right);\n firstRight = bisectRight(rights, left);\n firstBottom = bisectRight(bottoms, top);\n\n if (setInitial) {\n setInitialVisible();\n }\n }",
"function DefineWindowsAndImages( detectPartialLines )\n{\n // Define the working image windows and images.\n this.referenceImageWindow = ImageWindow.activeWindow;\n\n this.referenceImage = new Image( this.referenceImageWindow.mainView.image.width,\n this.referenceImageWindow.mainView.image.height,\n this.referenceImageWindow.mainView.image.numberOfChannels,\n this.referenceImageWindow.mainView.image.colorSpace,\n 32, SampleType_Real );\n\n this.referenceImage.apply( this.referenceImageWindow.mainView.image );\n\n if ( detectPartialLines )\n {\n this.referenceImageCopy = new Image( this.referenceImageWindow.mainView.image.width,\n this.referenceImageWindow.mainView.image.height,\n this.referenceImageWindow.mainView.image.numberOfChannels,\n this.referenceImageWindow.mainView.image.colorSpace,\n 32, SampleType_Real );\n\n this.referenceImageCopy.apply( this.referenceImageWindow.mainView.image );\n }\n\n this.referenceSSImage = new Image( this.referenceImage.width,\n this.referenceImage.height,\n this.referenceImage.numberOfChannels,\n this.referenceImage.colorSpace,\n 32, SampleType_Real );\n\n this.referenceSSImage.apply( this.referenceImage );\n\n this.lineModelWindow = new ImageWindow( this.referenceImage.width,\n this.referenceImage.height,\n this.referenceImage.numberOfChannels,\n 32, true, false, \"line_model\" );\n\n this.lineModelImage = new Image( this.referenceImage.width,\n this.referenceImage.height,\n this.referenceImage.numberOfChannels,\n this.referenceImage.colorSpace,\n 32, SampleType_Real );\n\n this.lineDetectionWindow = new ImageWindow( this.referenceImage.width,\n this.referenceImage.height,\n this.referenceImage.numberOfChannels,\n 32, true, false, \"line_detection\" );\n\n this.lineDetectionImage = new Image( this.referenceImage.width,\n this.referenceImage.height,\n this.referenceImage.numberOfChannels,\n this.referenceImage.colorSpace,\n 32, SampleType_Real );\n}",
"function addSourceBoxes(boxes, value, boxType, text, markers) {\n if (value && !isEmpty(value.sources)) {\n for (var s = 0; s < value.sources.length; s++) {\n var sourceReference = value.sources[s];\n if (!isEmpty(sourceReference.qualifiers)) {\n for (var q = 0; q < sourceReference.qualifiers.length; q++) {\n var qualifier = sourceReference.qualifiers[q];\n if (qualifier.name === \"http://gedcomx.org/RectangleRegion\") {\n var rectangle = new Rectangle(qualifier.value);\n var overlay = createOverlay(boxType, rectangle);\n boxes.push(overlay);\n if (text && markers) {\n addMarker(markers, overlay.id, text, boxType);\n }\n }\n }\n }\n }\n }\n }",
"function initilaizeImages() {\n for (let i = 0; i < imageSrcArray.length; i++) {\n createBlock(imageSrcArray[i]);\n }\n }",
"function fillImages() {\n $(\".box\").forEach(function (el, i) {\n let portion = getImagePortion(\n imgObject, // imgObj\n pieceSize, // newWidth\n pieceSize, // newHeight\n (i % boxSlice) * pieceSize, // startX\n Math.floor(i / boxSlice) * pieceSize // startY\n );\n el.src = portion;\n imageParts.push(el);\n });\n gameStart = true;\n}",
"function submitIntro(test){\n var windowURL = document.location.href;\n if(test === \"testEdit\"){\n $(\"#saveText\").html(\"Getting Leaf...\");\n $(\"#saveCover\").show();\n }\n else{\n $(\"#saveText\").html(\"Creating Leaf...\");\n $(\"#saveCover\").show();\n }\n \n var forProject = detectWho();\n \n //$(\".intro\").hide(\"blind\", \"300ms\", function(){$(\".imgAdditionArea\").show(\"explode\", \"500ms\");});\n $(\".intro\").hide();\n $(\".imgAdditionArea\").show(\"explode\", \"500ms\");\n if(test === \"testEdit\"){\n return false;\n }\n// if(windowURL.indexOf(\"demo=1\") > -1){\n// gatherRangesForArrange(1); //Should we populate this for the demo\n// return false;\n// }\n gatherRangesForArrange(1);\n $(\".leafPopover\").show();\n var newCanvas1ServerID = -1;\n var newCanvas2ServerID = -1;\n annoListCollection = new Array(3);\n //create a new leaf range and get ID. The leaf range will create 2 canvases whose ID's I will also need.\n canvasTag = 100;\n canvasTag = parseInt(canvasTag)+1;\n var newCanvasHolderImg = {\n \"@type\":\"oa:Annotation\",\n \"motivation\":\"sc:painting\",\n \"resource\":\n {\n \n \"format\":\"image/jpg\",\n \"@type\":\"dctypes:Image\",\n \n \"@id\" : \"http://brokenbooks.org/brokenBooks/images/imgNotFound.png\",\n \"service\":\n { \n \"@context\": \"http://iiif.io/api/image/2/context.json\",\n \"profile\":\"http://iiif.io/api/image/2/profiles/level2.json\",\n \"@id\" : \"http://brokenbooks.org/brokenBooks/images/imgNotFound.png\"\n },\n \"width\": 667,\n \"height\":1000\n },\n \"on\":\"\"\n };\n var newCanvas1 = {\n \"@id\" : \"http://www.example.org/reform/canvas/\"+canvasTag+\"\", //local\n \"@type\" : \"sc:Canvas\",\n \"label\" : \"Side A\",\n \"height\" : 1000,\n \"width\" : 667,\n \"images\" : [],\n \"forProject\" : forProject,\n \"otherContent\": [],\n \"within\" : \"\"\n };\n \n annoListID = parseInt(annoListID) + 1;\n $(\"#folioSide1\").attr(\"onclick\",\"enterCatalogueInfo('http://www.example.org/reform/canvases/\"+canvasTag+\"', 'recto');\"); //local\n \t $(\"#folioSide1\").attr(\"canvas\",\"http://www.example.org/reform/canvases/\"+canvasTag+\"\"); //local\n \t //testManifest.sequences[0].canvases.push(newCanvas1); //local\n \t var url = \"http://brokenbooks.org/brokenBooks/saveNewCanvas\";\n \t var params1 = {'content': JSON.stringify(newCanvas1)};\n if(windowURL.indexOf(\"demo=1\")>-1){\n var data = newCanvas1;\n var newCanvas1HolderImg = newCanvasHolderImg;\n newCanvas1HolderImg.on = data[\"@id\"];\n var newCanvas1AnnoList = {\n \"@id\":\"http://www.example.org/reform/annoList/\"+annoListID, \n \"@type\":\"sc:AnnotationList\",\n \"resources\" : [],\n \"forProject\": forProject,\n \"on\" : newCanvas1[\"@id\"],\n \t \t}; //local\n \n annoListCollection[0] = newCanvas1AnnoList;\n \t \t$(\"#folioSide1\").attr(\"onclick\",\"enterCatalogueInfo('\"+data[\"@id\"]+\"', 'recto');\"); \n \t \t$(\"#folioSide1\").attr(\"canvas\", data[\"@id\"]); \n \t \tmanifestCanvases.push(newCanvas1); //live\n var listID = newCanvas1AnnoList[\"@id\"];\n newCanvas1.images = [newCanvas1HolderImg];\n newCanvas1.otherContent = [{\"@id\":listID,\"@type\":\"sc:AnnotationList\"}];\n $(\"#folioSide1\").click();\n $(\"#catalogueInfoFor\").val(newCanvas1[\"@id\"]);\n alpha = true;\n beta= false;\n zeta = false;\n \t \tnewCanvas1ServerID = newCanvas1[\"@id\"];\n \t canvasTag = parseInt(canvasTag) + 1;\n annoListID = parseInt(annoListID) + 1;\n\n var urlCanvas = {\n \"@id\" : \"http://www.example.org/reform/canvas/\"+canvasTag+\"\",\n \"@type\" : \"sc:Canvas\",\n \"label\" : \"Side B\",\n \"height\" : 1000,\n \"width\" : 667,\n \"images\" : [],\n \"forProject\" : forProject,\n \"otherContent\" : [],\n \"within\" : \"\"\n };\n \n var newCanvas2 = urlCanvas;\n var newCanvas2HolderImg = newCanvasHolderImg;\n newCanvas2HolderImg.on = newCanvas2[\"@id\"];\n newCanvas2ServerID = newCanvas2[\"@id\"];\n $(\"#folioSide2\").attr(\"onclick\",\"enterCatalogueInfo('\"+ newCanvas2[\"@id\"]+\"','verso');\");\n $(\"#folioSide2\").attr(\"canvas\", newCanvas2[\"@id\"]);\n manifestCanvases.push(newCanvas2); //live\n var newCanvas2AnnoList = {\n \"@id\":\"http://www.example.org/reform/annoList/\"+annoListID, \n \"@type\":\"sc:AnnotationList\",\n \"resources\" : [],\n \"forProject\": forProject,\n \"on\" : newCanvas2[\"@id\"]\n };\n annoListCollection[1] = newCanvas2AnnoList;\n rangeID = parseInt(rangeID) + 1;\n annoListID = parseInt(annoListID) + 1;\n var leafRangeObject = {\n \"@id\" : \"http://www.example.org/reform/range/\"+rangeID,\n \"@type\":\"sc:Range\",\n \"label\":\"Manifest Page\" ,\n \"canvases\" : [\n //newCanvas1[\"@id\"], //local\n //newCanvas2[\"@id\"] //local\n newCanvas1ServerID, //live on dev server\n newCanvas2ServerID //live on dev server\n ],\n \"resources\" : [],\n \"ranges\" : [],\n \"isReferencedBy\":manifestID,\n \"forProject\": forProject,\n \"within\" : \"root\",\n \"otherContent\" : [],\n \"lockedup\" : \"false\",\n \"lockeddown\": \"false\",\n \"isOrdered\" : \"false\"\n };\n currentLeaf = \"http://www.example.org/reform/range/\"+rangeID; //local\n createNewRange(leafRangeObject, 'currentLeaf', \"\", \"\", \"\");\n \n }\n else{\n $.post(url, params1, function(data){ //save first new canvas\n //console.log(\"saved first canvas...\");\n \t \tdata = JSON.parse(data);\n \t \tnewCanvas1[\"@id\"] = data[\"@id\"];\n var newCanvas1HolderImg = newCanvasHolderImg;\n newCanvas1HolderImg.on = data[\"@id\"];\n annoListID = parseInt(annoListID) + 1;\n var newCanvas1AnnoList = {\n \"@id\":\"http://www.example.org/reform/annoList/\"+annoListID, \n \"@type\":\"sc:AnnotationList\",\n \"resources\" : [],\n \"forProject\": forProject,\n \"on\" : newCanvas1[\"@id\"]\n \t \t}; //local\n \n annoListCollection[0] = newCanvas1AnnoList;\n \t \t$(\"#folioSide1\").attr(\"onclick\",\"enterCatalogueInfo('\"+data[\"@id\"]+\"', 'recto');\"); \n \t \t$(\"#folioSide1\").attr(\"canvas\", data[\"@id\"]); \n \t \t//testManifest.sequences[0].canvases.push(newCanvas1); //live\n \n \t//save anno list for new canvas\n //annoListCollection[0] = newCanvas1AnnoList;\n \tvar listURL1 = \"http://brokenbooks.org/brokenBooks/saveNewRange\";\n \tvar listParams1 = {\"content\" : JSON.stringify(newCanvas1AnnoList)};\n \t$.post(listURL1, listParams1, function(data){ //save first canvas annotation list\n //add holder img annotation in to images field.\n //console.log(\"saved first canvas anno list\");\n \t\tdata = JSON.parse(data);\n \t\tannoListCollection[0][\"@id\"] = data[\"@id\"];\n var listID = data[\"@id\"];\n \t\tvar updateCanvasURL = \"http://brokenbooks.org/brokenBooks/updateCanvas\";\n var imgAnno = {\"@id\":newCanvas1[\"@id\"], \"images\":[newCanvas1HolderImg]};\n \t\tvar imgParams = {\"content\":JSON.stringify(imgAnno)};\n newCanvas1.otherContent =[{\"@id\":listID,\"@type\":\"sc:AnnotationList\"}];\n manifestCanvases.push(newCanvas1); //live\n \t\t$.post(updateCanvasURL, imgParams, function(data){\n //console.log(\"update canvas image with new image anno, we had to wait to sait on property.\");\n var paramObj = {\"@id\":newCanvas1[\"@id\"], \"otherContent\":[{\"@id\":listID,\"@type\":\"sc:AnnotationList\"}]};\n var params = {\"content\":JSON.stringify(paramObj)};\n $.post(updateCanvasURL, params, function(data){\n //console.log(\"update canvas other content\");\n $(\"#folioSide1\").click();\n $(\"#catalogueInfoFor\").val(newCanvas1[\"@id\"]);\n alpha = true;\n beta= false;\n zeta = false;\n });\n \t\t});\n \n \t});\n \t \tnewCanvas1ServerID = newCanvas1[\"@id\"];\n \t canvasTag = parseInt(canvasTag) + 1;\n annoListID = parseInt(annoListID) + 1;\n var urlCanvas = {\n \"@id\":\"http://www.example.org/reform/canvas/\"+canvasTag+\"\",\n \"@type\" : \"sc:Canvas\",\n \"label\" : \"Side B\",\n \"height\" : 1000,\n \"width\" : 667,\n \"images\" : [],\n \"forProject\" : forProject,\n \"otherContent\" : [],\n \"within\" : \"\"\n };\n \n\t \tvar params2 = {'content': JSON.stringify(urlCanvas)};\n\t \t$.post(url, params2, function(data){\n //console.log(\"saved second canvas\");\n var newCanvas2 = urlCanvas;\n\t \t\tdata=JSON.parse(data);\n newCanvas2[\"@id\"] = data[\"@id\"];\n var newCanvas2HolderImg = newCanvasHolderImg;\n newCanvas2HolderImg.on = data[\"@id\"];\n newCanvas2ServerID = newCanvas2[\"@id\"];\n \t \t\t$(\"#folioSide2\").attr(\"onclick\",\"enterCatalogueInfo('\"+ newCanvas2[\"@id\"]+\"','verso');\");\n \t \t\t$(\"#folioSide2\").attr(\"canvas\", newCanvas2[\"@id\"]);\n \t \t\t//testManifest.sequences[0].canvases.push(newCanvas2); //live\n \n var newCanvas2AnnoList = {\n\t \"@id\":\"http://www.example.org/reform/annoList/\"+annoListID, \n\t \"@type\":\"sc:AnnotationList\",\n\t \"resources\" : [],\n \"forProject\": forProject,\n\t \"on\" : newCanvas2[\"@id\"]\n\t \t};\n annoListCollection[1] = newCanvas2AnnoList;\n var listURL2 = \"http://brokenbooks.org/brokenBooks/saveNewRange\";\n\t \tvar listParams2 = {\"content\" : JSON.stringify(newCanvas2AnnoList)};\n\t \tvar canvasID = newCanvas2[\"@id\"];\n\t \t$.post(listURL2, listParams2, function(data){\n //console.log(\"saved second canvas list\");\n\t \t\tdata = JSON.parse(data);\n annoListCollection[1][\"@id\"] = data[\"@id\"];\n var listID = data[\"@id\"];\n\t \t\tvar updateCanvasURL = \"http://brokenbooks.org/brokenBooks/updateCanvas\";\n var imgAnno2 = {\"@id\":canvasID, \"images\":[newCanvas2HolderImg]};\n var imgParams2 = {\"content\":JSON.stringify(imgAnno2)};\n newCanvas2.otherContent = [{\"@id\":listID, \"@type\":\"sc:AnnotationList\"}];\n manifestCanvases.push(newCanvas2); //live\n $.post(updateCanvasURL, imgParams2, function(data){\n //console.log(\"update second canvas image\");\n var paramObj = {\"@id\":canvasID, \"otherContent\":[{\"@id\":listID, \"@type\":\"sc:AnnotationList\"}]};\n var params = {\"content\":JSON.stringify(paramObj)};\n $.post(updateCanvasURL, params, function(data){\n updateManifestSequence();\n });\n });\n\t \t});\n rangeID = parseInt(rangeID) + 1;\n annoListID = parseInt(annoListID) + 1;\n var leafRangeObject = {\n \"@id\" : \"http://www.example.org/reform/range/\"+rangeID,\n \"@type\":\"sc:Range\",\n \"label\":\"Manifest Page\" ,\n \"canvases\" : [\n //newCanvas1[\"@id\"], //local\n //newCanvas2[\"@id\"] //local\n newCanvas1ServerID, //live on dev server\n newCanvas2ServerID //live on dev server\n ],\n \"resources\" : [],\n \"ranges\" : [],\n \"isReferencedBy\":manifestID,\n \"forProject\": forProject,\n \"within\" : \"bucket\", //dont want these to appear until placed\n \"otherContent\" : [],\n \"lockedup\" : \"false\",\n \"lockeddown\": \"false\",\n \"isOrdered\" : \"false\"\n };\n currentLeaf = \"http://www.example.org/reform/range/\"+rangeID; //local\n createNewRange(leafRangeObject, 'currentLeaf', \"\", \"\", \"\");\n\n });\n });\n }\n \n\t}",
"loadImages() {\r\n let loadImages = document.querySelectorAll(\".box img\");\r\n\r\n let imageObserver = new IntersectionObserver((entries, observer) => {\r\n entries.forEach(entry => {\r\n if (entry.isIntersecting) {\r\n let image = entry.target;\r\n image.src = image.dataset.src;\r\n imageObserver.unobserve(image);\r\n }\r\n })\r\n });\r\n\r\n loadImages.forEach(image => {\r\n imageObserver.observe(image)\r\n });\r\n }",
"constructor(canvasElementId, canvasWidth = '', imageSrc = '',\n lineWidth = '2', lineColor = '#000000', lineHead = false, fontFamily = 'Arial',\n fontSize = '20', fontColor = '#000000', fontStyle = 'regular', fontAlign = 'center',\n fontBaseline = 'middle', mark = 'X', orderType = ORDER_TYPE_NUM,\n // Below are specific class parameters\n listObjectsCoords = [], listObjectsTags = [], strokeRectObject = true,) {\n\n super(canvasElementId, canvasWidth, imageSrc, lineWidth, lineColor, lineHead, fontFamily,\n fontSize, fontColor, fontStyle, fontAlign, fontBaseline, mark, orderType);\n\n // own properties of the class\n this.listObjectsCoords = listObjectsCoords; // array of objects coordinates in the image\n this.listObjectsTags = listObjectsTags; // array of objects tags in the image\n this._listObjectsTagged = []; // array to store the array of objects coordinates tagged by user\n this.strokeRectObject = strokeRectObject; // define if object will be put into a rectangle\n\n // binding click event to canvas element to allow the gap match exercise execution\n this._canvasElement.addEventListener(\"click\", this.clickAction.bind(this), false);\n }",
"function initAndPlaceElements(){\n\t\tplaceSlider();\n\n\t\tg_objSlider.run();\n\n g_lightbox.run();\n\t}",
"function agrandir(params) {\n\n var pageBigImg = new tabris.Page({\n //tabris.ui.set(\"toolbarVisible\", false);\n }).once(\"resize\", function () { // used \"resize\" event as workaround for tabris-js#597\n tabris.ui.set(\"toolbarVisible\", true);\n });\n var scrollAgrandir = new tabris.ScrollView({\n left: 0, right: 0, top: 0, bottom: 0,\n direction: \"horizontal\",\n background: \"#000\"\n }).appendTo(pageBigImg);\n //----\n var agrand = new tabris.ImageView({\n left: 0, right: 0, top: 0, bottom: 0, width: 1000, centerX: 0, centerX: 0,\n image: params,\n scaleMode: \"fill\"\n }).on(\"tap\", function () {\n // console.error(\"this img select wiiiiiii\");\n //reqBox_.reqBox(value,mapz);\n }).appendTo(scrollAgrandir);\n pageBigImg.open();\n }",
"allocateIBoxes(bounds) {\n this.rtree.load(bounds);\n }",
"function _via_load_canvas_regions() {\n // load all existing annotations into _via_canvas_regions\n var regions = _via_img_metadata[_via_image_id].regions;\n _via_canvas_regions = [];\n for ( var i = 0; i < regions.length; ++i ) {\n var regioni = new ImageRegion();\n for ( var key of regions[i].shape_attributes.keys() ) {\n var value = regions[i].shape_attributes.get(key);\n regioni.shape_attributes.set(key, value);\n }\n _via_canvas_regions.push(regioni);\n\n switch(_via_canvas_regions[i].shape_attributes.get('name')) {\n case VIA_REGION_SHAPE.RECT:\n var x = regions[i].shape_attributes.get('x') / _via_canvas_scale;\n var y = regions[i].shape_attributes.get('y') / _via_canvas_scale;\n var width = regions[i].shape_attributes.get('width') / _via_canvas_scale;\n var height = regions[i].shape_attributes.get('height') / _via_canvas_scale;\n\n _via_canvas_regions[i].shape_attributes.set('x', Math.round(x));\n _via_canvas_regions[i].shape_attributes.set('y', Math.round(y));\n _via_canvas_regions[i].shape_attributes.set('width' , Math.round(width) );\n _via_canvas_regions[i].shape_attributes.set('height', Math.round(height));\n break;\n\n case VIA_REGION_SHAPE.CIRCLE:\n var cx = regions[i].shape_attributes.get('cx') / _via_canvas_scale;\n var cy = regions[i].shape_attributes.get('cy') / _via_canvas_scale;\n var r = regions[i].shape_attributes.get('r') / _via_canvas_scale;\n _via_canvas_regions[i].shape_attributes.set('cx', Math.round(cx));\n _via_canvas_regions[i].shape_attributes.set('cy', Math.round(cy));\n _via_canvas_regions[i].shape_attributes.set('r' , Math.round(r));\n break;\n\n case VIA_REGION_SHAPE.ELLIPSE:\n var cx = regions[i].shape_attributes.get('cx') / _via_canvas_scale;\n var cy = regions[i].shape_attributes.get('cy') / _via_canvas_scale;\n var rx = regions[i].shape_attributes.get('rx') / _via_canvas_scale;\n var ry = regions[i].shape_attributes.get('ry') / _via_canvas_scale;\n _via_canvas_regions[i].shape_attributes.set('cx', Math.round(cx));\n _via_canvas_regions[i].shape_attributes.set('cy', Math.round(cy));\n _via_canvas_regions[i].shape_attributes.set('rx', Math.round(rx));\n _via_canvas_regions[i].shape_attributes.set('ry', Math.round(ry));\n break;\n\n case VIA_REGION_SHAPE.POLYGON:\n var all_points_x = regions[i].shape_attributes.get('all_points_x').slice(0);\n var all_points_y = regions[i].shape_attributes.get('all_points_y').slice(0);\n for (var j=0; j<all_points_x.length; ++j) {\n all_points_x[j] = Math.round(all_points_x[j] / _via_canvas_scale);\n all_points_y[j] = Math.round(all_points_y[j] / _via_canvas_scale);\n }\n _via_canvas_regions[i].shape_attributes.set('all_points_x', all_points_x);\n _via_canvas_regions[i].shape_attributes.set('all_points_y', all_points_y);\n break;\n\n case VIA_REGION_SHAPE.POINT:\n var cx = regions[i].shape_attributes.get('cx') / _via_canvas_scale;\n var cy = regions[i].shape_attributes.get('cy') / _via_canvas_scale;\n\n _via_canvas_regions[i].shape_attributes.set('cx', Math.round(cx));\n _via_canvas_regions[i].shape_attributes.set('cy', Math.round(cy));\n break;\n }\n }\n }",
"function InteractiveBound(image, wcX, wcY, bounds, isPreview) {\n var startingSize = 50; //Starting bound size in WC units\n this.isPreview = isPreview;\n \n //Array of bounding coordinates for scaling/moving bound\n this.sourceBounds = bounds;\n \n //Initialize bound sprite\n this.boundRenderable = new SpriteRenderable(image);\n this.boundRenderable.setColor([0,0,0,0]);\n this.boundRenderable.getXform().setPosition(wcX,wcY);\n this.boundRenderable.getXform().setSize(startingSize,startingSize);\n \n var squareSize = 5;\n \n //Bound Marker Squares\n this.leftSquare = new Renderable();\n this.leftSquare.setColor([1,0,0,1]); //red\n this.leftSquare.getXform().setSize(squareSize,squareSize);\n \n this.rightSquare = new Renderable();\n this.rightSquare.setColor([0,1,0,1]); //green\n this.rightSquare.getXform().setSize(squareSize,squareSize);\n \n this.topSquare = new Renderable();\n this.topSquare.setColor([0,0,1,1]); //blue\n this.topSquare.getXform().setSize(squareSize,squareSize);\n \n this.bottomSquare = new Renderable();\n this.bottomSquare.setColor([0,0.5,0.5,1]);\n this.bottomSquare.getXform().setSize(squareSize,squareSize);\n \n this.minWidth = 0;\n \n this.minHeight = 0;\n \n //Create preview bounds if this renderable is not a preview bound itself\n this.previewBounds = [];\n if(!isPreview) {\n for(var i = 1; i <= 4; i++) {\n var boundX = wcX + i * startingSize;\n var boundRenderable = new InteractiveBound(image, boundX, wcY, bounds,\n true);\n this.previewBounds.push(boundRenderable);\n }\n } \n \n //Flag whether or not to show previewBounds\n this.showPreview = false;\n}",
"function CarregarImagens()\n{\n\tvar blnSel \n\tfor(intIndex=0;intIndex<arguments.length;intIndex++)\n\t{\n\t\t//Imgens que representa os status do Teclado\n\t\tif (intIndex == 0) blnSel = true\n\t\telse blnSel = false\n\t\tobjAryStatus[intIndex] = new Array(blnSel,arguments[intIndex])\n\t}\t\n\n\t//Carrega as imagens do Teclado no cliente\n\tfor (var intIndex=0;intIndex<objAryStatus.length;intIndex++)\n\t{\n\t\tobjAryTeclado[intIndex] = new Image() \n\t\tobjAryTeclado[intIndex].src = objAryStatus[intIndex][1]\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create Zip and download | function makeZip() {
const { filename, content } = fflateBuildZipContent()
const [zipPromise, resolve, reject] = makePromise()
fflate.zip(content, (err, data) => {
if (err) {
reject(err)
return
}
resolve(data)
})
return zipPromise.then(makeBlob).then(blob => {
saveAs(blob, filename)
})
} | [
"async function createByZip() {\n debug('zip mode');\n await download(zipUrl, target, { extract: true });\n }",
"async function createZip() {\n await zipFolder.zip(`${__dirname}/uploads`, `${__dirname}/archive.zip`);\n}",
"function createZip( itcb ) {\n Y.doccirrus.media.zip.create( zipName, onZipCreated );\n function onZipCreated( err, newZipId ) {\n if ( err ) { return itcb( err ); }\n zipId = newZipId;\n Y.log( 'Created new zip for export: ' + zipId, 'info', NAME );\n itcb( null );\n }\n }",
"function createZipFile(self, data) {\n var zip = new JSZip();\n zip.file(\"readme.txt\", data.readme_blob); // backward compatibility for VoxForge 1.0 corpus\n zip.file(\"prompts.txt\", data.prompts_blob); // backward compatibility for VoxForge 1.0 corpus\n zip.file(\"license.txt\", data.license_blob);\n zip.file(\"profile.json\", data.profile_json_blob);\n zip.file(\"prompts.json\", data.prompts_json_blob);\n zip.file(\"debug.json\", data.debug_json_blob);\n\n for (var i = 0; i < data.audio.length; i++) {\n var filename = data.audio[i].filename;\n var audio_blob = data.audio[i].audioBlob;\n zip.file(filename, audio_blob);\n }\n\n /* inner function: create zip file in memory and puts it in a blob object */\n zip.generateAsync({type:\"blob\"})\n .then(\n function(zip_file_in_memory) {\n _saveSubmissionLocally(data, zip_file_in_memory);\n }\n )\n .catch(function(err) { console.log(err) }); \n}",
"function download_zip(pFilename,pZIP) {\n var vFilename = pFilename || \"my_loaded_files.zip\";\n pZIP.generateAsync({type:\"blob\"}).then(function (blob) { // 1) generate the zip file\n saveAs(blob, vFilename); // 2) trigger the download\n console.log(\"Save ZIP is called for Download\");\n }, function (err) {\n console.error(\"ERROR: generation of zip-file '\" + vFilename + \"' - \"+err);\n });\n}",
"_createArchive() {\n if (this._zipFile) return\n this._zipFile = new yazl.ZipFile()\n const directory = dirname(this.path)\n\n this._promise = ensureDirectoryExists(directory)\n .then(() => new Promise((resolve, reject) => {\n this._zipFile.outputStream\n .pipe(fs.createWriteStream(this.path))\n .on('error', reject)\n .on('close', resolve)\n }))\n // TODO: Unhandled rejection\n }",
"async createZipFile() {\n\n const qextFile = resolve(this.extOutDir, `./${this.extensionName}.qext`);\n const jsFile = resolve(this.extOutDir, `./${this.extensionName}.js`)\n const wbFolder = resolve(this.extOutDir, `./wbfolder.wbl`) ;\n\n /** create new JsZip instance and add extension specific files */\n const jsZip = new JsZip();\n jsZip.file(`${this.extensionName}.qext`, fs.readFileSync(qextFile));\n jsZip.file(`${this.extensionName}.js` , fs.readFileSync(jsFile));\n jsZip.file(`wbfolder.wbl`, fs.readFileSync(wbFolder));\n\n /** generate zip file content */\n const zipContent = await jsZip.generateAsync({\n type: 'nodebuffer',\n comment: this.qextFileData.description,\n compression: \"DEFLATE\",\n compressionOptions: {\n level: 9\n }\n });\n\n /** create zip file */\n fs.writeFileSync(resolve(this.extOutDir, `${this.extensionName}.zip`), zipContent);\n return true;\n }",
"zipFile()\n {\n const fileTree = this.getDirectoryFiles( BASE_DIR,\n `${ROOT_DIR}/${BASE_DIR}` );\n const zip = new JsZip();\n\n this.buildZipStructure( zip, fileTree, ROOT_DIR ).then( () =>\n {\n const now = this.lastBackup = Date.now();\n const nowDate = this.timestampToDatestamp( now );\n const next = this.timestampToDatestamp( this.nextBackup );\n\n zip.generateNodeStream( {\n streamFiles : true,\n } )\n .pipe( fs.createWriteStream( `./backup-${nowDate}.zip` ) )\n .on( 'finish', () =>\n {\n if ( CLEAN_UP )\n {\n rimraf( `${ROOT_DIR}/${BASE_DIR}`, NOOP );\n console.warn( `Temporary directory ${ROOT_DIR}/${BASE_DIR} removed` );\n }\n\n console.warn( `./backup-${nowDate}.zip written. Next backup at ${next}` ); // eslint-disable-line\n } );\n } );\n }",
"function createZip(filepaths, callback) {\n let callbackCalled = false;\n // There have been very occasional crashes in production due to the callback\n // function here being called multiple times.\n // I can't see why this might happen, so this function is a temporary way of\n // 1) preventing future crashes\n // 2) capturing what makes it happen - with a nudge via Slack so I don't miss it\n //\n // It is just a brute-force check to make sure we don't call callback twice.\n // I hope that the next time this happens, the URL and/or file path gives me\n // a clue as to why.\n //\n // Yeah, it's horrid. I know.\n function invokeCallbackSafely(err, zipPath, zipSize) {\n if (callbackCalled) {\n log.error({ filepaths }, 'Attempt to call callbackfn multiple times');\n notifications.notify('downloadAndZip failure', notifications.SLACK_CHANNELS.CRITICAL_ERRORS);\n }\n else {\n callbackCalled = true;\n if (err) {\n callback(err);\n }\n else {\n callback(err, zipPath, zipSize);\n }\n }\n }\n tmp.file({ keep: true, postfix: '.zip' }, (err, zipfilename) => {\n if (err) {\n log.error({ err, filepaths }, 'Failure to create zip file');\n return invokeCallbackSafely(err);\n }\n const outputStream = fs.createWriteStream(zipfilename);\n const archive = archiver('zip', { zlib: { level: 9 } });\n outputStream.on('close', () => {\n invokeCallbackSafely(undefined, zipfilename, archive.pointer());\n });\n outputStream.on('warning', (warning) => {\n log.error({ warning }, 'Unexpected warning event from writable filestream');\n notifications.notify('outputStream warning', notifications.SLACK_CHANNELS.CRITICAL_ERRORS);\n });\n outputStream.on('error', (ziperr) => {\n log.error({ err: ziperr }, 'Failed to write to zip file');\n invokeCallbackSafely(ziperr);\n });\n archive.pipe(outputStream);\n filepaths.forEach((filepath) => {\n archive.file(filepath, { name: path.basename(filepath) });\n });\n archive.finalize();\n });\n}",
"function zipFile() {\n\t\tfunction zipMake(type) {\n\t\t\tif(Array.isArray(type)) {\n\t\t\t\ttype.forEach((item, index) => {\n\t\t\t\t\tfs.mkdirSync(`${des}\\\\${item}`);\n\t\t\t\t\tif(item === 'js' || item === 'css') {\n\t\t\t\t\t\tfs.mkdirSync(`${des}\\\\${item}\\\\pad`);\n\t\t\t\t\t\tfs.mkdirSync(`${des}\\\\${item}\\\\touch`);\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}\n\t\t\tzipCopy(['js', 'css']);\n\t\t}\n\t\tfunction zipCopy(type) {\n\t\t\tif(Array.isArray(type)) {\n\t\t\t\ttype.forEach((item, index) => {\n\t\t\t\t\tvar file_input = item === 'css' ? 'css' : 'javascript';\n\t\t\t\t\tvar s = `${dist}\\\\${GLOBAL.project[0]}\\\\resources\\\\${file_input}\\\\build.${item}`;\n\t\t\t\t\tvar d = ['pad', 'touch'];\n\t\t\t\t\td.forEach((v, k) => {\n\t\t\t\t\t\tvar val = `${des}\\\\${item}\\\\${v}\\\\${item}.${item}`;\n\t\t\t\t\t\texec(`copy ${s} ${val}`);\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tvar zipTop = require('zip-zip-top');\n\t\tvar zt = new zipTop();\n\t\tvar exec = require('child_process').execSync, child;\n\t\tvar des = `${dist}\\\\${GLOBAL.project[0]}\\\\activity_package`;\n\t\tif(fs.existsSync(des)) {\n\t\t\texec(`rd /s /q ${des}`);\n\t\t}\n\t\tfs.mkdirSync(des);\n\t\t// copy js and css\n\t\tzipMake(['js', 'css', 'attribute', 'images', 'template']);\n\t\tzt.zipFolder(`${des}`, err => {\n\t\t\tif(err) throw err;\n\t\t\tzt.writeToFileSync(`${des}.zip`);\n\t\t});\n\t}",
"function getZipDownload() {\n if (checkIfReadyForProcessing()) {\n startZipWorker('save');\n }\n}",
"function createZipArchive(basePath, fileList, os, isBundle, downloadFilename, archiveId, dbDownloads, progressInfo, callback) {\n // create zip package\n var zipFileRel = downloadFilename + '_' + archiveId + '.zip';\n var zipFile = path.join(vars.DOWNLOADS_BASE_PATH, zipFileRel);\n var zipListFile = zipFile + '.list';\n var zipLogFile = zipFile + '.log';\n // for progress reporting\n progressInfo.zipListFile = zipListFile;\n progressInfo.zipLogFile = zipLogFile;\n // create file of files to zip\n async.eachSeries(fileList, function (file, callback) { // use eachSeries to prevent too many file handles open for appendFile\n fs.exists(path.join(basePath, file), function (fileExists) { // zip aborts if a file doesn't exist\n if (fileExists) {\n fs.appendFile(zipListFile, file + '\\n', function (err) { // TODO might be better to use a writestream\n if (err != null) {\n logger.error('Download: appendFile error: ' + JSON.stringify(err));\n }\n callback(err);\n });\n } else {\n callback();\n }\n });\n }, function () {\n fs.exists(zipListFile, function (zipListFileExists) {\n if (zipListFileExists === false) {\n callback(null, {link: 'api/download?file=' + 'NothingToDownload.txt' + '&source=local'});\n } else {\n // if there's only a single file to download don't zip it\n if (fileList.length === 1) {\n fs.stat(path.join(basePath, fileList[0]), function (err, stats) {\n if (err == null) {\n if (stats.isFile() === true) {\n callback(null, {link: 'api/download?file=' + encodeURIComponent(path.normalize(fileList[0])) + '&source=content'});\n } else {\n if(isBundle) {\n havePlatformSpecificZip(os, callback);\n }\n else{\n doZip(); // turned out to be a dir, zip it\n }\n }\n } else {\n logger.error('fs.stat: ' + JSON.stringify(err));\n callback('fs.stat failed. See log for details.');\n }\n });\n } else { // more than a single file to download...\n doZip();\n }\n }\n });\n\n function havePlatformSpecificZip(client_os, callback) {\n var cmd;\n var zip_from_repo_file;\n\n if (fileList[0].indexOf('/') > 0) {\n zip_from_repo_file = 'zips/' + fileList[0] +'/' +fileList[0].substring(fileList[0].indexOf('/')+1,fileList[0].length);\n }\n else {\n zip_from_repo_file = 'zips/' + fileList[0] + '/' + fileList[0];\n }\n\n const zip_from_repo_file_all = zip_from_repo_file + '__all.zip';\n if((client_os.indexOf('Mac') !== -1) || (client_os.indexOf('darwin') !== -1)) {\n zip_from_repo_file = zip_from_repo_file + '__macos.zip';\n\n } else if((client_os.indexOf('Win') !== -1) || (client_os.indexOf('win') !== -1)) {\n zip_from_repo_file = zip_from_repo_file + '__win.zip';\n }\n else if((client_os.indexOf('Linux') !== -1) || (client_os.indexOf('linux') !== -1) ) {\n zip_from_repo_file = zip_from_repo_file + '__linux.zip';\n }\n\n // James: use fs.copy\n if(vars.HOST.indexOf('darwin') !== -1) {\n cmd ='cp';\n }\n else if(vars.HOST.indexOf('linux') !== -1) {\n cmd ='cp';\n }\n else if(vars.HOST.indexOf('win') !== -1) {\n cmd ='copy';\n }\n\n fs.stat(vars.CONTENT_BASE_PATH + '/' + zip_from_repo_file, (err) => {\n const zip_from_repo_file_exists = !err;\n const use_all = fs.existsSync(vars.CONTENT_BASE_PATH + '/' + zip_from_repo_file_all);\n downloadFilename = (use_all ? zip_from_repo_file_all : zip_from_repo_file);\n\n if (!zip_from_repo_file_exists && !use_all) {\n doZip();\n }\n else {\n cmd = cmd + ' ' + (use_all ? zip_from_repo_file_all :\n zip_from_repo_file) + ' ' + zipFile;\n \n exec(cmd, {'cwd': vars.CONTENT_BASE_PATH}, function (error, stdout, stderr) {\n if (error !== null) {\n logger.error('copy/cp cmd: ' + cmd);\n logger.error('exec error: ' + error);\n doZip();\n } else {\n // add zip package info to db\n dbDownloads.insert([\n {'_id': archiveId, 'value': zipFileRel, 'downloadFilename': downloadFilename}\n ], function (err) {\n if (err) {\n logger.warn('Error inserting to dbDownloads: ' + JSON.stringify(err));\n }\n dbDownloads.save((err) => {\n if (err) {\n callback(err);\n return;\n }\n callback(null, {\n link: 'api/download?file=' + encodeURIComponent(zipFileRel) +\n '&clientfile=' + encodeURIComponent(downloadFilename) + '&source=cache'\n });\n });\n });\n }\n });\n }\n });\n }\n\n function doZip() {\n var zip;\n if (process.platform === 'darwin') {\n zip = 'zip'; // use the pre-installed one\n } else {\n zip = path.join(vars.BIN_BASE_PATH, 'zip');\n }\n var cmd = zip + ' ' + zipFile + ' -r -@ <' + zipListFile + ' >' + zipLogFile;\n exec(cmd, {'cwd': basePath}, function (error, stdout, stderr) {\n if (error) {\n logger.error('zip cmd: ' + cmd);\n logger.error('zip exec error: ' + error);\n callback(error);\n return;\n }\n // add zip package info to db\n dbDownloads.insert([\n {'_id': archiveId, 'value': zipFileRel, 'downloadFilename': downloadFilename}\n ], function (err) {\n if (err) {\n logger.warn('Error inserting to dbDownloads: ' + JSON.stringify(err));\n }\n dbDownloads.save();\n callback(null, {link: 'api/download?file=' + encodeURIComponent(zipFileRel) +\n '&clientfile=' + encodeURIComponent(downloadFilename) + '.zip' + '&source=cache'});\n });\n });\n }\n });\n}",
"static zip_folder(path_to_folder_to_zip){\n let zip = new AdmZip();\n zip.addLocalFolder(path_to_folder_to_zip)\n zip.writeZip(path_to_folder_to_zip + \".zip\")\n out(path_to_folder_to_zip + \".zip created.\")\n }",
"async function downloadProjectZip() {\n let response = await axios({\n method: \"get\",\n url: `../../diagram/download/${diagramName.innerHTML}`,\n responseType: \"blob\"\n });\n const url = window.URL.createObjectURL(new Blob([response.data]));\n const link = document.createElement(\"a\");\n link.href = url;\n link.setAttribute(\"download\", `erd-${diagramName.innerHTML}.zip`); //or any other extension\n document.body.appendChild(link);\n link.click();\n link.remove();\n }",
"function getZipAndExtract()\n{\n var metaUrl = 'https://www.quandl.com/api/v3/databases/BSE/metadata?api_key=AxRvGc-cgtRgMphua6dJ';\n var output = 'BSE_metadata_new.zip';\n var targetPath = '/finakya-stocks-mf-api/finakyaBackend/server/';\n \n request({url: metaUrl, encoding: null}, function(err, resp, body)\n {\n if(err)\n throw err;\n fs.writeFile(output, body, async function(err)\n {\n console.log(\"file written!\");\n try \n {\n await extract(output, { dir: targetPath });\n console.log('Extraction complete');\n\n deleteFromCollection();\n }\n catch (err) \n {\n console.log('Caught error!')\n console.log(err)\n } \n });\n });\n}",
"function download_zip_url() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n\n return exports.download_archive_url(merge(options, {\n target_format: \"zip\"\n }));\n}",
"async function download(){\n document.getElementById(\"stdout\").innerHTML = \"Preparing downloading file ... It might take a while\"\n let files = await CLI.ls(\".\"); // an array of files\n let zip = new JSZip();\n // download running log\n let runningSummary = document.getElementById(\"stderr\").value;\n let blob = new Blob([runningSummary], { type: \"text/plain;charset=utf-8\" });\n zip.file(\"fastp-running-log.txt\", blob);\n // let promises = [];\n for (let i = 0, f; f = files[i]; i++) {\n if (f.includes(\"filtered_\") || f.includes(\"fastp_\")) {\n console.log(\"Prepare downloading \", f);\n // let blob = new Blob([ await CLI.cat(f) ]);\n // let blob = await CLI.downloadBinary(f);\n let blob = await CLI.download(f).then(d => d.arrayBuffer());\n zip.file(f, blob);\n // promises.push(aa);\n }\n }\n // const d = await Promise.all(promises);\n console.log(\"Finished preparing downloanding!\");\n zip.generateAsync({type:\"blob\"})\n .then(function(content) {\n saveAs(content, \"filtered_fastqs.zip\");\n });\n}",
"function downloadProject()\n{\n const projectId = 5559;\n getToken().then(({token}) =>\n {\n const dataDownloadProject = {\n method: \"GET\",\n uri: `${restApiUrl}/projects/${projectId}/files/download?fileType=TARGET`,\n headers: generateAuthHeader(token)\n };\n request(dataDownloadProject).pipe(createWriteStream(tempZip)).on(\"close\", () => \n {\n console.log(\"Zip file Downloaded\");\n const zip = new admZip(tempZip);\n const zipEntries = zip.getEntries();\n for (const zipEntry of zipEntries)\n {\n const tmxFilePath = zipEntry.entryName;\n const tmxFilename = path.parse(tmxFilePath).base;\n const tmxLocale = path.dirname(tmxFilePath);\n const locale = tmxToLocalesMap[tmxLocale];\n const target = path.join(localesDir, locale, tmxFilename);\n console.log(`${target} updated with content of ${tmxFilePath}`);\n outputFileSync(target, zipEntry.getData());\n }\n removeSync(tempZip);\n console.log(\"Extracted\");\n });\n }).catch((err) =>\n {\n console.log(err);\n });\n}",
"function toZip( location ){\n\t\n\tvar myWorker = studio.SystemWorker;\n\t\n\tif( navigator.platform === 'Win32' ){\n\t\t\t\t/* Windows platform */\n\t\t\t\t \n\t\tvar zipItLoaction = studio.extension.getFolder().path + \"resources/zipit\";\n\t\tzipItLoaction = zipItLoaction.replace( /\\//g, \"\\\\\" );\n\t\tlocation = location.replace( /\\//g, \"\\\\\" );\n\t\tmyWorker.exec( \"cmd /c Zipit.exe \" + location + \".zip \" + location, zipItLoaction );\n\n\t\t\n\t\t//myWorker.prototype.wait();\n\t\t\n\t\t//studio.alert('ziping...');\n\t\t\n\t}\n\telse{\n\t\t\t /* Mac or Linux platform */\n\n\t\tmyWorker.exec( \"bash -c zip -r \" + location + \".zip \" + location );\n\t\t//myWorker.prototype.wait();\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
saveQuestion once we wont implement backend persistence, this website stores the question using the WebStorage API. save quetions in local storage | saveQuestion() {
if (typeof(Storage) == undefined) {
alert("Você precisa habilitar o uso de cookies antes de usar o site!");
return;
}
/* store the set of answer to a given question */
localStorage.setItem(this.quizTitle + this.id + "statement", this.statement);
localStorage.setItem(this.quizTitle + this.id+"right_answer", this.right_answer);
localStorage.setItem(this.quizTitle + this.id+"wrong_answer1", this.wrong_answer1);
localStorage.setItem(this.quizTitle + this.id+"wrong_answer2", this.wrong_answer2);
localStorage.setItem(this.quizTitle + this.id+"wrong_answer3", this.wrong_answer3);
} | [
"function saveQuestions(questions){\n\tlocalStorage.setItem(\"questions\",JSON.stringify(questions)); // setItem = insere ou remplace un élément dans la memoir du navigateur/:\n}",
"function storeQuestions(questions) {\n localStorage.questions = JSON.stringify(questions);\n }",
"function saveQuestions() {\n localStorage.setItem(\"questionList\", JSON.stringify(questionArray))\n}",
"function saveAnswers(){\n localStorage.setItem(\"quiz_answers\", getAnswers());\n }",
"function saveQuiz() {\r\n\tsessionStorage.sid = document.getElementById(\"sid\").value;\r\n\tsessionStorage.name = document.getElementById(\"name\").value;\r\n\tsessionStorage.famname = document.getElementById(\"famname\").value;\r\n\tsessionStorage.question1 = getAnswer(\"question1\");\r\n\tsessionStorage.question2 = document.getElementById(\"question2\").value;\r\n\tsessionStorage.question3 = document.getElementById(\"question3\").value;\r\n\tsessionStorage.question4 = getAnswer(\"question4\");\r\n\tsessionStorage.question5 = document.getElementById(\"question5\").value;\r\n\t\r\n\t// Increment the counter for user.\r\n\tvar count = localStorage.getItem(sessionStorage.sid);\r\n\tif (Number(count) >= \"1\") {\r\n\t\tlocalStorage.setItem(sessionStorage.sid, 1 + Number(count));\r\n\t}\r\n\t// Initialize the local storage for first time user.\r\n\telse {\r\n\t\tlocalStorage.setItem(sessionStorage.sid, 1);\r\n\t}\r\n}",
"function storeQuestion() {\n\t/* stores the number of the question */\n\tvar questionIndex = 0;\n\n\t/* gets view inputs */\n\tvar statement = $(\"#statement_question\").val();\n\tvar rans = $(\"#right_answer_txt\").val();\n\tvar wans1 = $(\"#wrong_answer_txt1\").val();\n\tvar wans2 = $(\"#wrong_answer_txt2\").val();\n\tvar wans3 = $(\"#wrong_answer_txt3\").val();\n\n\t/* validate form inputs */\n\tif (validateForm(statement, rans, wans1, wans2, wans3) == false) {\n\t\talert(\"preencha corretamente todos os campos\");\n\t\treturn false;\n\t}\n\n\t/* gets the title of the quiz (aka the name of the quiz) */\n\tvar quizTitle = localStorage.getItem(\"lastCreatedQuiz\");\n\n\t/* increments the question counter */\n\tvar labelValue = document.getElementById(\"question_tag\").textContent;\n\tvar currentID = parseInt(getQuestionId(labelValue));\n\tquestionIndex = currentID;\n\tvar nextQuestionId = currentID + 1;\n\tdocument.getElementById(\"question_tag\").textContent = \"Questão \" + nextQuestionId;\n\n\t/* stores locally the question */\n\tvar question = new Question(currentID, statement, rans, wans1, wans2, wans3);\n\tquestion.setQuestionOwner(quizTitle);\n\tquestion.saveQuestion();\n\n\treturn questionIndex;\n}",
"function qjSave() {\n var qj_content = $('#qj-master').html();\n localStorage.setItem(qj_local_key, qj_content);\n }",
"function save(){\n const a = JSON.stringify(answers);\n localStorage.setItem(\"answers\", a);\n}",
"function saveQuiz(quiz) {\n localStorage.setItem(\"savedQuiz\", JSON.stringify(quiz));\n}",
"function saveQuestion() {\n let category = $(\"#category\").val();\n let question = $(\"#question\").val();\n let dataArr = [];\n let dateStr = day + \".\" + month + \".\" + year;\n dateStr = \"<h2>Date: \" + dateStr + \"</h2>\";\n dataArr.push(dateStr, category, question);\n questions.push(dataArr);\n qStorage.questions = JSON.stringify(questions);\n console.log(JSON.stringify(questions));\n \n // Close and update\n closeForm();\n getQuestions();\n}",
"function saveQuestion(){\n rightPane.innerHTML = templates.renderQuestionForm();\n var questionForm = document.getElementById(\"question-form\");\n questionForm.addEventListener('click', function(event){\n event.preventDefault();\n var target = event.target;\n var submit = document.querySelector(\"input.btn\");\n if (target === submit){\n var textArea = questionForm.querySelector('textarea').value;\n var nameInput = questionForm.querySelector('input[type=\"text\"]').value;\n var newEntry = {\n subject: nameInput, \n question: textArea,\n id: Math.random(),\n responses: []\n }\n var oldList = getStoredQuestions();\n oldList.push(newEntry);\n storeQuestions(oldList);\n var questionHtml = templates.renderQuestion({ \n questions: getStoredQuestions()\n });\n leftPane.innerHTML = questionHtml;\n questionForm.querySelector('textarea').value = \"\";\n questionForm.querySelector('input[type=\"text\"]').value = \"\"; \n addListeners();\n }\n });\n }",
"function SaveQuestionData() \n{\n debugger;\n\t//alert(innerPage);\n\t var randomizationEnabled = trackObjects[SeqID].questionrandomization.toLowerCase();\t\n\t if (trackObjects[SeqID].singlePageRendering == \"yes\") {\n\t\t\tvar index = 0;\n\t\t\tfor (i = 0; i < getTotalPageInObject(SeqID) ; i++) {\n\t\t\t\tvar arrQA = getPageByIndex(i);\n\t\t\t\t if (arrQA.iscoao == \"ao\" && arrQA.type != \"summary\") { \n\t\t\t\t\tvar randomizationEnabled = trackObjects[SeqID].questionrandomization.toLowerCase();\t\t\n\t\t\t\t\tif (arrQA.useranswer != \"\" && arrQA.useranswer != undefined && arrQA.useranswer != \"NaN\" && arrQA.useranswer != \"NAN\" && arrQA.useranswer != \"nan\" && arrQA.useranswer != \"undefined\" && arrQA.status != undefined && arrQA.status != \"\") {\n\t\t\t\t\t if (trackObjects[SeqID].testType != '8' ){ \n\t\t\t\t\t\t\tif(randomizationEnabled == \"yes\" || (pooledQuestionsStringArray[SeqID] != \"\" && pooledQuestionsStringArray[SeqID] != undefined)){ \n\t\t\t\t\t\t\t\tarrQA.Qid = Number(arrQA.actualPageNumber)+1; \n\t\t\t\t\t\t\t}else{ \n\t\t\t\t\t\t\t\tarrQA.Qid = Number(arrQA.pageNumber) + 1;\n\t\t\t\t\t\t\t} \n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\tif(randomizationEnabled == \"yes\" || (pooledQuestionsStringArray[SeqID] != \"\" && pooledQuestionsStringArray[SeqID] != undefined)){ \n\t\t\t\t\t\t\t arrQA.Qid = arrQA.actualPageNumber; \n\t\t\t\t\t\t\t}else{ \n\t\t\t\t\t\t\t arrQA.Qid = arrQA.pageNumber;\n\t\t\t\t\t\t\t} \t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\tLMSSetQuestionData(arrQA, index); \n\t\t\t\t\t}\n\t\t\t\t\tindex = index + 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvar arrQA = getPageByIndex(innerPage);\n\t\t\tif (arrQA.iscoao == \"ao\" && arrQA.type != \"summary\") \n\t\t\t{\n\t\t\t if (arrQA.useranswer != \"\" && arrQA.useranswer != undefined && arrQA.useranswer != \"NaN\" && arrQA.useranswer != \"NAN\" && arrQA.useranswer != \"nan\" && arrQA.useranswer != \"undefined\" && arrQA.status != undefined && arrQA.status != \"\") { //Sunny on 2nd May 2017\n\t\t\t if (trackObjects[SeqID].testType != '8') {\n\t\t\t if (randomizationEnabled == \"yes\" || (pooledQuestionsStringArray[SeqID] != \"\" && pooledQuestionsStringArray[SeqID] != undefined)) {\n\t\t\t arrQA.Qid = Number(arrQA.actualPageNumber) + 1;\n\t\t\t } else {\n\t\t\t arrQA.Qid = Number(arrQA.pageNumber) + 1;\n\t\t\t }\n\t\t\t } else {\n\t\t\t if (randomizationEnabled == \"yes\" || (pooledQuestionsStringArray[SeqID] != \"\" && pooledQuestionsStringArray[SeqID] != undefined)) {\n\t\t\t arrQA.Qid = Number(arrQA.actualPageNumber);\n\t\t\t } else {\n\t\t\t arrQA.Qid = Number(arrQA.pageNumber);\n\t\t\t }\n\t\t\t }\n\t\t\t LMSSetQuestionData(arrQA, innerPage);\n\t\t\t }\n\t\t\t //if (trackObjects[SeqID].testType != '8' ){\n\t\t\t\t//\tif(randomizationEnabled == \"yes\" || (pooledQuestionsStringArray[SeqID] != \"\" && pooledQuestionsStringArray[SeqID] != undefined)){ \n\t\t\t\t//\t\tarrQA.Qid = Number(arrQA.actualPageNumber)+1; \n\t\t\t\t//\t}else{ \n\t\t\t\t//\t\tarrQA.Qid = Number(arrQA.pageNumber) + 1;\n\t\t\t\t//\t} \n\t\t\t\t//}else{\n\t\t\t\t//\tif(randomizationEnabled == \"yes\" || (pooledQuestionsStringArray[SeqID] != \"\" && pooledQuestionsStringArray[SeqID] != undefined)){ \n\t\t\t\t//\t\tarrQA.Qid = Number(arrQA.actualPageNumber); \n\t\t\t\t//\t}else{ \n\t\t\t\t//\t\tarrQA.Qid = Number(arrQA.pageNumber);\n\t\t\t\t//\t} \n //} \t\t\t\t\n\t\t\t //LMSSetQuestionData(arrQA, innerPage); \n\t\t\t}\n\t\t}\n\n }",
"function saveQuiz(e){\n e.preventDefault(); // preventing the button from refreshing the page\n\n // Bringing up the local storage\n let questionListContent = JSON.parse(localStorage.getItem('questionList'));\n let QuizName_storage = JSON.parse(localStorage.getItem('QuizName')); \n let FinishedQuizzes = JSON.parse(localStorage.getItem('Finished_Quizzes'));\n let DataContent = JSON.parse(localStorage.getItem('Data'));\n \n // Making the save quiz button to save the current changes before moving to prev/next question\n questionListContent[DataContent.num - 1] = DataContent;\n localStorage.setItem(\"questionList\", JSON.stringify(questionListContent));\n\n // A check to see if the user gave the quiz a name\n if (QuizName_storage === \"\") {\n return alert(\"השאלון לא קיבל שם.\")\n }\n\n // A check to see if the user is about to save a quiz with an already used name\n let FinishedQuizzes_check = JSON.parse(localStorage.getItem('Finished_Quizzes'));\n\n for (let i = 0; i < FinishedQuizzes_check.length; i++){\n const nameOfSavedQuiz = Object.values(Object.keys(FinishedQuizzes_check[i])).join(\"\")\n \n if (nameOfSavedQuiz === QuizName_storage){\n return alert(\"קיים שאלון עם השם הזה, נדרש להמציא שם חדש\");\n };\n };\n\n if (questionListContent.length === 1) {\n return alert(\"שאלון לא יכול להיות מורכב משאלה אחת בלבד!\");\n }\n\n // The final version of the quiz\n let finitoVer;\n\n // Assistance variables\n let problematic_index;\n let problematic_List = [];\n let problematicQuestion;\n \n \n // A loop that goes though the questions and checks for missing info\n for ( let i = 0; i < questionListContent.length; i++ ) {\n let index = questionListContent[i];\n \n if (index.questionIMG === '' || index.questionText === '' || index.correctAnswer === '' || index.answersBank === {first: '', second: '', third: '', fourth: ''}) { \n problematic_index = index;\n problematic_List.push(problematic_index);\n problematicQuestion = index.num;\n\n } else {\n problematicQuestion = \"all good\";\n }\n };\n\n // If any question misses info the site will tell about it to user through alert, the questions that will \n // be found missing info will added to a list and will be notified to the user.\n\n if (problematicQuestion === \"all good\") {\n\n // Making an object that will help us save the Quiz's info to the Quiz's name and add it to the finished list\n finitoVer = {\n [QuizName_storage]: questionListContent\n };\n\n FinishedQuizzes.push(finitoVer);\n localStorage.setItem(\"Finished_Quizzes\", JSON.stringify(FinishedQuizzes));\n\n\n alert(\"השאלון נשמר בהצלחה!\")\n\n //clearing local and moving back to home screen\n localStorage.removeItem(\"QuizName\");\n localStorage.removeItem(\"Data\");\n localStorage.removeItem(\"questionList\");\n\n window.location.href = \"../Home page/Home.html\";\n\n } else {\n\n // Making the variable for the filtered list \n let filteredList = questionListContent;\n\n for (let i = 0; i < problematic_List.length; i++){\n let r = confirm(`לשאלה ${problematic_List[i].num} חסרים פרטים, אם תמשיך היא לא תישמר`);\n\n // If the user wants to save without this question the code will filter it out.\n if (r) {\n filteredList = filteredList.filter( (item) => {\n return item !== problematic_List[i]})\n\n // prevent from asking about the next question if the user clicked cancel on one of the alerts \n } else {\n break;\n };\n\n // A check to see if its the last question thats lacks info\n if (r && problematic_List[i] === problematic_List[problematic_List.length-1]) {\n \n // Making an object that will help us save the Quiz's info to the Quiz's name and add it to the finished list\n finitoVer = {\n [QuizName_storage]: filteredList\n };\n\n FinishedQuizzes.push(finitoVer);\n localStorage.setItem(\"Finished_Quizzes\", JSON.stringify(FinishedQuizzes));\n\n alert(\"השאלון נשמר בהצלחה\");\n\n //clearing local and moving back to home screen\n localStorage.removeItem(\"QuizName\");\n localStorage.removeItem(\"Data\");\n localStorage.removeItem(\"questionList\");\n\n window.location.href = \"../Home page/Home.html\";\n }; \n }; \n };\n}",
"function saveEditedQA(e) {\n event.preventDefault();\n const index = qaSubmit.index;\n let qas;\n let titles;\n let classes;\n // get list of qas from storage\n if (localStorage.getItem(\"qas\") === null) {\n qas = [];\n titles = [];\n classes = [];\n } else {\n qas = JSON.parse(localStorage.getItem(\"qas\"));\n titles = JSON.parse(localStorage.getItem(\"titles\"));\n classes = JSON.parse(localStorage.getItem(\"classes\"));\n }\n // change QA attributes at index in storage\n qas[index] = qaHref.value;\n titles[index] = qaTitle.value;\n classes[index] = getIcon(qaHref.value);\n \n // set storage\n localStorage.setItem(\"qas\", JSON.stringify(qas));\n localStorage.setItem(\"titles\", JSON.stringify(titles));\n localStorage.setItem(\"classes\", JSON.stringify(classes));\n window.location.reload(false);\n}",
"function syncCollection () {\n localStorage.setItem('_questions', JSON.stringify(_questions));\n}",
"retrieveQuestion() {\n\t\tif (typeof(Storage) == undefined) {\n\t\t\talert(\"Você precisa habilitar o uso de cookies antes de usar o site!\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\t/* retrieves the set of questions to a given question */\n\t\tthis.statement = localStorage.getItem(this.quizTitle + this.id + \"statement\");\n\t\tthis.right_answer = localStorage.getItem(this.quizTitle + this.id + \"right_answer\");\n\t\tthis.wrong_answer1 = localStorage.getItem(this.quizTitle + this.id + \"wrong_answer1\");\n\t\tthis.wrong_answer2 = localStorage.getItem(this.quizTitle + this.id + \"wrong_answer2\");\n\t\tthis.wrong_answer3 = localStorage.getItem(this.quizTitle + this.id + \"wrong_answer3\");\t\n\t}",
"function storeAns($ques, $answer) {\n\tanswers[$ques] = $answer;\n\tdocument.getElementById($ques).innerHTML = \"<div class='saved'><i class='fas fa-check-circle'></i> Saved!</div>\";\n\t\n\tsetTimeout(function(){\n\t\tdocument.getElementsByClassName(\"saved\")[0].classList.add(\"fadein\");}, 10);\n\tsetTimeout(function(){disappear($ques);}, 1000);\n\t\n\tsessionStorage.setItem(\"useranswers\", JSON.stringify(answers));\n\t//console.log(answers);\n\t\n}",
"function submitSurvey(){\n localStorage.setItem('surveyComment',document.getElementById('surveyCommentText').value);\n localStorage.setItem('surveyCity',document.getElementById('surveyCityOpt').value);\n localStorage.setItem('surveyRoom',document.getElementById('surveyRoomOpt').value);\n}",
"function saveQuestion()\n{\n\tvar id = $('#questionIdInput').val();\n\tvar question = $('#questionLabelInput').val();\n\tvar answer = $('#questionAnswerInput').val();\n\tif (question && answer && isInt(id)) {\n\n\t\t// We get the tags of the question\n\t\tvar tags = [];\n\t\t$('.tagElement').each(function(){\n\t\t\ttags[tags.length] = {'id' : $(this).data('tagid'), 'name' : $(this).data('tagname')};\n\t\t});\n\n\t\t// We fill the args with form data\n\t\tvar argsArray = [];\n\t\targsArray[argsArray.length] = id;\n\t\targsArray[argsArray.length] = question;\n\t\targsArray[argsArray.length] = answer;\n\t\targsArray[argsArray.length] = tags;\n\n\t\t// AJAX call\n\t\tvar params = {\n\t\t\tphpclass:'QuestionActions',\n\t\t\tmethod:'saveQuestion',\n\t\t\targs: argsArray\n\t\t};\n\n\t\tsendAjaxRequest(params, afterQuestionAdded, handleErrorPage);\n\t} else{\n\t\taddErrorMessage('The fields \"Question\" and \"Answer\" are mandatory.', '#addQuestion');\n\t};\n\n\t// Cancel the click on the button\n\treturn false;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates an INSERT SQL query dynamically based on input from client. Minimum information require is handle and name. | function makeInsertQuery(reqObj, safeFields) {
let query = `INSERT INTO companies (`;
let valuesArr = [];
let valueStr = ") VALUES (";
let idx = 1;
for (let key in reqObj) {
if (safeFields.includes(key)){
query+= `${key}, `;
valueStr += `$${idx}, `;
valuesArr.push(reqObj[key]);
idx++;
}
}
valueStr = valueStr.slice(0, -2); // ", " = 2
// ", " = 2
query = query.slice(0, -2) + valueStr + `) RETURNING handle, name, num_employees, description, logo_url`;
return {query, valuesArr};
} | [
"insert() {\n const insertValues = this.single.insert || [];\n let sql = this.with() + `insert into ${this.tableName} `;\n if (Array.isArray(insertValues)) {\n if (insertValues.length === 0) {\n return '';\n }\n } else if (typeof insertValues === 'object' && isEmpty(insertValues)) {\n return sql + this._emptyInsertValue;\n }\n\n const insertData = this._prepInsert(insertValues);\n if (typeof insertData === 'string') {\n sql += insertData;\n } else {\n if (insertData.columns.length) {\n sql += `(${columnize_(\n insertData.columns,\n this.builder,\n this.client,\n this.bindingsHolder\n )}`;\n sql += ') values (';\n let i = -1;\n while (++i < insertData.values.length) {\n if (i !== 0) sql += '), (';\n sql += this.client.parameterize(\n insertData.values[i],\n this.client.valueForUndefined,\n this.builder,\n this.bindingsHolder\n );\n }\n sql += ')';\n } else if (insertValues.length === 1 && insertValues[0]) {\n sql += this._emptyInsertValue;\n } else {\n sql = '';\n }\n }\n return sql;\n }",
"function createInsertSQL(allowedKeys, optionalKeys, table, data)\r\n{\r\n validate(data, allowedKeys, optionalKeys);\r\n\r\n const entryID = uuidv4();\r\n console.log(`Creating insert statement with ID: ${entryID}`)\r\n console.log(Object.entries(data).map((e) => `\"${e[0]}\" = \"${e[1]}\"`));\r\n const query = `INSERT INTO ${table} (id, ${Object.keys(data).map(mysql.escapeId).join(\", \")}) VALUES (${mysql.escape(entryID)}, ${Object.values(data).map((v) => `${mysql.escape(v)}`).join(\", \")}); `;\r\n console.log(`QUERY:`)\r\n console.log(\"\\x1b[32m%s\\x1b[0m\", query);\r\n return query;\r\n}",
"insert() {\n const insertValues = this.single.insert || [];\n let sql = this.with() + `insert into ${this.tableName} `;\n if (Array.isArray(insertValues)) {\n if (insertValues.length === 0) {\n return '';\n }\n } else if (typeof insertValues === 'object' && isEmpty$3(insertValues)) {\n return sql + this._emptyInsertValue;\n }\n\n const insertData = this._prepInsert(insertValues);\n if (typeof insertData === 'string') {\n sql += insertData;\n } else {\n if (insertData.columns.length) {\n sql += `(${this.formatter.columnize(insertData.columns)}`;\n sql += ') values (';\n let i = -1;\n while (++i < insertData.values.length) {\n if (i !== 0) sql += '), (';\n sql += this.formatter.parameterize(\n insertData.values[i],\n this.client.valueForUndefined\n );\n }\n sql += ')';\n } else if (insertValues.length === 1 && insertValues[0]) {\n sql += this._emptyInsertValue;\n } else {\n sql = '';\n }\n }\n return sql;\n }",
"insert() {\n const insertValues = this.single.insert || [];\n let sql = this.with() + `insert into ${this.tableName} `;\n if (Array.isArray(insertValues)) {\n if (insertValues.length === 0) {\n return '';\n }\n } else if (typeof insertValues === 'object' && isEmpty(insertValues)) {\n return sql + this._emptyInsertValue;\n }\n\n const insertData = this._prepInsert(insertValues);\n if (typeof insertData === 'string') {\n sql += insertData;\n } else {\n if (insertData.columns.length) {\n sql += `(${this.formatter.columnize(insertData.columns)}`;\n sql += ') values (';\n let i = -1;\n while (++i < insertData.values.length) {\n if (i !== 0) sql += '), (';\n sql += this.formatter.parameterize(\n insertData.values[i],\n this.client.valueForUndefined\n );\n }\n sql += ')';\n } else if (insertValues.length === 1 && insertValues[0]) {\n sql += this._emptyInsertValue;\n } else {\n sql = '';\n }\n }\n return sql;\n }",
"insert() {\n const insertValues = this.single.insert || [];\n let sql = this.with() + `insert into ${this.tableName} `;\n if (Array.isArray(insertValues)) {\n if (insertValues.length === 0) {\n return ''\n }\n } else if (typeof insertValues === 'object' && isEmpty(insertValues)) {\n return sql + this._emptyInsertValue\n }\n\n const insertData = this._prepInsert(insertValues);\n if (typeof insertData === 'string') {\n sql += insertData;\n } else {\n if (insertData.columns.length) {\n sql += `(${this.formatter.columnize(insertData.columns)}`\n sql += ') values ('\n let i = -1\n while (++i < insertData.values.length) {\n if (i !== 0) sql += '), ('\n sql += this.formatter.parameterize(insertData.values[i], this.client.valueForUndefined)\n }\n sql += ')';\n } else if (insertValues.length === 1 && insertValues[0]) {\n sql += this._emptyInsertValue\n } else {\n sql = ''\n }\n }\n return sql;\n }",
"function asCommandText(){\n\t\t\t\tvar data = self.dataItem;\n\n\t\t\t\tvar sql=String.format(\"INSERT INTO {0}\", data.schema.table);\n\t\t\t\tvar fields=\"\";\n\t\t\t\tvar value=\"\";\n\t\t\t\tfor(var property in data){\n\t\t\t\t\tif(property==undefined || property==\"schema\"){continue;}\n\t\t\t\t\tfields=String.format(\"{0},{1}\", fields, property);\n\t\t\t\t\tvalue=String.format(\"{0},'{1}'\", value, !data[property]?\"\": data[property]);\n\t\t\t\t}\n\t\t\t\tfields=String.removeFirst(fields, \",\");\n\t\t\t\tvalue=String.removeFirst(value, \",\");\n\t\t\t\tsql=String.format(\"{0}({1}) VALUES({2})\", sql, fields, value);\n\n\t\t\t\treturn sql;\n\t\t\t}",
"getInsertQuery() {\n const obj = this.getSetValues();\n const keys = Object.keys(obj);\n const values = keys.map(k => obj[k]);\n const marks = keys.map(k => '?').join(', ');\n const string = `INSERT INTO campaigns (${keys}) VALUES (${marks});`\n return {string, values};\n }",
"insert(tableName, obj) {\n const keys = Object.keys(obj);\n const values = keys.map(key => obj[key]);\n const cols = keys.join(', ');\n const placeholders = values.map(() => '?').join(', ');\n const sql = `insert into ${tableName} (${cols}) values(${placeholders})`;\n\n this.log('insert: sql =', sql);\n return sql;\n }",
"static createInsert(queryObject){\n let prototype = 'INSERT INTO ' + queryObject.structure.table;\n if(queryObject.structure.insertColumns.length>0){\n prototype += '( '\n for(let i = 0; i < queryObject.structure.insertColumns.length; i++){\n prototype += queryObject.structure.insertColumns[i]\n if(i!=queryObject.structure.insertColumns.length-1){\n prototype+= ', '\n }\n else{\n prototype+= ' '\n }\n }\n prototype += ') '\n }\n else{\n prototype += ' '\n }\n prototype += 'VALUES'\n let queryString = [];\n for(let i = 0; i < queryObject.structure.insertValues.length; i++){\n let values = '( ';\n for(let j = 0; j < queryObject.structure.insertValues[i].length; j++){\n if(typeof(queryObject.structure.insertValues[i][j])==typeof(\"\")){\n values += \"'\"+queryObject.structure.insertValues[i][j]+\"'\";\n } else if(queryObject.structure.insertValues[i][j].isDate){\n values += `TO_DATE( '${queryObject.structure.insertValues[i][j].date}', '${queryObject.structure.insertValues[i][j].format}')`;\n } \n else{\n values += Query.checkForBooleans(queryObject.structure.insertValues[i][j]);\n }\n if(j!=queryObject.structure.insertValues[i].length-1){\n values+= ', '\n }\n else{\n values+= ' '\n }\n }\n values += ') ';\n queryString.push(prototype+values+(queryObject.structure.returnId?\"RETURN id INTO :id\":\"\"));\n }\n return queryString[0];\n }",
"function insertSQL (items) {\n let fields\n if (Array.isArray(items)) {\n fields = items.map(getNamedParametersForItem)\n } else {\n let item = items // just to clear on our intent\n fields = getNamedParametersForItem(item)\n }\n // this returns a (possibly mulitple) insert query\n return pgp.helpers.insert(fields, columnSet)\n}",
"function SQLify(car){\n var keys = [];\n var values = [];\n Object.keys(car).forEach(function(key) {\n\n keys.push(key);\n values.push(car[key]);\n \n });\n return \"INSERT INTO cars (\"+ keys.join(\",\") +\") VALUES (\" + values.join(\",\") + \");\";\n}",
"function insertClient(tx){\n \n tx.executeSql('insert into clients values(1, \"Adam Kinkaid\")');\n tx.executeSql( 'insert into clients values(2, \"Alex Wickerham\")'); \n tx.executeSql('insert into clients values(3, \"Bob Cabot\")'); \n tx.executeSql('insert into clients values(4, \"Caleb Booth\")' ); \n tx.executeSql('insert into clients values(5, \"Culver James\")' ); \n tx.executeSql('insert into clients values(6, \"Elizabeth Bacon\")'); \n tx.executeSql('insert into clients values(7, \"Emery Parker\")'); \n tx.executeSql('insert into clients values(8, \"Graham Smith\")'); \n tx.executeSql('insert into clients values(9, \"Mike Farnsworth\")' ); \n tx.executeSql('insert into clients values(10, \"Murray Vanderbuilt\")' ); \n tx.executeSql('insert into clients values(11, \"Nathan Williams\")' ); \n tx.executeSql('insert into clients values(12, \"Paul Baker\")' ); \n tx.executeSql('insert into clients values(13, \"Wakefield\")' ); \n \n}",
"function buildStatement(insert, rows) {\n const params = [];\n const chunks = [];\n\n rows.forEach((row) => { // for each row of data provided\n const valueClause = [];\n Object.keys(row).forEach((p) => {\n params.push(row[p]);\n valueClause.push(`$${params.length}`);\n });\n chunks.push(`(${valueClause.join(', ')})`);\n });\n return {\n text: insert + chunks.join(', '),\n values: params,\n };\n}",
"function makeQuery(do_command, table_name, name, value, amount){\r\n\r\n\tvar sql_query = '';\t\t\t\t// To be used as a function variable. Holds sql command.\r\n\r\n\r\n\r\n\tif(do_command == 'INSERT'){\r\n\r\n\t\tif(amount >= 5){\r\n\t\t\tsql_query = 'UPDATE ' + table_name;\r\n\t\t} else if( amount < 5) {\r\n\t\t\tsql_query = 'INSERT INTO ' + table_name;\r\n\t\t}\r\n\r\n\t\tif (sql_query == 'INSERT INTO ' + table_name){\r\n\r\n\t\t}\r\n\r\n\t\tsql_query = sql_query + ' SET';\r\n\r\n\t\tfor (var i in name){\r\n\t\t\tif (i > 0){\r\n\t\t\t\tsql_query = sql_query + ',';\r\n\t\t\t}\r\n\t\t\t\tsql_query = sql_query + ' ' + name[i] + '=' + '\\''+ value[i] + '\\'';\r\n\t\t}\r\n\r\n\r\n\t} else {\r\n\r\n\t\tsql_query = 'SELECT ';\r\n\r\n\t\tfor (var i in name){\r\n\t\t\tif (i > 0){\r\n\t\t\t\tsql_query = sql_query + ',';\r\n\t\t\t}\r\n\t\t\t\tsql_query = sql_query + ' ' + name[i];\r\n\t\t\t}\r\n\t\t\tsql_query = sql_query + ' FROM ' + table_name;\r\n\t\t}\r\n\treturn sql_query;\r\n}",
"function SQLify(car) {\n var keys = [];\n var values = [];\n Object.keys(car).forEach(function (key) {\n\n keys.push(key);\n values.push(car[key]);\n\n });\n return \"INSERT INTO cars (\" + keys.join(\",\") + \") VALUES (\" + values.join(\",\") + \");\";\n}",
"function insertStatement(ent) {\n var columns = [];\n var inputs = [];\n var p, query, entp;\n\n entp = makeEntity.forInsertion(ent);\n\n for ( p in entp ) {\n columns.push(p);\n inputs.push(entp[p]);\n }\n query = 'INSERT INTO ' + tablename(ent) + ' (' + columns.join(', ') + ') VALUES (' + inputs.join(', ') + ')';\n return query;\n}",
"function createInsertSql ( tableName, insertObj ) {\n\n let cols = \"\";\n let values = \"\";\n\n for ( let key in insertObj ){\n \n let val = convertSqlValue (insertObj[key]);\n \n if (cols.length === 0) {\n cols = key;\n values = val;\n } else {\n cols = cols + ', ' + key;\n values = `${values}, ${val}`;\n }\n }\n \n return `INSERT INTO ${tableName} ( ${cols} ) VALUES ( ${values})`;\n }",
"function dbGetInsertDriverString() {\n return dbGetInsertClause(dbDefs.DRIVER_TABLE)\n + ' ('\n + ' \"IPAddress\", \"DriverCollectionZIP\", \"DriverCollectionRadius\", \"AvailableDriveTimesLocal\"'\n + ', \"DriverCanLoadRiderWithWheelchair\", \"SeatCount\" '\n + ', \"DriverFirstName\", \"DriverLastName\"'\n + ', \"DriverEmail\", \"DriverPhone\"'\n + ', \"DrivingOnBehalfOfOrganization\", \"DrivingOBOOrganizationName\", \"RidersCanSeeDriverDetails\", \"DriverWillNotTalkPolitics\"'\n + ', \"PleaseStayInTouch\", \"DriverLicenseNumber\", \"DriverPreferredContact\" '\n + ', \"DriverWillTakeCare\" '\n + ')'\n + ' values($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, '\n + ' $13, $14, $15, $16, $17, $18 )'\n + ' returning \"UUID\" ';\n}",
"static sqlForCreate(table, items, returning) {\r\n\t\t// keep track of item indexes\r\n\t\t// store all the columns we want to update and associate with vals\r\n\r\n\t\tlet idx = 1;\r\n\t\tlet columns = [];\r\n\t\tlet valuesIdx = [];\r\n\r\n\t\t// filter out keys that start with \"_\" -- we don't want these in DB\r\n\t\tfor (let key in items) {\r\n\t\t\tif (key.startsWith(\"_\")) {\r\n\t\t\t\tdelete items[key];\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfor (let column in items) {\r\n\t\t\tcolumns.push(`${column}`);\r\n\t\t\tvaluesIdx.push(`$${idx}`);\r\n\t\t\tidx += 1;\r\n\t\t}\r\n\r\n\t\t// build query\r\n\t\tlet cols = columns.join(\", \");\r\n\t\tlet vals = valuesIdx.join(\", \");\r\n\t\treturning = returning.join(\", \");\r\n\t\tlet query = `INSERT INTO ${table} (${cols}) VALUES (${vals}) RETURNING ${returning}`;\r\n\r\n\t\tlet values = Object.values(items);\r\n\r\n\t\treturn { query, values, returning };\r\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function which shows the result of patient treatment in the activity log | function treatmentResults(liveOrDie) {
const patientId = document.getElementById('operatingTable').childNodes[1]
.childNodes[3].childNodes[3].textContent
fetch('/api/patient/' + patientId)
.then((response) => response.json())
.then((data) => {
const activityLog = document.getElementById('activityLog')
const listElement = document.createElement('li')
if (liveOrDie <= 5) {
activityLog.innerHTML = ''
listElement.innerHTML = `Procedure to cure ${data.data.condition} failed! ${data.data.firstName} ${data.data.lastName} didn't make it... <i class="fas fa-dizzy"></i>`
} else {
activityLog.innerHTML = ''
listElement.innerHTML = `Procedure to cure ${data.data.condition} succeeded! ${data.data.firstName} ${data.data.lastName} made a full recovery and was discharged! <i class="fas fa-smile-beam"></i>`
}
activityLog.appendChild(listElement)
})
} | [
"function printResults(trialMatcherResult) {\n if (trialMatcherResult.status === \"succeeded\") {\n const results = trialMatcherResult.results;\n if (results != undefined) {\n const patients = results.patients;\n for (const patientResult of patients) {\n console.log(`Inferences of Patient ${patientResult.id}`);\n for (const tmInferences of patientResult.inferences) {\n console.log(`Trial Id ${tmInferences.id}`);\n console.log(`Type: ${String(tmInferences.type)} Value: ${tmInferences.value}`);\n console.log(`Description ${tmInferences.description}`);\n }\n }\n }\n } else {\n const errors = trialMatcherResult.errors;\n if (errors) {\n for (const error of errors) {\n console.log(error.code, \":\", error.message);\n }\n }\n }\n}",
"function tc_treatment_plan_add_first_manual_treatment_plan()\n{\n try\n {\n var test_title = 'Treatment Plan - Add first manual treatment plan'\n login('cl3@regression','INRstar_5','Shared');\n add_patient('Regression', 'Add_manual_tp', 'M', 'Shared'); \n add_treatment_plan('W','Manual','','Shared','');\n \n result_set = new Array();\n \n //Check the confirmation banner is displayed\n var result_set_1 = banner_checker('The patient\\'s dosing method is currently set to : Manual Dosing')\n result_set.push(result_set_1);\n \n //Check the audit for adding the tp\n var result_set_2 = display_top_patient_audit('Add Treatment Plan Details');\n result_set.push(result_set_2);\n \n //Validate all the results sets are true\n var results = results_checker_are_true(result_set); \n Log.Message(results);\n \n //Pass in the result\n results_checker(results,test_title); \n \n Log_Off(); \n } \n catch(e)\n {\n Log.Warning('Test \"' + test_title + '\" FAILED Exception Occured = ' + e);\n Log_Off();\n }\n}",
"function MvPrescribeAntimicrobialMedication(TestName,exestatus)\n{\n \n//Controller for executing or skipping the feature\nif (equal(exestatus,true)) {\n\n\n//var tcDesc = Data.getData(TestName,\"OtherCare\",\"TC_DESC\");\n//Log.Checkpoint(\"Start Generating the Patient Details eHOC report \"+tcDesc ,\"The flow is started\");\n\t//Start of the feature \n\t\n\t\n\t vProcess = Sys.Process(\"iMDSoft.Metavision\");\n\n\t// Patient Details and defaults\n\t var ms = 6000;\n var HelpStr = \"Delaying test run for \" + ms + \" milliseconds, To Generate the PrescribeAntimicrobialMedication eHOC report.\";\n aqUtils.Delay (ms, HelpStr);\n \n\texestatus = mvObjects.selectMenuOption(exestatus,\"Medical\",\"eHOC\");\n\t// Wait for screen to appear\n\t\n\t\t// ** Fill in the Patient details\n\tLog.Message(\"*** enter Generate the PrescribeAntimicrobialMedication eHOC report***\");\n\t\n \t\t\n if (equal(exestatus,true)) {\n\t \t Log.Checkpoint(\"Generate eHOC report for PrescribeAntimicrobialMedication is successful\");\n Log.Checkpoint(\"End Generate eHOC report for PrescribeAntimicrobialMedication\",\"The flow is completed\");\n }\n }\n else {\n Log.Message(\"Skipped Generate eHOC report for PrescribeAntimicrobialMedication\",\"The feature is skipped since the execution status is set as '\"+exestatus+\"'\"); \n \n }\n return exestatus;\n \n}",
"function MvPatientDemographics(TestName,exestatus)\n{\n \n//Controller for executing or skipping the feature\n\nif (equal(exestatus,true)) {\n\t\n\t//Start of the feature \n\t//var objData = Data.getData(TestName,\"Navigation\");\n\tvar tcDesc = Data.getData(TestName,\"Navigation\",\"TC_DESC\");\n\tvar facility = Data.getData(TestName,\"Navigation\",\"Department\");\n\tvar layout = Data.getData(TestName,\"Navigation\",\"Layout\");\nLog.Checkpoint(\"Start Patient Demographics\",\"The flow is started.\");\n\n\t//var objData = Data.getData(TestName,\"Patient\"); \n\t// Patient Details and defaults\n\tlet patientDetails = new Object();\n\tpatientDetails.gender = Data.getData(TestName,\"Patient\",\"Gender\");\n\tpatientDetails.dob = Data.getData(TestName,\"Patient\",\"DOB\");\n\tpatientDetails.allergies = Data.getData(TestName,\"Patient\",\"Allergies\");\n \n\tvar lastName = Data.getData(TestName,\"Patient\",\"LastName\");\n\tvar firstName = Data.getData(TestName,\"Patient\",\"FirstName\");\n\tpatientDetails.lastName = lastName;\n\tpatientDetails.firstName = firstName;\n \nvar MRN = Data.getData(TestName,\"Patient\",\"MRN\");\nvar newPatientMRN = Data.getData(TestName,\"Patient\",\"newPatientMRN\");\nvar bedNumber = Data.getData(TestName,\"Patient\",\"Bed\");\nvar Title = Data.getData(TestName,\"Patient\",\"Title\");\nvar BirthCountry = Data.getData(TestName,\"Patient\",\"BirthCountry\");\nvar Aboriginal = Data.getData(TestName,\"Patient\",\"Aboriginal\");\nvar Religion = Data.getData(TestName,\"Patient\",\"Religion\");\nvar Maritalstatus = Data.getData(TestName,\"Patient\",\"Maritalstatus\");\nvar Pref_language = Data.getData(TestName,\"Patient\",\"Pref_language\");\nvar Interpreter = Data.getData(TestName,\"Patient\",\"Interpreter\");\nvar DateofDeath = Data.getData(TestName,\"Patient\",\"DateofDeath\");\nvar TimeofDeath = Data.getData(TestName,\"Patient\",\"TimeofDeath\");\nvar Contact_HmC1 = Data.getData(TestName,\"Patient\",\"Contact_HmC1\");\nvar Contact_HmC2 = Data.getData(TestName,\"Patient\",\"Contact_HmC2\");\nvar Contact_HmC3 = Data.getData(TestName,\"Patient\",\"Contact_HmC3\");\nvar Contact_Bus_C1 = Data.getData(TestName,\"Patient\",\"Contact_Bus_C1\");\nvar Contact_Bus_C2 = Data.getData(TestName,\"Patient\",\"Contact_Bus_C2\");\nvar Contact_Bus_C3 = Data.getData(TestName,\"Patient\",\"Contact_Bus_C3\");\nvar Res_Add_L1 = Data.getData(TestName,\"Patient\",\"Res_Add_L1\");\nvar Res_Add_L2 = Data.getData(TestName,\"Patient\",\"Res_Add_L2\");\nvar Res_Suburb = Data.getData(TestName,\"Patient\",\"Res_Suburb\");\nvar Res_State = Data.getData(TestName,\"Patient\",\"Res_State\");\nvar Res_Pcode = Data.getData(TestName,\"Patient\",\"Res_Pcode\");\nvar Res_Country = Data.getData(TestName,\"Patient\",\"Res_Country\");\nvar Mail_Add_L1 = Data.getData(TestName,\"Patient\",\"Mail_Add_L1\");\nvar Mail_Add_L2 = Data.getData(TestName,\"Patient\",\"Mail_Add_L2\");\nvar Mail_Suburb = Data.getData(TestName,\"Patient\",\"Mail_Suburb\");\nvar Mail_Pcode = Data.getData(TestName,\"Patient\",\"Mail_Pcode\");\nvar Mail_Country = Data.getData(TestName,\"Patient\",\"Mail_Country\");\nvar PC_ConType = Data.getData(TestName,\"Patient\",\"PC_ConType\");\nvar PC_Rel_Pat = Data.getData(TestName,\"Patient\",\"PC_Rel_Pat\");\nvar PC_Title = Data.getData(TestName,\"Patient\",\"PC_Title\");\nvar PC_Gname = Data.getData(TestName,\"Patient\",\"PC_Gname\");\nvar PC_Fname = Data.getData(TestName,\"Patient\",\"PC_Fname\");\nvar PC_HC1 = Data.getData(TestName,\"Patient\",\"PC_HC1\");\nvar PC_HC2 = Data.getData(TestName,\"Patient\",\"PC_HC2\");\nvar PC_HC3 = Data.getData(TestName,\"Patient\",\"PC_HC3\");\nvar PC_BC1 = Data.getData(TestName,\"Patient\",\"PC_BC1\");\nvar PC_BC2 = Data.getData(TestName,\"Patient\",\"PC_BC2\");\nvar PC_BC3 = Data.getData(TestName,\"Patient\",\"PC_BC3\");\nvar PC_Add_L1 = Data.getData(TestName,\"Patient\",\"PC_Add_L1\");\nvar PC_Add_L2 = Data.getData(TestName,\"Patient\",\"PC_Add_L2\");\nvar PC_Suburb = Data.getData(TestName,\"Patient\",\"PC_Suburb\");\nvar PC_State = Data.getData(TestName,\"Patient\",\"PC_State\");\nvar PC_Pcode = Data.getData(TestName,\"Patient\",\"PC_Pcode\");\nvar PC_Country = Data.getData(TestName,\"Patient\",\"PC_Country\");\nvar PC_Comments = Data.getData(TestName,\"Patient\",\"PC_Comments\");\nvar SC_ConType = Data.getData(TestName,\"Patient\",\"SC_ConType\");\nvar SC_Rel_Pat = Data.getData(TestName,\"Patient\",\"SC_Rel_Pat\");\nvar SC_Title = Data.getData(TestName,\"Patient\",\"SC_Title\");\nvar SC_Gname = Data.getData(TestName,\"Patient\",\"SC_Gname\");\nvar SC_Fname = Data.getData(TestName,\"Patient\",\"SC_Fname\");\nvar SC_HC1 = Data.getData(TestName,\"Patient\",\"SC_HC1\");\nvar SC_HC2 = Data.getData(TestName,\"Patient\",\"SC_HC2\");\nvar SC_HC3 = Data.getData(TestName,\"Patient\",\"SC_HC3\");\nvar SC_BC1 = Data.getData(TestName,\"Patient\",\"SC_BC1\");\nvar SC_BC2 = Data.getData(TestName,\"Patient\",\"SC_BC2\");\nvar SC_BC3 = Data.getData(TestName,\"Patient\",\"SC_BC3\");\nvar SC_Add_L1 = Data.getData(TestName,\"Patient\",\"SC_Add_L1\");\nvar SC_Add_L2 = Data.getData(TestName,\"Patient\",\"SC_Add_L2\");\nvar SC_Suburb = Data.getData(TestName,\"Patient\",\"SC_Suburb\");\nvar SC_State = Data.getData(TestName,\"Patient\",\"SC_State\");\nvar SC_Pcode = Data.getData(TestName,\"Patient\",\"SC_Pcode\");\nvar SC_Country = Data.getData(TestName,\"Patient\",\"SC_Country\");\nvar SC_Comments = Data.getData(TestName,\"Patient\",\"SC_Comments\");\nvar SDM_ConType = Data.getData(TestName,\"Patient\",\"SDM_ConType\");\nvar SDM_Rel_Pat = Data.getData(TestName,\"Patient\",\"SDM_Rel_Pat\");\nvar SDM_Title = Data.getData(TestName,\"Patient\",\"SDM_Title\");\nvar SDM_Gname = Data.getData(TestName,\"Patient\",\"SDM_Gname\");\nvar SDM_Fname = Data.getData(TestName,\"Patient\",\"SDM_Fname\");\nvar SDM_HC1 = Data.getData(TestName,\"Patient\",\"SDM_HC1\");\nvar SDM_HC2 = Data.getData(TestName,\"Patient\",\"SDM_HC2\");\nvar SDM_HC3 = Data.getData(TestName,\"Patient\",\"SDM_HC3\");\nvar SDM_BC1 = Data.getData(TestName,\"Patient\",\"SDM_BC1\");\nvar SDM_BC2 = Data.getData(TestName,\"Patient\",\"SDM_BC2\");\nvar SDM_BC3 = Data.getData(TestName,\"Patient\",\"SDM_BC3\");\nvar SDM_Add_L1 = Data.getData(TestName,\"Patient\",\"SDM_Add_L1\");\nvar SDM_Add_L2 = Data.getData(TestName,\"Patient\",\"SDM_Add_L2\");\nvar SDM_Suburb = Data.getData(TestName,\"Patient\",\"SDM_Suburb\");\nvar SDM_State = Data.getData(TestName,\"Patient\",\"SDM_State\");\nvar SDM_Pcode = Data.getData(TestName,\"Patient\",\"SDM_Pcode\");\nvar SDM_Country = Data.getData(TestName,\"Patient\",\"SDM_Country\");\nvar SDM_Comments = Data.getData(TestName,\"Patient\",\"SDM_Comments\");\nvar AC1_ConType = Data.getData(TestName,\"Patient\",\"AC1_ConType\");\nvar AC1_Rel_Pat = Data.getData(TestName,\"Patient\",\"AC1_Rel_Pat\");\nvar AC1_Title = Data.getData(TestName,\"Patient\",\"AC1_Title\");\nvar AC1_Gname = Data.getData(TestName,\"Patient\",\"AC1_Gname\");\nvar AC1_Fname = Data.getData(TestName,\"Patient\",\"AC1_Fname\");\nvar AC1_HC1 = Data.getData(TestName,\"Patient\",\"AC1_HC1\");\nvar AC1_HC2 = Data.getData(TestName,\"Patient\",\"AC1_HC2\");\nvar AC1_HC3 = Data.getData(TestName,\"Patient\",\"AC1_HC3\");\nvar AC1_BC1 = Data.getData(TestName,\"Patient\",\"AC1_BC1\");\nvar AC1_BC2 = Data.getData(TestName,\"Patient\",\"AC1_BC2\");\nvar AC1_BC3 = Data.getData(TestName,\"Patient\",\"AC1_BC3\");\nvar AC1_Add_L1 = Data.getData(TestName,\"Patient\",\"AC1_Add_L1\");\nvar AC1_Add_L2 = Data.getData(TestName,\"Patient\",\"AC1_Add_L2\");\nvar AC1_Suburb = Data.getData(TestName,\"Patient\",\"AC1_Suburb\");\nvar AC1_State = Data.getData(TestName,\"Patient\",\"AC1_State\");\nvar AC1_Pcode = Data.getData(TestName,\"Patient\",\"AC1_Pcode\");\nvar AC1_Country = Data.getData(TestName,\"Patient\",\"AC1_Country\");\nvar AC1_Comments = Data.getData(TestName,\"Patient\",\"AC1_Comments\");\nvar AC2_ConType = Data.getData(TestName,\"Patient\",\"AC2_ConType\");\nvar AC2_Rel_Pat = Data.getData(TestName,\"Patient\",\"AC2_Rel_Pat\");\nvar AC2_Title = Data.getData(TestName,\"Patient\",\"AC2_Title\");\nvar AC2_Gname = Data.getData(TestName,\"Patient\",\"AC2_Gname\");\nvar AC2_Fname = Data.getData(TestName,\"Patient\",\"AC2_Fname\");\nvar AC2_HC1 = Data.getData(TestName,\"Patient\",\"AC2_HC1\");\nvar AC2_HC2 = Data.getData(TestName,\"Patient\",\"AC2_HC2\");\nvar AC2_HC3 = Data.getData(TestName,\"Patient\",\"AC2_HC3\");\nvar AC2_BC1 = Data.getData(TestName,\"Patient\",\"AC2_BC1\");\nvar AC2_BC2 = Data.getData(TestName,\"Patient\",\"AC2_BC2\");\nvar AC2_BC3 = Data.getData(TestName,\"Patient\",\"AC2_BC3\");\nvar AC2_Add_L1 = Data.getData(TestName,\"Patient\",\"AC2_Add_L1\");\nvar AC2_Add_L2 = Data.getData(TestName,\"Patient\",\"AC2_Add_L2\");\nvar AC2_Suburb = Data.getData(TestName,\"Patient\",\"AC2_Suburb\");\nvar AC2_State = Data.getData(TestName,\"Patient\",\"AC2_State\");\nvar AC2_Pcode = Data.getData(TestName,\"Patient\",\"AC2_Pcode\");\nvar AC2_Country = Data.getData(TestName,\"Patient\",\"AC2_Country\");\nvar AC2_Comments = Data.getData(TestName,\"Patient\",\"AC2_Comments\");\nvar AC3_ConType = Data.getData(TestName,\"Patient\",\"AC3_ConType\");\nvar AC3_Rel_Pat = Data.getData(TestName,\"Patient\",\"AC3_Rel_Pat\");\nvar AC3_Title = Data.getData(TestName,\"Patient\",\"AC3_Title\");\nvar AC3_Gname = Data.getData(TestName,\"Patient\",\"AC3_Gname\");\nvar AC3_Fname = Data.getData(TestName,\"Patient\",\"AC3_Fname\");\nvar AC3_HC1 = Data.getData(TestName,\"Patient\",\"AC3_HC1\");\nvar AC3_HC2 = Data.getData(TestName,\"Patient\",\"AC3_HC2\");\nvar AC3_HC3 = Data.getData(TestName,\"Patient\",\"AC3_HC3\");\nvar AC3_BC1 = Data.getData(TestName,\"Patient\",\"AC3_BC1\");\nvar AC3_BC2 = Data.getData(TestName,\"Patient\",\"AC3_BC2\");\nvar AC3_BC3 = Data.getData(TestName,\"Patient\",\"AC3_BC3\");\nvar AC3_Add_L1 = Data.getData(TestName,\"Patient\",\"AC3_Add_L1\");\nvar AC3_Add_L2 = Data.getData(TestName,\"Patient\",\"AC3_Add_L2\");\nvar AC3_Suburb = Data.getData(TestName,\"Patient\",\"AC3_Suburb\");\nvar AC3_State = Data.getData(TestName,\"Patient\",\"AC3_State\");\nvar AC3_Pcode = Data.getData(TestName,\"Patient\",\"AC3_Pcode\");\nvar AC3_Country = Data.getData(TestName,\"Patient\",\"AC3_Country\");\nvar AC3_Comments = Data.getData(TestName,\"Patient\",\"AC3_Comments\");\nvar GP_Title = Data.getData(TestName,\"Patient\",\"GP_Title\");\nvar GP_Gname = Data.getData(TestName,\"Patient\",\"GP_Gname\");\nvar GP_Fname = Data.getData(TestName,\"Patient\",\"GP_Fname\");\nvar GP_Pnum = Data.getData(TestName,\"Patient\",\"GP_Pnum\");\nvar GP_Mnum = Data.getData(TestName,\"Patient\",\"GP_Mnum\");\nvar GP_Fax = Data.getData(TestName,\"Patient\",\"GP_Fax\");\nvar GP_Email = Data.getData(TestName,\"Patient\",\"GP_Email\");\nvar GP_Add_L1 = Data.getData(TestName,\"Patient\",\"GP_Add_L1\");\nvar GP_Add_L2 = Data.getData(TestName,\"Patient\",\"GP_Add_L2\");\nvar GP_Suburb = Data.getData(TestName,\"Patient\",\"GP_Suburb\");\nvar GP_State = Data.getData(TestName,\"Patient\",\"GP_State\");\nvar GP_Pcode = Data.getData(TestName,\"Patient\",\"GP_Pcode\");\nvar GP_Country = Data.getData(TestName,\"Patient\",\"GP_Country\");\nvar MO_CHS = Data.getData(TestName,\"Patient\",\"MO_CHS\");\nvar MO_AD_Title = Data.getData(TestName,\"Patient\",\"MO_AD_Title\");\nvar MO_AD_Gname = Data.getData(TestName,\"Patient\",\"MO_AD_Gname\");\nvar MO_AD_Mname = Data.getData(TestName,\"Patient\",\"MO_AD_Mname\");\nvar MO_AD_Fname = Data.getData(TestName,\"Patient\",\"MO_AD_Fname\");\nvar MO_AM_Title = Data.getData(TestName,\"Patient\",\"MO_AM_Title\");\nvar MO_AM_Gname = Data.getData(TestName,\"Patient\",\"MO_AM_Gname\");\nvar MO_AM_Mname = Data.getData(TestName,\"Patient\",\"MO_AM_Mname\");\nvar MO_AM_Fname = Data.getData(TestName,\"Patient\",\"MO_AM_Fname\");\nvar MO_CM1_Title = Data.getData(TestName,\"Patient\",\"MO_CM1_Title\");\nvar MO_CM1_Gname = Data.getData(TestName,\"Patient\",\"MO_CM1_Gname\");\nvar MO_CM1_Mname = Data.getData(TestName,\"Patient\",\"MO_CM1_Mname\");\nvar MO_CM1_Fname = Data.getData(TestName,\"Patient\",\"MO_CM1_Fname\");\nvar MO_CM2_Title = Data.getData(TestName,\"Patient\",\"MO_CM2_Title\");\nvar MO_CM2_Gname = Data.getData(TestName,\"Patient\",\"MO_CM2_Gname\");\nvar MO_CM2_Mname = Data.getData(TestName,\"Patient\",\"MO_CM2_Mname\");\nvar MO_CM2_Fname = Data.getData(TestName,\"Patient\",\"MO_CM2_Fname\");\nvar MO_RM_Title = Data.getData(TestName,\"Patient\",\"MO_RM_Title\");\nvar MO_RM_Gname = Data.getData(TestName,\"Patient\",\"MO_RM_Gname\");\nvar MO_RM_Mname = Data.getData(TestName,\"Patient\",\"MO_RM_Mname\");\nvar MO_RM_Fname = Data.getData(TestName,\"Patient\",\"MO_RM_Fname\");\nvar Add_Cont_Info = Data.getData(TestName,\"Patient\",\"Add_Cont_Info\");\n\n\t vProcess = Sys.Process(\"iMDSoft.Metavision\");\n\n\t// Open Patient demographcs\n\texestatus = mvObjects.selectMenuOption(exestatus,\"Menu\", \"Patient Demographics\");\n\t// Wait for screen to appear\n\texestatus = mvObjects.waitForObject(vProcess, \"WPFObject(\\\"capXP\\\")\", 120,exestatus);\n\t\n\t// ** Fill in the Patient details\n\tLog.Message(\"*** enter patient demographics form data ***\");\n\t\n\t\n\t// Patient Details tab\n\texestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"TextBlock\\\", \\\"Patient Details\\\", 1)\",exestatus);\n\ttabUpObject = vProcess.Find(\"Name\", \"WPFObject(\\\"cmdTabUp\\\")\", 120);\n\t\n\t//dobDay = aqString.substring(patientDetails.dob, 0, 2);\n dobDay = aqDateTime.GetDay(patientDetails.dob);\n\t//dobmonth = aqString.substring(patientDetails.dob, 3, 2);\n dobmonth = aqDateTime.GetMonth(patientDetails.dob);\n\t//dobyear = aqString.substring(patientDetails.dob, 6, 4);\n dobyear = aqDateTime.GetYear(patientDetails.dob);\n \n \n\texestatus = mvObjects.enterImdDateTimePicker(vProcess, \"WPFObject(\\\"dtpDate_1\\\")\", dobDay, dobmonth, dobyear, \"04\", \"45\",exestatus);\n\texestatus = mvObjects.selectComboItem(vProcess, \"WPFObject(\\\"cboTextCombo_1\\\")\", patientDetails.gender,exestatus);\n\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_1\\\")\",Title,exestatus);\n exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_3\\\")\", Aboriginal,exestatus);\n//<<<<<<< HEAD\n \texestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_2\\\")\",BirthCountry,exestatus);\n//=======\n \n exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_2\\\")\",BirthCountry,exestatus);\n//>>>>>>> 97b79a015b17a49c84c04036b31595b7daf33fe4\n exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_4\\\")\",Religion,exestatus);\n exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_5\\\")\",Maritalstatus,exestatus);\n //exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_6\\\")\",Pref_language,exestatus);\n exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_7\\\")\",Interpreter,exestatus);\n //exestatus = mvObjects.enterImdDateTimePicker(vProcess,\"WPFObject(\\\"dtpDate_2\\\")\",dobDay,dobmonth,dobyear, \"04\", \"45\",exestatus);\n //exestatus = mvObjects.enterImdDateTimePicker(vProcess,\"WPFObject(\\\"dtpDate_3\\\")\",TimeofDeathTime, \"04\", \"45\",exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_2\\\")\",Contact_HmC1,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_3\\\")\",Contact_HmC2,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_4\\\")\",Contact_HmC3,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_5\\\")\",Contact_Bus_C1,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_6\\\")\",Contact_Bus_C2,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_7\\\")\",Contact_Bus_C3,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_8\\\")\",Res_Add_L1,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_9\\\")\",Res_Add_L2,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_10\\\")\",Res_Suburb,exestatus);\n exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_8\\\")\",Res_State,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_11\\\")\",Res_Pcode,exestatus);\n //exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_9\\\")\",Res_Country,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_12\\\")\",Mail_Add_L1,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_13\\\")\",Mail_Add_L2,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_14\\\")\",Mail_Suburb,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_15\\\")\",Mail_Pcode,exestatus);\n //exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_11\\\")\",Mail_Country,exestatus);\n//<<<<<<< HEAD\n \n//=======\n//>>>>>>> 97b79a015b17a49c84c04036b31595b7daf33fe4\n \n\t// ******* Add other combo boxes\n\n\t// Contacts tab\n\texestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"TextBlock\\\", \\\"Contacts\\\", 1)\",exestatus);\n\ttabUpObject.click();\n\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_16\\\")\",PC_ConType,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_17\\\")\",PC_Rel_Pat,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_18\\\")\",PC_Title,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_19\\\")\",PC_Gname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_20\\\")\",PC_Fname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_21\\\")\",PC_HC1,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_22\\\")\",PC_HC2,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_23\\\")\",PC_HC3,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_24\\\")\",PC_BC1,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_25\\\")\",PC_BC2,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_26\\\")\",PC_BC3,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_27\\\")\",PC_Add_L1,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_28\\\")\",PC_Add_L2,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_29\\\")\",PC_Suburb,exestatus);\n exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_12\\\")\",PC_State,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_30\\\")\",PC_Pcode,exestatus);\n //exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_13\\\")\",PC_Country,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_31\\\")\",PC_Comments,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_32\\\")\",SC_ConType,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_33\\\")\",SC_Rel_Pat,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_34\\\")\",SC_Title,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_35\\\")\",SC_Gname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_36\\\")\",SC_Fname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_37\\\")\",SC_HC1,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_38\\\")\",SC_HC2,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_39\\\")\",SC_HC3,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_40\\\")\",SC_BC1,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_41\\\")\",SC_BC2,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_42\\\")\",SC_BC3,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_43\\\")\",SC_Add_L1,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_44\\\")\",SC_Add_L2,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_45\\\")\",SC_Suburb,exestatus);\n exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_14\\\")\",SC_State,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_46\\\")\",SC_Pcode,exestatus);\n //exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_15\\\")\",SC_Country,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_47\\\")\",SC_Comments,exestatus);\n exestatus = mvObjects.scrollUntilVisible(\"WPFObject(\\\"txtFreeText_52\\\")\",exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_48\\\")\",SDM_ConType,exestatus);\n exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_16\\\")\",SDM_Rel_Pat,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_49\\\")\",SDM_Title,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_50\\\")\",SDM_Gname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_51\\\")\",SDM_Fname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_52\\\")\",SDM_HC1,exestatus);\n exestatus = mvObjects.scrollUntilVisible(\"WPFObject(\\\"txtFreeText_57\\\")\",exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_53\\\")\",SDM_HC2,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_54\\\")\",SDM_HC3,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_55\\\")\",SDM_BC1,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_56\\\")\",SDM_BC2,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_57\\\")\",SDM_BC3,exestatus);\n exestatus = mvObjects.scrollUntilVisible(\"WPFObject(\\\"txtFreeText_62\\\")\",exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_58\\\")\",SDM_Add_L1,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_59\\\")\",SDM_Add_L2,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_60\\\")\",SDM_Suburb,exestatus);\n exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_17\\\")\",SDM_State,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_61\\\")\",SDM_Pcode,exestatus);\n //exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_18\\\")\",SDM_Country,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_62\\\")\",SDM_Comments,exestatus);\n exestatus = mvObjects.scrollUntilVisible(\"WPFObject(\\\"txtFreeText_68\\\")\",exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_63\\\")\",AC1_ConType,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_64\\\")\",AC1_Rel_Pat,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_65\\\")\",AC1_Title,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_66\\\")\",AC1_Gname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_67\\\")\",AC1_Fname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_68\\\")\",AC1_HC1,exestatus);\n exestatus = mvObjects.scrollUntilVisible(\"WPFObject(\\\"txtFreeText_73\\\")\",exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_69\\\")\",AC1_HC2,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_70\\\")\",AC1_HC3,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_71\\\")\",AC1_BC1,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_72\\\")\",AC1_BC2,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_73\\\")\",AC1_BC3,exestatus);\n exestatus = mvObjects.scrollUntilVisible(\"WPFObject(\\\"txtFreeText_78\\\")\",exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_74\\\")\",AC1_Add_L1,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_75\\\")\",AC1_Add_L2,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_76\\\")\",AC1_Suburb,exestatus);\n exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_19\\\")\",AC1_State,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_77\\\")\",AC1_Pcode,exestatus);\n //exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_20\\\")\",AC1_Country,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_78\\\")\",AC1_Comments,exestatus);\n exestatus = mvObjects.scrollUntilVisible(\"WPFObject(\\\"txtFreeText_88\\\")\",exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_79\\\")\",AC2_ConType,exestatus);\n //exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_21\\\")\",AC2_Rel_Pat,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_80\\\")\",AC2_Title,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_81\\\")\",AC2_Gname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_82\\\")\",AC2_Fname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_83\\\")\",AC2_HC1,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_84\\\")\",AC2_HC2,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_85\\\")\",AC2_HC3,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_86\\\")\",AC2_BC1,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_87\\\")\",AC2_BC2,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_88\\\")\",AC2_BC3,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_89\\\")\",AC2_Add_L1,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_90\\\")\",AC2_Add_L2,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_91\\\")\",AC2_Suburb,exestatus);\n exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_22\\\")\",AC2_State,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_92\\\")\",AC2_Pcode,exestatus);\n //exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_23\\\")\",AC2_Country,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_93\\\")\",AC2_Comments,exestatus);\n exestatus = mvObjects.scrollUntilVisible(\"WPFObject(\\\"txtFreeText_103\\\")\",exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_94\\\")\",AC3_ConType,exestatus);\n //exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_24\\\")\",AC3_Rel_Pat,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_95\\\")\",AC3_Title,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_96\\\")\",AC3_Gname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_97\\\")\",AC3_Fname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_98\\\")\",AC3_HC1,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_99\\\")\",AC3_HC2,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_100\\\")\",AC3_HC3,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_101\\\")\",AC3_BC1,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_102\\\")\",AC3_BC2,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_103\\\")\",AC3_BC3,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_104\\\")\",AC3_Add_L1,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_105\\\")\",AC3_Add_L2,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_106\\\")\",AC3_Suburb,exestatus);\n exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_25\\\")\",AC3_State,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_107\\\")\",AC3_Pcode,exestatus);\n //exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_26\\\")\",AC3_Country,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_108\\\")\",AC3_Comments,exestatus);\n \n \n\t// GP and Carers tab\n\texestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"TextBlock\\\", \\\"GP and Carers\\\", 1)\", exestatus);\n\ttabUpObject.click(); \n\texestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_109\\\")\",GP_Title,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_110\\\")\",GP_Gname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_111\\\")\",GP_Fname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_112\\\")\",GP_Pnum,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_113\\\")\",GP_Mnum,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_114\\\")\",GP_Fax,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_115\\\")\",GP_Email,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_119\\\")\",GP_Add_L1,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_116\\\")\",GP_Add_L2,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_117\\\")\",GP_Suburb,exestatus);\n exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_27\\\")\",GP_State,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_118\\\")\",GP_Pcode,exestatus);\n //exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_28\\\")\",GP_Country,exestatus);\n \n\t// Medical Officers tab\n\texestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"TextBlock\\\", \\\"Medical Officers\\\", 1)\",exestatus); \n\ttabUpObject.click(); \n//<<<<<<< HEAD\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_120\\\")\",MO_CHS,exestatus); \n//=======\n\t//exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_120\\\")\",MO_CHS,exestatus); \n//>>>>>>> 97b79a015b17a49c84c04036b31595b7daf33fe4\n\texestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_121\\\")\",MO_AD_Title,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_122\\\")\",MO_AD_Gname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_123\\\")\",MO_AD_Mname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_124\\\")\",MO_AD_Fname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_125\\\")\",MO_AM_Title,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_126\\\")\",MO_AM_Gname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_127\\\")\",MO_AM_Mname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_128\\\")\",MO_AM_Fname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_129\\\")\",MO_CM1_Title,exestatus);\t \n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_130\\\")\",MO_CM1_Gname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_131\\\")\",MO_CM1_Mname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_132\\\")\",MO_CM1_Fname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_133\\\")\",MO_CM2_Title,exestatus);\t \n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_134\\\")\",MO_CM2_Gname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_135\\\")\",MO_CM2_Mname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_136\\\")\",MO_CM2_Fname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_137\\\")\",MO_RM_Title,exestatus);\t \n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_138\\\")\",MO_RM_Gname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_139\\\")\",MO_RM_Mname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_140\\\")\",MO_RM_Fname,exestatus);\n exestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_141\\\")\",Add_Cont_Info,exestatus);\n//<<<<<<< HEAD\n \n \n \t \n//=======\n \t \n//>>>>>>> 97b79a015b17a49c84c04036b31595b7daf33fe4\n\t// Get the save time value\n\tvar timeSavedValue = mvObjects.getObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"mvtFormTime\\\")\", \"Value\",exestatus); \n\ttimeSavedValue = aqString.Replace(timeSavedValue, \":00\", \"\", false);\n\ttimeSavedValue = aqString.Replace(timeSavedValue, \"0\", \"\", false);\n\tLog.Checkpoint(\"PatientDemographics Saved Time: \"+ timeSavedValue);\n \n\t// save the form data\n\texestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"cmdApply\\\")\",exestatus);\n\n\t// wait for the form to save.. maybe this object if below don't work -> WPFObject(\"sessionscontrol\") \n\texestatus = mvObjects.waitForObject(vProcess, \"WPFObject(\\\"cmdNewSessionText\\\")\", 120,exestatus);\n \n\t// Click Refresh\n\texestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"cmdRefresh\\\")\",exestatus); \n\t// to do - check values..\n \n\t// close the form \n\texestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"cmdCancel\\\")\",exestatus);\n\texestatus = mvObjects.waitForObjectNotVisible(vProcess, \"WPFObject(\\\"cmdCancel\\\")\", 120,exestatus);\n\t\n\t// find Status bar object\n\tvContentControl5 = vProcess.Find(\"Name\", \"WPFObject(\\\"ContentControl\\\", \\\"\\\", 5)\", 1000);\n\t\n\t// Check logged in user\n\tvGrid1 = vContentControl5.Find(\"Name\", \"WPFObject(\\\"ContentPresenter\\\", \\\"\\\", 2)\", 1000);\n\tvStatusBarText1 = mvObjects.getObjectProperty(vGrid1, \"Name\", \"WPFObject(\\\"txtParamValue\\\")\", \"Text\",exestatus);\n\t\n\t Log.Checkpoint( vStatusBarText1 + \" user logged on\");\n\t\n\t// Check for correct facility\n \tvGrid2 = vContentControl5.Find(\"Name\", \"WPFObject(\\\"ContentPresenter\\\", \\\"\\\", 3)\", 1000);\n\tvStatusBarText2 = mvObjects.getObjectProperty(vGrid2, \"Name\", \"WPFObject(\\\"txtParamValue\\\")\", \"Text\",exestatus);\n\tif (aqString.Compare(vStatusBarText2, facility, false) == 0) {\n\t Log.Checkpoint(facility + \" Department Loaded\");\n\t} else {\n\t Log.Error(facility + \" Department not loaded, found value: \" + vStatusBarText2);\n\t exestatus = false;\n\t}\n\t\n\tvar status = \"Admitted\";\n \n\t// Check for correct status\n\tif (!equal(status, undefined)) {\n\t \tvGrid2 = vContentControl5.Find(\"Name\", \"WPFObject(\\\"ContentPresenter\\\", \\\"\\\", 4)\", 1000);\n\t\tvStatusBarText3 = mvObjects.getObjectProperty(vGrid2, \"Name\", \"WPFObject(\\\"txtParamValue\\\")\", \"Text\",exestatus);\n \n\t\tif (aqString.Compare(vStatusBarText3, status, false) == 0) {\n\t\t Log.Checkpoint(\"Patient Status is \" + status);\n\t\t} else {\n\t\t Log.Error(\"Patient Status should be \" + status + \". Found status: \" + vStatusBarText3);\n\t\t exestatus = false;\n\t\t}\n\t}\n\t\n\t// Check for correct Research Studies\n\t//if (!equal(research, undefined)) {\n\t// \tvGrid2 = vContentControl5.Find(\"Name\", \"WPFObject(\\\"ContentPresenter\\\", \\\"\\\", 5)\", 1000);\n\t//\tvStatusBarText4 = mvObjects.getObjectProperty(vGrid2, \"Name\", \"WPFObject(\\\"txtParamValue\\\")\", \"Text\");\n\t\t//if (aqString.Compare(vStatusBarText4, research, false) == 0) {\n\t\t// Log.Checkpoint(\"Research Studies are \" + research);\n\t//\t} else {\n\t\t// Log.Error(\"Research Studies are \" + research + \". Found research: \" + vStatusBarText4);\n\t\t// exestatus = false;\n\t//\t}\n\t//}\n\t// find Caption bar object\n\tvContentControl5 = vProcess.Find(\"Name\", \"WPFObject(\\\"captionItemsGrid\\\", \\\"\\\")\", 1000);\n\t\n\texestatus = mvObjects.verifyCaptionElement(\"1\", layout, \"Layout\",exestatus);\n\texestatus = mvObjects.verifyCaptionElement(\"2\", bedNumber, \"Bed\",exestatus);\n\texestatus = mvObjects.verifyCaptionElement(\"3\", newPatientMRN, \"MRN\",exestatus);\n\t\n\t// Combine First and last name\n\tvar patientName = patientDetails.firstName + \" \" + patientDetails.lastName\n\texestatus = mvObjects.verifyCaptionElement(\"4\", patientName, \"Patient Name\",exestatus);\n\t\n\texestatus = mvObjects.verifyCaptionElement(\"5\", patientDetails.allergies, \"Allergies\",exestatus);\n\texestatus = mvObjects.verifyCaptionElement(\"6\", patientDetails.gender, \"Patient Gender\",exestatus);\n \n if (dobDay < 10) \n {dobDay = \"0\"+dobDay}\n if (dobmonth < 10) \n {dobmonth = \"0\"+dobmonth}\n \n var tDOB = dobDay +\"/\"+ dobmonth +\"/\"+ dobyear;\n\texestatus = mvObjects.verifyCaptionElement(\"7\", tDOB, \"Patient DOB\",exestatus);\n\t\n\t\n\t\t\n\tif (equal(exestatus,true)) {\n\t \t Log.Checkpoint(\"Patient Demographics is successful.\");\n Log.Checkpoint(\"End Patient Demographics\",\"The flow is completed.\");\n }\n\t\n }\n else {\n Log.Message(\"Skipped Patient Demographics\",\"The feature is skipped since the execution status is set as '\"+exestatus+\"'\"); \n \n }\n return exestatus;\n \n}",
"function MveHOCPatientDetails(TestName,exestatus)\n{\n \n//Controller for executing or skipping the feature\nif (equal(exestatus,true)) {\n\n\n//var tcDesc = Data.getData(TestName,\"OtherCare\",\"TC_DESC\");\n//Log.Checkpoint(\"Start Generating the Patient Details eHOC report \"+tcDesc ,\"The flow is started\");\n\t//Start of the feature \n\t\n\t\n\t vProcess = Sys.Process(\"iMDSoft.Metavision\");\n\n\t// Patient Details and defaults\n\t var ms = 6000;\n var HelpStr = \"Delaying test run for \" + ms + \" milliseconds, To Generate the Patient Details eHOC report.\";\n aqUtils.Delay (ms, HelpStr);\n \n\texestatus = mvObjects.selectMenuOption(exestatus,\"Medical\",\"eHOC\");\n\t// Wait for screen to appear\n\t\n\t\t// ** Fill in the Patient details\n\tLog.Message(\"*** enter Generate the Patient Details eHOC report***\");\n\t\n \t\t\n if (equal(exestatus,true)) {\n\t \t Log.Checkpoint(\"Generate eHOC report for eHOCPatientDetails is successful\");\n Log.Checkpoint(\"End Generate eHOC report for eHOCPatientDetails\",\"The flow is completed\");\n }\n }\n else {\n Log.Message(\"Skipped Generate eHOC report for eHOCPatientDetails\",\"The feature is skipped since the execution status is set as '\"+exestatus+\"'\"); \n \n }\n return exestatus;\n \n}",
"function logResponse(passcount,failcount,linenumber){\nvar str= \"TestCases\"+\" \"+\"Passed =\" + passcount + ','+ \"Failed =\" + failcount + ',' + \"linenumber\" + linenumber;\nlogResult(str);\n}",
"static log () {\n this.ads.forEach(ad => {\n const {\n isVisible,\n percentage,\n viewabilityTime,\n clicks\n } = ad.state.getStats()\n const verbiage = `AD : ${ad.id} \\nVISIBLE : ${isVisible} \\nPERCENTAGE: ${this.round(percentage)}% \\nTIME : ${this.round(viewabilityTime)}s \\nCLICKS : ${clicks}`\n\n if (percentage < 50) {\n console.warn(verbiage)\n } else {\n console.info(verbiage)\n }\n })\n }",
"function printResults(cancerProfilingResult) {\n if (cancerProfilingResult.status === \"succeeded\") {\n const results = cancerProfilingResult.results;\n if (results) {\n for (const patientResult of results.patients) {\n console.log(`Inferences of Patient ${patientResult.id}`);\n for (const { type, value, confidenceScore, evidence } of patientResult.inferences) {\n console.log(\n `Clinical Type: ${String(type)} Value: ${value}, ConfidenceScore: ${confidenceScore}`\n );\n for (const { patientDataEvidence } of evidence || []) {\n if (patientDataEvidence) {\n console.log(\n `Evidence: ${patientDataEvidence.id} ${patientDataEvidence.offset} ${patientDataEvidence.length} ${patientDataEvidence.text}`\n );\n }\n }\n }\n }\n }\n } else {\n const errors = cancerProfilingResult.errors;\n if (errors) {\n for (const error of errors) {\n console.log(error.code, \":\", error.message);\n }\n }\n }\n}",
"function tc_add_a_new_patient()\n{\n try\n {\n var test_title = 'Patient - Add a new patient';\n login('cl3@regression','INRstar_5','Shared');\n add_patient('Regression', 'add_a_new_patient', 'M', 'Shared'); \n var results = validate_top_patient_audit(test_title,\"Add Patient\");\n \n results_checker(results, test_title)\n \n Log_Off();\n }\n catch (e)\n {\n Log.Warning('Test \"' + test_title + '\" FAILED Exception Occured = ' + e);\n Log_Off(); \n } \n}",
"function CMP14_TC002(TestName)\n{\nvar exestatus = true;\n \n// add a comment\n//Login\nexestatus = Features.MvLogin(TestName,exestatus);\n//Enter Patient Register\nexestatus = Features.MvPatientRegister(TestName,exestatus);\n//Enter Patient Demographics\nexestatus = Features.MvPatientDemographics(TestName,exestatus);\n//Enter Admission Summary details \nexestatus = Features.MvAdmissionSummary(TestName,exestatus);\n\nexestatus = Features.MvRecordVentilation(TestName,exestatus)\n//Enter Weights and Dimensions\nexestatus = Features.MvWeightsandDimensions(TestName,exestatus);\n//Enter details for Medical Dischare Summary\nexestatus = Features.MVMedicalDischargeSummary(TestName,exestatus);\n// ANZICS details \nexestatus = Features.MVANZICSDetails(TestName,exestatus);\n//Logout\nexestatus = Features.MvLogout(TestName,exestatus);\n \n}",
"function stepCorrelationAlert(drug, weather, drugName) {\n var nothing =\n 'We have found no reason why your step count DECREASED. We suggest you to take more action and do more walking.';\n var starter =\n 'We have found your step count today is ABNORMAL using sample standard deviation and correlation. But we also found that: <br>';\n var drugMsg =\n '- your medicine ' +\n drugName +\n ' might be making you FATIGUE by using FDA drug complaint database.<br> Here is a link to <a href=http://www.webmd.com/drugs/search.aspx?stype=drug&query=' +\n drugName +\n ' target=\"_blank\">WEBMD</a>';\n var weatherMsg =\n \"- today's weather around your location is bad. There was either rain, snow, hail, thunderstorm, fog, tornado or combination of these.\";\n // hard threshold for FDA drug, no reason for the number\n var drugThreshold = 1000;\n if (drug >= drugThreshold && weather > 0) {\n return starter + drugMsg + ' <br> AND <br>' + weatherMsg;\n } else if (drug >= drugThreshold && weather == 0) {\n return starter + drugMsg;\n } else if (drug < drugThreshold && weather == 0) {\n return nothing;\n } else if (drug < drugThreshold && weather > 0) {\n return starter + weatherMsg;\n }\n}",
"publ report(){\n if(this.error){\n return \"Test '%s' has failed after %s ms due to:\\n\\n%s\".format(this.name, this.duration, this.error.toTraceString().indent(4));\n }else{\n return \"Test '%s' completed in %s ms\".format( this.name, this.duration);\n }\n }",
"function CMP11_TC007(TestName)\n{\nvar exestatus = true;\n \n// add a comment\n//Login\nexestatus = Features.MvLogin(TestName,exestatus);\n\n//Enter Patient Register\nexestatus = Features.MvPatientRegister(TestName,exestatus);\n\n//Enter Patient Demographics\n//exestatus = Features.MvPatientDemographics(TestName,exestatus);\n\n//Validation to Print Patient Belongings List \nexestatus = Features.MvPrintPatientBelongings(TestName,exestatus);\n \n//Logout\nexestatus = Features.MvLogout(TestName,exestatus);\n \n}",
"function phaseActivity(res){\n\tvar file = 'scatter_group_phase_activity.tsv';\n\tvar arr = []; arr[0]=[];arr[1]=[];arr[2]=[];arr[3]=[],arr[4]=[];\n\t\n\tfor(var i = 0; i < cleanlog.length; i++){\t\n\t\ttry{\n\t\t\tcleanlog[i].group = userData[cleanlog[i].user]['GruppeP1'];\n\t\t\tif(arr[cleanlog[i].phase][cleanlog[i].group] == undefined){ \n\t\t\t\tarr[cleanlog[i].phase][cleanlog[i].group] = 0;\n\t\t\t} \n\t\t\tarr[cleanlog[i].phase][cleanlog[i].group]++;\n\t\t} catch(e){\n\t\t\tconsole.log(e);\n\t\t\t//console.log(JSON.stringify(cleanlog[i],null,4));\n\t\t}\n\t\t\t\n\t}\n\t\n\t// prepare tsv\n\tvar dataset = \"activity\\tphase\\tgroup\\n\";\n\tfor(var phase in arr){\n\t\tfor(var group in arr[phase]){\n\t\t//console.log('xx: '+arr[phase][group]+\"__\"+phase+\"__\"+group+\"\\n\");\n\t\t\tdataset += arr[phase][group]+\"\\t\"+phase+\"\\t\"+group+\"\\n\";\n\t\t}\t\n\t}\n\tconsole.log(dataset);\n\t\n\t// write it\n\tfs.writeFile(__dirname+'/../public/vi-lab/analysis/data/'+file, dataset, function(err){\n\t if(err) {\n\t console.log(err);\n\t } else {\n\t \t console.log('Date generated: '+file);\n\t\t}\t\n\t});\n}",
"function logAnalysis() {\n console.log('======== LYRICA RAW ANALYSIS RESULTS ========');\n Object.keys(Lyrica.Analyser.state.results.prolific).map(category => {\n if (category == 'primaryArtists') console.log('Category :: ======== Primary Lyrical Sections ========')\n if (category == 'actualArtists') console.log('Category :: ======== Actual Lyrical Sections ========')\n if (category == 'uniqueWords') console.log('Category :: ======== Unique Words ========')\n Lyrica.Analyser.state.results.prolific[`${category}`].map((result, idx) => {\n if (category == 'primaryArtists') console.log(`Artist RAnk #${idx+1} — ${result[0]} :: ${result[1]} Primary Lyrical Sections`)\n if (category == 'actualArtists') console.log(`Artist RAnk #${idx+1} — ${result[0]} :: ${result[1]} Actual Lyrical Sections`)\n if (category == 'uniqueWords') console.log(`Artist RAnk #${idx+1} — ${result[0]} :: ${result[1]} Unique Words`)\n })\n })\n console.log('======== LYRICA RAW ANALYSIS RESULTS ========');\n}",
"function MvRecordPatientDeath(TestName,exestatus)\n{\n \n//Controller for executing or skipping the feature\nif (equal(exestatus,true)) {\n\n\nvar tcDesc = Data.getData(TestName,\"Navigation\",\"TC_DESC\");\n\nLog.Checkpoint(\"To Record Patient Death \",\"The flow is started\");\n\t\n //Start of the feature \n\t vProcess = Sys.Process(\"iMDSoft.Metavision\");\n \n//var DeathTime = Data.getData(TestName,\"Patient\",\"DeathTime\");\n\t// Open Patient demographcs\n\texestatus = mvObjects.selectMenuOption(exestatus,\"Menu\", \"Patient Demographics\");\n\t// Wait for screen to appear\n\texestatus = mvObjects.waitForObject(vProcess, \"WPFObject(\\\"capXP\\\")\", 120,exestatus);\n \n let PatientDemo = new Object();\n \n PatientDemo.DeathDate = Data.getData(TestName,\"Patient\",\"DeathDate\")\n DTDay = aqString.substring(PatientDemo.DeathDate, 0, 2);\n\t DTMonth = aqString.substring(PatientDemo.DeathDate, 3, 2);\n\t DTYear= aqString.substring(PatientDemo.DeathDate, 6, 4);\n \nexestatus = mvObjects.enterImdDateTimePicker(vProcess, \"WPFObject(\\\"dtpDate_2\\\")\", DTDay,DTMonth,DTYear,\"00\",\"00\",exestatus); \nexestatus = mvObjects.enterImdDateTimePicker(vProcess, \"WPFObject(\\\"dtpDate_3\\\")\", \"00\",\"00\",\"0000\",\"12\",\"00\",exestatus); \n//exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"dtpDate_3\\\")\",DeathTime ,exestatus);\n \nexestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"cmdSave\\\")\",exestatus); \n\n if (equal(exestatus,true)) {\n\t \t Log.Checkpoint(\"Record Patient Death updated successfully\");\n Log.Checkpoint(\"End of Record Patient Death\",\"The flow is completed\");\n }\n }\n else {\n Log.Message(\"Skipped updating Record Patient Death\",\"The feature is skipped since the execution status is set as '\"+exestatus+\"'\"); \n \n }\n return exestatus;\n \n}",
"function MvMedicationChart(TestName,exestatus)\n{\n \n//Controller for executing or skipping the feature\nif (equal(exestatus,true)) {\n\n//var objData = Data.getData(TestName,\"MedicalCare\");\nvar tcDesc = Data.getData(TestName,\"MedicalCare\",\"TC_DESC\");\nLog.Checkpoint(\"Start of medication chart \"+tcDesc ,\"The flow is started\");\n\t\n \n //Start of the feature \n\t vProcess = Sys.Process(\"iMDSoft.Metavision\");\n\n\t \n //** Fill in the details for prescribe medication tab**\n// \nLog.Message(\"*** Enter details for Prescribe medication\");\nvar drug = Data.getData(TestName,\"MedicalCare\",\"drug\");\nvar template=Data.getData(TestName,\"MedicalCare\",\"template\");\nvar medicaltype=Data.getData(TestName,\"MedicalCare\",\"medicaltype\");\nvar quantity = Data.getData(TestName,\"MedicalCare\",\"quantity\");\nvar DoseRate = Data.getData(TestName,\"MedicalCare\",\"DoseRate\");\nvar Rate = Data.getData(TestName,\"MedicalCare\",\"Rate\");\nvar PRNdrug = Data.getData(TestName,\"MedicalCare\",\"PRNdrug\");\nvar PRNtemplate = Data.getData(TestName,\"MedicalCare\",\"PRNtemplate\");\nvar PRNmedicaltype = Data.getData(TestName,\"MedicalCare\",\"PRNmedicaltype\");\nvar PRNquantity = Data.getData(TestName,\"MedicalCare\",\"PRNquantity\");\nvar PRNText = Data.getData(TestName,\"MedicalCare\",\"PRNText\");\nvar SetInterval = Data.getData(TestName,\"MedicalCare\",\"SetInterval\");\n//var type = Data.getData(TestName,\"MedicalCare\",\"type\");\n//Log.message(\"Drug type value is \",type);\n//var seldrfam = Data.getData(TestName,\"MedicalCare\",\"seldrfam\");\n//Log.message(\"Selected Drug family is \",seldrfam);\n//var seldrfam1 = Data.getData(TestName,\"MedicalCare\",\"seldrfam1\");\n//Log.message(\"Selected Drug family is \",seldrfam1);\n//var med = Data.getData(TestName,\"MedicalCare\",\"med\");\n//Log.message(\"Medication \",med);\n//var ingr = Data.getData(TestName,\"MedicalCare\",\"ingr\");\n//Log.message(\"Ingredient \",ingr);\n//var msc = Data.getData(TestName,\"MedicalCare\",\"msc\");\n//Log.message(\"Miscellaneous \",msc);\n//var Rea = Data.getData(TestName,\"MedicalCare\",\"Rea\");\n//Log.message(\"Reactions \",Rea);\n//var Comment = Data.getData(TestName,\"MedicalCare\",\"Comment\");\n\n//var objData = Data.getData(TestName,\"Navigation\");\nvar Password = Data.getData(TestName,\"Navigation\",\"Password\"); \n\nLog.Message(\"*** Enter details for PRN Medication\");\n//Prescribe Medication- To order PRN medication \nexestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"TabItem\\\"),\\\"\\\"\\,11\",exestatus);\n\n//Click on Prescribe \nexestatus = mvObjects.buttonClick(vProcess,\"FullName\", \"*WPFObject(\\\"CustomWrapPanel\\\", \\\"\\\", 1).WPFObject(\\\"ImdButton\\\", \\\"\\\",1)\",exestatus);\n\naqUtils.Delay(10000);\n\n//Entering values in orderable window \nexestatus = mvObjects.SearchSelectItem(vProcess, \"WPFObject(\\\"FindComboBoxEdit\\\")\",5,2,PRNdrug,2,exestatus);\nexestatus = mvObjects.selectToggleItem(vProcess,\"Text\",PRNtemplate,exestatus);\nexestatus = mvObjects.buttonClick(vProcess,\"FullName\",\"*WPFObject(\\\"Frequency_Row1\\\").WPFObject(\\\"LayoutItem\\\", \\\"\\\", 1).WPFObject(\\\"PRNToggleButton\\\")\",exestatus);\nexestatus = mvObjects.Fullnametext(vProcess,\"*WPFObject(\\\"Frequency_Row1\\\").WPFObject(\\\"LayoutItem\\\", \\\"\\\", 2).WPFObject(\\\"Border\\\", \\\"\\\", 1).WPFObject(\\\"TextEdit\\\", \\\"\\\", 1)\",PRNText,exestatus);\nexestatus = mvObjects.wildcardfullname(vProcess, \"*WPFObject(\\\"Frequency_Row2\\\").WPFObject(\\\"LayoutItem\\\", \\\"\\\", 2).WPFObject(\\\"ComboBoxEdit\\\", \\\"\\\", 1).WPFObject(\\\"ButtonContainer\\\", \\\"\\\", 1).WPFObject(\\\"PART_Item\\\")\",\"ComboBoxEditItem\",PRNmedicaltype,exestatus)\nexestatus = mvObjects.Fullnametext(vProcess,\"*WPFObject(\\\"Frequency_Row2\\\").WPFObject(\\\"LayoutItem\\\", \\\"\\\", 3).WPFObject(\\\"ContentControl\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"Border\\\", \\\"\\\", 1).WPFObject(\\\"SpinEdit\\\", \\\"\\\", 1)\",SetInterval,exestatus);\n\n\n\n// Enter medication quantity\nexestatus = mvObjects.Fullnametext(vProcess,\"*WPFObject(\\\"LayoutGroup\\\", \\\"\\\", 2).WPFObject(\\\"ContentControl\\\", \\\"\\\", 1).WPFObject(\\\"GridMedications\\\").WPFObject(\\\"DVGridMedications\\\").WPFObject(\\\"view\\\").WPFObject(\\\"HierarchyPanel\\\", \\\"\\\", 1).WPFObject(\\\"GridRow\\\", \\\"\\\", 1).WPFObject(\\\"BandedViewContentSelector\\\", \\\"\\\", 1).WPFObject(\\\"GridCellContentPresenter\\\", \\\"\\\", 4).WPFObject(\\\"TextEdit\\\", \\\"\\\", 1)\",PRNquantity,exestatus);\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"Button\\\", \\\"Save & Close\\\",1)\",exestatus);\n\n//Click on Signow\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"cmdSign\\\")\",exestatus);\n\n//Click on Signnow in Signature Review\n\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WinFormsObject(\\\"cmdSignNow\\\")\",exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"PasswordBoxEdit\\ ,\\\"\\\"\\,1)\", Password,exestatus);\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"Button\\\" , \\\"OK\\\",1)\",exestatus); \n\n\nLog.Message(\"*** Enter details for Nutrition\");\n//Prescribe Medication\nexestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"TabItem\\\"),\\\"\\\"\\,11\",exestatus);\n//Click on Prescribe TPN Products \nexestatus = mvObjects.buttonClick(vProcess,\"FullName\", \"*WPFObject(\\\"CustomWrapPanel\\\", \\\"\\\", 1).WPFObject(\\\"ImdButton\\\", \\\"\\\",4)\",exestatus);\n\n// Click on Blood Products\nexestatus = mvObjects.buttonClick(vProcess,\"FullName\", \"*WPFObject(\\\"HwndSource: ImdGenericWindow\\\", \\\"\\\").WPFObject(\\\"ImdGenericWindow\\\", \\\"\\\", 1).WPFObject(\\\"Border\\\", \\\"\\\", 1).WPFObject(\\\"Border\\\", \\\"\\\", 1)*.WPFObject(\\\"ImdButton\\\", \\\"\\\",2)\",exestatus);\n\n// Click on TPN-BLT\n\nexestatus = mvObjects.buttonClick(vProcess,\"FullName\",\"*WPFObject(\\\"picTabs\\\")*.WPFObject(\\\"cmdAction_3\\\")\",exestatus);\n\n\n//Entering values in orderable window \n\n\nexestatus = mvObjects.Fullnametext(vProcess, \"*WPFObject(\\\"OrderingStyle\\\").WPFObject(\\\"OrderingStyleView\\\", \\\"\\\", 1).WPFObject(\\\"Order_Style_Group\\\").WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 2).WPFObject(\\\"Grid\\\", \\\"\\\", 2).WPFObject(\\\"Border\\\", \\\"\\\", 1).WPFObject(\\\"RateRange\\\")\",Rate,exestatus);\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"Button\\\", \\\"OK\\\", 1)\",exestatus);\nexestatus = mvObjects.buttonClick(vProcess,\"FullName\",\"*WPFObject(\\\"FormActionStackPanel\\\").WPFObject(\\\"cmdCancel\\\")\",exestatus);\n\n\n//Click on Signow\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"cmdSign\\\")\",exestatus);\n\n//Click on Signnow in Signature Review\n\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WinFormsObject(\\\"cmdSignNow\\\")\",exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"PasswordBoxEdit\\ ,\\\"\\\"\\,1)\", Password,exestatus);\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"Button\\\" , \\\"OK\\\",1)\",exestatus);\n\n\nLog.Message(\"*** Enter details for Medication\");\n//Prescribe Medication\nexestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"TabItem\\\"),\\\"\\\"\\,11\",exestatus);\n\n//Click on Prescribe \nexestatus = mvObjects.buttonClick(vProcess,\"FullName\", \"*WPFObject(\\\"CustomWrapPanel\\\", \\\"\\\", 1).WPFObject(\\\"ImdButton\\\", \\\"\\\",1)\",exestatus);\n\n//Entering values in orderable window \nexestatus = mvObjects.SearchSelectItem(vProcess, \"WPFObject(\\\"FindComboBoxEdit\\\")\",5,2,drug,2,exestatus);\nexestatus = mvObjects.selectToggleItem(vProcess,\"Text\",template,exestatus);\nexestatus = mvObjects.wildcardfullname(vProcess, \"*WPFObject(\\\"Frequency_Row2\\\").WPFObject(\\\"LayoutItem\\\", \\\"\\\", 2).WPFObject(\\\"ComboBoxEdit\\\", \\\"\\\", 1).WPFObject(\\\"ButtonContainer\\\", \\\"\\\", 1).WPFObject(\\\"PART_Item\\\")\",\"ComboBoxEditItem\", medicaltype,exestatus)\n\n//\n//exestatus = mvObjects.Fullnametext(vProcess, \"*WPFObject(\\\"OrderingStyleRow\\\").WPFObject(\\\"OrderingStyleView\\\", \\\"\\\", 1).WPFObject(\\\"Order_Style_Group\\\").WPFObject(\\\"LayoutItem\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 2).WPFObject(\\\"Grid\\\", \\\"\\\", 2).WPFObject(\\\"RateRange\\\")\",Rate,exestatus);\n\n// Enter medication quantity\nexestatus = mvObjects.Fullnametext(vProcess,\"*WPFObject(\\\"LayoutGroup\\\", \\\"\\\", 2).WPFObject(\\\"ContentControl\\\", \\\"\\\", 1).WPFObject(\\\"GridMedications\\\").WPFObject(\\\"DVGridMedications\\\").WPFObject(\\\"view\\\").WPFObject(\\\"HierarchyPanel\\\", \\\"\\\", 1).WPFObject(\\\"GridRow\\\", \\\"\\\", 1).WPFObject(\\\"BandedViewContentSelector\\\", \\\"\\\", 1).WPFObject(\\\"GridCellContentPresenter\\\", \\\"\\\", 4).WPFObject(\\\"TextEdit\\\", \\\"\\\", 1)\",quantity,exestatus);\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"Button\\\", \\\"Save & Close\\\",1)\",exestatus);\n\n//Click on Signow\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"cmdSign\\\")\",exestatus);\n\n//Click on Signnow in Signature Review\n\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WinFormsObject(\\\"cmdSignNow\\\")\",exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"PasswordBoxEdit\\ ,\\\"\\\"\\,1)\", Password,exestatus);\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"Button\\\" , \\\"OK\\\",1)\",exestatus); \n\nLog.Message(\"*** Enter details for Blood/ Fluid Products\");\n\n//Click on Prescribe Fresh Blood Products and Albumin button\nexestatus = mvObjects.buttonClick(vProcess,\"FullName\", \"*WPFObject(\\\"CustomWrapPanel\\\", \\\"\\\", 1).WPFObject(\\\"ImdButton\\\", \\\"\\\",3)\",exestatus);\n\n\n\n// Click on Blood Products\nexestatus = mvObjects.buttonClick(vProcess,\"FullName\", \"*WPFObject(\\\"HwndSource: ImdGenericWindow\\\", \\\"\\\")*.WPFObject(\\\"ImdButton\\\", \\\"\\\",3)\",exestatus);\n\n\n//Entering values in orderable window \n\nexestatus = mvObjects.Fullnametext(vProcess, \"*WPFObject(\\\"OrderingStyle\\\").WPFObject(\\\"OrderingStyleView\\\", \\\"\\\", 1).WPFObject(\\\"Order_Style_Group\\\").WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 2).WPFObject(\\\"Border\\\", \\\"\\\", 1).WPFObject(\\\"DoseRange\\\")\",DoseRate,exestatus);\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"Button\\\", \\\"OK\\\", 1)\",exestatus);\nexestatus = mvObjects.buttonClick(vProcess,\"FullName\", \"*WPFObject(\\\"HwndSource: ImdGenericWindow\\\", \\\"\\\")*.WPFObject(\\\"Button\\\", \\\"\\\", 3)\",exestatus);\n\n\n//Click on Signow\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"cmdSign\\\")\",exestatus);\n\n//Click on Signnow in Signature Review\n\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WinFormsObject(\\\"cmdSignNow\\\")\",exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"PasswordBoxEdit\\ ,\\\"\\\"\\,1)\", Password,exestatus);\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"Button\\\" , \\\"OK\\\",1)\",exestatus);\n\n//Log.Message(\"*** Enter allergy details for a patient\");\n\n//// Selecting Allergies/ADR from menu\n//exestatus = mvObjects.selectMenuOption(exestatus,\"Nursing\", \"Allergies/ADR\");\n//\n//// Validation of allergies\n//var allergies = vProcess.Find(\"Name\", \"WinFormsObject(\\\"MvcmdRemoveAllergy\\\")\", 1000);\n//var Msgwindow = vProcess.Find(\"Name\", \"WinFormsObject(\\\"FormCaption\\\")\", 1000);\n// \n// if (allergies.Enabled == true)\n// {\n// exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WinFormsObject(\\\"MvcmdRemoveAllergy\\\")\",exestatus);\n// Log.message(\"Delete the exisiting allergies\");\n// }\n// exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WinFormsObject(\\\"mvcmdAddAllergy\\\")\",exestatus);\n// Log.Message(\"Enter Allergy details\");\n//\n//\n//// Entering details for allergies\n//\n//exestatus = mvObjects.ImdListBoxSelection(\"WinFormsObject(\\\"cboObjectType\\\")\",type,exestatus);\n//\n//\n//switch(type){\n//case (\"Drug Family\"):\n//exestatus = mvObjects.ImdListBoxSelection(\"WinFormsObject(\\\"cboSelectedObject\\\")\",seldrfam,exestatus);\n//break;\n//\n//case (\"Drug subfamily\"):\n//exestatus = mvObjects.ImdListBoxSelection(\"WinFormsObject(\\\"cboSelectedObject\\\")\",seldrfam1,exestatus);\n//break;\n//\n//case (\"Medication\"):\n//exestatus = mvObjects.ImdListBoxSelection(\"WinFormsObject(\\\"cboSelectedObject\\\")\",med,exestatus);\n//break;\n//\n//case (\"Ingredient\"):\n//exestatus = mvObjects.ImdListBoxSelection(\"WinFormsObject(\\\"cboSelectedObject\\\")\",ingr,exestatus);\n//break;\n//\n//case (\"Miscellaneous\"):\n//exestatus = mvObjects.ImdListBoxSelection(\"WinFormsObject(\\\"cboSelectedObject\\\")\",msc,exestatus);\n//break;\n//\n//default:\n//Log.Message(\"Did not enter drug type\");\n//\n//}\n////exestatus = mvObjects.selectComboItem(vProcess, \"WinFormsObject(\\\"cboSelectedObjectFamily\\\")\",selecteddrugfam,exestatus);\n////exestatus = mvObjects.ImdListBoxSelection(\"WinFormsObject(\\\"cboSelectedObject\\\")\",seldfm,exestatus);\n////exestatus = mvObjects.ImdListBoxSelection(\"WinFormsObject(\\\"mvstlReactions\\\")\",rea,exestatus);\n//exestatus = mvObjects.ClickCoordinates(vProcess,\"Name\", \"WinFormsObject(\\\"mvstlReactions\\\")\",25,56,exestatus);\n//exestatus = mvObjects.ClickCoordinates(vProcess,\"Name\", \"WinFormsObject(\\\"stCombobox\\\")\",346,15,exestatus); \n//exestatus = mvObjects.SearchSelectItem(vProcess,\"WinFormsObject(\\\"Panel\\\" , \\\"\\\"\\)\",1,1,Rea,2,exestatus);\n//exestatus = mvObjects.enterEditText(vProcess, \"WinFormsObject(\\\"TextBox\\\", \\\"\\\"\\)\", Comment,exestatus);\n//exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WinFormsObject(\\\"cmdOK\\\")\",exestatus);\n//\n//\n////Check for Popup message (Allergen was previouly documented for this patient\n//\n//var Msgwindow = vProcess.Find(\"Name\", \"WinFormsObject(\\\"ImdFormBase\\\")\", 1000);\n//if (Msgwindow.Exists)\n// {\n// exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WinFormsObject(\\\"OK\\\")\",exestatus);\n// Log.Message(\"Allergen details was previously documented for this patient\");\n// }\n// else\n//{\n//Log.Message(\"Allergen details have not been documented for this patient\");\n//}\n//\n////Click on Save button in drug details window\n//\n//exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WinFormsObject(\\\"cmdSave\\\")\",exestatus);\n//\n////Verify Action issues popup is displayed\n//\n//var Allmsgwindow = vProcess.Find(\"Name\", \"WinFormsObject(\\\"frmAllergiesActionIssues\\\")\", 1000);\n//\n//\n//if (Allmsgwindow.Exists)\n// {\n// exestatus = mvObjects.ClickCoordinates(vProcess,\"Name\", \"WinFormsObject(\\\"stlIssues\\\")\",98,55,exestatus);\n// exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WinFormsObject(\\\"ImdButton\\\" ,\\\"View and Acknowledge\\\")\",exestatus);\n// exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WinFormsObject(\\\"cmdOk\\\")\",exestatus); \n// exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WinFormsObject(\\\"cmdProceed\\\")\",exestatus);\n// \n//\n// Log.Checkpoint(\"Allergy Popup message is displayed\");\n// }\n// else\n//{\n//Log.Message(\"Allergy Popup message is NOT displayed\");\n//}\n\n// Medication chart validation will be done as a part of eNMIC validation\n \n \n //var objData = Data.getData(TestName,\"Patient\");\n \t//var newPatientMRN = objData(\"MRN\").Value;\n\n \n if (equal(exestatus,true)) {\n\t \t Log.Checkpoint(\"Successfully validated medication chart \");\n Log.Checkpoint(\"End of medication chart \",\"The flow is completed\");\n }\n }\n else {\n Log.Message(\"Skipped medication chart \",\"The feature is skipped since the execution status is set as '\"+exestatus+\"'\"); \n \n }\n return exestatus;\n \n}",
"function CMP7_TC015(TestName)\n{\nvar exestatus = true;\n \n//Login\nexestatus = Features.MvLogin(TestName,exestatus);\n\n//Enter Patient Register\nexestatus = Features.MvPatientRegister(TestName,exestatus);\n\n//Enter Patient Demographics\n//exestatus = Features.MvPatientDemographics(TestName,exestatus);\n\n// Feature to initiate and document drain\nexestatus = Features.MvOtherDrain(TestName,exestatus);\n\n// Feature to initiate and document tube\nexestatus = Features.MvNasoduodenalTube(TestName,exestatus);\n\n// Feature to initate lines and review of drains, tube and lines\nexestatus = Features.MvArterialCatheter(TestName,exestatus);\n\n//Logout\nexestatus = Features.MvLogout(TestName,exestatus);\n \n}",
"async viewLogs(patientName){\r\n await contract.then(async optrakContract => {\r\n console.log(optrakContract);\r\n var transactions = await optrakContract.allEvents();\r\n console.log(transactions);\r\n })\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Internal function to get the index of the given handler within the internal array. If the handler cannot be found, 1 is returned. | function getIndex(handler) {
var index = -1;
each(function (event, i) {
if (event.handler === handler) {
index = i;
}
return index === -1;
});
return index;
} | [
"findIndex(callback) {\n for (let i = 0; i < this.arr.length; ++i) {\n if (callback(this.arr[i])) {\n return i;\n }\n }\n\n return -1;\n }",
"function helper_get_data_item_index(arr, sel){\n for(var i=0; i<arr.length; i++) if(arr[i][0]==sel) return i;\n return (-1);\n}",
"function findHandleIndex(panel, target) {\n var children = panel.children;\n for (var i = 0, n = children.length; i < n; ++i) {\n var handle = getHandle(children.get(i));\n if (handle.node.contains(target))\n return i;\n }\n return -1;\n}",
"findIndex (callback, context) {\n return this.then(async function (array) {\n for (let i = 0, length = array.length; i < length; ++i) {\n if (await callback.call(context, array[i], i, array)) {\n return i\n }\n }\n return -1\n })\n }",
"function magicIndex(array) {\n for (let i = 0; i < array.length; i++) {\n if (array[i] === i) {\n return i;\n }\n }\n return -1;\n}",
"async function getArrayIndex(arr, arrVal) {\n\tif (arr === undefined) throw new Error('Array not defined in array/getArrayIndex');\n\tif (arrVal === undefined) throw new Error('Array Element Value not defined in array/getArrayIndex');\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tif (arr[i] == arrVal) return i;\n\t}\n\treturn undefined;\n}",
"findItemIndex(middlewareOrName) {\n if (typeof middlewareOrName === 'number') {\n return middlewareOrName;\n }\n else if (typeof middlewareOrName === 'string') {\n return this.findIndex(item => this.getMiddlewareName(item) === middlewareOrName);\n }\n else {\n return this.findIndex(item => item === middlewareOrName);\n }\n }",
"index(listener) {\n const listeners = this.listeners;\n const count = listeners.length;\n for (let i = 0; i < count; i++) {\n if (listener === listeners[i])\n return i;\n }\n }",
"function getIndexOf(obj) {\n\tvar i = 0;\n\tvar found = false;\n\tvar length = this.getLength();\n\twhile (i < length && !found) {\n\t\tif (this.get(i) == obj) {\n\t\t\tfound = true;\n\t\t} else {\n\t\t\ti++;\n\t\t}\n\t}\n\treturn i == length ? null : i;\n}",
"idx(element, array) {\n return array.indexOf(element);\n }",
"function findIndex(arr, val) {\n\n}",
"getIndex (id, array) {\n for (let i = 0; i < array.length; ++i)\n if (array[i].id === id) return i;\n return -1;\n }",
"function myIndexOf(array, target) {\n for (var i = 0; i < array.length; i += 1) {\n var element = array[i]\n\n if (element === target) {\n return i\n }\n }return -1;\n}",
"function findIndex(arr, predicate) {\n var i = 0;\n if (!arr || arr.length < 1) {\n return undefined;\n }\n var len = arr.length;\n while (i < len) {\n if (predicate(arr[i], i)) {\n return i;\n }\n i++;\n }\n return undefined;\n}",
"function myIndexOf(array, ele) {\n // your code here...\n for (var i = 0; i < array.length; i++) {\n if (array[i] === ele) {\n return i;\n }\n }\n\n return -1;\n}",
"function findIndex(array, cb) {\n var index = -1;\n for (var i = 0; array && i < array.length; i++) {\n if (cb(array[i], i)) {\n index = i;\n break;\n }\n }\n return index;\n}",
"function findIndexByKey(array, key) {\n for (let i=0; i < array.length; i++) {\n if (array[i][0] === key) {\n return i;\n }\n }\n\n return -1;\n}",
"function get_index_of_el(el) {\n for (var i = 0, len = children_num; i < len; i++) {\n if (self.el.children[i] == el) {\n return i;\n }\n }\n }",
"function myIndexOf(array, ele) {\n for (var i = 0; i < array.length; i++) {\n if (array[i] === ele) {\n return i;\n }\n }\n return -1;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Bracket seeding / Pourpose: Seeds matches' decoys in bracket. Prec: decoys must be in order. decoys.length == 2^n Ret: balanced bracket with all decoys seed | function seed_decoys(decoys){
var fst = decoys.shift();
return decoys.reduce(place_decoy_in_bracket, fst);
} | [
"function BuildBracketSeedValues(BracketSize) {\n // Declaring variables.\n var i = 0;\n var j = 0;\n var BracketLayers = Math.log2(BracketSize);\n // Establishing address arrays.\n SeedAddressTmp = InitialiseArray(BracketSize, 1, 0);\n SeedAddressGlobal = InitialiseArray(BracketSize, 1, 0);\n\n SeedAddressTmp[0] = 1;\n // Special case where there is only 1 player in the bracket.\n if (BracketLayers == 0) {\n SeedAddressGlobal[0] = 1;\n } // end if BracketLayers\n\n for (i = 1; i <= BracketLayers; i++) {\n for (j = 1; j <= Math.pow(2, i - 1); j++) {\n if (j % 2 == 0){\n SeedAddressGlobal[2 * j - 1] = SeedAddressTmp[j - 1];\n SeedAddressGlobal[2 * j - 2] = Math.pow(2, i) + 1 - SeedAddressGlobal[2 * j - 1];\n } else {\n SeedAddressGlobal[2 * j - 2] = SeedAddressTmp[j - 1];\n SeedAddressGlobal[2 * j - 1] = Math.pow(2, i) + 1 - SeedAddressGlobal[2 * j - 2];\n } // end if else\n } // next j\n for (j = 1; j <= Math.pow(2, i); j++) {\n SeedAddressTmp[j - 1] = SeedAddressGlobal[j - 1];\n } // next j\n } // next i\n\n return SeedAddressGlobal;\n\n} // end function",
"function generateDE4(bracket){\n var table = document.getElementById(\"bracket\");\n table.innerHTML = \"\" //remove all children\n let rounds = bracket[bracket.length-1].round\n let countR1 = 0\n let numRows = 13\n let height = parseFloat(100/numRows) + \"%\"\n for(let rw = 0; rw < numRows; rw++){\n let newRow = document.createElement(\"tr\")\n table.appendChild(newRow)\n }\n let rows = table.rows\n let rw = 0\n rw += generateMatchDE(bracket[0], rows, rw, 4, height)\n rw += generateMatchDE(bracket[1], rows, rw, 4, height)\n rw += addBlankSpace(rows, rw, 1, height, false)\n rw += generateMatchDE(bracket[2], rows, rw, 4, height)\n rw = 0\n rw += addBlankSpace(rows, rw, 1, height, false)\n rw += generateMatchDE(bracket[3], rows, rw, 6, height)\n rw += addBlankSpace(rows, rw, 1, height, false)\n rw += generateMatchDE(bracket[4], rows, rw, 4, height)\n rw += addBlankSpace(rows, rw, 1, height, false)\n}",
"createMatches(category, numRiders) {\n let numMatches = numRiders - 1;\n let tournamentID = \"ID\";\n let matchID = 0;\n\n let matchList = [numMatches];\n\n // Initialize all empty matches for the whole bracket\n for (let i = 0; i < numMatches; i++) {\n let match = {matchNumber: i, category: category};\n matchList[i] = match;\n database.createMatch(category, i, match)\n }\n\n let racerList = database.getRacersByCategory(category);\n\n // Populate empty matches with racerID's\n let seed1Index = 0;\n let seed2Index = numRiders - 1;\n let matchIndex = numMatches - 1;\n // First half of first round\n for (let i = 0; i < numRiders / 4; i++) {\n matchList[i].racer1ID = racerList[seed1Index].id;\n matchList[i].racer2ID = racerList[seed2Index].id;\n matchList[i].racer1Number = racerList[seed1Index].racerNumber;\n matchList[i].racer2Number = racerList[seed2Index].racerNumber;\n database.updateMatch(matchList[i]);\n seed1Index += 2;\n seed2Index -= 2;\n matchIndex -= 1;\n }\n\n /* Ex: 16 riders: In the loop above, seed1Index ended with value of 8 and seed2Index with value of 7.\n To populate the lower half of the first round of brackets, we decrement seed1Index by 1 and increment\n seed2Index by 1. From here, we decrement seed1Index by 2 and increment seed2Index by 2 instead of\n incrementing and decrementing respectively as in the first half.\n */\n seed1Index -= 1;\n seed2Index += 1;\n for (let i = 0; i < numRiders / 4; i++) {\n matchList[i].racer1ID = racerList[seed1Index].id;\n matchList[i].racer2ID = racerList[seed2Index].id;\n matchList[i].racer1Number = racerList[seed1Index].racerNumber;\n matchList[i].racer2Number = racerList[seed2Index].racerNumber;\n database.updateMatch(matchList[i]);\n seed1Index -= 2;\n seed2Index += 2;\n matchIndex -= 1;\n }\n return matchList\n }",
"static generateStartingBracket(teams_list) {\n\n var amnt_of_teams = teams_list.length;\n\n var rounds_cnt = Bracket.getRoundsCnt(amnt_of_teams);\n\n var empty_rounds = Bracket.generateEmptyBracket(amnt_of_teams, rounds_cnt);\n\n var starting_rounds = empty_rounds.slice(0);\n var teams_left = teams_list.slice(0);\n\n for (var i = 0; i < starting_rounds[0].length; i ++) {\n\n var team_one;\n var team_two;\n\n var match;\n\n if (teams_left.length >= 2) {\n team_one = teams_left.pop();\n team_two = teams_left.pop();\n match = new Match(team_one.id, team_two.id);\n }else if (teams_left.length <= 0) {\n match = new Match(null, null);\n match.setWinner(Match.TEAM_ONE);\n }else {\n team_one = teams_left.pop();\n match = new Match(team_one.id, null);\n match.setWinner(Match.TEAM_ONE);\n }\n\n starting_rounds[0][i] = match;\n\n }\n\n return starting_rounds;\n\n }",
"function snakeSeed() {\n let poolIndex = 0;\n let increase = true;\n let hold = true;\n let maxPoolIndex = pools.length - 1;\n for (var i = 0; i < teams.length; i++) {\n pools[poolIndex].teams.push(teams[i]);\n if ((poolIndex >= 0) && (poolIndex < maxPoolIndex) && increase) {\n poolIndex++;\n hold = true;\n } else if (poolIndex === maxPoolIndex && hold) {\n hold = false;\n increase = false;\n } else if (poolIndex === maxPoolIndex && !hold) {\n poolIndex--;\n hold = true;\n } else if (poolIndex > 0 && !increase) {\n poolIndex--;\n } else if (poolIndex === 0 && hold) {\n hold = false;\n increase = true;\n } else if (poolIndex === 0 && !hold && increase) {\n poolIndex++;\n hold = true;\n }\n }\n}",
"function BracketCombinations(n) { \n if( n === 0 ) {\n return 1;\n }\n let parenthesis = [\n ['(', 1, 0]\n ];\n while( true ) {\n let openParenthesisCount = parenthesis[0][1];\n let closeParenthesisCount = parenthesis[0][2];\n // RULE 3\n if( openParenthesisCount == closeParenthesisCount && closeParenthesisCount == n && openParenthesisCount == n ) {\n break;\n }\n let data = parenthesis.shift();\n let temp = [];\n let str = \"\";\n // RULE 1\n if( openParenthesisCount < n ) {\n str = data[0] + \"(\";\n [, o, c] = data;\n temp.push(str, ++o, c);\n parenthesis.push(temp);\n temp = [];\n }\n // RULE 2\n if( openParenthesisCount > closeParenthesisCount ) {\n str = data[0] + \")\";\n [, o, c] = data;\n temp.push(str, o, ++c);\n parenthesis.push(temp);\n temp = [];\n }\n }\n return parenthesis.map( result => result[0] ).length;\n}",
"function replace_decoys(bracket){\n if(bracket.is_decoy){\n return bracket.match;\n }else{\n bracket.branch_1 = replace_decoys(bracket.branch_1);\n bracket.branch_2 = replace_decoys(bracket.branch_2);\n return bracket;\n }\n }",
"function generateParentheses(n){\n let res = [];\n backtrack(res,'',0,0,n);\n return res;\n\n function backtrack(arr,current,numOpen,numClosed,numPairs){\n if(current.length === numPairs*2){//base case\n arr.push(current);\n return;\n }\n if(numOpen < numPairs){//decision (your number of opening parentheses will be the same as numPairs)\n backtrack(arr,current+'(',numOpen+1,numClosed,numPairs);\n }\n if(numClosed < numOpen){//decision (you cannot have closing parentheses before open ones)\n backtrack(arr,current+')',numOpen,numClosed+1,numPairs);\n }\n }\n}",
"function fillBracketDom(rounds, last_round) {\n\tclearPage();\n\n\tlet bracket_span = document.getElementById(\"bracket_span\");\n\n\tlet height = getHeight('.bracket_image');\n\tlet width = getWidth('.bracket_image') * 2;\n\n\tlet vertical_offset = 0;\n\tlet num_rounds;\n\tif (rounds == -1) {\n\t\tnum_rounds = 4;\n\t}\n\telse {\n\t\tnum_rounds = rounds;\n\t}\n\n\tlet cur_round = last_round - rounds + 1;\n\tfor (let i = 0; i < rounds; i++) {\n\t\tlet p = document.createElement(\"p\");\n\t\tp.className = \"round_text\";\n\t\tp.innerHTML = \"Round \" + cur_round;\n\t\tp.style.position = \"absolute\";\n\t\tp.style.left = \"\" + i*426 + \"px\";\n\n\t\tlet bracket_rounds = document.getElementById(\"bracket_rounds\");\n\t\tbracket_rounds.appendChild(p);\n\n\t\tcur_round += 1;\n\t}\n\n\tfor (let i = 0; i < num_rounds; i++) {\n\t\tvertical_offset += i*(height/2);\n\t\tlet round_div = document.createElement(\"div\");\n\t\tround_div.style.position = \"absolute\";\n\t\tround_div.style.left = \"\" + i*426 + \"px\";\n\n\t\t// Offset the bracket to account for \"Round X\" text.\n\t\tlet vertical_round_offset = 100;\n\n\t\tfor (let j = 0; j < Math.pow(2, num_rounds-i-1); j++) {\n\t\t\tlet elem = createRound(\"bracket\");\n\t\t\telem.style.position = \"absolute\";\n\n\t\t\tlet round_height = j*height*Math.pow(2, i) + vertical_round_offset;\n\t\t\tif (i == 1) {\n\t\t\t\tround_height += Math.pow(2, i-1);\n\t\t\t\tround_height += height/2;\n\t\t\t}\n\t\t\telse if (i != 0) {\n\t\t\t\tround_height += Math.pow(2, i-1) * height;\n\t\t\t\tround_height -= height/2;\n\t\t\t}\n\t\t\telem.style.top = round_height + \"px\";\n\t\t\tround_div.appendChild(elem);\n\t\t}\n\t\tbracket_span.appendChild(round_div);\n\n\t\tlet bracket_div = document.createElement(\"div\");\n\t\tbracket_div.style.position = \"absolute\";\n\t\tbracket_div.style.left = \"\" + ((i+1)*326 + (i*100)) + \"px\";\n\t\tfor (let j = 0; j < Math.pow(2, num_rounds-i-2); j++) {\n\t\t\tlet foo_span = document.createElement(\"span\");\n\t\t\tlet round_height = j*height*Math.pow(2, i+1) + vertical_round_offset;\n\t\t\tround_height += Math.pow(2, i-1) * height;\n\t\t\tfoo_span.style.position = \"absolute\";\n\t\t\tfoo_span.style.top = round_height + \"px\";\n\n\t\t\tlet bracket = document.createElement(\"img\");\n\t\t\tbracket.src = \"images/bracketcropped.png\";\n\t\t\tbracket.setAttribute(\"height\", height* Math.pow(2, (i)));\n\t\t\tbracket.setAttribute(\"width\", 100);\n\t\t\t\n\t\t\tfoo_span.appendChild(bracket);\n\t\t\tbracket_div.appendChild(foo_span);\n\t\t}\n\t\t\n\t\t// There shouldn't be a bracket image after the last round.\n\t\tif (i != num_rounds-1) {\n\t\t\tbracket_span.appendChild(bracket_div);\n\t\t}\t\n\t}\n}",
"function christmasTreeWithSameToys(n){\n let toys = '^0*&$G*j';\n let str = '';\n for(let i = 1, k = 1; i <= n * 2 - 1; i += 2, k++){\n let index = Math.trunc(Math.random() * toys.length);\n str += (' ').repeat(n - k) + (toys[index]).repeat(i) + (' ').repeat(n - k) + '\\n';\n }\n for(let i = 1; i < n / 2; i++){\n str += (' ').repeat(n - 1) + '|' + (' ').repeat(n - 1) + '\\n';\n }\n return str.slice(0, -1);\n}",
"GenerateBracket() {\n this._bracket = BracketHelper.GenerateBracket(this._participants);\n }",
"function fillDeck(deck){\n\n for(var i = 0; i < Ranks.length; i++){\n deck.push(\n new BindedCard(\n DOMCreateCard(Suits.hearts, Ranks[i]),\n new Card(Suits.hearts, Ranks[i]), \n ))\n }\n\n for(var i = 0; i < Ranks.length; i++){\n deck.push(\n new BindedCard(\n DOMCreateCard(Suits.diamonds, Ranks[i]),\n new Card(Suits.diamonds, Ranks[i]), \n ))\n }\n\n for(var i = 0; i < Ranks.length; i++){\n deck.push(\n new BindedCard(\n DOMCreateCard(Suits.clubs, Ranks[i]),\n new Card(Suits.clubs, Ranks[i]), \n ))\n }\n\n for(var i = 0; i < Ranks.length; i++){\n deck.push(\n new BindedCard(\n DOMCreateCard(Suits.spades, Ranks[i]),\n new Card(Suits.spades, Ranks[i]), \n ))\n }\n\n}",
"function Bracket8TeamDoubleElimFull (teams) {\n\tBracket.call(this, 17, 19);\n\t\n\tthis.description = \"8 Team, Best of 1, Double Elimination with 7th/8th and 5th/6th place matches\"\n\tfor (var i = 0; i < teams.length; i++){\n\t\tthis.teams.push(teams[i]);\n\t}\n\tfor (var i = 0; i < 16; i++){\n\t\tthis.matches.push(new Game());\n\t}\n\tthis.matches[0].team1 = this.teams[0];\n\tthis.matches[0].team2 = this.teams[7];\n\tthis.matches[1].team1 = this.teams[3];\n\tthis.matches[1].team2 = this.teams[4];\n\tthis.matches[2].team1 = this.teams[1];\n\tthis.matches[2].team2 = this.teams[6];\n\tthis.matches[3].team1 = this.teams[2];\n\tthis.matches[3].team2 = this.teams[5];\n\tthis.advancesTo = [6, 6, 7, 7, 8, 9, 13, 13, 12, 12, undefined, undefined, 14, 15, 15];\n\tthis.retreatsTo = [4, 4, 5, 5, 10, 10, 9, 8, 11, 11, undefined, undefined, undefined, 14];\n\tthis.resultsRank= [0,0,0,0,0,0,0,0];\n\t\n\tthis.display[0][0] = \"Round 1\"; this.dispClasses[0][0] = \"b-title\";\n\tthis.display[13][0] = \"Round 2\"; this.dispClasses[13][0] = \"b-title\";\n\tthis.display[0][4] = \"Round 2\"; this.dispClasses[0][4] = \"b-title\";\n\tthis.display[10][4] = \"Round 3\"; this.dispClasses[10][4] = \"b-title\";\n\tthis.display[0][8] = \"Winner's Semifinal\"; this.dispClasses[0][8] = \"b-title\";\n\tthis.display[5][8] = \"Loser's Semifinal\"; this.dispClasses[5][8] = \"b-title\";\n\tthis.display[11][8] = \"7th/8th Place Match\"; this.dispClasses[11][8] = \"b-title\";\n\tthis.display[5][11] = \"3rd Place Match\"; this.dispClasses[5][11] = \"b-title\";\n\tthis.display[11][11] = \"5th/6th Place Match\"; this.dispClasses[11][11] = \"b-title\";\n\tthis.display[2][15] = \"Final\"; this.dispClasses[2][15] = \"b-title\";\n\tthis.dispFill[1][0] = \"m0.t1.\"; this.dispFill[1][1] = \"m0.s1.\"; this.dispFill[2][0] = \"m0.t2.\"; this.dispFill[2][1] = \"m0.s2.\";\n\tthis.dispFill[4][0] = \"m1.t1.\"; this.dispFill[4][1] = \"m1.s1.\"; this.dispFill[5][0] = \"m1.t2.\"; this.dispFill[5][1] = \"m1.s2.\";\n\tthis.dispFill[7][0] = \"m2.t1.\"; this.dispFill[7][1] = \"m2.s1.\"; this.dispFill[8][0] = \"m2.t2.\"; this.dispFill[8][1] = \"m2.s2.\";\n\tthis.dispFill[10][0] = \"m3.t1.\"; this.dispFill[10][1] = \"m3.s1.\"; this.dispFill[11][0] = \"m3.t2.\"; this.dispFill[11][1] = \"m3.s2.\";\n\tthis.dispFill[14][0] = \"m4.t1.\"; this.dispFill[14][1] = \"m4.s1.\"; this.dispFill[15][0] = \"m4.t2.\"; this.dispFill[15][1] = \"m4.s2.\";\n\tthis.dispFill[17][0] = \"m5.t1.\"; this.dispFill[17][1] = \"m5.s1.\"; this.dispFill[18][0] = \"m5.t2.\"; this.dispFill[18][1] = \"m5.s2.\";\n\tthis.dispFill[1][4] = \"m6.t1.\"; this.dispFill[1][5] = \"m6.s1.\"; this.dispFill[2][4] = \"m6.t2.\"; this.dispFill[2][5] = \"m6.s2.\";\n\tthis.dispFill[5][4] = \"m7.t1.\"; this.dispFill[5][5] = \"m7.s1.\"; this.dispFill[6][4] = \"m7.t2.\"; this.dispFill[6][5] = \"m7.s2.\";\n\tthis.dispFill[11][4] = \"m8.t1.\"; this.dispFill[11][5] = \"m8.s1.\"; this.dispFill[12][4] = \"m8.t2.\"; this.dispFill[12][5] = \"m8.s2.\";\n\tthis.dispFill[15][4] = \"m9.t1.\"; this.dispFill[15][5] = \"m9.s1.\"; this.dispFill[16][4] = \"m9.t2.\"; this.dispFill[16][5] = \"m9.s2.\";\n\tthis.dispFill[12][8] = \"m10.t1.\"; this.dispFill[12][9] = \"m10.s1.\"; this.dispFill[13][8] = \"m10.t2.\"; this.dispFill[13][9] = \"m10.s2.\";\n\tthis.dispFill[12][11] = \"m11.t1.\"; this.dispFill[12][12] = \"m11.s1.\"; this.dispFill[13][11] = \"m11.t2.\"; this.dispFill[13][12] = \"m11.s2.\";\n\tthis.dispFill[6][8] = \"m12.t1.\"; this.dispFill[6][9] = \"m12.s1.\"; this.dispFill[7][8] = \"m12.t2.\"; this.dispFill[7][9] = \"m12.s2.\";\n\tthis.dispFill[1][8] = \"m13.t1.\"; this.dispFill[1][9] = \"m13.s1.\"; this.dispFill[2][8] = \"m13.t2.\"; this.dispFill[2][9] = \"m13.s2.\";\n\tthis.dispFill[6][11] = \"m14.t1.\"; this.dispFill[6][12] = \"m14.s1.\"; this.dispFill[7][11] = \"m14.t2.\"; this.dispFill[7][12] = \"m14.s2.\";\n\tthis.dispFill[3][15] = \"m15.t1.\"; this.dispFill[3][16] = \"m15.s1.\"; this.dispFill[4][15] = \"m15.t2.\"; this.dispFill[4][16] = \"m15.s2.\";\n\tthis.dispClasses[1][2] = \"bottom spacing\"; this.dispClasses[4][2] = \"bottom\"; this.dispClasses[7][2] = \"bottom\"; this.dispClasses[10][2] = \"bottom\"; this.dispClasses[14][2] = \"bottom\"; this.dispClasses[17][2] = \"bottom\";\n\tthis.dispClasses[1][3] = \"bottom spacing\"; this.dispClasses[5][3] = \"bottom\"; this.dispClasses[11][3] = \"bottom\"; this.dispClasses[15][3] = \"bottom\";\n\tthis.dispClasses[1][6] = \"bottom spacing\"; this.dispClasses[5][6] = \"bottom\"; this.dispClasses[11][6] = \"bottom\"; this.dispClasses[15][6] = \"bottom\";\n\tthis.dispClasses[1][7] = \"bottom spacing\"; this.dispClasses[6][7] = \"bottom\";\n\tthis.dispClasses[1][10] = \"bottom spacing\"; this.dispClasses[6][10] = \"bottom\"; this.dispClasses[1][11] = \"bottom\"; this.dispClasses[1][12] = \"bottom\";\n\tthis.dispClasses[1][13] = \"bottom spacing\"; this.dispClasses[6][13] = \"bottom\"; this.dispClasses[3][14] = \"bottom spacing\";\n\tvar cols = [3,3,3,3,3,3,3,3, 3, 3, 3, 3, 3, 7,7,7,7,7,7,7,7, 7, 7, 7, 7, 7, 14,14,14,14,14];\n\tvar rows = [2,3,4,6,7,8,9,10,12,13,14,16,17,2,3,4,5,7,8,9,10,11,12,13,14,15,2, 3, 4, 5, 6];\n\tfor (var i = 0; i < rows.length; i++){\n\t\tif (this.dispClasses[rows[i]][cols[i]]){\n\t\t\tthis.dispClasses[rows[i]][cols[i]] += \" left\";\n\t\t} else {\n\t\t\tthis.dispClasses[rows[i]][cols[i]] = \"left\";\n\t\t}\n\t}\n}",
"async function generateBracketsData() {\n // Build Map of opening to closing bracket codepoints\n let response = await fetch('https://www.unicode.org/Public/13.0.0/ucd/BidiBrackets.txt')\n let txt = await response.text()\n let pairs = new Map()\n let reversePairs = new Map()\n txt.split('\\n').forEach(line => {\n line = line.trim()\n if (!line || line.startsWith('#')) return\n const match = line.match(/^([A-Z0-9.]+)\\s*;\\s*([A-Z0-9.]+)\\s*;\\s*o/)\n if (match) {\n const opener = parseInt(match[1], 16)\n const closer = parseInt(match[2], 16)\n pairs.set(opener, closer)\n reversePairs.set(closer, opener)\n }\n })\n\n // Get canonical equivs for each closing bracket\n response = await fetch('https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt')\n txt = await response.text()\n const canonical = new Map()\n txt.split('\\n').forEach(line => {\n if (!line || line.startsWith('#')) return\n const fields = line.split(';')\n const nonCanon = parseInt(fields[0], 16)\n const canon = fields[5] && fields[5].replace(/^<[^>]+>\\s*/, '')\n if (canon && (pairs.has(nonCanon) || reversePairs.has(nonCanon))) {\n canonical.set(\n nonCanon,\n parseInt(canon, 16)\n )\n }\n })\n\n // Encode to strings\n const out = {\n pairs: encodeCodePointsMap(pairs),\n canonical: encodeCodePointsMap(canonical)\n }\n\n const fileContent = `// Bidi bracket pairs data, auto generated\nexport default ${JSON.stringify(out, null, 2)}\n`\n const filePath = new URL('../src/data/bidiBrackets.data.js', import.meta.url)\n writeFileSync(filePath, fileContent)\n\n console.log(`Wrote file ${filePath}, size ${fileContent.length}`)\n}",
"function createFinalDeck() {\n //clear the deck\n finalDeck.splice(0, finalDeck.length);\n //generate 8 new decks and add their elements to the finalDeck which will be played with\n for (var i = 0; i < 8; i++) {\n // console.log('pushing new deck');\n finalDeck.push.apply(finalDeck, generateDeck());\n }\n }",
"function balancedParens(n) {\n let combos = []\n getCombinations = (openNum,closingNum,curr) => {\n if (openNum === 0 && closingNum === 0)\n combos.push(curr);\n if (openNum > 0) {\n getCombinations(openNum-1, closingNum + 1, curr + \"(\");\n }\n if (closingNum > 0) {\n getCombinations(openNum, closingNum - 1, curr + \")\");\n }\n }\n\n getCombinations(n,0,\"\");\n\n return combos;\n}",
"function GenerateParenthesis(n) {\n if (n <= 0) {\n return []\n }\n \n function addCombo(currentCombo, left, right) {\n if (currentCombo.length === n*2) {\n output.push(currentCombo)\n return\n }\n \n if (left < n) \n addCombo(currentCombo + '(', left + 1, right)\n \n \n if (right < left) \n addCombo(currentCombo + ')', left, right + 1)\n \n }\n \n output = []\n addCombo('', 0, 0)\n return output\n}",
"drawBracketed() {\n const ctx = this.context;\n let is_pedal_depressed = false;\n let prev_x;\n let prev_y;\n const pedal = this;\n // Iterate through each note\n this.notes.forEach((note, index, notes) => {\n // Each note triggers the opposite pedal action\n is_pedal_depressed = !is_pedal_depressed;\n // Get the initial coordinates for the note\n let x = 0; // VexFlowPatch (further smaller diffs below)\n if (note) {\n //default to note head begin\n x = note.getNoteHeadBeginX();\n if (this.BeginsStave) {\n x = note.getStave().getNoteStartX();\n }\n } else {\n x = this.endStave.end_x + this.endStaveAddedWidth;\n }\n\n //If this pedal doesn't end a stave...\n if(!this.EndsStave){\n if(note){\n //pedal across a single note or just the end note\n if(!is_pedal_depressed){\n switch(pedal.style) {\n case PedalMarking.Styles.BRACKET_OPEN_END:\n case PedalMarking.Styles.BRACKET_OPEN_BOTH:\n case PedalMarking.Styles.MIXED_OPEN_END:\n x = note.getNoteHeadEndX();\n break;\n default:\n if(this.ChangeEnd){\n //Start in the middle of the note\n x = note.getAbsoluteX();\n } else {\n x = note.getNoteHeadBeginX() - pedal.render_options.text_margin_right;\n this.startMargin = -pedal.render_options.text_margin_right;\n }\n break;\n }\n } else if(this.ChangeBegin){\n x = note.getAbsoluteX();\n }\n }\n } else {\n //Ends stave and we are at the end...\n if(!is_pedal_depressed){\n //IF we are the end, set the end to the stave end\n if(note){\n if(this.ChangeEnd){\n //Start in the middle of the note\n x = note.getAbsoluteX();\n } else {\n x = note.getStave().end_x + this.endStaveAddedWidth - pedal.render_options.text_margin_right;\n }\n } else {\n x = this.endStave.end_x + this.endStaveAddedWidth - pedal.render_options.text_margin_right;\n }\n \n this.endMargin = -pedal.render_options.text_margin_right;\n } else if (this.ChangeBegin){\n x = note.getAbsoluteX();\n }\n }\n\n let stave = this.endStave; // if !note\n if (note) {\n stave = note.getStave();\n }\n let y = stave.getYForBottomText(pedal.line + 3);\n if (prev_y) { // compiler complains if we shorten this\n if (prev_y > y) { // don't slope pedal marking upwards (nonstandard)\n y = prev_y;\n }\n }\n\n // Throw if current note is positioned before the previous note\n if (x < prev_x) {\n // TODO this unnecessarily throws for missing endNote fix\n // throw new Vex.RERR(\n // 'InvalidConfiguration', 'The notes provided must be in order of ascending x positions'\n // );\n }\n\n // Determine if the previous or next note are the same\n // as the current note. We need to keep track of this for\n // when adjustments are made for the release+depress action\n const next_is_same = notes[index + 1] === note;\n const prev_is_same = notes[index - 1] === note;\n\n let x_shift = 0;\n if (is_pedal_depressed) {\n // Adjustment for release+depress\n x_shift = prev_is_same ? 5 : 0;\n\n if ((pedal.style === PedalMarking.Styles.MIXED || pedal.style === PedalMarking.Styles.MIXED_OPEN_END) && !prev_is_same) {\n // For MIXED style, start with text instead of bracket\n if (pedal.custom_depress_text) {\n // If we have custom text, use instead of the default \"Ped\" glyph\n const text_width = ctx.measureText(pedal.custom_depress_text).width;\n ctx.fillText(pedal.custom_depress_text, x - (text_width / 2), y);\n x_shift = (text_width / 2) + pedal.render_options.text_margin_right;\n } else {\n // Render the Ped glyph in position\n drawPedalGlyph('pedal_depress', ctx, x, y, pedal.render_options.glyph_point_size);\n x_shift = 20 + pedal.render_options.text_margin_right;\n }\n } else {\n // Draw start bracket\n ctx.beginPath();\n if (pedal.style === PedalMarking.Styles.BRACKET_OPEN_BEGIN || pedal.style === PedalMarking.Styles.BRACKET_OPEN_BOTH) {\n ctx.moveTo(x + x_shift, y);\n } else {\n if(this.ChangeBegin){\n x += 5;\n }\n ctx.moveTo(x, y - pedal.render_options.bracket_height);\n if(this.ChangeBegin){\n x += 5;\n }\n ctx.lineTo(x + x_shift, y);\n }\n ctx.stroke();\n ctx.closePath();\n }\n } else {\n // Adjustment for release+depress\n x_shift = next_is_same && !this.EndsStave ? -5 : 0;\n\n // Draw end bracket\n ctx.beginPath();\n ctx.moveTo(prev_x, prev_y);\n ctx.lineTo(x + x_shift, y);\n if (pedal.style !== PedalMarking.Styles.BRACKET_OPEN_END && pedal.style !== PedalMarking.Styles.MIXED_OPEN_END &&\n pedal.style !== PedalMarking.Styles.BRACKET_OPEN_BOTH) {\n if(this.ChangeEnd){\n x += 5;\n }\n ctx.lineTo(x, y - pedal.render_options.bracket_height);\n }\n ctx.stroke();\n ctx.closePath();\n }\n\n // Store previous coordinates\n prev_x = x + x_shift;\n prev_y = y;\n });\n }",
"function balacedBracket(input) {\n let stack = [] // \"the stack\" will be represented as an array\n const openers = [\"{\", \"[\", \"(\"] // opening brackets\n const closers = [\"}\", \"]\", \")\"] // closing brackets, with corresponding indices\n\n // Iterate over each character in the input string\n for (let i = 0; i < input.length; i++) {\n // If the character is an opening bracket, add it to the stack\n if (openers.includes(input[i])) {\n stack.push(input[i])\n // If the character is a closing bracket, we need to check if it closes the most recently added opening bracket\n } else if (closers.includes(input[i])) {\n // Compare the type of bracket with the most recently added element on the stack\n if (closers.indexOf(input[i]) === openers.indexOf(stack[stack.length - 1])) {\n // If it matches and hence 'closes' the most recently added element on the stack, remove the last element from the stack\n stack.pop()\n } else {\n // It doesn't match, and we have an unbalanced bracket input string\n console.log(\"NO\")\n return 0\n }\n }\n }\n // If we iterate through the entire input string and successfully open and close all bracket pairs,\n // the input is balanced, so return yes.\n console.log(\"YES\")\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
convert the link root for aliCloud and amazonCloud | convertLinkRoot(json){
var txt = JSON.stringify(json);
var newTxt = txt.replace(/\/\/doporro-hangzhou.oss-cn-hangzhou.aliyuncs.com\/DE-Product-Images\//g, "//s3.eu-central-1.amazonaws.com/manufacture-shop-pictures/");
return JSON.parse(newTxt);
} | [
"function getBaseLink (link) {\n var tmpLinkArr = link.split(/\\//)\n return tmpLinkArr.slice(0, 3).join('/')\n }",
"function mapUrl(url) {\n\n if (url.includes(\"//www.dropbox.com\")) {\n return url.replace(\"//www.dropbox.com\", \"//dl.dropboxusercontent.com\");\n }\n else if (url.includes(\"//drive.google.com\")) {\n return igv.Google.driveDownloadURL(url);\n }\n else if (url.includes(\"//www.broadinstitute.org/igvdata\")) {\n return url.replace(\"//www.broadinstitute.org/igvdata\", \"//data.broadinstitute.org/igvdata\");\n }\n else {\n return url;\n }\n }",
"_build_link(){\n\n\t\tconst link_data = [\n\t\t\tthis.opts.link_version,\n\t\t\tthis.opts.link_random_data,\n\t\t\tbtoa(this.names.flat().join(\"/\") + \"|\" + this.mapping.join(\"/\"))\n\t\t].join(\".\")\n\n\t\treturn `${this.opts.link_root}${link_data}`\n\t}",
"get urlRoot() {\n\t\t//for ask or show HN stories\n\t\tif(this.isLocalHNUrl){\n\t\t\treturn ''; \n\t\t}\n\t\t//removes first part of url (http://www.)\n\t\tvar base_url = this.url;\n\t\tbase_url = base_url.replace(/^http(s)?:\\/\\/(www.)?/, '');\n\t\t//removes subfolders from url (/index.html)\n\t\tbase_url = base_url.replace(/\\/.*$/, '');\n\t\t//removes get requests from url (?q=something)\n\t\treturn '(' + base_url.replace(/\\?.*$/,'') + ')';\n\t}",
"function normalizeUrlRoot(urlRoot) {\n urlRoot = urlRoot.replace(/^\\/|\\/$/g, \"\") + \"/\";\n if (!/^https?:\\/\\//.test(urlRoot))\n urlRoot = \"/\"+urlRoot;\n return urlRoot;\n }",
"function _links_add_base($m) {\n global $_links_add_base;\n //1 = attribute name 2 = quotation mark 3 = URL\n return $m[1] . '=' . $m[2] .\n ( preg_match( '#^(\\w{1,20}):#', $m[3], $protocol ) && in_array( $protocol[1], wp_allowed_protocols() ) ?\n $m[3] :\n path_join( $_links_add_base, $m[3] ) )\n . $m[2];\n }",
"function normalizeLink(s) {\n return s.replace(/\\\\/g, '/');\n}",
"_formatAmazonUrl(url) {\n if (url == null) {\n return null;\n }\n\n var indexStart = url.indexOf('/dp/');\n var indexEnd = indexStart + 14;\n var amazonUrl = \"https://www.amazon.ca\" + url.substring(indexStart, indexEnd);\n\n return amazonUrl;\n }",
"function getRootURL() {return /https?:\\/\\/[a-zA-Z0-9]+\\.([^\\/]+)/i.exec(document.URL)[1];}",
"p2l_converter(link, path) {\r\n if (!path) return null;\r\n\r\n // Path to Link converter\r\n const slash = process.platform === \"win32\" || path.includes(\"\\\\\") ? \"\\\\\" : \"/\";\r\n const sroot = this.constants().file.locations.root;\r\n const storage = sroot.storage.source(false);\r\n const actualPath = [];\r\n const splitPath = path.split(slash);\r\n\r\n splitPath.forEach((split) => {\r\n if (storage === split || actualPath.length !== 0) {\r\n actualPath.push(split);\r\n }\r\n });\r\n\r\n return link + actualPath.join(\"/\");\r\n }",
"function makeUrl (url) {\n url = url.replace(/\\/$/,'');\n return [ARCHIVE_BASE_URL, '*', url].join('/');\n }",
"function convertWeatherIconLink(link) {\n var icon = link.split(\"/\").pop();\n return \"http://icons.wxug.com/i/c/j/\"+icon;\n}",
"function mapUrl(url) {\n\n if (url.includes(\"//www.dropbox.com\")) {\n return url.replace(\"//www.dropbox.com\", \"//dl.dropboxusercontent.com\");\n }\n else if (url.includes(\"//drive.google.com\")) {\n return igv.Google.driveDownloadURL(url);\n }\n else {\n return url;\n }\n }",
"function setArgosLink(item){\n\tvar deal_image = item.deal_image;\n\tvar splitSrc = deal_image.split(\"/\");\n\tvar imageName = splitSrc[(splitSrc.length)-1];\n\tvar splitImage = imageName.split(\".\");\n\treturn splitImage[0];\t\n}",
"prismicLinkResolver (ctx, doc) {\n if (doc.isBroken) {\n return;\n }\n\n // For prismic collection files append 'index.html'\n // Leave it out for prismic link paths\n var filename = doc.data ? 'index.html' : '';\n switch (doc.type) {\n case 'home':\n return '/' + filename;\n default:\n return '/' + doc.type + '/' + (doc.uid || doc.slug) + '/' + filename;\n }\n }",
"function getRootUrl() { var a = window.location.protocol + \"//\" + (window.location.hostname || window.location.host); if (window.location.port || !1) a += \":\" + window.location.port; return a += \"/\", a; }",
"function convertUrl(url) {\n if (url.includes(\"github.com\")) {\n // get count of '/' in the url\n // if count is 4, then return the url\n if (url.split(\"/\").length === 4) {\n console.log(\"url is already in the preferred format\");\n console.log(url);\n return url;\n }\n else if (url.split(\"/\").length > 4) {\n // split the url at '/tree'\n // return the url before '/tree'\n console.log(url.split(\"/tree\")[0]);\n return url.split(\"/tree\")[0];\n }\n else {\n return \"https://github.com/\";\n }\n\n }\n else if (url.includes(\"gitlab.com\")) {\n if (url.includes(\"/-/\")) {\n url = url.split(\"/-/\")[0];\n }\n return url + \".git\";\n }\n else if (url.includes(\"bitbucket.org\")) {\n // split the url at '/src'\n // return the url before '/src'\n return url.split(\"/src\")[0] + \".git\";\n }\n else if (url.includes(\"git.savannah.gnu.org\")) {\n return url;\n }\n else if (url.includes(\"codeberg.org\")) {\n return url + \".git\";\n }\n else {\n return url;\n }\n}",
"function buildAmzLink(listItem) {\n var itemName = listItem.itemName.split(\" \");\n var amazonRef = \"https:\" +\"/\"+\"/\"+ \"www.amazon.com\" + \"/\" + \"s?k=\" + itemName[0];\n\n for(i=1; i<itemName.length; i++){\n amazonRef += \"+\" + itemName[i];\n }\n return amazonRef;\n }",
"function constructIgUri(igServer){\n var uri = \"\";\n\n uri = igServer.protocol + \"://\" + igServer.host\n\n return uri;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Carga una imagen de la ruta | function cargarImagen(ruta) {
root.actividad = 0
mapa.ocultarCanvas()
marca1.reset()
marca2.reset()
marca3.reset()
marca4.reset()
Glo.hayTrazoRojo = false
Glo.hayTrazoVerde = false
// ocultamos para liberar memoria (@todo: refactorizar)
mapa.ocultarTrazos()
mapa.mostrarTrazos()
miProxy.cargarImagen(ruta)
mapa.actualizImagen()
barraTabs.habilitarTab(1)
barraTabs.habilitarTab(2)
barraTabs.habilitarTab(3)
barraTabs.habilitarTab(4)
barraTabs.habilitarTab(5)
} | [
"function cargarImagenArticulo()\n{\n\tif(($photo.length != 0)){\n\t\t$('#preview img').attr('src', $basePath +\"/public/img/inventories/\"+ $photo);\n\t}\n}",
"function limpiar_foto(img_foto)\n{\n img_foto.src = \"../../../kernel/images/tools20/blanco.jpg\";\n}",
"function mostrarFoto(file, imagen) {\n var reader = new FileReader();\n reader.addEventListener(\"load\", function () {\n imagen.src = reader.result;\n });\n reader.readAsDataURL(file);\n}",
"function pasarFoto() {\r\n // se incrementa el indice (posicionActual)\r\n\r\n // ...y se muestra la imagen que toca.\r\n }",
"precargar(){\r\n this.gif = this.app.createImg('./Recursos/Balon.gif');\r\n this.gif.size(95, 95);\r\n }",
"function ocultarImagenes(){\n\tfor(var a=0;a<imagenesOcultas.length;a++){\n\t\timagenesOcultas[a].src=\"imagenes/parejas/atras.png\";\n\t}\n}",
"function imagen(){\n\t\tsubirImagen(\"#form_imagen\", \"imagen\", \"#foto\", \"imagen_registrar\");\n\t}",
"function getImage() {\n // Retrieve image file location from specified source\n \n\tnavigator.camera.getPicture(abrirProfFotoSubir, function(message) {\n\t\t\tnavigator.notification.alert('Error al recuperar una imagen',okAlert,'MIA','Cerrar');\n },{\n quality: 50,\n destinationType: navigator.camera.DestinationType.FILE_URI,\n sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY\n }\n );\n \n \n\n }",
"function cargaImagenes() {\n for (var i = 0; i < 12; i++) {\n fuentesNotas[i] = p.loadImage(\"fuentes/\" + i + \".png\");\n }\n }",
"function loadImg(name){\r\n\tvar img = new Image(WIDTH, HEIGHT);\r\n\timg.onerror = function() {\r\n\t // doesn't exist or error loading\r\n\t console.log(\"There is no image\");\r\n\t};\r\n img.onload = function() {\r\n\t // code to set the src on success\r\n\t var imgTag = document.getElementById(\"disc\");\r\n\t imgTag.setAttribute('src', this.src);\r\n\t\timgTag.setAttribute('style', 'width:' + WIDTH + 'px;' + 'height:' + HEIGHT + 'px;');\r\n\t};\r\n\timg.src = IMG_FOLDER + name;\r\n\tconsole.log(img);\r\n\t//console.log(\"img nummer: \" + imgNum);\r\n\t//console.log(\"last image: \" + lastImg);\r\n}",
"function img(ref){ return pack_grafico + \"img/\" + idioma + \"/\" + ref; }",
"function buscaImagem(){\n\tvar funcao = 'cd_id=1'; //LEMBRAR DE ARRUMAR\n\tAJAX(SERVLET_IMAGEM, funcao, function(retorno){\n\t\t\n\t\tvar baseString = retorno;\n\t\t// data:image/png;base64\n\t\t\n\t\tif(empty(baseString)){\n\t\t\t$(\"#imagem\").prop('src',\"\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif(baseString.substring(0,4) != \"data\"){\n\t\t\tbaseString = \"data:image/png;base64,\" + baseString;\n\t\t}\n\t\t\n\t\t$(\"#imagem\").prop('src',baseString);\t\n\t});\n}",
"function cargaImagenes() {\n for (var i = 0; i < 13; i++) {\n fuentesNotas[i] = p.loadImage(\"fuentes/\" + i + \".png\");\n }\n }",
"function loadImage(firstLoad){\n img = new Image()\n zoomed = false\n if (!firstLoad){\n basename = images[curIndex]\n }\n src = path.join(dirname, basename)\n img.src = src\n img.onload = () => {\n setOriDim()\n setSvgDim()\n setDefaultScale()\n setImgDim()\n setImgPos()\n updateImg()\n setTitle()\n }\n}",
"function capturarImagemFachada(){\n navigator.camera.getPicture(capturarSuccessFachada, capturarFail,\n {\n destinationType : Camera.DestinationType.FILE_URI,\n sourceType : Camera.PictureSourceType.CAMERA\n });\n}",
"function setImage(loadedImageFile) {\n img = loadedImageFile;\n}",
"function img_res(fileName) {\n var i = new Image();\n i.src = \"img/\"+fileName;\n return i;\n}",
"function cargarListaImagenes(lista,padre){\n\n\t\tvar i;\t\n\t\t\t\tfor(i=0;i<lista.length;i++){\n\t\t\t\tvar img = document.createElement('img');\n\t\t\t\timg.src = \"Imagenes/\"+lista[i][1];\n\t\t\t\timg.style.width = '80px';\n img.style.height = '80px';\n\t\t\t\tconsole.log(img.src);\n\t\t\t\tpadre.appendChild(img);\n\t\t}\t\t\n}",
"function retrocederFoto() {\r\n // se incrementa el indice (posicionActual)\r\n posicionActual--;\r\n if (posicionActual < 0) {\r\n posicionActual = IMAGENES.length - 1;\r\n }\r\n // ...y se muestra la imagen que toca.\r\n renderizarImagen();\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a list of free time slots between the given bookings | function getFreeBookingSlots(list, min_size = 30) {
/* istanbul ignore else */
if (!list) {
return [
{
start: 0,
end: Object(date_fns__WEBPACK_IMPORTED_MODULE_1__["startOfMinute"])(new Date()).getTime() * 10,
},
];
}
const slots = [];
let start = new Date(0);
list.sort((a, b) => a.date - b.date);
for (const booking of list) {
const bkn_start = new Date(booking.date);
const bkn_end = Object(date_fns__WEBPACK_IMPORTED_MODULE_1__["add"])(bkn_start, { minutes: booking.duration });
if (Object(date_fns__WEBPACK_IMPORTED_MODULE_1__["isAfter"])(bkn_start, start)) {
const diff = Math.abs(Object(date_fns__WEBPACK_IMPORTED_MODULE_1__["differenceInMinutes"])(bkn_start, start));
/* istanbul ignore else */
if (diff >= min_size) {
slots.push({ start: start.valueOf(), end: bkn_start.valueOf() });
}
start = bkn_end;
}
else if (Object(date_fns__WEBPACK_IMPORTED_MODULE_1__["startOfMinute"])(start).getTime() === Object(date_fns__WEBPACK_IMPORTED_MODULE_1__["startOfMinute"])(bkn_start).getTime()) {
start = bkn_end;
}
}
slots.push({
start: start.getTime(),
end: Object(date_fns__WEBPACK_IMPORTED_MODULE_1__["startOfMinute"])(new Date()).getTime() * 10,
});
return slots;
} | [
"function getFreeBookingSlots(list, min_size = 30) {\n if (!list) {\n return [\n {\n start: 0,\n end: dayjs__WEBPACK_IMPORTED_MODULE_4__().startOf('m').valueOf() * 10,\n },\n ];\n }\n const slots = [];\n let start = dayjs__WEBPACK_IMPORTED_MODULE_4__(0);\n list.sort((a, b) => a.date - b.date);\n for (const booking of list) {\n const bkn_start = dayjs__WEBPACK_IMPORTED_MODULE_4__(booking.date);\n const bkn_end = bkn_start.add(booking.duration, 'm');\n if (bkn_start.isAfter(start)) {\n const diff = Math.abs(bkn_start.diff(start, 'm'));\n if (diff >= min_size) {\n slots.push({ start: start.valueOf(), end: bkn_start.valueOf() });\n }\n start = bkn_end;\n }\n else if (start.startOf('m').valueOf() === bkn_start.startOf('m').valueOf()) {\n start = bkn_end;\n }\n }\n slots.push({\n start: start.valueOf(),\n end: dayjs__WEBPACK_IMPORTED_MODULE_4__().startOf('m').valueOf() * 10,\n });\n return slots;\n}",
"function getBookedTables (bookings) {\n var currentTime = new Date()\n var bookedTables = []\n bookings.forEach(function (booking) {\n // console.log(booking.time.substring(0,2))\n if (parseInt(booking.time.substring(0, 2)) <= currentTime.getHours() && parseInt(booking.time.substring(0, 2)) + 1 >= currentTime.getHours()) {\n bookedTables.push(parseInt(booking.tableID))\n }\n })\n return bookedTables\n}",
"function getAvailableTimes(formInput, listOfBusyTimes) {\n\n console.log(listOfBusyTimes);\n\n var today = new Date(formInput.startDate);\n var tomorrow = new Date(formInput.endDate);\n tomorrow.setDate(tomorrow.getDate() + 1);\n\n var timeslots = createIntervals(today, tomorrow, formInput.length);\n\n //for each element in the list of busy times\n for (var i = 0; i < listOfBusyTimes.length; i++) {\n\n var startDate = new Date(listOfBusyTimes[i].start);\n var endDate = new Date(listOfBusyTimes[i].end);\n\n //for each timeslot, see if it conflicts with the busy time\n //NOTE: DOES THIS FUCK UP SCHEDULING AT THE LAST AVAILABLE TIME?\n\n // what about 15 minute intervals\n\n for (var x = 0; x < timeslots.length-1; x++) {\n\n //calendar event starts in this timeslot\n if (startDate >= timeslots[x].time && startDate < timeslots[x+1].time ) {\n timeslots[x].free = false;\n }\n\n //calendar event bleeds into this timeslot from a previous start\n if (startDate <= timeslots[x].time && endDate > timeslots[x].time) {\n timeslots[x].free = false;\n }\n }\n }\n\n console.log(timeslots);\n\n spaceLines();\n\n appendPre('Available Times: \\n');\n\n var availabilityBlocks = [];\n\n for (var i = 0; i < timeslots.length; i++) {\n if (timeslots[i].free) {\n\n \tvar availBlock = {\n \t 'first': timeslots[i].time,\n \t 'last': timeslots[i].time\n \t};\n\n var ogDate = timeslots[i].time.getDate();\n\n while (i < timeslots.length) {\n\n if(timeslots[i].free) {\n\n if (i == timeslots.length-1) { break; }\n\n //if the timeslot is a different day, wind back a slot and break\n if (timeslots[i].time.getDate() != ogDate) { i--; break; }\n\n i++;\n\n } else {\n break;\n }\n }\n\n availBlock.last = timeslots[i].time;\n availabilityBlocks.push(availBlock);\n\n }\n }\n\n console.log(availabilityBlocks);\n\n appendPre(\"Times in \" + Intl.DateTimeFormat().resolvedOptions().timeZone.toString() + \" time. \\n\");\n\n var lastDateString = \"\";\n\n for (block in availabilityBlocks) {\n\n \tvar firstTime = availabilityBlocks[block].first;\n \tvar lastTime = availabilityBlocks[block].last;\n\n \t//print the date – \"Sat Jun 29, 2019\"\n\n \tvar dateString = dayNames[firstTime.getDay()] + \" \" + monthNames[firstTime.getMonth()] + \" \" +\n \t firstTime.getDate() + \", \" + firstTime.getFullYear();\n\n \tif (dateString != lastDateString) {\n \t\tappendPre(\"\\n\" + dateString);\n \t\tlastDateString = dateString;\n \t}\n\n \tvar firstTimeString = addZeroBefore(firstTime.getHours()) + \":\" + \n \t\t\t\t\t\t addZeroBefore(firstTime.getMinutes());\n \tvar lastTimeString = addZeroBefore(lastTime.getHours()) + \":\" + \n \t\t\t\t\t\t addZeroBefore(lastTime.getMinutes());\n\n \tappendPre(\" * \" + firstTimeString + \" - \" + lastTimeString);\n\n\n }\n\n spaceLines();\n\n}",
"function detFreeTime(appointments)\n{\n var freeBlocks = new Array();\n\n var freeStart = new Date(); // current date and time\n\n // For the first block, the currentAppt start date is at least 30 minutes from now\n if(freeStart.getMinutes() < 30)\n freeStart.addMinutes(30-freeStart.getMinutes());\n else\n freeStart.addMinutes(60-freeStart.getMinutes());\n\n if(appointments.length)\n {\n // End the first block of free time at the next appt\n var freeEnd = new Date(appointments[0].startDate);\n for (let curAppt of appointments)\n {\n // Only consider appt if it ends after the previous appt ends\n var nextStart = new Date(curAppt.endDate);\n if (nextStart > freeStart)\n {\n // Try block from end of previous to start of current appointment\n freeEnd = new Date(curAppt.startDate);\n \n var minEndDate = new Date(freeStart);\n minEndDate.addMinutes(30);\n \n // Don't use a block of time less than 30 minutes long; keep\n // iterating until you find space\n if(freeEnd >= minEndDate)\n {\n var curBlock = new Block(freeStart, freeEnd);\n freeBlocks.push(curBlock);\n }\n\n freeStart = new Date(nextStart);\n }\n }\n }\n \n freeEnd = new Date(freeStart);\n freeEnd.addMinutes(60000);\n curBlock = new Block(freeStart, freeEnd);\n freeBlocks.push(curBlock);\n\n return freeBlocks;\n}",
"function createSlots(\n startSlot,\n n,\n opts = { duration: 60, buffer: 20, lunch: 30 }\n) {\n const { duration, buffer, lunch } = opts;\n const slots = [];\n let end = moment(startSlot, \"HH:mm\");\n for (var i = 0; i < n; i++) {\n let start = moment(end);\n end.add(duration, \"m\");\n // print slot duration\n slots.push(`${start.format(\"HH:mm\")} – ${end.format(\"HH:mm\")}`);\n end.add(buffer, \"m\");\n // add lunch break\n if (start.hour() < 12 && end.hour() > 12) {\n end.add(lunch, \"m\");\n }\n }\n return slots;\n}",
"function getTimeSlots() {\n var start = new Date('2018-01-01T10:00:00+00:00');\n var timeSlots = {};\n \n for (var i = 0; i < NUM_SLOTS; i++) {\n var time = Utilities.formatDate(start, Session.getScriptTimeZone(), 'HH:mm');\n timeSlots[time] = i;\n start.setMinutes(start.getMinutes() + 15);\n }\n return timeSlots;\n}",
"function timeSlotCreator(end, numberOfSlots) {\n let i = 0;\n const slots = [];\n const TIME_PER_SLOT = 0.5; // this is fixed to 30 minutes according to specification.\n while (i < numberOfSlots) {\n slots.push({\"start\": end-TIME_PER_SLOT, \"end\": end});\n end -= TIME_PER_SLOT;\n i++;\n }\n return slots;\n}",
"function availableAppointmentSlotsCreator(booked, possible) {\n const availableAppointments = [];\n let shouldBeAdded = true;\n for (const appointment of possible) {\n for (const bookedAppointment of booked) {\n if (_.isEqual(appointment, bookedAppointment)) {\n shouldBeAdded = false;\n }\n }\n if(shouldBeAdded) {\n availableAppointments.push(appointment);\n }\n shouldBeAdded = true;\n }\n return availableAppointments; //this might need to be turned into a proper json object for consistency.\n}",
"function generateTimeSlots(shift) {\n // starting at 600, keep adding 15 to it, and everytime you do, add {num: 2} to your dict\n var timeSlots = {}\n\n for(var t = shift.start; t <= shift.end; t += shift.interval) {\n timeSlots[t] = shift.tables\n }\n\n return timeSlots\n }",
"function getAvailableTimes(rooms) {\n \n // Append the available times.\n $('#leftColumn').append('<h3 class=\"ui-widget-header\">Available Times</h3>');\n \n // Get the data from the space browsing page.\n $.get('https://marrs-gsb.stanford.edu/marrs/BrowseForSpace.aspx', function(data) {\n $output = $('<div></div>');\n \n // Lop through all the rooms.\n for (index = 0; index < rooms.length; index++) {\n // Set some defaults.\n lists = '<ul>';\n times = [];\n \n // Find the room information and loop through all the reservations.\n $(data).find('a[title^=\"' + rooms[index] + '\"]').parent().parent().parent().find('.e.eb.ec').each(function() {\n \n // Parse out the length and time of the reservation.\n attributes = $(this).attr('style').split(';width:');\n apptTime = attributes[0].replace('left:', '').replace('.00%', '');\n apptLength = attributes[1].replace('.00%', '');\n \n apptTime = parseInt(apptTime) - 8;\n apptLength = parseInt(apptLength);\n \n // Build the time array with all the times and the lengths.\n times[apptTime] = apptLength;\n });\n \n startTime = 28;\n ranges = {};\n \n // Loop through all the times and create availability ranges.\n for (i = 28; i<=88; i++) {\n if (times[i]) {\n if (startTime != i) {\n ranges[startTime] = i;\n }\n \n i = i + times[i] - 1;\n startTime = i + 1;\n }\n }\n \n // Add the last range.\n if (startTime < 88) {\n ranges[startTime] = 88;\n }\n \n // Convert the ranges into times and add them as li's\n for (start in ranges) {\n startTime = convertTime(start);\n endTime = convertTime(ranges[start]);\n lists += '<li>' + startTime + ' - ' + endTime + '</li>';\n }\n \n // Close our list.\n lists += '</ul>';\n \n // Append the room title to the output.\n $output.append('<h4>' + rooms[index] + '</h4>');\n \n // Append the list.\n $output.append(lists);\n }\n \n // Append it to the page.\n $('#leftColumn').append($output);\n });\n \n // This is needed because the session tends to timeout if we don't recall the url.\n $.get(document.URL, function(data) {\n });\n }",
"function calcFreeTime(busyTimesArray) {\n let freeTime = [0, 1440];\n\n for(let i = 0; i < busyTimesArray.length; i++) {\n let busyTime = busyTimesArray[i].split(\" to \");\n let startBusy = toSeconds(busyTime[0]);\n let endBusy = toSeconds(busyTime[1]);\n\n for(let j = 0; j < freeTime.length; j++) {\n if (freeTime[j] < startBusy) {\n\n }\n }\n }\n}",
"function getComingReservations(roomUsages){\n\tvar comingReservations = [];\n\tvar today = new moment().format(\"YYYY-MM-DD\");\n\t$.each(roomUsages, function(inedx, roomUsage){\n\t\tif(roomUsage.reservedDate > today){\n\t\t\tcomingReservations.push(roomUsage);\n\t\t}\n\t});\n\treturn comingReservations;\n}",
"function meetingPlanner(slotsA, slotsB, dur) {\n\n let timeA = slotsA\n let timeB = slotsB\n \n let lower = 0\n let upper = 0\n \n let pointerA = 0\n let pointerB = 0\n \n while(pointerA < timeA.length && pointerB < timeB.length){\n let slot1 = timeA[pointerA]\n let slot2 = timeB[pointerB]\n if(slot1[0] >= slot2[0]) {\n lower = slot1[0]\n } else {\n lower = slot2[0]\n }\n \n if(slot1[1] >= slot2[1]) {\n upper = slot2[1]\n } else {\n upper = slot1[1]\n }\n \n if(upper - lower >= dur){\n if(lower + dur < upper){\n return [lower, lower+dur]\n } else {\n return [lower, upper]\n }\n }\n \n else {\n if(slot1[1] >= slot2[1]){\n pointerB++\n } else {\n pointerA++\n }\n }\n }\n return []\n }",
"function requestToBook() {\n let booked = [...bookings];\n let requests = generateRequests(10, 4); // wanted to test a bit more - so I'm generating these, but they can overlap\n console.log(\"original bookings: \", bookings);\n console.log(\"randomly generated requests: \", requests);\n let allBookings = requests\n .reduce((results, request) => {\n if (\n booked.reduce((acc, booking) => acc && !overlap(request, booking), true)\n ) {\n results.push(request);\n }\n return results;\n }, booked)\n .sort((a, b) => a.start - b.start);\n console.log(\"all bookings: \", allBookings);\n return allBookings;\n}",
"function generateTimeslots(timeInterval, startTime, endTime, storeId, maxPeoplePerSlot) {\n // Assert valid time interval.\n if (timeInterval < 20 || timeInterval > 60 || timeInterval % 10 !== 0) {\n throw new Error('Can only accept 20, 30, 60')\n }\n \n // Break down start and end hours/minutes.\n const [startHour, startMinute] = startTime.split(':')\n const endMinute = endTime.split(':')[1]\n \n // Check for interval validity with regards to start and end times.\n const validIntervalMap = {\n 20: ['00', '20', '40'],\n 30: ['00', '30'],\n 60: ['00'],\n }\n if (\n validIntervalMap[timeInterval].indexOf(startMinute) === -1 ||\n validIntervalMap[timeInterval].indexOf(endMinute) === -1\n ) {\n throw new Error('Incorrect time interval')\n }\n \n // Dumb time slot class.\n class Time {\n constructor (hour, minute) {\n this.hour = parseInt(hour, 10)\n this.minute = parseInt(minute, 10)\n }\n \n /**\n * Return formatted time as string of hour:minute\n *\n * @returns {string}\n */\n get () {\n let formatted = { hour: this.hour, minute: this.minute }\n for (let prop in formatted) {\n if (formatted[prop] < 10) {\n formatted[prop] = `0${formatted[prop]}`\n }\n }\n return `${formatted.hour}:${formatted.minute}`\n }\n \n /**\n * Add minutes to a time\n *\n * @param {number} minute\n * @returns {string}\n */\n add (minute) {\n const newMinute = this.minute + minute\n if (newMinute >= 60) {\n this.hour += parseInt(newMinute / 60, 10)\n this.minute = newMinute % 60\n } else {\n this.minute = newMinute\n }\n \n return this.get()\n }\n }\n \n // Instantiate start and end times\n const start = new Time(startHour, startMinute)\n // Add the first slot.\n const slots = [start.get()]\n \n // Keep adding slots until the expected end slot is reached.\n while (slots.lastIndexOf(endTime) === -1) {\n slots.push(start.add(timeInterval))\n }\n\n const pairedSlots = generatePairs(slots, startTime, endTime, storeId, maxPeoplePerSlot);\n \n return pairedSlots; \n }",
"function getAvailableTimes(hours, appointments, stylist_id, todayIndex){\n\tvar startH = Number(hours[todayIndex].open.hours);\n\tvar startM = Number(hours[todayIndex].open.minutes);\n\tvar closeH = Number(hours[todayIndex].close.hours);\n\tvar closeM = Number(hours[todayIndex].close.minutes);\n\n\tvar unavailable = extractStylistAppointments(appointments, stylist_id);\n\n\tvar unavailableHours = new Array();\n\tfor(var i = 0; i < unavailable.length; i++)\n\t{\n\t\tunavailableHours.push(unavailable[i][0]);\n\t}\n\n\tvar available = new Array();\n\n\t//NOTE: I HAVE NO IDEA WHY TWO LOOPS OF THE SAME THING ARE NEEDED HERE\n\t//BUT FOR SOME REASON WHEN I COMMENT IT OUT IT ONLY SHOWS THE FIRST APPOINTMENT TIME\n\t//I AM SO CONFUSED!?!?!\n\t//I HOPE MY CAPS LOCK IS INDICATING MY CONFUSION\n\tfor(var i = startH; i < closeH; i++)\n\t{\n\n\t\tfor(var i = startH; i < closeH; i++)\n\t\t{\n\t\t\t\tif(unavailableHours.indexOf(i) < 0 && !availableContains(i, available))\n\t\t\t\t{\n\t\t\t\t\tavailable.push([i, startM]);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t}\n\n\t}\n\tvar formattedTimes = new Array();\n\n\tfor(var i = 0; i < available.length; i++)\n\t{\n\t\tvar time = formatTime(available[i][0], available[i][1]);\n\t\tformattedTimes.push(time);\n\t}\n\n\t// return ['9:00 AM', '10:00 AM', '1:00 PM', '3:00 PM'];\n\treturn formattedTimes;\n}",
"async getAvailabilities() {\n const bkgs = await getBookings(this.props.token, this.props.userType, this.props.userName).then()\n var avs = []\n\n var future = false\n var currentTime = roundedCurrentTime(30)\n var formattedTime = formatTime(currentTime)\n var next = formatTime(nextSlot(currentTime, 30))\n var nextNext = formatTime(nextSlot(currentTime, 60))\n\n // Filter available timeslots from booked timeslots\n for (let i = 0; i < bkgs.length; i++) { \n if (bkgs[i][\"customer\"] === null) { \n\n // Only add slots in the future\n if (future)\n avs.push(bkgs[i]) \n if (parseDateString(bkgs[i][\"timeslot\"][\"date\"]) > parseDateString(formattedTime) || parseDateString(bkgs[i][\"timeslot\"][\"date\"]) > parseDateString(next) ||parseDateString(bkgs[i][\"timeslot\"][\"date\"]) > parseDateString(nextNext)) { \n future = true\n }\n\n }\n }\n this.setState({availabilites: avs})\n return avs\n }",
"function meetingPlanner(slotsA, slotsB, dur){\n let iA=0;\n let iB=0;\n let start;\n let end;\n\n while (iA < slotsA.length && iB < slotsB.length){\n start = Math.max(slotsA[iA][0], slotsB[iB][0]);\n end = Math.min(slotsA[iA][1], slotsB[iB][1]);\n\n if (start + dur <= end) return [start, start+dur];\n\n if (slotsA[iA][1] <= slotsB[iB][1]) {\n iA++;\n } else {\n iB++;\n }\n }\n\n return [];\n}",
"function createTimeSlots(){\n\tfor(var i = 0; i <= 6; ++i){\n\t\tfor (var j = 8; j < 24; ++j){\n\t\t\tdb.run(`insert into timeslots (day, startTime, endTime) values (?, ?, ?)`, [i, j, j+1]);\n\t\t}\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
textSentiments function receives a text string and sentiment score object. Returns the sentiment score of the text. | function textSentiment(text,sentimentobject){
var sentiment_score = 0
var words = text.split(/[^\w\']/).filter(function(el) {return el.length != 0}); // Splits the text in to words.Filters empty strings.
var wordlen = words.length
for(var i=0;i<wordlen;i++){
if(words[i] in sentimentobject){
sentiment_score = sentiment_score + sentimentobject[words[i]]
}
}
return sentiment_score
} | [
"function sentimentText(aTextSentences, sLangCode) {\n\n // Output\n var sentiment = {\n score: 0,\n comparative: 0,\n vote: 'neutral',\n accuracy: 0,\n meanings: [],\n positive: [],\n negative: []\n };\n\n // Iterate over array of sentences\n for (var i = 0; i < aTextSentences.length; i++) {\n var sentenceSentiment = sentimentSentence(aTextSentences[i], sLangCode);\n sentiment.score += sentenceSentiment.score;\n var meanings = sentiment.meanings.concat(sentenceSentiment.meanings);\n sentiment.meanings = meanings;\n var positive = sentiment.positive.concat(sentenceSentiment.positive);\n sentiment.positive = positive;\n var negative = sentiment.negative.concat(sentenceSentiment.negative);\n sentiment.negative = negative;\n }\n\n // Handle vote\n if (sentiment.score > 0) {\n sentiment.vote = 'positive';\n } else if (sentiment.score < 0) {\n sentiment.vote = 'negative';\n }\n\n // Accuracy\n // Returns a percentage of words evaluated as sentimental\n // against all meaningful words (all tokens, stopwords excluded)\n sentiment.accuracy = (sentiment.positive.length + sentiment.negative.length) * 100 / sentiment.meanings.length;\n\n // Comparative\n sentiment.comparative = sentiment.score / sentiment.meanings.length;\n\n return sentiment;\n}",
"function analyzeSentimentOfText(text) {\n console.log(process.env.GOOGLE_AUTH_JSON_PATH)\n const client = new language.LanguageServiceClient({\n keyFilename: process.env.GOOGLE_AUTH_JSON_PATH,\n });\n const document = { content: text, type: 'PLAIN_TEXT' };\n return client\n .analyzeSentiment({document})\n .then(results => results[0].documentSentiment)\n .catch(err => console.error('ERROR:', err));\n}",
"function sentiment(text) {\n var words = text.split(/\\s/);\n var scored = {};\n var count = 0;\n\n for (var i = 0, len = words.length; i < len; ++i) {\n var word = words[i].replace(/[^\\w]/,' ').replace(/^\\s*/,'').replace(/\\s*$/,'').toLowerCase();\n //sys.puts(\"check: \" + word);\n var found = anew.lookup(word);\n if (found) {\n //sys.puts(\"found: \" + word);\n //scored.push(found);\n if (!scored[word]) {\n scored[word] = {anew:found,frequency:0};\n }\n scored[word].frequency++;\n count += 1;\n }\n }\n\n // compute the score\n var sum = 0;\n for (var word in scored) {\n sum += (scored[word].frequency * scored[word].anew.valence_mean)\n }\n\n if (count > 0) {\n\n var score = (1 / count) * sum;\n\n return sprintf('%.2f', score);\n }\n else {\n return null; // neutral we can't determine\n }\n}",
"function analyze(text) {\n const result = sentiment.analyze(text);\n const comp = result.comparative;\n const out = comp / 5;\n return out;\n}",
"analyze(token, text) {\n let res = sentiment(text);\n res.score\n }",
"analyze( text ) {\n let score = 0;\n let negative = 0;\n let positive = 0;\n let comparative = 0;\n let list = this._splitWords( text );\n let total = list.length;\n let i = total;\n\n // loop filtered input words\n while ( i-- ) {\n if ( !this._afinn.hasOwnProperty( list[ i ] ) ) continue; // not found\n\n let w = list[ i ]; // current word\n let p = ( i > 0 ) ? list[ i - 1 ] : ''; // previous word\n let s = parseFloat( this._afinn[ w ] ) | 0; // word score\n\n if ( !p || !s ) continue; // no score\n if ( this._negators.indexOf( p ) >= 0 ) s *= -1; // flip score\n if ( s > 0 ) positive += s;\n if ( s < 0 ) negative += s;\n score += s;\n }\n\n // sentiment string params\n let params = [ '', 'Neutral', 'icon-help iconLeft text-info' ];\n // positive\n if ( score === 1 ) params = [ '+', 'Ok', 'icon-help iconLeft text-success' ];\n if ( score > 1 ) params = [ '+', 'Positive', 'icon-like iconLeft text-success' ];\n if ( score > 10 ) params = [ '+', 'Positive', 'icon-like iconLeft text-gain' ];\n // negative\n if ( score === -1 ) params = [ '-', 'Ok', 'icon-help iconLeft text-danger' ];\n if ( score < -1 ) params = [ '-', 'Negative', 'icon-dislike iconLeft text-danger' ];\n if ( score < -10 ) params = [ '-', 'Negative', 'icon-dislike iconLeft text-loss' ];\n\n // build sentiment info\n let [ sign, word, styles ] = params;\n let sentiment = [ word, sign + Math.abs( score ) ].join( ' ' );\n\n // build final data\n comparative = total ? ( score / total ) : 0;\n return { score, positive, negative, comparative, sign, word, styles, sentiment };\n }",
"function getSentimentScore(string) {\n var temp = [];\n var songArray = splitString(string);\n\n //if theres no lyrics, thre is no need to do anything else\n if (songArray.length < 20) {\n return 'No Lyrics';\n }\n\n //getting the stem from each word, to increase the number of matches with the afinn database\n songArray.forEach(function(word) {\n var tempWord = snowball.stemword(word);\n temp.push(tempWord);\n })\n var editedLyrics = temp.join(' ');\n var sentimentAnalysis = sentiment(editedLyrics);\n\n return sentimentAnalysis;\n}",
"function getSentiments() {\n var originalReviews = window.reviews.original;\n var parsedConcepts = window.reviews.parsedConcepts;\n var key, concept, regex, match;\n for (key in parsedConcepts) {\n concept = parsedConcepts[key].name;\n regex = new RegExp(concept, \"gi\");\n var matches = originalReviews.filter(function(o) {\n return o.match(regex);\n });\n window.reviews.sentimentsIndividual[concept] = matches;\n var aggregateText = \"\";\n for (match in matches) {\n aggregateText += matches[match] + \"+\";\n }\n getSentiment(aggregateText, concept);\n }\n}",
"function datumBoxsentimentAnalyser(text){\n\t\tconsole.log(\"Text: \" + text);\n\t\t\n\t\tvar api_key = '1bce051279fc6005c060e0360b7b16c6';\n\t\tvar datumbox_base_url = 'http://api.datumbox.com/1.0/';\n\t\tvar analyser = 'SentimentAnalysis.json'\n\t\tvar datumbox_url = datumbox_base_url + analyser;\n\t\t\n\t\tvar data = {'api_key': api_key, 'text': text}\n\t\n\t\tvar sentiment;\n\t\t\n\t\t//Get request on Datumbox API\n\t\t$.ajax({ \n\t\t\turl: datumbox_url, \n\t\t\tdataType: 'json', \n\t\t\tdata: data, \n\t\t\tasync: false, \n\t\t\tsuccess: function(json){ \n\t\t\t\tif(json.output.status != 0){\n\t\t\t\t\tsentiment = json.output.result;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tsentiment = 'error';\n\t\t\t\t}\n\t\t\t} \n\t\t});\n\t\treturn sentiment;\n\t}",
"function getSentiment(str) {\n if (sentimentDB === \"afinn\") {\n return sentimentAfinn(str).score;\n }\n return sentimentClips.get(str).polarity;\n }",
"async function sentimentAnalysis(client,userText){\n console.log(\"Running sentiment analysis on: \" + userText);\n // Make userText into an array\n const sentimentInput = [ userText ];\n // call analyzeSentiment and get results\n const sentimentResult = await client.analyzeSentiment(sentimentInput);\n console.log(\"Got sentiment result\");\n\n // This is where you send the sentimentInput and sentimentResults to a database or storage instead of the console\n\n sentimentResult.forEach(document => {\n console.log(`ID: ${document.id}`);\n console.log(`\\tDocument Sentiment: ${document.sentiment}`);\n console.log(`\\tDocument Scores:`);\n console.log(`\\t\\tPositive: ${document.confidenceScores.positive.toFixed(2)} \\tNegative: ${document.confidenceScores.negative.toFixed(2)} \\tNeutral: ${document.confidenceScores.neutral.toFixed(2)}`);\n console.log(`\\tSentences Sentiment(${document.sentences.length}):`);\n document.sentences.forEach(sentence => {\n console.log(`\\t\\tSentence sentiment: ${sentence.sentiment}`)\n console.log(`\\t\\tSentences Scores:`);\n console.log(`\\t\\tPositive: ${sentence.confidenceScores.positive.toFixed(2)} \\tNegative: ${sentence.confidenceScores.negative.toFixed(2)} \\tNeutral: ${sentence.confidenceScores.neutral.toFixed(2)}`);\n });\n });\n }",
"function analyseSentiment(data){\n\tconst params = {\n\t\ttext : data\n\t};\n\treturn new Promise(function(fulfill, reject){\n\t\ttry{\n\t\t\trequest.get({url:\"http://localhost:4000/aylien/sentiment\", qs: params}, function(error, response, data){\n\t\t\t\t//console.log(\"Error: \", error);\n\t\t\t\t//console.log(\"Response: \", response);\n\t\t\t\t//console.log(\"Data: \", data);\n\t\t\t\tif(error){\n\t\t\t\t\treject({status: \"400\", data: error});\n\t\t\t\t} else{\n\t\t\t\t\tfulfill({status: \"200\", data: data});\n\t\t\t\t}\n\t\t\t});\n\t\t} catch(ex){\n\t\t\treject({status: \"400\", data: ex});\n\t\t}\n\t\t\n\t});\n}",
"function evalMsg(msg){\n params.Text = msg;\n comprehend.detectSentiment(params, function(err, data) {\n if (err) console.log(err, err.stack);// an error occurred\n else console.log(data); // successful response\n toBeHandled[0].sentiment = data.Sentiment;\n handleSentiment(toBeHandled.shift());\n });\n}",
"function countSentences(text) {\n return tokenizeEnglish.sentences()(text).length;\n}",
"function evalMsg(msg){\r\n params.Text = msg;\r\n comprehend.detectSentiment(params, function(err, data) {\r\n// if (err) console.log(err, err.stack);// an error occurred\r\n// else console.log(data); // successful response\r\n toBeHandled[0].sentiment = data.Sentiment;\r\n handleSentiment(toBeHandled.shift());\r\n });\r\n}",
"function getSentenceWeight(text){\n let position = searchElementReturnPosition(text, words.words);\n if(position !== -1) {\n return words.words[position].weight;\n } else {\n return -1;\n }\n }",
"function measureSentiment () {\n sentimentScoreTotal = 0;\n\n angular.forEach($scope.tweets, function(tweet, key) {\n sentimentScoreTotal = sentimentScoreTotal + tweet.sentiment.score;\n });\n\n $scope.avgSentiment = (Math.round((sentimentScoreTotal / TWEET_SAMPLE_SIZE) * 100) / 100).toFixed(2);\n $scope.sentimentState = getSentimentState($scope.avgSentiment);\n }",
"function calculateSentiment(responceJson) {\n const sentences = responceJson.sentences;\n const scoreArray = [];\n const magArray = [];\n const add = (a, b) => a + b;\n for (let i = 0; i < sentences.length; i++) {\n const sentenceScore = sentences[i].sentiment.score;\n const sentenceMagnitude = sentences[i].sentiment.magnitude;\n if (sentences[i].text.content.length >= 40) {\n scoreArray.push(sentenceScore);\n magArray.push(sentenceMagnitude);\n }\n }\n const magnitudeSum = magArray.reduce(add);\n const scoreSum = scoreArray.reduce(add);\n const articleMagnitude = magnitudeSum / magArray.length;\n const articleSentiment = scoreSum / scoreArray.length;\n const sentimentNumber = findSentimentNum(articleSentiment);\n const magnitudeString = findMagnitude(articleMagnitude);\n return [sentimentNumber, magnitudeString];\n}",
"function processAvgSentiment() {\n let avg_score =\n parseFloat(neg_sentiment_score) + parseFloat(pos_sentiment_score);\n setAvgSentiment(parseFloat(avg_score).toFixed(1));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show and hide captions on photos Inspirations page | function showCaption1() {
document.getElementById("caption1").style.display = "block";
} | [
"function showOrHideCaptionEditingModeElements(displayMode)\n{\n var photoSlideShowBackgroundDiv = document.getElementById('photoSlideShowBackground');\n photoSlideShowBackgroundDiv.style.display=displayMode;\n var photoSlideShowCanvas = document.getElementById('photoSlideShowCanvas');\n photoSlideShowCanvas.style.display=displayMode;\n var leftArrow = document.getElementById('leftArrow');\n leftArrow.style.display=displayMode;\n var rightArrow = document.getElementById('rightArrow');\n rightArrow.style.display=displayMode;\n var photoCaption = document.getElementById('photoCaption');\n photoCaption.style.display=displayMode;\n var cancelPhotoCaptionEdit = document.getElementById('cancelPhotoCaptionEdit');\n cancelPhotoCaptionEdit.style.display=displayMode;\n var okPhotoCaptionEdit = document.getElementById('okPhotoCaptionEdit');\n okPhotoCaptionEdit.style.display=displayMode;\n // var deletePhotoCaptionEdit = document.getElementById('deletePhotoCaptionEdit');\n // deletePhotoCaptionEdit.style.display=displayMode;\n\n}",
"function displayCaption() {\n if ($('#caption').is(':visible')) {\n $('#caption').hide();\n } else {\n $('#caption').show();\n }\n}",
"function associateCaptions() {\n // for edit mode, the popup consists of the image name, not the caption\n for (var q = 0; q < noOfPix; q++) {\n var img = $photos[q];\n captions.push(img.alt);\n }\n return;\n}",
"function showCaptions() {\n // If there's no caption toggle, bail\n if (!player.elements.buttons.captions) {\n return;\n }\n\n toggleClass(player.elements.container, config.classes.captions.enabled, true);\n\n // Try to load the value from storage\n var active = player.storage.captions;\n\n // Otherwise fall back to the default config\n if (!is.boolean(active)) {\n active = config.captions.defaultActive;\n }\n\n if (active) {\n toggleClass(player.elements.container, config.classes.captions.active, true);\n toggleState(player.elements.buttons.captions, true);\n }\n }",
"function captionVisiblity(){\n\tvar winH = window.innerHeight ? window.innerHeight : $(window).height();\n\tvar photo_info_opacity = 1-($(document).scrollTop()/(winH/2));\n\t$('.photo-info').css({'opacity': photo_info_opacity });\n}",
"function closedCaptions() {\n\tif (vid.textTracks[0].mode == \"showing\") {\n\t\tvid.textTracks[0].mode = \"hidden\";\n\t}\n\telse {\n\t\tvid.textTracks[0].mode = \"showing\";\n\t}\n}",
"function _showCaptions() {\n // If there's no caption toggle, bail\n if (!plyr.buttons.captions) {\n return;\n }\n\n _toggleClass(plyr.container, config.classes.captions.enabled, true);\n\n // Try to load the value from storage\n var active = plyr.storage.captionsEnabled;\n\n // Otherwise fall back to the default config\n if (!_is.boolean(active)) {\n active = config.captions.defaultActive;\n }\n\n if (active) {\n _toggleClass(plyr.container, config.classes.captions.active, true);\n _toggleState(plyr.buttons.captions, true);\n }\n }",
"function showCaption(id) {\r\n let caption = document.getElementById(id);\r\n if (caption.style.display === \"none\") {\r\n caption.style.display = \"block\";\r\n } else {\r\n caption.style.display = \"none\";\r\n }\r\n}",
"function displayCaption(caption) {\n $(\"#img-caption\").html(`\n <p>${caption}</p>`);\n }",
"function viewInfoToggler() {\n // hide it if shown\n if ($('#imgdetails').hasClass('show')) {\n $('.img-caption').css({\n 'visibility': 'hidden'\n });\n $('#imgdetails').removeClass('show');\n } else {\n // show it -if hidden\n $('.img-caption').css({\n 'visibility': 'visible'\n });\n $('#imgdetails').addClass('show');\n }\n }",
"function toggleCaption() {\n\tif($(\".caption-msg\").css(\"visibility\") != \"visible\")\n\t\tshowCaption();\n\telse\n\t\thideCaption();\n}",
"function showHideDetails() {\n /*var images, paragraphs, i, p;\n images = this.parentNode.getElementsByTagName(\"img\");\n for (i = 0; i < images.length; i += 1) {\n if (images[i].style.display === \"none\") {\n images[i].style.display = \"block\";\n } else {\n images[i].style.display = \"none\";\n }\n }\n paragraphs = this.parentNode.getElementsByTagName(\"p\");\n for (p = 0; p < paragraphs.length; p += 1) {\n if (paragraphs[p].style.display === \"none\") {\n paragraphs[p].style.display = \"block\";\n } else {\n paragraphs[p].style.display = \"none\";\n }\n }*/\n\t\t$(this).siblings().toggle(\"easeOutQuart\");\n }",
"function displayModalImage() {\n modal.style.display = \"block\";\n modalImg.src = this.src;\n captionText.innerHTML = this.alt;\n}",
"function handleCaption(elem){\r\n\t//elem = $(data.orig_event.target)\r\n\telem = elem == null ? $('.current.page').find('.caption') : $(elem)\r\n\r\n\tif(elem.is('.image-fit-height, .image-fit, .image-with-caption') \r\n\t\t\t|| elem.parents('.image-fit-height, .image-fit, .image-with-caption').length > 0){\r\n\r\n\t\t// prevent doing anything in ribbon mode..\r\n\t\tif(togglePageView('?') == 'off'){\r\n\t\t\treturn\r\n\t\t}\r\n\r\n\t\tif(!elem.hasClass('caption')){\r\n\t\t\telem = elem.parents('.page').find('.caption')\r\n\t\t}\r\n\r\n\t\t// hide and do not show empty captions...\r\n\t\tif(elem.text().trim() != ''){\r\n\t\t\telem.toggleClass('hidden')\r\n\t\t} else {\r\n\t\t\telem.addClass('hidden')\r\n\t\t}\r\n\t}\r\n}",
"function showRandomCaption() {\n\t//creates a variable that needs math applied to const all captions to ensure it is a random caption that will show\n let randomNumber = Math.floor(Math.random() * allcaptions.length);\n //use for each to ensure each caption is getting the function applied to it\n allcaptions.forEach(function(caption){\n \t//caption is hidden unless the function is applied to it\n \tcaption.style.display = \"none\";\n })\n\n //if applied and chosen at random the caption will display past the card and display as \"block\"\n allcaptions[randomNumber].style.display = \"block\";\n \n\n}",
"function hidePhoto()\n\t{\n\t\tdocument.getElementById('img').style.display='none';\n\t}",
"function hidePhotoPage() {\n photoPage.style.display = \"none\";\n}",
"function onCaptions()\r\n\t{\r\n\t\t// publish to the showClosedCaptions\r\n\t\tplayerObject.mb.publish( \"showClosedCaptions\" );\r\n\t\ttoggleVideoLanguagePopup();\r\n\t}",
"function hideArtCovers() {\n artCoverShowStyleElement.innerHTML = '';\n HIDE_COVERS = true;\n GM_setValue(HIDE_COVERS_VAL_KEY, HIDE_COVERS);\n document.getElementById('ds-art-cover-toggle-button').innerHTML = 'Show Album Covers';\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calls the setData method of the model | setData(data){
this.model.setData(data);
} | [
"setData() {\n\t\tthis.data = this.getData()\n\t}",
"setData() {\r\n this.fireSlimGridEvent(\"onBeforeDataUpdate\", {});\r\n\r\n this.generateColumns();\r\n this.generateFilters();\r\n this.setOptions();\r\n\r\n this.dataView.beginUpdate();\r\n this.setDataViewData();\r\n this.dataView.endUpdate();\r\n\r\n this.fireSlimGridEvent(\"onDataViewUpdate\", {});\r\n this.fireSlimGridEvent(\"onAfterDataUpdate\", {});\r\n }",
"setData(data) {\n this.data = data;\n }",
"setDataViewData() {\r\n if (!this.dataView) return;\r\n\r\n this.dataView.setItems(this.data, this.pk);\r\n }",
"_setDataToUI() {\n const data = this._data;\n if (data === undefined) return;\n console.log('View#_setDataToUI', this);\n\n if (data instanceof Object) {\n eachEntry(data, ([name, val]) => this._setFieldValue(name, val))\n } else {\n this._setVal(this.el, data)\n }\n }",
"setData(data) {\n this.data = this.addDefaultData(data);\n this.resetCache();\n }",
"setData(data) {\n // convert to Immutable if not\n this.data = data;\n }",
"setData(data) {\n this.selectedShippingMethod.label = data.label;\n this.selectedShippingMethod.value = data.value;\n // this.selectedShippingMethod.deliveryDetails = data.deliveryDetails;\n this.selectedShippingMethod.name = data.name;\n this.selectedShippingMethod.cost = data.cost;\n }",
"set data(arr) {\n\t\tthis.wrapper.setData(arr);\n\t\tthis._tableData = arr;\n\t}",
"set data(val) {\n this._data = val;\n }",
"function _setData() {\n try {\n this.hideOptions();\n } catch(exception) {\n logger.metric({\n ns: 'milo.supercombo.error',\n msg: 'Hide option failed in when called in set data',\n exception: exception\n });\n return; // should stop as before\n }\n this.toggleAddButton(false);\n this._comboInput.data.off('', { subscriber: onDataChange, context: this });\n //supercombo listeners off\n this.data.set(this._selected);\n this._comboInput.data.on('', { subscriber: onDataChange, context: this });\n //supercombo listeners on\n}",
"setData(state, data) {\r\n state.data = data\r\n }",
"setData(data) {\n const sourceData = data.data ? data.data : data;\n this.itemsArr = mapItems(sourceData, this.defaultValue);\n }",
"function refreshDataInModelSuaban() {\n}",
"set(data) {\n this.dc.ww.just('dataset-op', {\n id: this.id,\n type: 'set',\n data: data\n })\n }",
"update(data) {\n for (let key of data) {\n let val = data[key];\n if (key == \"id\" && this._data.id) {\n continue;\n }\n this._data[key] = val;\n }\n this.dispatchEvent('Model.Change', { path: null, value: data }, true);\n }",
"set datavalue(val) {\n if (this.multiple) {\n val = extractDataAsArray(val);\n }\n this._modelByValue = val;\n this.selectByValue(val);\n // changes on the datavalue can be subscribed using listenToDatavalue\n this.datavalue$.next(val);\n // invoke on datavalue change.\n this.invokeOnChange(val, undefined, true);\n }",
"setData(list) {\n this._originalData = list;\n this.data = this._originalData.slice();\n\n if (this._filters.length > 0) {\n this._applyFilters();\n }\n\n if (this._sorter) {\n this._applySorter();\n }\n }",
"setAll(data) {\n this.data = data;\n this._updateConfig();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
fomartBodyPages: sets basic structure for all body pages | function formatBodyPages(){
//applies upper frame
var topframe = "<div class='page-frame'></div>";
$('.body-page').prepend(topframe);
$(document.getElementsByClassName('body-page')[0]).addClass('page-active');
} | [
"function allPages(req, res, template, block, next) {\n \n calipso.theme.renderItem(req, res, template, block, {});\n next();\n \n}",
"function bodyLoadCommonAfter()\r\n{\r\n wireUpEventHandlers();\r\n loadSettings();\r\n\r\n // make body visible, now that we're ready to render\r\n document.body.style.visibility = \"visible\";\r\n \r\n // if this is web output, sync the TOC\r\n syncToc(); \r\n}",
"function setPageObjects() {\n\tobjContent = new pageObject(\"centerContent\");\n objCenter = new pageObject(\"center\");\n objAddress = new pageObject(\"address\");\n \tobjFooter = new pageObject(\"footer\");\n\tobjTopTasks = new pageObject(\"topTasks\");\n\tobjMidStuff = new pageObject(\"centerInfo\");\n\tobjIntro = new pageObject(\"centerHeader\");\n\tobjRightBar = new pageObject(\"rightBar\");\n\tobjLeftNav = new pageObject(\"leftNav\");\n}//end setPageObjects",
"function encodeBody(e) {\n state.pageHeight = e.getPageHeight();\n state.pageWidth = e.getPageWidth();\n return DOCUMENT_HEADER + encodeChildren(e) + encodeReferences() + DOCUMENT_FOOTER;\n}",
"function pages(cb) {\n\n async.forEach(config.pages, function (p, callback) {\n // bench('pre page')\n var readLoc = dir + '/source/templates/pages/' + p.template + '.jade'\n , writeLoc = dir + '/preview/' + p.template + '.html'\n\n fs.readFile(readLoc, 'utf8', function (err, data) {\n if (err) return callback(err)\n var template = jade.compile(data,\n { filename: readLoc\n , pretty: true\n })\n\n fs.writeFile(writeLoc, template(p.data), function (err) {\n if (!err) {\n console.log((' Rendered ' + p.template + '.jade → ' + p.template + '.html').blue)\n }\n // bench('post page')\n callback(err)\n })\n\n })\n\n }, cb)\n\n}",
"function layoutPages(){\n for (var secteur_counter = 0; secteur_counter < ARRAY_SECTEURS.length; secteur_counter++){\n var master_name =ARRAY_SECTEURS[secteur_counter][\"master\"];\n var folder_to_save = ARRAY_SECTEURS[secteur_counter][\"folder\"];\n for (csv_counter = 0; csv_counter < ARRAY_SECTEURS[secteur_counter][\"csv\"].length; csv_counter++){\n var csv_LINK = ARRAY_SECTEURS[secteur_counter][\"csv\"][csv_counter];\n layoutFromCsv(File(PAGE_MODEL), csv_LINK, master_name, folder_to_save);\n }\n }\n}",
"function setPages(){\n\t\t\t// Foreach all articles\n\t\t\t$.each(articles, function(key, value){\n\t\t\t\tvar totalCounted\t\t=\t0;\n\t\t\t\tvar elements\t\t\t=\tvalue[\"article\"];\n\t\t\t\tvar marge\t\t\t\t=\t0;\n\t\t\t\tarticleTitles[key]\t\t=\tvalue[\"title\"];\n\t\t\t\t\n\t\t\t\t// Current values\n\t\t\t\tvar current\t\t\t\t=\t[];\n\t\t\t\tcurrent[\"column\"] \t=\t1;\n\t\t\t\tcurrent[\"page\"]\t\t=\t0;\n\t\t\t\tcurrent[\"element\"]\t=\t-1;\n\t\t\t\t\n\t\t\t\t// Height of page\n\t\t\t\tvar HM\t=\t(getDocHeight()-120)%lineHeight;\n\t\t\t\tvar heightOfPage\t=\t(HM < lineHeight/2)\n\t\t\t\t\t?(getDocHeight()-120)-HM\n\t\t\t\t\t:(getDocHeight()-120)+(lineHeight-HM);\t\n\n\t\t\t\tvar done = false;\n\t\t\t\tvar marginTop = 0;\n\t\t\t\tvar lastItemHeight;\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t// If determined number of columns does not fit onto the page it will recalculate the number of columns\n\t\t\t\tif(value[\"data-cols\"]*(widthOfColumn+space+10) > getDocWidth())\n\t\t\t\t{\n\t\t\t\t\tvar cols\t=\tMath.floor(getDocWidth()/(widthOfColumn+space+10));\n\t\t\t\t\tif(cols == 1){\n\t\t\t\t\t\t$(\".sideMenu\").hide();\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tvar cols\t=\tvalue[\"data-cols\"];\n\t\t\t\t}\n\n\t\t\t\t\n\t\t\t\tdo{\n\t\t\t\t\t// This makes the first page of an article\n\t\t\t\t\tif(current[\"page\"] == 0){\n\t\t\t\t\t\tcurrent[\"page\"]++;\n\t\t\t\t\t\t$(\".viewer\", thisElement).append('<div class=\"page page-'+current[\"page\"]+' theme-'+value[\"data-theme\"]+' first\" id=\"article_'+key+'\" data-pageNumber=\"'+current[\"page\"]+'\" data-articleNumber=\"'+key+'\" style=\"width: '+(widthOfColumn+space)+'px; height: '+heightOfPage+'px\"><div class=\"column column_'+current[\"column\"]+'\" style=\"height: '+heightOfPage+'px\"></div></div>');\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t// If needed it makes a new page\t\t\t\t\t\n\t\t\t\t\tif(marge == 0){\n\t\t\t\t\t\tcurrent[\"element\"]++;\n\t\t\t\t\t}else{\n\t\t\t\t\t\tmarginTop = lastItemHeight-marge;\n\t\t\t\t\t\tmarge = 0;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t// Removes headers if its shown half on a page (#1)\n\t\t\t\t\tvar remove = false;\n\t\t\t\t\tif((heightOfPage-totalCounted) < (5*lineHeight) && heightOfPage-totalCounted > 0 && heightOfPage > 7*lineHeight){\n\t\t\t\t\t\tif(typeof(elements[current[\"element\"]]) != 'undefined'){\n\t\t\t\t\t\t\tif(elements[current[\"element\"]][\"node\"] == \"H2\"){\n\t\t\t\t\t\t\t\ttotalCounted += heightOfPage-totalCounted;\n\t\t\t\t\t\t\t\tremove = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\t\t\t\n\t\t\t\t\t// Check if all elements are done\n\t\t\t\t\tif(typeof(elements[current[\"element\"]]) == 'undefined'){\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t\t$(\".page\").hide();\n\t\t\t\t\t\t$(\".first#article_0\").show();\n\t\t\t\t\t\t$(\".page-\"+current[\"page\"]+\"#article_\"+key).addClass(\"last\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif(elements[current[\"element\"]][\"node\"] != \"FIGURE\"){\n\t\t\t\t\t\t// Place the content into the current pages/columns\n\t\t\t\t\t\tvar iden = key+\"_\"+current[\"page\"]+\"_\"+current[\"column\"];\n\t\t\t\t\t\t$(\".page-\"+current[\"page\"]+\"#article_\"+key+\" .column_\"+current[\"column\"]).append('<'+elements[current[\"element\"]][\"node\"]+' id=\"'+iden+'\">'+elements[current[\"element\"]][\"value\"]+'</'+elements[current[\"element\"]][\"node\"]+'>');\n\t\t\t\t\t\ttotalCounted += $(\"#\"+iden).outerHeight(true);\n\t\t\t\t\t}else{\n\t\t\t\t\t\t//figure\n\t\t\t\t\t\t$(\".page-\"+current[\"page\"]+\"#article_\"+key+\" .column_\"+current[\"column\"]).append('<'+elements[current[\"element\"]][\"node\"]+'>'+elements[current[\"element\"]][\"value\"]+'</'+elements[current[\"element\"]][\"node\"]+'>');\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t// Checks if item has to be removed (#1)\n\t\t\t\t\tif(remove){\n\t\t\t\t\t\t$(\"#\"+iden).hide();\n\t\t\t\t\t\tremove = false;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t// Use the margin on a element if there is any\n\t\t\t\t\tif(marginTop != 0){\n\t\t\t\t\t\tif(marginTop < 0){\n\t\t\t\t\t\t\tmarginTop = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(current[\"column\"] == (value[\"data-cols\"]-1)){\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttotalCounted -= marginTop;\n\t\t\t\t\t\t$(\"#\"+iden).css(\"marginTop\", -marginTop+\"px\");\n\t\t\t\t\t\tmarginTop = 0;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t// Gets the height of the last placed element And removes the id attribute\n\t\t\t\t\tlastItemHeight\t=\t$(\"#\"+iden).outerHeight();\n\t\t\t\t\t$(\"#\"+iden).removeAttr(\"id\");\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t// Makes a new column\n\t\t\t\t\tif(totalCounted > heightOfPage){\n\t\t\t\t\t\tif(current[\"column\"] >= cols){\n\t\t\t\t\t\t\t$(\".page-\"+current[\"page\"]+\"#article_\"+key+\" .column_\"+current[\"column\"]).addClass(\"last_column\");\n\t\t\t\t\t\t\tcurrent[\"page\"]++;\n\t\t\t\t\t\t\tcurrent[\"column\"]\t\t=\t1;\n\t\t\t\t\t\t\t$(\".viewer\", thisElement).append('<div class=\"page page-'+current[\"page\"]+' theme-'+value[\"data-theme\"]+'\" id=\"article_'+key+'\" data-pageNumber=\"'+current[\"page\"]+'\" data-articleNumber=\"'+key+'\" style=\"width: '+(widthOfColumn+space)+'px; height: '+heightOfPage+'px\"></div>');\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\tcurrent[\"column\"]++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$(\".page-\"+current[\"page\"]+\"#article_\"+key).append('<div class=\"column column_'+current[\"column\"]+'\" style=\"height: '+heightOfPage+'px\"></div>');\n\t\t\t\t\t\t$(\".page-\"+current[\"page\"]+\"#article_\"+key).width((widthOfColumn+space)*current[\"column\"]);\n\t\t\t\t\t\tmarge = (totalCounted-heightOfPage);\n\t\t\t\t\t\ttotalCounted = 0;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\twhile(done != true);\n\t\t\t\t\n\t\t\t});\n\t\t\tafterLoading();\n\t\t}",
"function AllPages() { }",
"function setContentOfPage() {\n //The object we will pass to markup that will be used to generate the HTML.\n var context = { \"listitems\": _data.items };\n \n //The SDK automatically parses any templates you associate with this view on the bc.templates object.\n var markupTemplate = bc.templates[\"first-page-tmpl\"];\n \n //The generated HTML for this template.\n var html = Mark.up( markupTemplate, context );\n \n //Set the HTML of the element.\n $( \"#first-page-content\" ).html( html );\n }",
"function updatePages() {\n buildPage(\"home\", \"all\");\n\n for (var schema in wholeDoc.blob) {\n if (schema != \"instructions\") {\n for (var key in wholeDoc.blob[schema]) {\n buildPage(schema, key);\n var owner = wholeDoc.blob.instructions[schema].settings.owner;\n // TODO: App specific code\n if (wholeDoc.blob[schema][key][owner] == client.username &&\n schema != \"reservations\") {\n buildPage(schema, key, \"edit\");\n }\n }\n }\n }\n\n}",
"function setUpPage(){\r\n displayHeader();\r\n displayFooter();\r\n displaySideBar();\r\n createEventListeners();\r\n}",
"function initPages() {\n // Initialize the pages which may be dependent upon some of the data.\n\tpageStack[0] = pages.loading;\n\t\n\tfor (p in pages) {\n\t\tvar pg = pages[p];\n\t\tif (typeof (pg.init) == \"function\") {\n\t\t\tpg.init();\n\t\t}\n\t}\n}",
"function initClientDocument( documentStruct ){\n\t\t\n\t$doc().append('<div class=\"page\"></div>');\n\tvar thisPage = $doc().children(':first');\t\n\t\n\tfor( var i = 0; i < documentStruct.length; i++ ){\t\t\n\t\tif( documentStruct[i] == 'pageBreak' ){\n\t\t\tthisPage.after('<div class=\"pageBreak\"></div>');\n\t\t\tthisPage.after('<div class=\"page\"></div>');\n\t\t\tthisPage = $( thisPage[0].nextSibling.nextSibling );\n\t\t}else{\n\t\t\tthisPage.append( documentStruct[i] );\n\t\t\tpageRender.pageOverflow( thisPage );\n\t\t\tthisPage = $doc().children(':last');\n\t\t}\t\t\n\t}\n}",
"function setupBodyHTML() {\r\n\r\n // here we retrieve the token from session storage\r\n const token = sessionStorage.getItem('token');\r\n\r\n // we first retrieve the existing root HTML element\r\n const root = document.getElementById('root');\r\n\r\n // setting up the outer main class\r\n const main = document.createElement('main');\r\n main.setAttribute('role', 'main');\r\n main.id = 'main';\r\n\r\n // setting up the feed element within main\r\n const feed = document.createElement('ul');\r\n feed.id = 'feed';\r\n feed.setAttribute('data-id-feed', \"\");\r\n main.appendChild(feed);\r\n\r\n // adding a feed header to this feed element\r\n const feedHeader = document.createElement('div');\r\n feedHeader.classList.add('feed-header');\r\n feed.appendChild(feedHeader);\r\n\r\n // for this feed header, the first item is a title\r\n const feedTitle = document.createElement('h3');\r\n feedTitle.classList.add('feed-title', 'alt-text');\r\n feedTitle.textContent = 'Feed';\r\n feedHeader.appendChild(feedTitle);\r\n\r\n // the feed header also contains a post button\r\n const postButton = document.createElement('button');\r\n postButton.classList.add('button', 'button-secondary');\r\n postButton.textContent = 'Post';\r\n feedHeader.appendChild(postButton);\r\n\r\n // logged in users also have added functionality\r\n if (token !== null) {\r\n \r\n // we first allow a logged in user to create a post\r\n // by using the post button\r\n postButton.addEventListener('click', function() {\r\n postContent();\r\n });\r\n\r\n // we also allow a logged in user to navigate between\r\n // pages of posts in their feed\r\n setupPagination(main);\r\n }\r\n\r\n // here we create all the post elements to show\r\n // within this feed\r\n createFeed(feed);\r\n\r\n // once all the elements are setup, we add it before\r\n // the footer element within the HTMLs\r\n const footer = document.getElementById('footer');\r\n root.insertBefore(main, footer);\r\n}",
"function renderPageForBots() {\n\n /* Fill the body content with either a blog-index, post or page. */\n if (gsConfig.blogIndexIsActive()) {\n\n /* use the sitemap instead of the blog index */\n var gsSitemap = new Sitemap(gsConfig);\n PrettyMarkdownTextToHTML(gsSitemap.links(), gs_body_id);\n\n } else if (gsConfig.postIsActive()) {\n /* If a post was found in the url query. */\n MarkdownFileToBody(gs_post_path+'/'+gsConfig.requested_page);\n\n /* render previous and next links */\n var gsPagination = new PageNav(gsConfig);\n gsPagination.genPostNavListTags();\n\n } else {\n /* The active page needs to correspond to a file at this point so \n * that the getter can download it. The getter should be post aware.*/\n MarkdownFileToBody(gsConfig.requested_page); \n }\n\n /* render the simple sitemap */\n if (gsConfig.sitemapIsActive()) {\n var gsSitemap = new Sitemap(gsConfig);\n PrettyMarkdownTextToHTML(gsSitemap.links(), gs_body_id);\n }\n\n /* Fill the body content with either a blog-index, post or page. */\n /* fill in the navbar */\n var gsNav = new Nav(gsConfig);\n \n}",
"createPages() {\n // Example:\n // this.pages = {\n // [this.pageNames.mainMenu]: new TestPage(ObjectFinder.find(\"plane0\"),this),\n // [this.pageNames.textMenu]: new TestPage(ObjectFinder.find(\"3dText0\"),this)\n // };\n }",
"function prepareNextPage() {\n pageDOM.push(NEW_PAGE);\n\n currentHeight = 0;\n\n // This function is responsible for handling the headers and footers.\n // This provides support for a unique first-page header and footer.\n // Pass the first page header or footer in along with the other page\n // headers and footers.\n function processAndWrite(firstPage, otherPages) {\n\n // Replace the content of all spans with the page-no class withi the\n // relevant page number. This is the current page count.\n function processPageNumbers(element) {\n element.querySelectorAll('span.page-no').forEach(function (item) {\n item.innerHTML = pageCount;\n });\n }\n\n // The element to write to the pageDOM.\n var writeElement;\n\n if (pageCount == 1) {\n writeElement = firstPage;\n } else {\n writeElement = otherPages;\n }\n\n // Process the element to write to the pageDOM.\n if (writeElement) {\n processPageNumbers(writeElement);\n pageDOM.push(writeElement.cloneNode(true));\n currentHeight += computeRealHeight(writeElement);\n }\n }\n\n // Write the headers and footers using the function described\n // above.\n processAndWrite(firstPageHeader, header);\n processAndWrite(firstPageFooter, footer);\n\n console.log('--- ON PAGE ' + pageCount + ' ---');\n pageCount++;\n\n }",
"function buildPages() {\n pageBuildList.forEach((page) => {\n let result;\n // Call the render function\n let template = Handlebars.compile(templates.layouts[page.template]);\n\n // Note: if no partial then no page can be built\n if (templates.partials[page.partial] !== undefined) {\n // Register helpers and partials for Handlebars \n HandlebarsHelpers.registerHelpers(Handlebars);\n Handlebars.registerPartial('body', templates.partials[page.partial]);\n // Build template out to html using page data\n result = template(page.data);\n fs.writeFile(__dirname + page.outputLocation + page.fileName + '.html', result);\n }\n });\n}",
"function createPages() {\n\n var targetPage;\n\n if (currentPage > (pageTemplates.length - 1)) {\n targetPage = pageTemplates[pageTemplates.length - 1];\n } else {\n targetPage = pageTemplates[currentPage];\n }\n \n // This block clones the desired template, and places the newly cloned template in the flexbox \n // element which contains all instantiated pages. The setImmediate function improves performnace\n // when creating a large number of pages.\n var flexboxElement = document.getElementById('pageContainer');\n WinJS.UI.Fragments.render(targetPage, flexboxElement).done(function () {\n setImmediate(function () {\n currentPage += 1;\n // Here we simply find the last instantiated page, then the last region on the page,\n // to find out if content is overflowing the page. If so, we call layout again, and the\n // process continues until all content has been laid out.\n var /*@override*/ flexboxElement = document.getElementById('pageContainer');\n var pages = flexboxElement.querySelectorAll('.page');\n var lastPage = pages[pages.length - 1];\n var regions = lastPage.querySelectorAll(searchClass);\n var lastRegion = regions[regions.length - 1];\n // msRegionOverflow has 3 different values - overflow indicates that there is still\n // content that the region was not able to display, empty means that no content from the\n // steam was left to place in this particular region\n if (lastRegion.msRegionOverflow === 'overflow') {\n createPages();\n }\n });\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
deleteAllBooks Function removes all book cards from the DOM and clears the libraryBooks array | function deleteAllBooks() {
const bookCards = document.querySelectorAll(".book-card");
bookCards.forEach((card) => {
card.remove();
libraryBooks = [];
});
} | [
"function clearBooks() {\n books = [];\n}",
"function clearDom(){\n Array.from(allBooks).forEach(book => {\n book.remove();\n });\n}",
"function deleteBookCards(){\n\tfor(const x of myLibrary){\n\t\tconst book = document.getElementById(\"\" + x.id);\n\t\n\t\t//check if book exists \n\t\tif(book){\n\t\t\tbookHolder.removeChild(book);\n\t\t}\n\t\t\n\t}\n}",
"confirmDeleteAll() {\r\n\t\tlet allItems = document.querySelectorAll(\".books-item\");\r\n\t\tfor (let item of allItems){\r\n\t\t\tbookList.tableBody.removeChild(item);\r\n\t\t}\r\n\t\tbookList.emptyLibrary(bookList.library);\r\n\t\thelper.closeModal(deleteAllModal.backdrop);\r\n\t}",
"function deleteBook(book) {\n //remove book from html\n let bookContainer = document.getElementById(book.pages);\n container.removeChild(bookContainer);\n\n //also remove from array\n //find where in the library the book is (index)\n let bookIndex = myLibrary.indexOf(book);\n //delete the book at index\n myLibrary.splice(bookIndex, 1);\n\n // return myLibrary;\n}",
"function clearAll()\n{\n let templib = JSON.parse(localStorage.getItem(\"bookarray\"));\n removeAllBooks(templib);\n localStorage.clear();\n}",
"function removeAllBooks(book)\n{\n book.forEach(e=>\n {\n removeBook(e.id);\n })\n}",
"function removeAll() {\n const elements = document.getElementsByClassName(\"book\");\n while(elements.length > 0){\n elements[0].parentNode.removeChild(elements[0]);\n }\n}",
"function resetBooks(){\n while(library.hasChildNodes())\n library.removeChild(library.childNodes[0]); \n}",
"function clearBook() {\n var bookTitles = document.getElementsByClassName(\"bookTitle\")\n var body = document.getElementById(\"bookresults\")\n while (bookTitles.length > 0) {\n body.removeChild(bookTitles[0])\n }\n}",
"function removeBook() {\n bookNum = this.dataset.id;\n myLibrary.splice(bookNum,1);\n saveLibrary();\n clearCards();\n makeCards();\n}",
"function clearData(){\n document.querySelectorAll(\".book-card\").forEach((bookCard)=>{\n bookCard.remove();\n })\n }",
"function deleteBook(book) {\n let bookToDelete = findBookDiv(book);\n let bookIDToDelete = findBookID(bookToDelete);\n\n bookToDelete.remove(); // Remove the book div from the DOM\n myLibrary = myLibrary.filter((book) => book.bookID != bookIDToDelete); // Remove the book from library array\n updateLocalStorageLibrary();\n}",
"function deleteBook() {\n let bookDiv = this.parentNode;\n let title = getTitleOfBookDiv(bookDiv);\n let author = getAuthorOfBookDiv(bookDiv);\n deleteBookFromArray(title, author);\n // remove bookDiv from DOM\n bookDiv.remove(); \n}",
"function removeBook() {\n const book = this.parentElement;\n for (let i = 0; i < library.length; i++) {\n if (library[i].timestamp.toString() === book.id) {\n removeBookInStorage(library.splice(i,1)[0]);\n break;\n }\n }\n book.remove();\n}",
"deleteBookFromShoppingCart(book) {\n\n let removeBook = document.getElementById(\"RemoveButton\" + book.bookIsbn);\n removeBook.parentElement.remove();\n\n for (let i = 0; i < shop.shoppingCart.books.length; i++) {\n // richtiges Buch wird in dem Buch Array des shoppingCarts gesucht und gelöscht.\n if (shop.shoppingCart.books[i].bookIsbn === book.bookIsbn) {\n shop.shoppingCart.books.splice(i, 1);\n }\n }\n //die Summe des Shoppingcats wird wieder neu upgedatet.\n shop.shoppingCart.showSumInShoppingCart();\n\n }",
"function removeBooks() {\n let bookTable = document.querySelector(\"#booksTable\");\n let tableHeader = bookTable.querySelector(\"tbody\");\n while(tableHeader.nextElementSibling)\n bookTable.removeChild(tableHeader.nextElementSibling);\n}",
"function removeBook (e) {\n removeBtn = e.srcElement;\n let removedRow = removeBtn.id;\n for (i = 0; i < myLibrary.length; i++) {\n if (i == removedRow) {\n myLibrary.splice(i, 1);\n break;\n }\n }\n viewBooks();\n\n}",
"function clearDisplay() {\n let container = document.querySelector('.book-container')\n let books = document.querySelectorAll('.book-component')\n for (let i = 0; i < books.length; i++) {\n container.removeChild(books[i])\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The Debug mode generates a skeleton diagram for debugging. There will be a button at the top of the page, and click to generate a skeleton map. | async debugGenSkeleton(options) {
const switchElement = document.createElement('button');
switchElement.innerHTML = '开始生成骨架图';
Object.assign(switchElement.style, {
width: '100%',
zIndex: 9999,
color: '#FFFFFF',
background: 'red',
fontSize: '30px',
height: '100px',
});
document.body.prepend(switchElement);
// Need to wait for event processing, so use Promise for packaging
return new Promise((resolve, reject) => {
try {
switchElement.onclick = async () => {
removeElement(switchElement);
await this.startGenSkeleton();
await sleep(options.debugTime || 0);
resolve();
};
} catch (e) {
console.error('==startGenSkeleton Error==', e);
reject(e);
}
});
} | [
"function setupDebugDraw(){\n if(ctx == null) ctx = canvas.getContext('2d');\n \n var debugDraw = new b2DebugDraw();\n \n // Use the canvas context for drawing the debugging screen\n debugDraw.SetSprite(ctx);\n // Set the scale\n debugDraw.SetDrawScale(scale);\n // Set the alpha transparency for boxes\n debugDraw.SetFillAlpha(0.5);\n // Draw lines with a thickness of 1.0\n debugDraw.SetLineThickness(1.0);\n // Display all shapes and joints\n debugDraw.SetFlags(\n b2DebugDraw.e_shapeBit |\n\t\t// b2DebugDraw.e_centerOfMassBit |\n b2DebugDraw.e_jointBit \n );\n \n // Start using the debug draw in the world\n world.SetDebugDraw(debugDraw);\n}",
"debug(state) {\n if (state) {\n this.debugGraphics = new PIXI.Graphics;\n this.debugGraphics.lineStyle(2, 0xFF0000, 1);\n this.ent.addChild(this.debugGraphics);\n } else {\n this.debugGraphics = undefined;\n }\n }",
"function createDebug(){\n\t\tdebug = document.createElement('div');\n\t\tdebug.id = 'birdview_debug';\n\t\tdebug.innerHTML = 'DEBUG';\n\t\tbody.appendChild(debug);\n\t}",
"function createSkeleton()\n\t{\t\n\t\tif( document.getElementById('skeletonFrame') ) return; // just print only one skeleton\n\t\t\n\t\t/** create a frame to get all joints together by selecting one element**/\n\t\tskeleton.frame = document.createElement('div');\n\t\tskeleton.frame.className = 'skeletonFrame';\n\t\tskeleton.frame.id = 'skeletonFrame';\n\t\tradardiv.appendChild( skeleton.frame );\n\t\t\n\t\t/** create the object that contains all joints **/\n\t\tskeleton.joints = new Object;\n\t\t\t\t\n\t\t/** create all joints, with his name **/\n\t\tfor( jt in jointsArray )\tcreateSkeletonElement( jointsArray[jt] );\n\t}",
"async startGenSkeleton() {\n this.init();\n try {\n this.handleNode(document.body);\n } catch (e) {\n console.log('==genSkeleton Error==\\n', e.message, e.stack);\n }\n }",
"function debug(scene) {\n //Debug: show Scene Explore and Inspector\n scene.debugLayer.show();\n}",
"function draw() {\n // the background color is different whether the program is or isn't considering diagonals\n let bgCol = hasDiagonals ? color(200, 200, 200) : 0;\n background(bgCol);\n\n showGrid(grid, hasDiagonals, color(200, 200, 200), color(255, 100, 100));\n showDataStructure(openSet, color(100, 255, 100));\n\n if (head) tracePath(head, hasDiagonals, color(0, 255, 255));\n\n if (end) tracePath(end, hasDiagonals, color(0, 255, 255));\n if (end) end.show(color(255, 0, 0));\n if (start) start.show(color(0, 0, 255));\n}",
"_triggerDebugPaint(debug) {\n if (debug) {\n let obj = {\n file: this.file,\n id: this.id,\n title: this.title,\n author: this.author,\n description: this.description,\n license: this.license,\n metadata: this.metadata,\n items: this.items\n };\n let span = document.createElement(\"span\");\n span.innerHTML = JSON.stringify(obj, null, 2);\n this.shadowRoot.appendChild(span.cloneNode(true));\n } else {\n this.render();\n }\n }",
"function setDebugDraw(w){\n\tvar debugDraw = new b2DebugDraw();\n\tdebugDraw.SetSprite(document.getElementById(\"canvas\").getContext(\"2d\"));\n\tdebugDraw.SetDrawScale(PTM_RATIO); // Set draw scale\n\tdebugDraw.SetFillAlpha(0.3);\n\tdebugDraw.SetLineThickness(1.0);\n\tdebugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);\n\t// set debug draw to the world\n\tw.SetDebugDraw(debugDraw); \n}",
"function generateDebugBody( body ) {\n\n\t\tvar frameUnit = 2;// In pixels\n\t\tvar debugBody = Crafty.e( RenderingMode );\n var debugBodyBody = Crafty.e( RenderingMode + ', Color' );\n var debugBodyTopFrame = Crafty.e( RenderingMode + ', Color' );\n\t\tvar debugBodyRightFrame = Crafty.e( RenderingMode + ', Color' );\n var debugBodyDownFrame = Crafty.e( RenderingMode + ', Color' );\n var debugBodyLeftFrame = Crafty.e( RenderingMode + ', Color' );\n\n\t\tdebugBody.attach( debugBodyBody );\n\t\tdebugBody.attach( debugBodyTopFrame );\n\t\tdebugBody.attach( debugBodyRightFrame );\n\t\tdebugBody.attach( debugBodyDownFrame );\n\t\tdebugBody.attach( debugBodyLeftFrame );\n\n\t\t// TODO cleaner code.\n\t\tvar attr = {\n\t\t\tx: body.vertices[ 0 ].x,\n\t\t\ty: body.vertices[ 0 ].y,\n\t\t\tw: body.vertices[ 0 ].x,\n\t\t\th: body.vertices[ 0 ].y\n\t\t};\n\n\t\t//We iterate to have a square shape for circles and polygons/\n\t\tfor ( var i = 1; i < body.vertices.length; i++ ) {\n\t\t\tif ( body.vertices[ i ].x < attr.x ) {\n\t\t\t\tattr.x = body.vertices[ i ].x;\n\t\t\t}\n\n\t\t\tif ( body.vertices[ i ].y < attr.y ) {\n\t\t\t\tattr.y = body.vertices[ i ].y;\n\t\t\t}\n\n\t\t\tif ( body.vertices[ i ].x > attr.w ) {\n\t\t\t\tattr.w = body.vertices[ i ].x;\n\t\t\t}\n\n\t\t\tif ( body.vertices[ i ].y > attr.h ) {\n\t\t\t\tattr.h = body.vertices[ i ].y;\n\t\t\t}\n\t\t}\n\n\t\tdebugBody.attr( {\n\t\t\tx: attr.x,\n\t\t\ty: attr.y,\n\t\t\tw: Math.abs( attr.w - attr.x ),\n\t\t\th: Math.abs( attr.h - attr.y )\n\t\t} );\n\n\t\tdebugBody.origin( 'center' );\n\n\t\tdebugBodyBody.color( 'blue' );\n\t\tdebugBodyBody.alpha = 0.5;\n\t\tdebugBodyBody.z = debugBody._z + 1;\n\t\tdebugBodyBody.origin( 'center' );\n\n\t\tdebugBodyTopFrame.color( 'blue' );\n\t\tdebugBodyTopFrame.h = frameUnit;\n\t\tdebugBodyTopFrame.z = debugBody._z + 1;\n\t\tdebugBodyTopFrame.origin( 'center' );\n\n\t\tdebugBodyRightFrame.color( 'blue' );\n\t\tdebugBodyRightFrame.x = debugBodyBody._x + ( debugBodyBody._w - frameUnit );\n\t\tdebugBodyRightFrame.w = frameUnit;\n\t\tdebugBodyRightFrame.z = debugBody._z + 1;\n\t\tdebugBodyRightFrame.origin( 'center' );\n\n\t\tdebugBodyDownFrame.color( 'blue' );\n\t\tdebugBodyDownFrame.y = debugBodyBody._y + ( debugBodyBody._h - frameUnit );\n\t\tdebugBodyDownFrame.h = frameUnit;\n\t\tdebugBodyDownFrame.z = debugBody._z + 1;\n\t\tdebugBodyDownFrame.origin( 'center' );\n\n\t\tdebugBodyLeftFrame.color( 'blue' );\n\t\tdebugBodyLeftFrame.w = frameUnit;\n\t\tdebugBodyLeftFrame.z = debugBody._z + 1;\n\t\tdebugBodyLeftFrame.origin( 'center' );\n\n\t\treturn debugBody;\n\t}",
"function generateDebugBody( body ) {\n\n\t\t\tvar frameUnit = 2;// In pixels\n\t\t\tvar debugBody = Crafty.e( RenderingMode );\n\t var debugBodyBody = Crafty.e( RenderingMode + ', Color' );\n\t var debugBodyTopFrame = Crafty.e( RenderingMode + ', Color' );\n\t\t\tvar debugBodyRightFrame = Crafty.e( RenderingMode + ', Color' );\n\t var debugBodyDownFrame = Crafty.e( RenderingMode + ', Color' );\n\t var debugBodyLeftFrame = Crafty.e( RenderingMode + ', Color' );\n\n\t\t\tdebugBody.attach( debugBodyBody );\n\t\t\tdebugBody.attach( debugBodyTopFrame );\n\t\t\tdebugBody.attach( debugBodyRightFrame );\n\t\t\tdebugBody.attach( debugBodyDownFrame );\n\t\t\tdebugBody.attach( debugBodyLeftFrame );\n\n\t\t\t// TODO cleaner code.\n\t\t\tvar attr = {\n\t\t\t\tx: body.vertices[ 0 ].x,\n\t\t\t\ty: body.vertices[ 0 ].y,\n\t\t\t\tw: body.vertices[ 0 ].x,\n\t\t\t\th: body.vertices[ 0 ].y\n\t\t\t};\n\n\t\t\t//We iterate to have a square shape for circles and polygons/\n\t\t\tfor ( var i = 1; i < body.vertices.length; i++ ) {\n\t\t\t\tif ( body.vertices[ i ].x < attr.x ) {\n\t\t\t\t\tattr.x = body.vertices[ i ].x;\n\t\t\t\t}\n\n\t\t\t\tif ( body.vertices[ i ].y < attr.y ) {\n\t\t\t\t\tattr.y = body.vertices[ i ].y;\n\t\t\t\t}\n\n\t\t\t\tif ( body.vertices[ i ].x > attr.w ) {\n\t\t\t\t\tattr.w = body.vertices[ i ].x;\n\t\t\t\t}\n\n\t\t\t\tif ( body.vertices[ i ].y > attr.h ) {\n\t\t\t\t\tattr.h = body.vertices[ i ].y;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdebugBody.attr( {\n\t\t\t\tx: attr.x,\n\t\t\t\ty: attr.y,\n\t\t\t\tw: Math.abs( attr.w - attr.x ),\n\t\t\t\th: Math.abs( attr.h - attr.y )\n\t\t\t} );\n\n\t\t\tdebugBody.origin( 'center' );\n\n\t\t\tdebugBodyBody.color( 'blue' );\n\t\t\tdebugBodyBody.alpha = 0.5;\n\t\t\tdebugBodyBody.z = debugBody._z + 1;\n\t\t\tdebugBodyBody.origin( 'center' );\n\n\t\t\tdebugBodyTopFrame.color( 'blue' );\n\t\t\tdebugBodyTopFrame.h = frameUnit;\n\t\t\tdebugBodyTopFrame.z = debugBody._z + 1;\n\t\t\tdebugBodyTopFrame.origin( 'center' );\n\n\t\t\tdebugBodyRightFrame.color( 'blue' );\n\t\t\tdebugBodyRightFrame.x = debugBodyBody._x + ( debugBodyBody._w - frameUnit );\n\t\t\tdebugBodyRightFrame.w = frameUnit;\n\t\t\tdebugBodyRightFrame.z = debugBody._z + 1;\n\t\t\tdebugBodyRightFrame.origin( 'center' );\n\n\t\t\tdebugBodyDownFrame.color( 'blue' );\n\t\t\tdebugBodyDownFrame.y = debugBodyBody._y + ( debugBodyBody._h - frameUnit );\n\t\t\tdebugBodyDownFrame.h = frameUnit;\n\t\t\tdebugBodyDownFrame.z = debugBody._z + 1;\n\t\t\tdebugBodyDownFrame.origin( 'center' );\n\n\t\t\tdebugBodyLeftFrame.color( 'blue' );\n\t\t\tdebugBodyLeftFrame.w = frameUnit;\n\t\t\tdebugBodyLeftFrame.z = debugBody._z + 1;\n\t\t\tdebugBodyLeftFrame.origin( 'center' );\n\n\t\t\treturn debugBody;\n\t\t}",
"function drawSkeleton() {\n\t// Loop through all the skeletons detected\n\tfor (let i = 0; i < poses.length; i++) {\n\t\tlet skeleton = poses[i].skeleton;\n\t\t// For every skeleton, loop through all body connections\n\t\tfor (let j = 0; j < skeleton.length; j++) {\n\t\t\tlet partA = skeleton[j][0];\n\t\t\tlet partB = skeleton[j][1];\n\t\t\tstroke(255);\n\t\t\tstrokeWeight(1);\n\t\t\tline(\n\t\t\t\tpartA.position.x,\n\t\t\t\tpartA.position.y,\n\t\t\t\tpartB.position.x,\n\t\t\t\tpartB.position.y\n\t\t\t);\n\t\t}\n\t}\n}",
"function showDebugInfo() {\n\t\t\tconsole.log();\n\t\t}",
"drawDebug() {\n if (!this.debugCanvas) return;\n let ctx = this.debugCanvas.getContext('2d');\n ctx.clearRect(0, 0, this.debugCanvas.width, this.debugCanvas.height);\n \n //bound\n let bound = this.bounds;\n ctx.strokeStyle = '#FF0000';\n if (bound) {\n \n ctx.beginPath();\n ctx.rect(bound.left, \n bound.top, \n bound.right - bound.left, \n bound.bottom - bound.top);\n ctx.stroke();\n }\n //bounds\n ctx.beginPath();\n ctx.rect(this.bounds.left,\n this.bounds.top,\n this.bounds.right - this.bounds.left,\n this.bounds.bottom - this.bounds.top);\n ctx.stroke();\n\n //springNodes\n ctx.strokeStyle = '#00FF00';\n for (let n = 0; n < this.springNodes.length; n++) {\n let node = this.springNodes[n];\n \n ctx.beginPath();\n ctx.arc(node.x, node.y,5,0,2*Math.PI);\n ctx.stroke();\n }\n\n //smoothNodes\n ctx.strokeStyle = '#00FFFF';\n for (let n = 0; n < this.smoothNodes.length; n++) {\n let node = this.smoothNodes[n];\n\n ctx.beginPath();\n ctx.arc(node.x, node.y,10,0,2*Math.PI);\n ctx.stroke();\n }\n }",
"function BpmnDiagrams(){//Code conversion for Bpmn Shapes\n//Start Region\n/** @private */this.annotationObjects={};//constructs the BpmnDiagrams module\n}",
"function showDiagram() {\n if (Cats.IDE.project)\n Cats.IDE.editorTabView.addEditor(new Cats.Gui.Editor.UMLEditor(\"Class Diagram\"));\n }",
"function drawDiagram () {\n drawQueues();\n drawArrows();\n drawTransitions();\n drawStages();\n drawCounters();\n}",
"enableDebug() {\n if (!this._debugGraphics) {\n this._debugGraphics = this.game.add.graphics(0, 0);\n this._debugGraphics.alpha = 0.5;\n }\n }",
"function startDemo() {\n View.set('Demo');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if it has at least one castable important ability | hasCastableImportant(){
const actions = this.player.getActions('e');
for( let action of actions ){
if( action.hasTag([stdTag.acNpcImportant, stdTag.acNpcImportantLast]) && action.castable() )
return true;
}
} | [
"typecheck() {\n return this.is_compatible(this.a);\n }",
"_canAccess(obj) {\n // TODO: `Object.getPrototypeOf` can trigger a proxy trap; need to check on that as well.\n\n // check if objects of this type have already been floodgated\n return !this._readErrorsByType.has(Object.getPrototypeOf(obj));\n }",
"abilityIsAssigned(ability) {\n return _.contains(this.form.abilities, ability);\n }",
"static isPickupable(reaction) {\n // Check if message has dropped emoji and by Cooper (official/valid drop).\n if (!this.isDroppedItemMsg(reaction.message)) return false;\n\n // Check if they are trying to collect via basket\n if (reaction.emoji.name !== EMOJIS.BASKET) return false;\n\n // Don't allow more pickups after 1 count.\n if (reaction.count > 2) return false;\n \n // Appears to be safe to pickup.\n return true;\n }",
"hasAbility (usage) {\n return this.abilities[USAGE[usage]] !== undefined;\n }",
"areAnyPermissionsAllowed() {\n for (const name in this.permissions) {\n if (this.find(name).allowed) {\n return true;\n }\n }\n\n return false;\n }",
"canAttach(player, card) {\n if(!card) {\n return false;\n }\n\n if((this.getType() !== 'goods') && (this.getType() !== 'spell')) {\n return false;\n }\n if(card.getType() !== 'dude' && card.getType() !== 'outfit' && card.getType() !== 'deed') {\n return false;\n } \n return true;\n }",
"canAdd() {\n return this.addable().length > 0;\n }",
"appliesToAbility(ability) {\n\n // Check the ability ID property\n if (this.abilityId == ability.id) {\n return true;\n }\n\n // Check the ID property of an attached ability, if any\n if (this.ability && this.ability.id == ability.id) {\n return true;\n }\n\n // There's no other ways we could match, so we're done here\n return false;\n\n }",
"function isCasting () {\n return state.playing.location === 'chromecast' || state.playing.location === 'airplay'\n}",
"isUsable() {\r\n return this._obj.title && this._obj.lyrics && this._obj.album && this._obj.artist;\r\n }",
"function isCollectable() {\n\treturn collectable; \n}",
"hasOwnAbility(abilityId) {\n return false;\n }",
"abilityIsAssigned(ability) {\n return _.includes(this.updateTokenForm.abilities, ability);\n }",
"canEmit() {\n if (this.typeParameters === undefined) {\n return true;\n }\n return this.typeParameters.every(typeParam => {\n if (typeParam.constraint === undefined) {\n return true;\n }\n return canEmitType(typeParam.constraint, type => this.resolveTypeReference(type));\n });\n }",
"function identifyRemoveEnchantmentCouldBeCast(player)\r\n{\r\n\tvar removeEnchantmentGestures = \"PDWP\";\r\n\r\n\tidentifyCastableSpell(removeEnchantmentGestures, player);\r\n\r\n\tvalidationChecks[removeEnchantmentGestures] = new Object();\r\n\tvalidationChecks[removeEnchantmentGestures].gesture = \"P\";\r\n\tvalidationChecks[removeEnchantmentGestures].targetValue = \"/^[^.]+$/\";\r\n\tvalidationChecks[removeEnchantmentGestures].confirmQuestion = \"use the default target of remove enchantment (your opponent)\"\r\n}",
"function isInheritable(skill, charName) {\n\t\"use strict\";\n\tvar moveType = charInfo[charName].move_type;\n\tvar color = charInfo[charName].color;\n\tvar weaponType = charInfo[charName].weapon_type;\n\n\tvar range = weaponTypeRange(weaponType);\n\n\tvar dragon = false;\n\tif (weaponType === \"Red Breath\" || weaponType === \"Green Breath\" || weaponType === \"Blue Breath\") {\n\t\tdragon = true;\n\t}\n\n\treturn (!skill.hasOwnProperty(\"char_unique\") && (!skill.hasOwnProperty(\"move_unique\") || skill.move_unique === moveType) && \n\t\t\t(!skill.hasOwnProperty(\"color_restrict\") || skill.color_restrict !== color) && (!skill.hasOwnProperty(\"range_unique\") || skill.range_unique === range) && \n\t\t\t(!skill.hasOwnProperty(\"weapon_restrict\") || skill.weapon_restrict !== weaponType) && (!skill.hasOwnProperty(\"weapon_unique\") || skill.weapon_unique === weaponType) && \n\t\t\t(!skill.hasOwnProperty(\"dragon_unique\") || dragon) && (!skill.hasOwnProperty(\"move_restrict\") || skill.move_restrict !== moveType));\n}",
"canAttack() {\n return this.hasCombatTarget() && this.inRange() && this.timerCooled() && this.notMoving()\n }",
"function checkAvailableAtdDrag( event ){\n if( event && event.dataTransfer && event.dataTransfer.items\n && event.dataTransfer.items.length ){\n return event.dataTransfer.items[0].type === 'atd';\n }\n return false;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
secretReveal When mouseover, secret is revealed | function secretReveal() {
// if ($(this).css('color') === 'black') {
$(this).css('color', 'orange');
secretsFound++;
$('#found').text(`${secretsFound}`);
$(this).off('mouseover');
// }
if (secretsFound === secretsTotal) {
$('body').append('<p id="ending"> You found all the secrets! </p>')
}
} | [
"function onMouserover(){\n // highlighting\n $(this).removeClass(\"secret\").addClass(\"found\");\n $(this).off('mouseover'); // it is found so no more mouseover handling\n secretsFound++; // increment the num of found secrets\n $(\"#secrets-found\").text(secretsFound); // update the ui\n}",
"function isOver() {\n\t\talert(\"You won!\");\n\t\treveal();\n\t}",
"function secretFound() {\n // Change its style to make it look invisible\n $(this).addClass(\"found\");\n // Check is the mouse is over the text component\n $(this).off(\"mouseover\", secretFound);\n // Adjust counter for the remaining amont of secrets to be found\n $secretTotal -= 1;\n}",
"function showHover() {\n $('#reddit-hover').show();\n}",
"mouseOver() {\n this.tooltipBox\n .text(this.tooltips[0])\n .style(\"visibility\", \"visible\");\n }",
"function revelation() {\n $(`span`).each(attemptReveal)\n}",
"function revealSecret() {\n\n $(this).addClass('found');\n secretsFound += 1;\n //update the total and turn off the span\n $secretsTotal = $('.secret').length;\n $(this).off();\n\n}",
"function mouseover(){\n tooltip.transition()\n .duration(200)\n .style(\"opacity\", .9);\n }",
"function mouseOver(){\n\tdocument.getElementById(\"hireNow\").innerHTML = \"Starts at LKR 2000.00<br>HIRE NOW!!!\";\n\tdocument.getElementById(\"hireNow\").style.display = \"block\";\n\tdocument.getElementById(\"pkgNameChanger\").innerHTML = \"...Non - A/C Package...\";\n}",
"function reveal() {\n //TODO\n //Teaser Preview (continued)\n //6. Restore the article contents to the original HTML\n //7. Animate the restored article to give a visual cue to the user\n}",
"function showHover() {\n $('#sentiment-hover').show();\n}",
"function secretLover() {\n // Change background to depressing color\n background(bg.rSad, bg.gSad, bg.bSad);\n\n // Display circle1\n displayCircle(circle1.fill.r, circle1.fill.g, circle1.fill.b, circle1.x, circle1.y, circle1.size);\n\n // Display circle2\n displayCircle(circle2.fill.r, circle2.fill.g, circle2.fill.b, circle2.x, circle2.y, circle2.size);\n\n // Display secretCircle\n secretCircle.x = circle2.x + secretCircle.size/2;\n secretCircle.y = circle2.y + secretCircle.size/2;\n\n displayCircle(secretCircle.fill.r, secretCircle.fill.g, secretCircle.fill.b, secretCircle.x, secretCircle.y, secretCircle.size);\n\n // Display narrator text inside a textbox\n narratorSays(narrator.text.secretLover);\n}",
"onReveal () {\n this.revealAll()\n this.state.channel.trigger(EVENT_REVEAL, {})\n }",
"function updateSpan() {\n let r = Math.random();\n if (r < REVEAL_POSSIBILITY) {\n $(this).removeClass('redacted');\n $(this).addClass('revealed');\n // If all are revealed, lose the game\n if ($('.revealed').length === redactables) {\n clearInterval(revealTimer);\n $spans.off('click');\n $secretSpans.off('mouseover');\n $('body').append('<p id=\"ending\"> You let everything leak! You lose! </p>')\n }\n }\n}",
"function revealWaste() {\n\n nextRevealWaste++;\n // confirm that both definitions have been viewed before revealing next href //\n nextReveal = nextRevealValue * nextRevealWaste;\n\n if (nextReveal > 0) {\n revealNext();\n }\n $(\"#arrowmaskvalue\").animate({ //Credit: https://www.tutorialrepublic.com/codelab.php?topic=faq&file=jquery-slide-left-and-right-effect\n width: '33vw'\n });\n $(\"#arrowmaskwaste\").animate({ //Credit: https://www.tutorialrepublic.com/codelab.php?topic=faq&file=jquery-slide-left-and-right-effect\n width: 0\n });\n}",
"function activateEvilEye() {\n $('#evilEye').css('display', \"inline\");\n $('#evilEye').on('click', displayEvilEyeFigure);\n}",
"function showReactions(e) {\n let icons = document.getElementById(\"reaction-hidden-\" + e.target.value);\n if (buttonBeingHovered !== null) {\n if (buttonBeingHovered !== icons) {\n buttonBeingHovered.style.display = \"none\";\n }\n }\n clearTimeout(endhover);\n\n if (icons !== null) {\n icons.style.display = \"flex\";\n buttonBeingHovered = icons;\n }\n}",
"mouseOver() {\n this.tooltipBox\n .text(this.predicateFn() ? this.tooltips[0] : this.tooltips[1])\n .style(\"visibility\", \"visible\");\n }",
"function revealAboutText()\n{\n\t$('.skill-icon').on('hover', (ev)=>\n\t{\n\t\tvar id = $(ev.target).attr('rel')\n\n\t\tvar target = id + '-text'\n\t\t$('[rel='+target+']').toggleClass('hide')\n\t})\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check slot status and if spun long enough stop it on result | function _check_slot( offset, result ) {
if ( now - that.lastUpdate > SPINTIME ) {
var c = parseInt(Math.abs( offset / SLOT_HEIGHT)) % ITEM_COUNT;
if ( c == result ) {
if ( result == 0 ) {
if ( Math.abs(offset + (ITEM_COUNT * SLOT_HEIGHT)) < (SLOT_SPEED * 1.5)) {
return true; // done
}
} else if ( Math.abs(offset + (result * SLOT_HEIGHT)) < (SLOT_SPEED * 1.5)) {
return true; // done
}
}
}
return false;
} | [
"function _check_slot( offset, result ) {\n \tconsole.log(\"RSLTD: \"+result);\n\t\tif ( now - that.lastUpdate > SPINTIME ) {\n\t\t var c = parseInt(Math.abs( offset / SLOT_HEIGHT)) % ITEM_COUNT;\n\t\t if ( c == result ) {\n\t\t\t\tif ( result == 0 ) {\n\t\t\t\t if ( Math.abs(offset + (ITEM_COUNT * SLOT_HEIGHT)) < (SLOT_SPEED * 1.5)) {\n\t\t\t\t\treturn true; // done\n\t\t\t\t }\n\t\t\t\t} else if ( Math.abs(offset + (result * SLOT_HEIGHT)) < (SLOT_SPEED * 1.5)) {\n\t\t\t\t return true; // done\n\t\t\t\t}\n\t\t }\n\t\t}\n\t\treturn false;\n }",
"function _check_slot( offset, result ) {\n\t\tif ( now - that.lastUpdate > SPINTIME ) {\n\t\t var c = parseInt(Math.abs( offset / SLOT_HEIGHT)) % ITEM_COUNT;\n\t\t if ( c == result ) {\n\t\t\tif ( result == 0 ) {\n\t\t\t if ( Math.abs(offset + (ITEM_COUNT * SLOT_HEIGHT)) < (SLOT_SPEED * 1.5)) {\n\t\t\t\treturn true; // done\n\t\t\t }\n\t\t\t} else if ( Math.abs(offset + (result * SLOT_HEIGHT)) < (SLOT_SPEED * 1.5)) {\n\t\t\t return true; // done\n\t\t\t}\n\t\t }\n\t\t}\n\t\treturn false;\n\t }",
"function _check_slot(offset, result) {\n if (now - that.lastUpdate > SPINTIME) {\n var c = parseInt(Math.abs(offset / SLOT_HEIGHT)) % ITEM_COUNT;\n if (c === result) {\n if (result === 0) {\n if (Math.abs(offset + ITEM_COUNT * SLOT_HEIGHT) < SLOT_SPEED * 1.5) {\n return true; // done\n }\n } else if (Math.abs(offset + result * SLOT_HEIGHT) < SLOT_SPEED *1.5) {\n return true; // done\n }\n }\n }\n return false;\n }",
"function _check_slot( offset, result ) {\n\tif ( now - that.lastUpdate > SPINTIME ) {\n\t var c = parseInt(Math.abs( offset / SLOT_HEIGHT)) % ITEM_COUNT;\n\t if ( c === result ) {\n\t\tif ( result === 0 ) {\n\t\t if ( Math.abs(offset + (ITEM_COUNT * SLOT_HEIGHT)) < (SLOT_SPEED * 1.5)) {\n\t\t\treturn true; // done\n\t\t }\n\t\t} else if ( Math.abs(offset + (result * SLOT_HEIGHT)) < (SLOT_SPEED * 1.5)) {\n\t\t return true; // done\n\t\t}\n\t }\n\t}\n\treturn false;\n }",
"function _check_slot(offset, result) {\n\n function _find(items, id) {\n for (var i = 0; i < items.length; i++) {\n if (items[i].id == id) return i;\n }\n }\n\n // fixes infinite spinniing bug hopefully, but debug here\n// console.log('checkslot now, lastUPdate', now - that.lastUpdate, SPINTIME);\n\n if ((now - that.lastUpdate) > SPINTIME) {\n var c = parseInt(Math.abs(offset / SLOT_HEIGHT)) % ITEM_COUNT;\n\n if (c == result) {\n if (result == 0) {\n if (Math.abs(offset + (ITEM_COUNT * SLOT_HEIGHT)) < (SLOT_SPEED * 1.5)) {\n return true; // done\n }\n } else if (Math.abs(offset + (result * SLOT_HEIGHT)) < (SLOT_SPEED * 1.5)) {\n return true; // done\n }\n }\n }\n return false;\n }",
"function checktimeslot() {\n\n\t}",
"stateWaitCycleResultsStop()\n {\n if( !this.isCycleResultsAnimating() )\n {\n for( let i = 0; i < this.slotGroupAry.length; ++i )\n this.slotGroupAry[i].deactivateCycleResults();\n\n this.slotState = slotDefs.ESLOT_PLACE_WAGER;\n }\n }",
"leave(args) {\n const slot_number = parseInt(args[0]);\n\n const slotIndex = this.slotsUsed.indexOf(args);\n if (slotIndex !== -1) {\n this.slotsUsed.splice(slotIndex, 1);\n } else {\n console.log('Not found');\n }\n\n const carIndex = this.cars.findIndex(car => car.slot_number === slot_number);\n if (carIndex !== -1) this.cars.splice(carIndex, 1);\n\n this.slotsAvailable.push(slot_number);\n this.slotsAvailable.sort();\n\n console.log('Slot number ' + slot_number + ' is free');\n }",
"function equipCheck(itemId, slot, result) {\n var item = Maps.findMobileById(itemId);\n\n if (!item) {\n result.result = false;\n return;\n }\n\n result.result = (item.equipmentSlots.indexOf(slot) !== -1);\n }",
"async function systemRequest(slotEmpty)\n{\n var exitTCompare;\n var flagEmptyIsBlocking = 0;\n var resCheck = [];\n\n var tempParkingSNum2 = slotEmpty;\n var kEmpty = Math.floor(tempParkingSNum2 / 10);\n var pEmpty = tempParkingSNum2 % 10;\n\n //call to checkSystemRequest function:\n //find exitT to compare:\n if (kEmpty == 0 || kEmpty == 4 || kEmpty == 5 || kEmpty == 9)//when the row is 'isParking' row\n exitTCompare = null; \n else if (kEmpty == 1 || kEmpty == 3 || kEmpty == 6 || kEmpty == 8) {//if it is a blocking row\n flagEmptyIsBlocking = 1;\n if (kEmpty == 1) blockedRow = 0;\n else if (kEmpty == 3) blockedRow = 4;\n else if (kEmpty == 6) blockedRow = 5;\n else if (kEmpty == 8) blockedRow = 9;\n exitTCompare = await getexitTDB(blockedRow * 10 + pEmpty);\n \n }\n resCheck = await checkSystemRequest(exitTCompare, slotEmpty);\n var rowResFrom = Math.floor(resCheck[1] / 10);\n var colResFrom = resCheck[1] % 10;\n\n if (resCheck!=false) //if the valet need to move car to the empty parking slot\n {\n //save details of the user we move from\n var tempUserID = await getIDDB(resCheck[1]);\n var tempExitT = await getexitTDB(resCheck[1]);\n //update at db that the slot is empty:\n slot.exitT = -1;\n slot.userID = -1;\n setSlot(resCheck[1], slot);\n //update in DB the flag of the blocked car:\n if (rowResFrom == 1) blockedRow2 = 0;\n else if (rowResFrom == 3) blockedRow2 = 4;\n else if (rowResFrom == 6) blockedRow2 = 5;\n else if (rowResFrom == 8) blockedRow2 = 9;\n\n var idBlocked = await getIDDB(blockedRow2 * 10 + colResFrom);\n var driver = await getDriver(idBlocked);\n driver.isBlock = false;\n updateDriver(idBlocked, driver);\n\n //move to the empty parking slot:\n slot.exitT = tempExitT;\n slot.userID = tempUserID;\n setSlot(resCheck[2], slot);\n\n var tempUserID = await getIDDB(slotEmpty);\n var driver = await getDriver(tempUserID);\n var outPutRequest = {\n carNumber: driver.carNumber,\n current: resCheck[1],\n future: resCheck[2]\n };\n setOutPutRequest(outPutRequest);\n }\n else if (resCheck == false) return false; //return false=there is not car to move to the empty parking slot\n}//end of systemRequest func",
"function _haveFreeSlot() {\n var res = $rootScope.recordFlowControl.occupiedSlots < $rootScope.recordFlowControl.maxRequests;\n if (!res) {\n $log.debug(\"No free slot available.\");\n }\n return res;\n }",
"relinquish_slot() {\n this.port.postMessage('release slot');\n }",
"_timer2() {\n //console.log(this);\n let list = this.list.filter(pred => pred.status === Giveaway.status.ENDING);\n\n for (let i = 0; i < list.length; i++) {\n let item = list[i];\n\n if (item.hasEnded()[0]) {\n this.emit(\"giveaway_ended\", item);\n continue;\n //return;\n }\n }\n }",
"_onSlotChange() {\n // Update useless spins if needed\n if (this._uselessSpinsRemaining >= 1) {\n if (this._selectedSlot == this._startedUselessSpinOnIndex) {\n this._uselessSpinsRemaining--;\n // When useless spins are done,\n if (this._uselessSpinsRemaining <= 0) {\n this._needsSpin = true;\n }\n }\n }\n else {\n // End spin when reached target\n if (this._selectedSlot == this._targetSlot) {\n if (this._spinCompleteCallback != undefined) {\n this._spinCompleteCallback();\n }\n this._needsSpin = false;\n }\n }\n }",
"checkNearestSlot(callback)\n {\n let nearestSlot=mainClassObject.checkForParkingSlot(undefined,(mainClassObject.noOfLots/2),mainClassObject.noOfSlots)\n callback(nearestSlot)\n }",
"async function exitCar(inputSlotNum, employeeNum, requestNum) {\n var resCheck1;//output of checkSystemRequest function\n\n //update empty slot in DB:\n slot.exitT = -1;\n slot.userID = -1;\n setSlot(inputSlotNum, slot);\n\n var tempParkingSNum = inputSlotNum;\n var tempRowNum = Math.floor(tempParkingSNum / 10);\n var tempColNum = tempParkingSNum % 10;\n\n if (tempRowNum == 0 || tempRowNum == 4 || tempRowNum == 5 || tempRowNum == 9)//when the row is 'isParking' row\n resCheck1 = await checkSystemRequest(null, inputSlotNum);// check if to add a system request to valet's tasks table\n else if (tempRowNum == 1 || tempRowNum == 3 || tempRowNum == 6 || tempRowNum == 8) //when the row is 'isBlockingParking' row\n {\n if (tempRowNum == 1) blockedRow = 0;\n else if (tempRowNum == 3) blockedRow = 4;\n else if (tempRowNum == 6) blockedRow = 5;\n else if (tempRowNum == 8) blockedRow = 9;\n\n //update in DB the flag of the blocked car:\n var resIDBlocked = await getIDDB(blockedRow * 10 + tempColNum);\n var driver = await getDriver(resIDBlocked);\n driver.isBlock = false;\n updateDriver(resIDBlocked, driver);\n\n var ExitTisParking = await getExitTDriverSlot(blockedRow * 10 + tempColNum);//get exit time of the blocked row\n resCheck1 = await checkSystemRequest(ExitTisParking, inputSlotNum);// check if to add a system request to valet's tasks table\n }\n if (resCheck1 != false) {//if find car to move to the empty parking slot\n //add requst to valet's tasks table\n var request = await getRequest(employeeNum, requestNum);\n request.requestNumber = requestNum;\n request.flagPriority = true;\n updateRequest(employeeNum, request);\n\n } //end of exitCars function\n}",
"async checkStop(context) {\n if (context.checkingStop || context.ended) {\n return;\n }\n context.checkingStop = true;\n let job;\n try {\n job = await self.db.findOne({ _id: context._id });\n if (!job) {\n self.apos.util.error('job never found');\n return;\n }\n if (job.canceling) {\n if (job.canCancel) {\n return await halt('cancel', 'canceled');\n } else if (job.canStop) {\n return await halt('stop', 'stopped');\n }\n }\n } catch (err) {\n self.apos.util.error(err);\n await self.db.updateOne({ _id: context._id }, {\n $set: {\n ended: true,\n canceling: false,\n status: 'failed'\n }\n });\n } finally {\n context.checkingStop = false;\n if (job && job.ended) {\n clearInterval(context.interval);\n }\n }\n async function halt(verb, status) {\n await context.options[verb](job);\n const $set = {\n ended: true,\n canceling: false,\n status: status\n };\n await self.db.updateOne({ _id: job._id }, { $set: $set });\n }\n }",
"async function checkSystemRequest(exitTCompare,emptyS) {\n var blockedRow;\n var flagSystemReq;\n var outPutCheckSystemReq=[];\n\n for (var k = 0; k < Config.x; k++) {\n for (var p = 0; p < Config.y; p++) {\n if (k == 1 || k == 3 || k == 6 || k == 8) {//just if it is a blocking row\n if (k == 1) blockedRow = 0;\n else if (k == 3) blockedRow = 4;\n else if (k == 6) blockedRow = 5;\n else if (k == 8) blockedRow = 9;\n\n var idblocking = await getIDDB(k * 10 + p);\n var exitTblocking = await getexitTDB(k * 10 + p);\n var exitTblocked = await getexitTDB(blockedRow * 10 + p);\n\n if (idblocking != -1 && exitTblocking > exitTblocked) //if parking slot is not empty, and blockingcar's exitT > blockedcar's exitT\n if ((exitTCompare != null && exitTblocking <= exitTCompare) || exitTCompare == null) //if blockingcar's exitTime<=exitTCompare\n flagSystemReq = 1; \n }\n if (flagSystemReq == 1) break;\n }\n if (flagSystemReq == 1) break;\n }\n //the output is only used in systemRequest function\n if (flagSystemReq != 1) return false;//no need system request\n else {//need system request\n outPutCheckSystemReq.push(idblocking);//the driver we want to moving to the empty slot\n outPutCheckSystemReq.push(k * 10 + p); //the slot of the car we want to move\n outPutCheckSystemReq.push(emptyS);//the empty slot\n return outPutCheckSystemReq;\n }\n}",
"decrementAvailability() {\n this.slotsAvailability--;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
adds a lily pad to a linked list | function addLilyPad() {
const r = rnd(10, 10);
const c = {
p: vec(rnd(20, 80), -r),
r,
a: rnd(PI * 2),
v: rnds(0.03, 0.08),
l: 2,
next: undefined,
};
if (lastLilyPad != null) {
lastLilyPad.next = c;
}
if (playersLilyPad == null) {
playersLilyPad = c;
}
// makes the color of the lilypad that the player is on
// a different shade of green
color ("green");
char("a", playersLilyPad.p);
// pushed new lilypad to the list
lastLilyPad = c;
lilypads.push(c);
} | [
"addtoLL(val, loc) {\n var node = {value: val};\n // if node is inserted at first location\n if (loc == 0) {\n node.next = this.list.head;\n this.list.head = node;\n } else {\n let i = 0;\n var tmpnode = this.list.head;\n while (i !== loc-1) {\n // location is greater than length; insert at last location\n tmpnode = tmpnode.next;\n if (tmpnode.next === null) break;\n i++;\n }\n node.next = tmpnode.next;\n tmpnode.next = node;\n // if node is inserted at last location...\n if (node.next === null) this.list.tail = node;\n } \n }",
"addAtStart(data) {\n let node = new Node(data);\n\n node.next = head;\n head = node;\n\n this.listSize++;\n }",
"addToTail(val) {\n debugger;\n let newNode = new Node(val);\n if (this.length === 0){\n this.head = newNode;\n this.tail = newNode;\n } else {\n this.tail.next = newNode;\n this.tail = newNode;\n }\n this.length++;\n return this;\n }",
"unshift(val) {\n const newNode = new Node(val);\n newNode.next = this.head;\n\n // if node(s) are already on the list, set the 'prev' \n // pointer for the current first node to the new node.\n if (this.head) {\n this.head.prev = newNode;\n } else {\n // head pointer is null, list is empty, tail should\n // also be null.\n this.tail = newNode;\n }\n\n this.head = newNode;\n\n this.length++;\n\n }",
"unshift(val) {\n const newNode = new Node(val);\n // base case for adding to empty list\n if (!this.head) {\n this.head = this.tail = newNode;\n }\n else {\n this.head.prev = newNode;\n newNode.next = this.head;\n this.head = newNode;\n }\n this.length++;\n }",
"insertAt(id, list) {\n // append remainder of the list to the newly added list\n // this = pink\n // list = red\n if (this.id === id) return list.append(this);\n else return new ListNode(this.value, this.next ? this.next.insertAt(id, list) : null);\n }",
"function addWhiteSpaceToList(list){\n var space = document.createElement('li');\n space.style.display = \"inline\";\n space.style.color = \"white\";\n space.innerHTML = \" \"\n list.appendChild(space);\n }",
"function addWhiteSpaceToList(list){\r\n var space = document.createElement('li');\r\n space.style.display = \"inline\";\r\n space.style.color = \"white\";\r\n space.innerHTML = \" \"\r\n list.appendChild(space);\r\n }",
"function tp_zero_pad(n, l)\n{\n\tn = n.toString();\n\tl = Number(l);\n\tvar pad = '0';\n\twhile (n.length < l) {n = pad + n;}\n\treturn n;\n}",
"addToTail(val) {\n let newNode = new Node(val);\n if(!this.head){\n this.head = newNode;\n }\n if(this.tail) {\n this.tail.next = newNode;\n }\n this.tail = newNode;\n this.length++;\n return this;\n }",
"function DLList_append (list, data) {\n\n\tvar New = new DLList_node(data);\n\n\tNew.next = null;\n\tNew.prev = list.tail;\n\tlist.tail = New;\n\n\t/***** empty list? *****/\n\n\tif (!list.head)\n\t\tlist.head = New;\n\telse\n\t\tNew.prev.next = New;\n\t\t\n\tlist.length++;\n\n\treturn New;\n}",
"appendleft(val) {\n\n // doubleLinkedList\n this._doubleLinkedList.unshift(val);\n this.first = this._doubleLinkedList.head;\n this.last = this._doubleLinkedList.tail;\n this.size = this._doubleLinkedList.length;\n }",
"addNodeAtLastPosition(data) {\n // 1. Create a Node\n const newNode = new Node(data);\n\n // 2. If list is empty\n if (this.isListEmpty()) {\n // attach newly created Node to Head\n this.head = newNode;\n this.length++;\n } else { // List is not empty\n let trav = this.head;\n while (trav.next !== null)\n trav = trav.next;\n // attach newly created Node at Last\n trav.next = newNode;\n this.length++;\n }\n }",
"function addKitchen() {\n\tvar newItem = document.createElement(\"LI\");\n var textnode = document.createTextNode(\"Cleaning the kitchen\");\n newItem.appendChild(textnode);\n\n var list = document.getElementById(\"demo2\");\n list.insertBefore(newItem, list.childNodes[0]);\n}",
"function padL(len, m) {\n if (m.length < len) { return repeat(len - m.length, 0).concat(m); }\n else { return m; }\n}",
"addAt(data, pos) {\n\n if (pos < 1) {\n alert(\"Invalid position\");\n return;\n\n } else {\n let node = new Node(data);\n if (pos === 1) {\n this.addAtStart(node);\n } else {\n let curr = this.head;\n for (let i = 1; i <= pos - 2; i++) {\n curr = curr.next;\n }\n\n let temp = curr.next;\n curr.next = node;\n node.next = temp;\n }\n }\n }",
"function list_Input(new_LinkedList, element) {\r\n\r\n for (var index = start_Position; index < end_Position; index++) \r\n new_LinkedList.insert(parseInt(node_Array[index], 0));\r\n \r\n return new_LinkedList;\r\n}",
"addToHead(value) {\n const newNode = new ListNode(value, null, this.head);\n // if this.head exist- point the new node to the prev \n if (this.head) {\n this.head.prev = newNode;\n }\n // if there is no tail the tail is now the newNode we're inserting\n if (!this.tail) {\n this.tail = newNode;\n }\n this.head = newNode;\n }",
"function sumListsFollowUp(l1, l2) {\n const l1Length = getLength(l1);\n const l2Length = getLength(l2);\n\n if (l1Length < l2Length) {\n l1 = padList(l1, l2Length - l1Length);\n } else if (l1Length > l2Length) {\n l2 = padList(l2, l1Length - l2Length);\n }\n\n let result = recurse(l1, l2);\n if (result.data >= 10) {\n result.data = result.data % 10;\n const n = new Node(1);\n n.next = result;\n result = n;\n }\n\n return result;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
if we invited users, handle additional postresponse processing | async postProcessInvitedUsers () {
if (this.userInviter) {
return this.userInviter.postProcess();
}
} | [
"async confirmUser () {\n\t\t// in the case of a user accepting an invite, they might have signed up with an email different\n\t\t// from the email they were originally invited with, here we detect that scenario and make sure\n\t\t// the invited user record has the correct email\n\t\tif (this.user.get('email') !== this.invitedUser.get('email') && this.user.get('originalEmail')) {\n\t\t\tthis.invitedUser.attributes.email = this.user.get('email');\n\t\t\tthis.invitedUser.attributes.searchableEmail = this.user.get('email').toLowerCase();\n\t\t\tthis.invitedUser.attributes.username = this.user.get('email').split('@')[0];\n\t\t}\n\t\tconst accessToken = ((this.invitedUser.get('accessTokens') || {}).web || {}).token;\n\t\tif (accessToken) {\n\t\t\tthis.responseData = {\n\t\t\t\taccessToken\n\t\t\t};\n\t\t} else {\n\t\t\t// only copy providerInfo if we are not doing New Relic IdP, if we are, the provider credentials\n\t\t\t// will be set separately\n\t\t\tconst providerInfo = this.request.request.headers['x-cs-enable-uid'] ? undefined : this.user.get('providerInfo');\n\t\t\tconst providerIdentities = this.request.request.headers['x-cs-enable-uid'] ? undefined : this.user.get('providerIdentities');\n\t\t\tthis.responseData = await new this.confirmHelperClass({ // avoids a circular require\n\t\t\t\trequest: this.request,\n\t\t\t\tuser: this.invitedUser,\n\t\t\t\tnotRealLogin: true,\n\t\t\t\tdontGenerateAccessToken: this.request.request.serviceGatewayAuth\n\t\t\t}).confirm({\n\t\t\t\temail: this.user.get('email'),\n\t\t\t\tusername: this.user.get('username'),\n\t\t\t\tpasswordHash: this.user.get('passwordHash'),\n\t\t\t\tproviderInfo,\n\t\t\t\tproviderIdentities\n\t\t\t});\n\t\t}\n\n\t\tObject.assign(this.responseData, {\n\t\t\tuserId: this.invitedUser.id,\n\t\t\tteamId: this.team.id\n\t\t});\n\t}",
"async publishNumUsersInvited () {\n\t\tif (this.dontPublishToInviter) { return; }\n\t\tif (!this.transforms.invitingUserUpdateOp) { return; }\n\t\tconst channel = 'user-' + this.user.id;\n\t\tconst message = {\n\t\t\tuser: this.transforms.invitingUserUpdateOp,\n\t\t\trequestId: this.request.request.id\n\t\t};\n\t\ttry {\n\t\t\tawait this.api.services.broadcaster.publish(\n\t\t\t\tmessage,\n\t\t\t\tchannel,\n\t\t\t\t{ request: this.request }\n\t\t\t);\n\t\t}\n\t\tcatch (error) {\n\t\t\t// this doesn't break the chain, but it is unfortunate\n\t\t\tthis.request.warn(`Unable to publish inviting user update message to channel ${channel}: ${JSON.stringify(error)}`);\n\t\t}\n\t}",
"function checkIfInvited (user) {\n\n var invite = Invites.findOne({ invitedUserEmail : Users.getEmail(user) });\n\n if(invite){\n\n var invitedBy = Meteor.users.findOne({ _id : invite.invitingUserId });\n\n Users.update(user._id, { $set: {\n \"telescope.isInvited\": true,\n \"telescope.invitedBy\": invitedBy._id,\n \"telescope.invitedByName\": Users.getDisplayName(invitedBy)\n }});\n\n Invites.update(invite._id, {$set : {\n accepted : true\n }});\n\n }\n}",
"handleInvite (event) {\n this.setState({loading: true});\n event.preventDefault()\n const mail = {\n email: this.state.email\n }\n axios.post(`${BASE_API_URL}/guest/invite`, mail).then(response => { \n var msg = response.data.success;\n this.setState({loading: false});\n if(msg == true){\n return this.goToHome();\n }\n else{\n return this.invitationFailed();\n }\n })\n }",
"function inviteUser(req, res) {\n if (validator.isEmail(req.body.email)) {\n User.findOne({email: req.body.email}, function(err, userRecord) {\n if (err) {\n res.json({code: Constant.ERROR_CODE, 'message': Constant.INTERNAL_ERROR});\n } else {\n if (userRecord) {\n CompanyUser.findOne({userId: userRecord._id, companyId: req.body.companyId, deleted: false}, function(err, companyRecord) {\n if (err) {\n res.json({code: Constant.ERROR_CODE, 'message': Constant.INTERNAL_ERROR});\n } else {\n if (companyRecord) {\n res.json({code: Constant.ERROR_CODE, 'message': Constant.ALREADY_INVITED_USER});\n } else {\n var CompanyUserData = {\n userId: userRecord._id,\n companyId: req.body.companyId,\n userImage: '',\n firstname: req.body.firstname,\n lastname: req.body.lastname,\n email: req.body.email,\n roles: req.body.roles,\n isAccepted: 0,\n status: 0,\n deleted: false\n };\n var CompanyUserRecord = new CompanyUser(CompanyUserData);\n // call the built-in save method to save to the database\n CompanyUserRecord.save(function(err, CompanyUserInfo) {\n if (err) {\n res.json({code: Constant.ERROR_CODE, 'message': Constant.INTERNAL_ERROR});\n } else {\n var usersInfo = {\n userId: userRecord._id,\n firstname: req.body.firstname,\n lastname: req.body.lastname,\n email: req.body.email,\n company: req.body.company,\n roles: req.body.roles,\n status: 0,\n email_verified: userRecord.email_verified,\n companyId: req.body.companyId,\n isAccepted: 0,\n }\n if (userRecord.password) {\n nodemailerMailgun.sendMail({\n from: Config.EMAIL_FROM, // sender address\n to: req.body.email, //Config.EMAIL_TEMP, // 'smartData@yopmail.com' For Sandbox subdomains add the address to authorized recipients in Account Settings or Please add your own domain for email\n subject: 'Account invitation from ' + req.body.companyName, // Subject line\n text: 'Account invitation from ' + req.body.companyName, // plaintext body\n html: '<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\\n\\\n <tbody><tr><td>\\n\\\n <table align=\"center\" border=\"0\" cellpadding=\"5\" cellspacing=\"0\" style=\"width:640px;background-color:rgb(57,65,81);\">\\n\\\n <tbody><tr>\\n\\\n <td></td>\\n\\\n </tr></tbody></table>\\n\\\n <table align=\"center\" border=\"0\" cellpadding=\"10\" cellspacing=\"0\" style=\"width:640px;background-color:#fff\">\\n\\\n <tbody><tr><td>\\n\\\n <p>Hello ' + req.body.firstname + ',</p>\\n\\\n <p><br />You have been invited by company <b>' + req.body.companyName + '</b>. Please click below link to accept invitation and set your password to continue with TelPro Flex.</p>\\n\\\n <p><a target=\"_blank\" href=\"' + Config.WebFrontEndUrl + '/acceptCompanyInvitation/' + usersInfo.userId + '/' + req.body.companyId + '\">' + Config.WebFrontEndUrl + '/acceptCompanyInvitation/' + usersInfo.userId + '/' + req.body.companyId + '</a><br /><br /></p>\\n\\\n <p>Sincerely,<br />TelPro Flex</p>\\n\\\n <div style=\"border-bottom: 2px solid rgb(57,65,81); height: 0px;\"> </div>\\n\\\n <p>Copyright © ' + currentYear + ' TelPro Flex.</p>\\n\\\n </td></tr></tbody></table></td></tr>\\n\\\n </tbody></table>' // html body\n }, function(err, info) {\n if (err) {\n res.json({code: Constant.SUCCESS_CODE, 'message': Constant.SENT_USER_EMAIL_FAILED, data: usersInfo});\n }\n else {\n res.json({code: Constant.SUCCESS_CODE, 'message': Constant.USER_INVITE_SUCCESS + req.body.email, data: usersInfo});\n }\n });\n } else {\n nodemailerMailgun.sendMail({\n from: Config.EMAIL_FROM, // sender address\n to: req.body.email, //Config.EMAIL_TEMP, // 'smartData@yopmail.com' For Sandbox subdomains add the address to authorized recipients in Account Settings or Please add your own domain for email\n subject: 'Account invitation from ' + req.body.companyName, // Subject line\n text: 'Account invitation from ' + req.body.companyName, // Subject line\n html: '<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\\n\\\n <tbody><tr><td>\\n\\\n <table align=\"center\" border=\"0\" cellpadding=\"5\" cellspacing=\"0\" style=\"width:640px;background-color:rgb(57,65,81);\">\\n\\\n <tbody><tr>\\n\\\n <td></td>\\n\\\n </tr></tbody></table>\\n\\\n <table align=\"center\" border=\"0\" cellpadding=\"10\" cellspacing=\"0\" style=\"width:640px;background-color:#fff\">\\n\\\n <tbody><tr><td>\\n\\\n <p>Hello ' + req.body.firstname + ',</p>\\n\\\n <p><br />You have been invited by company <b>' + req.body.companyName + '</b>. Please click below link to accept invitation and set your password to continue with TelPro Flex.</p>\\n\\\n <p><a target=\"_blank\" href=\"' + Config.WebFrontEndUrl + '/acceptinvite/' + usersInfo.userId + '/' + req.body.companyId + '\">' + Config.WebFrontEndUrl + '/acceptinvite/' + usersInfo.userId + '/' + req.body.companyId + '</a><br /><br /></p>\\n\\\n <p>Sincerely,<br />TelPro Flex</p>\\n\\\n <div style=\"border-bottom: 2px solid rgb(57,65,81); height: 0px;\"> </div>\\n\\\n <p>Copyright © ' + currentYear + ' TelPro Flex.</p>\\n\\\n </td></tr></tbody></table></td></tr>\\n\\\n </tbody></table>' // html body\n }, function(err, info) {\n if (err) {\n res.json({code: Constant.SUCCESS_CODE, 'message': Constant.SENT_USER_EMAIL_FAILED});\n }\n else {\n res.json({code: Constant.SUCCESS_CODE, 'message': Constant.USER_INVITE_SUCCESS + req.body.email, data: usersInfo});\n }\n });\n }\n\n }\n });\n }\n }\n })\n } else {\n var userData = {\n username: req.body.email,\n firstname: req.body.firstname,\n lastname: req.body.lastname,\n email: req.body.email,\n company: req.body.companyName,\n status: 0,\n email_verified: false,\n joiningTime: new Date().toISOString(),\n deleted: false,\n roles: req.body.roles,\n };\n var UsersRecord = new User(userData);\n // call the built-in save method to save to the database\n UsersRecord.save(function(err, userInfo) {\n if (err) {\n res.json({code: Constant.ERROR_CODE, 'message': Constant.INTERNAL_ERROR});\n } else {\n if (userInfo) {\n var CompanyUserData = {\n userId: userInfo._id,\n companyId: req.body.companyId,\n userImage: '',\n firstname: req.body.firstname,\n lastname: req.body.lastname,\n company: req.body.companyName,\n email: req.body.email,\n roles: req.body.roles,\n isAccepted: 0,\n status: 0,\n deleted: false\n };\n var CompanyUserRecord = new CompanyUser(CompanyUserData);\n // call the built-in save method to save to the database\n CompanyUserRecord.save(function(err, CompanyUserInfo) {\n if (err) {\n res.json({code: Constant.ERROR_CODE, 'message': Constant.INTERNAL_ERROR});\n } else {\n var usersInfo = {\n userId: userInfo._id,\n firstname: req.body.firstname,\n lastname: req.body.lastname,\n email: req.body.email,\n company: req.body.companyName,\n roles: req.body.roles,\n status: 0,\n email_verified: false,\n companyId: req.body.companyId,\n isAccepted: 0,\n }\n nodemailerMailgun.sendMail({\n from: Config.EMAIL_FROM, // sender address\n to: req.body.email, //Config.EMAIL_TEMP, // 'smartData@yopmail.com' For Sandbox subdomains add the address to authorized recipients in Account Settings or Please add your own domain for email\n subject: 'Account invitation from ' + req.body.companyName, // Subject line\n text: 'Account invitation from ' + req.body.companyName, // plaintext body\n html: '<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\\n\\\n <tbody><tr><td>\\n\\\n <table align=\"center\" border=\"0\" cellpadding=\"5\" cellspacing=\"0\" style=\"width:640px;background-color:rgb(57,65,81);\">\\n\\\n <tbody><tr>\\n\\\n <td></td>\\n\\\n </tr></tbody></table>\\n\\\n <table align=\"center\" border=\"0\" cellpadding=\"10\" cellspacing=\"0\" style=\"width:640px;background-color:#fff\">\\n\\\n <tbody><tr><td>\\n\\\n <p>Hello ' + req.body.firstname + ',</p>\\n\\\n <p><br />You have been invited by company <b>' + req.body.companyName + '</b>. Please click below link to accept invitation and set your password to continue with TelPro Flex.</p>\\n\\\n <p><a target=\"_blank\" href=\"' + Config.WebFrontEndUrl + '/acceptinvite/' + usersInfo.userId + '/' + req.body.companyId + '\">' + Config.WebFrontEndUrl + '/acceptinvite/' + usersInfo.userId + '/' + req.body.companyId + '</a><br /><br /></p>\\n\\\n <p>Sincerely,<br />TelPro Flex</p>\\n\\\n <div style=\"border-bottom: 2px solid rgb(57,65,81); height: 0px;\"> </div>\\n\\\n <p>Copyright © ' + currentYear + ' TelPro Flex.</p>\\n\\\n </td></tr></tbody></table></td></tr>\\n\\\n </tbody></table>' // html body\n }, function(err, info) {\n if (err) {\n res.json({code: Constant.SUCCESS_CODE, 'message': Constant.SENT_USER_EMAIL_FAILED, data: usersInfo});\n }\n else {\n res.json({code: Constant.SUCCESS_CODE, 'message': Constant.USER_INVITE_SUCCESS + req.body.email, data: usersInfo});\n }\n });\n }\n });\n\n }\n }\n });\n }\n }\n });\n } else {\n res.json({code: Constant.ERROR_CODE, 'message': Constant.INVALID_EMAIL});\n }\n}",
"async sendInviteEmails () {\n\t\tif (this.delayEmail) {\t// allow client to delay the email sends, for testing purposes\n\t\t\tsetTimeout(this.sendInviteEmails.bind(this), this.delayEmail);\n\t\t\tdelete this.delayEmail;\n\t\t\treturn;\n\t\t}\n\n\t\tawait Promise.all(this.invitedUsers.map(async userData => {\n\t\t\t// using both of these flags is kind of perverse, but i don't want to affect existing behavior ...\n\t\t\t// dontSendEmail is set on the POST /users request, and the expectation is that the invites information won't\n\t\t\t// be updated either ... that behavior came first and i want to leave it alone\n\t\t\t// but on the other hand when users are created on the fly in a review or codemark,\n\t\t\t// we don't want to send invite emails but we DO want to update the invite info\n\t\t\tif (!this.dontSendEmail && !this.dontSendInviteEmail) {\n\t\t\t\tawait this.sendInviteEmail(userData);\n\t\t\t}\n\t\t\tif (!this.dontSendEmail) {\n\t\t\t\tawait this.updateInvites(userData);\n\t\t\t}\n\t\t}));\n\t}",
"function hasInvitations(req, res, next) {\n inviteMapper.getAll((err, invites) => {\n if (err) {\n return next(err);\n }\n //filter only those which are related to our logged in user\n req.setOfInvites = invites.filter((elem) => {\n return elem.to === req.user.username;\n });\n next();\n });\n}",
"function handleResponse(data) {\n // We're only looking for messages that have invitations\n // (i.e., messages from another user to us)\n return $(data).find(`#${INBOX_ID} .feedmessage`);\n }",
"function resendInvitation(req, res) {\n CompanyUser.findOne({userId: req.body.userId, companyId: req.body.companyId, deleted: false})\n .populate('userId', '_id email email_verified password')\n .populate('companyId')\n .exec(function(err, companyUsers) {\n if (err) {\n res.json({code: Constant.ERROR_CODE, message: Constant.INTERNAL_ERROR});\n } else {\n if (companyUsers) {\n if (companyUsers.userId.password) {\n nodemailerMailgun.sendMail({\n from: Config.EMAIL_FROM, // sender address\n to: companyUsers.userId.email, //Config.EMAIL_TEMP, // 'smartData@yopmail.com' For Sandbox subdomains add the address to authorized recipients in Account Settings or Please add your own domain for email\n subject: 'Account invitation from ' + companyUsers.companyId.company, // Subject line\n text: 'Account invitation from ' + companyUsers.companyId.company, // plaintext body\n html: '<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\\n\\\n <tbody><tr><td>\\n\\\n <table align=\"center\" border=\"0\" cellpadding=\"5\" cellspacing=\"0\" style=\"width:640px;background-color:rgb(57,65,81);\">\\n\\\n <tbody><tr>\\n\\\n <td></td>\\n\\\n </tr></tbody></table>\\n\\\n <table align=\"center\" border=\"0\" cellpadding=\"10\" cellspacing=\"0\" style=\"width:640px;background-color:#fff\">\\n\\\n <tbody><tr><td>\\n\\\n <p>Hello ' + companyUsers.firstname + ',</p>\\n\\\n <p><br />You have been invited by company <b>' + companyUsers.companyId.company + '</b>. Please click below link to accept invitation and set your password to continue with TelPro Flex.</p>\\n\\\n <p><a target=\"_blank\" href=\"' + Config.WebFrontEndUrl + '/acceptCompanyInvitation/' + req.body.userId + '/' + req.body.companyId + '\">' + Config.WebFrontEndUrl + '/acceptCompanyInvitation/' + req.body.userId + '/' + req.body.companyId + '</a><br /><br /></p>\\n\\\n <p>Sincerely,<br />TelPro Flex</p>\\n\\\n <div style=\"border-bottom: 2px solid rgb(57,65,81); height: 0px;\"> </div>\\n\\\n <p>Copyright © ' + currentYear + ' TelPro Flex.</p>\\n\\\n </td></tr></tbody></table></td></tr>\\n\\\n </tbody></table>' // html body\n }, function(err, info) {\n if (err) {\n res.json({code: Constant.SUCCESS_CODE, 'message': Constant.SENT_USER_EMAIL_FAILED});\n }\n else {\n res.json({code: Constant.SUCCESS_CODE, 'message': Constant.RESENT_INVITATION_SUCCESS});\n }\n });\n }\n else {\n nodemailerMailgun.sendMail({\n from: Config.EMAIL_FROM, // sender address\n to: companyUsers.userId.email, //Config.EMAIL_TEMP, // 'smartData@yopmail.com' For Sandbox subdomains add the address to authorized recipients in Account Settings or Please add your own domain for email\n subject: 'Account invitation from ' + companyUsers.companyId.company, // Subject line\n text: 'Account invitation from ' + companyUsers.companyId.company, // plaintext body\n html: '<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\\n\\\n <tbody><tr><td>\\n\\\n <table align=\"center\" border=\"0\" cellpadding=\"5\" cellspacing=\"0\" style=\"width:640px;background-color:rgb(57,65,81);\">\\n\\\n <tbody><tr>\\n\\\n <td></td>\\n\\\n </tr></tbody></table>\\n\\\n <table align=\"center\" border=\"0\" cellpadding=\"10\" cellspacing=\"0\" style=\"width:640px;background-color:#fff\">\\n\\\n <tbody><tr><td>\\n\\\n <p>Hello ' + companyUsers.firstname + ',</p>\\n\\\n <p><br />You have been invited by company <b>' + companyUsers.companyId.company + '</b>. Please click below link to accept invitation and set your password to continue with TelPro Flex.</p>\\n\\\n <p><a target=\"_blank\" href=\"' + Config.WebFrontEndUrl + '/acceptinvite/' + req.body.userId + '/' + req.body.companyId + '\">' + Config.WebFrontEndUrl + '/acceptinvite/' + req.body.userId + '/' + req.body.companyId + '</a><br /><br /></p>\\n\\\n <p>Sincerely,<br />TelPro Flex</p>\\n\\\n <div style=\"border-bottom: 2px solid rgb(57,65,81); height: 0px;\"> </div>\\n\\\n <p>Copyright © ' + currentYear + ' TelPro Flex.</p>\\n\\\n </td></tr></tbody></table></td></tr>\\n\\\n </tbody></table>' // html body\n }, function(err, info) {\n if (err) {\n res.json({code: Constant.SUCCESS_CODE, 'message': Constant.SENT_USER_EMAIL_FAILED});\n }\n else {\n res.json({code: Constant.SUCCESS_CODE, 'message': Constant.RESENT_INVITATION_SUCCESS});\n }\n });\n }\n }\n else {\n res.json({code: Constant.NOT_FOUND_ERROR_CODE, message: Constant.USER_NO_LONGER_EXIST});\n }\n }\n });\n}",
"async invite({ request, auth, response, session }) {\n if (auth.user.admin === 0) {\n return response.json({\n status: 'error',\n message: 'You are not authorized to do that.'\n })\n }\n let userData = request.only([\n 'first_name',\n 'last_name',\n 'email',\n 'password',\n 'admin',\n 'permissions'\n ])\n userData.permissions = parseInt(userData.permissions)\n if (userData.admin) {\n userData.admin = true\n await User.create(userData)\n await Mail.send('emails.welcome-invite', userData, message => {\n message\n .to(userData.email)\n .from(Env.get('MAIL_USERNAME'))\n .subject('New Account Created - Great American Buildings')\n })\n session.flash({ notification: 'Admin User Added!' })\n return response.redirect('back')\n }\n const user = await User.create(userData)\n if (userData.permissions == 3) {\n this.getOwnerId(user.email, user.id)\n }\n await Mail.send('emails.welcome-invite', userData, message => {\n message\n .to(userData.email)\n .from(Env.get('MAIL_USERNAME'))\n .subject('New Account Created - Great American Buildings')\n })\n session.flash({ notification: 'User Added!' })\n return response.redirect('back')\n }",
"inviteUser (callback) {\n\t\tif (this.byDomainJoining) { return callback(); }\n\t\tif (this.dontInvite) { return callback(); }\n\t\tthis.expectedVersion++;\n\t\tthis.doApiRequest(\n\t\t\t{\n\t\t\t\tmethod: 'post',\n\t\t\t\tpath: '/users',\n\t\t\t\tdata: {\n\t\t\t\t\temail: this.currentUser.user.email,\n\t\t\t\t\tteamId: this.team.id\n\t\t\t\t},\n\t\t\t\ttoken: this.users[1].accessToken\n\t\t\t},\n\t\t\tcallback\n\t\t);\n\t}",
"function InviteFriends_DoInvite()\n {\n closeinvitefriendpopup();\n var thisUser = JSON.parse(window.sessionStorage.getItem(\"facebookuser\"));\n var inviteMessage = \"You've been invited to play King Of The Kop by \" + thisUser.name + \"!!\";\n FB.ui(\n {\n method: 'apprequests',\n message: inviteMessage\n },\n function (response)\n {\n if (response && response.request && response.to)\n {\n //if we get here can I assume the invites were sent????\n var NumInvitesLogged;\n try {\n //now log in the DB all the fbuserid's of those invited and the fbrequest which we received \n var fbUserIDList = \"\";\n var friendsInvited = response.to.length;\n\n\n if (friendsInvited <= 0) {\n //nobody invited!!!!\n alert(\"No invites were sent\")\n }\n else {\n //people WERE invited!!!!!\n //log in DB - see does user get their powerplay!!!!!\n\n for (var i = 0; i < response.to.length; i++) {\n if (i == 0) {\n fbUserIDList = response.to[i];\n }\n else {\n fbUserIDList += \",\" + response.to[i];\n }\n }\n\n $.ajax({\n url: WS_URL_ROOT + \"/Game/LogInviteFriends\",\n type: \"POST\",\n data: \"userid=\" + thisUser.id + \"&fbREquest=\" + response.request + \"&FBUserID_List=\" + fbUserIDList + \"&fixtureID=\" + GetCurrentfixtureID(),\n dataType: \"html\",\n error: function (XMLHttpRequest, textStatus, errorThrown) {\n AjaxFail(\"LogInviteFriends\", XMLHttpRequest, textStatus, errorThrown);\n },\n success: function (response) {\n if (response >= 0) //response is the number of power plays the user has earned!!!!\n {\n \n thisFixture.remainingpowerplays = thisFixture.remainingpowerplays + response;\n var message = '<span>' + thisFixture.remainingpowerplays + '</span>Power Play';\n if (thisFixture.remainingpowerplays > 1) {\n message += \"s\";\n }\n $('#' + displaymode + '_powerplayclickbtn').html(message);\n $('#powerplayclickbtn2 span').html(thisFixture.remainingpowerplays)\n\n $('.popup-notify-invites > h1').text(\"Invites sent - You have earned \" + response + \" extra power play(s)\");\n $('.popup-notify-invites').fadeIn(200).delay(3000).fadeOut(200);\n\n $('.GameFeedInfo').prepend(\"<b>Invites sent - You have earned \" + response + \" extra power play(s)!</b> <br />\");\n refreshScroller(GameFeedScroller, \"GameFeedInfo\");\n }\n else if (response == 1) {\n $('.popup-notify-invites > h1').text(\"Invites sent!\");\n $('.popup-notify-invites').fadeIn(200).delay(1000).fadeOut(200);\n\n $('.GameFeedInfo').prepend(\"<b>\" + response + \" new friend requests sent!</b> <br />\");\n refreshScroller(GameFeedScroller, \"GameFeedInfo\");\n }\n //else if (response > 0)\n //{\n // $('.popup-notify-invites > h1').text(response + \" new invites sent!\");\n // $('.popup-notify-invites').fadeIn(200).delay(1000).fadeOut(200);\n\n // $('.GameFeedInfo').prepend(\"<b>\" + response + \" new friend requests sent!</b> <br />\");\n // refreshScroller(GameFeedScroller, \"GameFeedInfo\");\n //}\n else \n {\n //error logging (OR no new friends) - BUT invites WERE sent!!!!\n $('.popup-notify-invites > h1').text(\"Invites sent!\");\n $('.popup-notify-invites').fadeIn(200).delay(1000).fadeOut(200);\n\n $('.GameFeedInfo').prepend(\"<b>Friends invited!!</b> <br />\");\n refreshScroller(GameFeedScroller, \"GameFeedInfo\");\n }\n }\n });\n\n } //end else\n\n }catch (ex) { }\n } //no response recieved\n }//end function\n );//end FB.ui\n }//end InviteFriends",
"acceptInvite(){\n\n }",
"function sendMeetingInvitation(req, res)\n\t{\n\t\treq.addListener('data', function(message)\n\t\t{\n\t\t\tvar command = JSON.parse(message);\t\t\t\n\t\t\tvar usersList = command.userslist;\n\t\t\tvar roomId = command.roomid;\n\t\t\tvar userName = command.username;\n\t\t\t\n\t\t\tvar moderatorUserName = null;\n\t\t\tif(meetingRooms[roomId]!=null)\n\t\t\t{\n\t\t\t\tmoderatorUserName =\tmeetingRooms[roomId].moderatorUserName;\t\t\n\t\t\t}\n\t\t\tfor(var index in usersList)\n\t\t\t{\n\t\t\t\tvar data ={'roomId':roomId,'moderatorUserName':moderatorUserName};\n\t\t\t\tsendNotifiedEvent(usersList[index].userName,'getInvitationByModerator',data);\n\t\t\t\tvar meetingDetails ={'moderatorUserName':moderatorUserName,'roomId':roomId,'meetingStatus:':'STARTED'};\n\t\t\t\tMeetingManager.saveData(\"MEETING_LIST_\"+usersList[index].userName,JSON.stringify(meetingDetails));\t\t\t\n\t\t\t}\n\t\t\tres.send('SendMeetingInvitation Successfully done');\n\t\t});\n\t\n\t}",
"function webhookListener(req, res) {\n\tconsole.log(\"Got ICM\");\n\tif (!req.body || !req.body.entry[0] || !req.body.entry[0].messaging) return console.error(\"no entries on received body\");\n\tlet messaging_events = req.body.entry[0].messaging;\n\tfor (let messagingItem of messaging_events) {\n\t\tlet user_id = messagingItem.sender.id;\n //HERE - this is the key function. It sends out the info to see if we have\n //a user. if not it will make a new user. either way it will pass the\n //message and the user info to the game.parseIncoming callback function\n //where the game logic code decides what to do\n\t\tdb.getUserById(user_id, messagingItem, game.parseIncoming);\n\t}\n\tres.sendStatus(200);\n}",
"inviteUser (callback) {\n\t\tconst data = this.userFactory.getRandomUserData();\n\t\tthis.doApiRequest(\n\t\t\t{\n\t\t\t\tmethod: 'post',\n\t\t\t\tpath: '/users',\n\t\t\t\tdata: {\n\t\t\t\t\tteamId: this.team.id,\n\t\t\t\t\temail: data.email,\n\t\t\t\t\tfullName: data.fullName,\n\t\t\t\t\t_pubnubUuid: data._pubnubUuid,\n\t\t\t\t\t_confirmationCheat: this.apiConfig.sharedSecrets.confirmationCheat\n\t\t\t\t},\n\t\t\t\ttoken: this.token\n\t\t\t},\n\t\t\t(error, response) => {\n\t\t\t\tif (error) { return callback(error); }\n\t\t\t\tthis.inviteCode = response.inviteCode;\n\t\t\t\tthis.invitedUser = response.user;\n\t\t\t\tcallback();\n\t\t\t}\n\t\t);\n\t}",
"function sendInvitation(self) {\n var invite = {\n 'userId': $(this).attr('current_user'),\n 'userName': $(this).attr('current_username'),\n 'friendId': $(this).attr('friend_user')\n };\n\n $.ajax({\n type: 'POST',\n url: '/user/sendFriendshipInvitation/',\n data: invite,\n }).done(function( response ) {\n // Check for a successful (blank) response\n if (response.msg === '') {\n alert('You have successfully sent friendship invitation.');\n }\n else {\n alert('Error: ' + response.msg);\n }\n });\n}",
"function responseChatInvitation(data) {\n ajaxRequest.performPostRequest(serviceRootUrl + 'response-chat-invitation', data,\n function (data) {\n //console.log('Response to chat invitation -> ', data);\n },\n function (error) {\n serverErrorsTreatment(error);\n });\n }",
"async getInvitedUser () {\n\t\tif (!this.inviteCode) {\n\t\t\treturn;\n\t\t}\n\t\tthis.signupToken = await this.request.api.services.signupTokens.find(\n\t\t\tthis.inviteCode,\n\t\t\t{ requestId: this.request.request.id }\n\t\t);\n\t\tif (!this.signupToken) {\n\t\t\tthrow this.errorHandler.error('notFound', { info: 'invite code' });\n\t\t}\n\t\telse if (this.signupToken.expired) {\n\t\t\tthrow this.errorHandler.error('tokenExpired');\n\t\t}\n\n\t\tif (this.user && this.signupToken.userId === this.user.id) {\n\t\t\t// user is the same as the user that was invited, and same email came from the identity provider,\n\t\t\t// so we are all good\n\t\t\tthis.request.log('Invite code matched existing user');\n\t\t\treturn;\n\t\t}\n\n\t\t// get the user that was invited\n\t\tthis.invitedUser = await this.data.users.getById(this.signupToken.userId);\n\t\tif (!this.invitedUser) {\n\t\t\tthrow this.errorHandler.error('notFound', { info: 'invited user' });\n\t\t}\n\n\t\t// have to deal with a little weirdness here ... if we get an invite code, and the invite code references\n\t\t// a user that already exists, and they don't match the email the user is trying to register with,\n\t\t// we will effectively change the invited user's email to the user they are registered with ... but we\n\t\t// can't allow this if the invited user is already registered (which shouldn't happen in theory), or if the\n\t\t// email the user is trying to register with already belongs to another invited user\n\t\tif (this.invitedUser.get('email').toLowerCase() !== this.providerInfo.email.toLowerCase()) {\n\t\t\tif (this.invitedUser.get('isRegistered')) {\n\t\t\t\tthrow this.errorHandler.error('alreadyAccepted');\n\t\t\t}\n\t\t\telse if (this.user) {\n\t\t\t\tthrow this.errorHandler.error('inviteMismatch');\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis.request.log(`Existing unregistered user ${this.invitedUser.get('email')} will get their email changed to ${this.providerInfo.email}`);\n\t\t\t\tthis.user = this.invitedUser;\n\t\t\t}\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks for user is logged in. And creates a Switch button. | function checkForLoggedIn() {
const loginBtn = document.querySelector('form[action^="login.php"] input.button');
if (loginBtn) { // Have login button
const swAccount = Object.assign(document.createElement('a'), {href: '#', textContent: 'Switch', id: 'multiacc'});
loginBtn.parentNode.appendChild(swAccount);
return '#multiacc';
}
} | [
"function signIn (){\n\tif (userName.value === 'mirko' && userPassword.value === 'bit') {\n\tsignInOutSwitch = true;\n\talert('Welcome');\n divMovie.classList.toggle('disabled-div');\n divProgram.classList.toggle('disabled-div');\n\t}\n\telse {\n\t\talert('Wrong User name or Password');\n\t} \n}",
"function handleLogBtn() {\n if (user.userName) {\n // if there's a user, button shows 'Logout', and click means log out.\n tripsAPI.getLogout(loggedOut);\n } else {\n // otherwise there's not a user, button shows 'Login', and click\n // means log in.\n setUser({\n ...user,\n showLogin : true\n })\n }\n }",
"function signinToggleButton(){\n if($scope.pwHide){\n retrievePW();\n }\n else if(!$scope.pwHide){\n signinUser();\n }\n }",
"function UpdateButtons() {\n CheckUserStatus( function(user_status) {\n var loginbtn = $(\"a[id*=loginbtn]\");\n var logoutbtn = $(\"a[id*=logoutbtn]\");\n if (user_status === null) {\n loginbtn.show();\n logoutbtn.hide();\n } else {\n logoutbtn.text(\"Logout (\" + user_status + \")\");\n logoutbtn.show();\n loginbtn.hide();\n }\n $(\"a[id*=homebtn]\").attr(\"href\", using_prefix);\n });\n}",
"function toggleLoginAndProfile() {\r\n // check if user has logged in or not to show or hide login/profile.\r\n}",
"function displayLogIn(){\n\t\t\t//change button oplogin's appearance to Log In\n\t\t\tvar openlogin = document.getElementById(\"openlogin\");\n\t\t\topenlogin.innerHTML = \"Log In\";\n\t\t}",
"function switchToLogin(){\n\t\tturnService.closeWaitingAlert();\n\t\t$userLoginArea.show();\t\t\n\t\t$pageWrapper.hide();\n\t}",
"function updateLoginStatus() {\n var loggedIn = adyen.isLoggedIn();\n loginButton.setEnabled(!loggedIn);\n logoutButton.setEnabled(loggedIn);\n removeAllDevicesButton.setEnabled(loggedIn);\n }",
"function updateButtonAvailable() {\n if (myUser.type == TypeEnum.TRAPPED || bGameOver) { // only allow shouting after the game is over\n document.getElementById('buttons').style.visibility = 'hidden';\n document.getElementById('shoutButton').style.visibility = 'visible';\n } else {\n document.getElementById('shoutButton').style.visibility = 'hidden';\n document.getElementById('buttons').style.visibility = 'visible';\n }\n\n if (myUser.type == TypeEnum.ACTIVE) {\n document.getElementById('myonoffswitch').checked = true;\n }\n else if (myUser.type == TypeEnum.PASSIVE) {\n document.getElementById('myonoffswitch').checked = false;\n }\n}",
"function controlUserButtons(islogin,userType)\n{\n if (islogin == false)\n {\n\n $('#buttonLogin').show();\n $('#buttonSignup').show();\n $('#buttonUserManage').hide();\n $('#containerUsername').hide();\n $('#buttonLogout').hide();\n }\n else\n {\n $('#buttonLogin').hide();\n $('#buttonSignup').hide();\n $('#buttonLogout').show();\n $('#containerUsername').show();\n if (userType == constUserTypeAdmin)\n {\n $('#buttonUserManage').show();\n }\n }\n}",
"function setupUI(user) {\n const logged_out_links = document.querySelectorAll('.logged_out');\n const logged_in_links = document.querySelectorAll('.logged_in');\n if (user) {\n //user is logged in \n logged_in_links.forEach(item => item.style.display = 'block');\n logged_out_links.forEach(item => item.style.display = 'none');\n \n } else {\n //user is logged out\n logged_in_links.forEach(item => item.style.display = 'none');\n logged_out_links.forEach(item => item.style.display = 'block');\n }\n}",
"function changeUiOnLogIn(user) {\n\t$(\"#userName\").text(user.email);\n\t$(\"#userName\").append(\"<span class='caret'></span>\");\n\t$(\".loggedInUI\").show();\n\t$(\".loggedOutUI\").hide();\n}",
"function watchDemoBtn() {\n $('#demo-login').click(event => {\n const userData = {\n username: 'demouser1124',\n password: 'demopassword1124'\n };\n\n HTTP.loginUser({\n userData,\n onSuccess: res => {\n const authUser = res.user;\n authUser.jwtToken = res.jwtToken;\n CACHE.saveAuthenticatedUser(authUser);\n window.open('/user/hub.html', '_self');\n },\n onError: err => {\n $('#error-message').html(`\n <p>Your username and/or password were incorrect.</p>\n `);\n }\n });\n })\n}",
"userCreation_and_LoginBar_Toggle(buttonValue) {\n if (buttonValue === 1) {\n document.getElementById('userCreationFormContainer').style.display = \"block\";\n } else if (buttonValue === 2) {\n document.getElementById('userCreationFormContainer').style.display = \"none\";\n\n document.getElementById('userCreationError').innerHTML = \"\"; //Sets error message to nothing\n\n // Sets all user creation input fields to empty\n document.getElementById('userNameInput').value = \"\";\n document.getElementById('userPasswordInput').value = \"\";\n document.getElementById('userRepeatPasswordInput').value = \"\";\n\n } else if (buttonValue === 3) {\n document.getElementById('userLoginFormContainer').style.display = \"block\";\n } else {\n document.getElementById('userLoginFormContainer').style.display = \"none\";\n\n document.getElementById('userCreationErrorLogin').innerHTML = \"\"; //Sets error message to nothing\n\n // Sets all user creation input fields to empty\n document.getElementById('userNameInputLogin').value = \"\";\n document.getElementById('userPasswordInputLogin').value = \"\";\n }\n }",
"function displayUser() {\n console.log(\"displayUser\");\n userInfoH3.innerHTML = `Currently logged in as: ${currentUser.username}`;\n\n logOutButton = document.createElement(\"button\");\n logOutButton.innerHTML = \"Log Out\";\n userInfoDiv.appendChild(logOutButton);\n logOutButton.classList.add(\"btn-11\");\n\n loginForm.style.display = \"none\";\n startButton.style.display = \"block\";\n\n startButton.addEventListener(\"click\", () => startNewGame());\n\n logOutButton.addEventListener(\"click\", () => logOut());\n displayBoards();\n}",
"function setLoginButtonStatus(callbackOnSuccess, callbackOnFailure) {\n\tisLoggedIn(function () {\n\t\tconsole.log(\"setLoginButtonStatus: true\");\n\t\t// $('#login-content').slideToggle();\n\t // $(this).toggleClass('active'); \n \n \tif ($(this).hasClass('active')) $(this).find('span').html('▲')\n \telse $(this).find('span').html('▼')\n\t\tdocument.getElementById(\"incorrect-login\").style.display = \"none\";\n\t\tdocument.getElementById(\"submitlogin\").value = \"Log Out\";\n\t\tsetFullNameFromSession(\"login-trigger\");\n\t\tdocument.getElementById(\"inputs\").style.display = \"none\";\n\t\tdocument.getElementById(\"submitlogin\").onclick = doLogout;\n\n\t\tif(callbackOnSuccess) {\n\t\t\tcallbackOnSuccess();\n\t\t}\n\n\t}, function () {\n\t\tconsole.log(\"setLoginButtonStatus: false\");\n\t\tdocument.getElementById(\"incorrect-login\").style.display = \"block\";\t\n\t\tdocument.getElementById(\"inputs\").style.display = \"block\";\n\t\tif(callbackOnFailure) {\n\t\t\tcallbackOnFailure();\n\t\t}\n\t}); \n}",
"function generateLoggedInButton(){\n\n var loggedInUser = getUserInfo();\n var loggedInAs = loggedInUser[0].userName;\n\n\n if(loggedInAs!=null && typeof(loggedInAs)!='undefined'){\n alert('loggedIn');\n //document.getElementById('loggedInUserLabel').innerHTML = 'Logged as : '+loggedInAs; \n var header = document.getElementsByTagName('header')[0];\n\n var logOutbutton = document.createElement('button');\n logOutbutton.setAttribute(\"id\",\"logout\");\n logOutbutton.setAttribute(\"class\" ,\"navitems\");\n logOutbutton.addEventListener(\"click\", userLogOut);\n var logOutbuttonText = document.createTextNode('Logged In: '+loggedInAs);\n logOutbutton.appendChild(logOutbuttonText);\n\n header.appendChild(logOutbutton);\n}\n}",
"function set_logged_in() {\n if (!logged_in) {\n chrome.browserAction.setIcon({path: \"images/lock_green.png\"});\n chrome.browserAction.setTitle({title: \"You are logged in\"});\n logged_in = true;\n }\n}",
"function updateDashboard() {\n if(loggedIn){\n $('#HeaderUser').text(Username);\n $('.Dashboard').addClass('Loggedin');\n } else {\n $('.Dashboard').removeClass('Loggedin');\n }\n \n // Enable/Disable buttons based on login state\n $('.Dashboard > button.LoginRequired').addClass('locked').prop(\"disabled\",true);\n $('.Loggedin > button.LoginRequired').removeClass('locked').prop(\"disabled\",false);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stop the animation and clear the canvas. | function stop() {
if (timer) clearInterval(timer);
timer = null;
var brush = canvas.getContext("2d");
brush.clearRect(0, 0, canvas.width, canvas.height);
} | [
"stop() {\n clearInterval(this.animation);\n this.canvas.clear();\n }",
"function stopAnimation() {\n\tclearInterval(intervalRef);\n\t// erase the canvas with clearRect\n\tcontext.clearRect(0,0,600,400);\n\t}",
"stop() {\n if (this.animation) {\n this.animation.stop();\n if (this.events.animationCancel) {\n this.events.animationCancel.notify();\n }\n }\n this.clearAnimation();\n }",
"stop() {\n if (this.animation) {\n this.animation.stop();\n if (this.events.animationCancel) {\n this.events.animationCancel.notify();\n }\n }\n this.clearAnimation();\n }",
"stop() {\n if (this.animation) {\n this.animation.stop();\n if (this.events.animationCancel) {\n this.events.animationCancel.notify();\n }\n }\n this.clearAnimation();\n }",
"stop() {\n if (this.stopAnimation) {\n this.stopAnimation();\n if (this.events.animationCancel) {\n this.events.animationCancel.notify();\n }\n }\n this.clearAnimation();\n }",
"_clearAnimation() {\n if (this._animation) {\n clearInterval(this._animation);\n this._animation = null;\n }\n }",
"_stopSpectrumAnalyzer () {\n this._canvasContext.clearRect(0, 0, this._canvas.width, this._canvas.height)\n window.cancelAnimationFrame(this._animationId)\n }",
"stopDrawing() {\n this.updateAnimation = false;\n }",
"stop() {\r\n if (this.loop) {\r\n this.frameCounter = 0;\r\n } else {\r\n this.animationRunning = false;\r\n }\r\n }",
"clearCurrentAnimation() {\n this.currentAnimation.stop();\n this.currentAnimation = new tween.Tween();\n }",
"stop() {\n window.cancelAnimationFrame(this.afr);\n this.running = false;\n }",
"function stop() {\n cancelAnimationFrame(animationFrame);\n isRunning = false;\n setElementDisplay(canvas, 'none');\n deletePokeBall();\n clearSparks();\n }",
"stopAnimation(){\r\n\t\tTWEEN.removeAll()\r\n\t\tinitialPosition()\r\n\t\tanimationStopped = true\r\n\t}",
"function cancelAnimation() {\n window.cancelAnimationFrame(animation);\n }",
"stop() {\n this._animationState = 3 /* stopped */;\n this._clearAnimation();\n this._map && this._toggleFrameVisibility(this._currentFrameIndex, false);\n this._currentFrameIndex = 0;\n }",
"function stopAnimations(){\r\n\tctx.clearRect(0, 0, W, H);\r\n\tcloudsAnimation=false;\r\n\trainAnimation=false;\r\n\tsnowAnimation=false;\r\n\tsunBool=false;\r\n\tclearInterval(thunderstormAnimation);\r\n}",
"stopAnimation() {\n cancelAnimationFrame(this.requestId);\n }",
"cancelAnimation(){\n delete this.animation;\n this.animation = null;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that sets details of the outcome in UI. It sets color and signs both of opponent and player. | function setOutcomeDetails(currentRoundUi, currentRound, opponentColor, playerColor){
currentRoundUi.statusBoxOpponent.style.background = opponentColor;
currentRoundUi.statusBoxPlayer.style.background = playerColor;
var opponentUrl = currentRound.getOpponentSign() !== null ? currentRound.getOpponentSign().getImgUrl() : 'images/question.png';
var playerUrl = currentRound.getPlayerSign() !== null ? currentRound.getPlayerSign().getImgUrl() : 'images/question.png';
currentRoundUi.opponentSign.style.backgroundImage = 'url("'+opponentUrl+'")';
currentRoundUi.playerSign.style.backgroundImage = 'url("'+playerUrl+'")';
} | [
"setCurrentTurnUI() {\n let htmlTurnText = \"Player 1's turn\";\n let styleColor = \"red\";\n if (!this.isPlayer1Turn) {\n styleColor = \"darkcyan\";\n htmlTurnText = \"Player 2's turn\";\n }\n this.currentPlayerUI.innerHTML = htmlTurnText;\n this.currentPlayerUI.style.color = styleColor;\n }",
"function outcome(result) {\n if (result === 'win') {\n player.win++;\n displayWinSpan.textContent = player.win;\n showMessage('You Win!', currentDate, currentTime);\n showWinLossImage('win');\n } else if (result === 'loss') {\n player.loss++;\n displayLossSpan.textContent = player.loss;\n showMessage('You Lose!', currentDate, currentTime);\n showWinLossImage('loss');\n } else if (result === 'draw') {\n player.draw++;\n displayDrawSpan.textContent = player.draw;\n showMessage('Draw!', currentDate, currentTime);\n hideWinLossImage();\n }\n}",
"buttonSettings(indexOfPlayer) {\n // Get the index of the assassin\n let indexOfAssassin = -1;\n for (let i = 0; i < this.thisRoom.playersInGame.length; i++) {\n if (this.thisRoom.playersInGame[i].role === this.role) {\n indexOfAssassin = i;\n break;\n }\n }\n\n const obj = {\n green: {},\n red: {},\n };\n\n if (indexOfPlayer === indexOfAssassin) {\n obj.green.hidden = false;\n obj.green.disabled = true;\n obj.green.setText = 'Shoot';\n\n obj.red.hidden = true;\n obj.red.disabled = true;\n obj.red.setText = '';\n }\n // If it is any other player who isn't special role\n else {\n obj.green.hidden = true;\n obj.green.disabled = true;\n obj.green.setText = '';\n\n obj.red.hidden = true;\n obj.red.disabled = true;\n obj.red.setText = '';\n }\n return obj;\n }",
"function UI()\r\n{\r\n mode0.style.color = 'white';\r\n mode1.style.color = 'white';\r\n mode2.style.color = 'white';\r\n if (noPlayer)\r\n mode0.style.color = \"rgb(127, 0, \"+ neonColor +\")\";\r\n else if (!multiPlayer)\r\n mode1.style.color = \"rgb(127, 0, \"+ neonColor +\")\";\r\n else\r\n mode2.style.color = \"rgb(127, 0, \"+ neonColor +\")\";\r\n}",
"function setPropertiesForWinner() {\n document.querySelector(\"#name-\" + activePlayer).textContent = \"Winner!\";\n document.querySelector(\".dice\").style.display = \"none\";\n document\n .querySelector(\".player-\" + activePlayer + \"-panel\")\n .classList.add(\"winner\");\n document\n .querySelector(\".player-\" + activePlayer + \"-panel\")\n .classList.remove(\"active\");\n gamePlaying = false;\n\n if (activePlayer === 0) {\n changeButtonColor(true);\n }\n}",
"function setWinnerDetailsToExAequo() {\n document.getElementById(\"winnerTitle\").innerHTML = \"Tie Game\";\n document.getElementById(\"theWinnerIs\").innerHTML = \"Player 1 & Player 2\";\n document.getElementById(\"finalScore\").innerHTML = \"ex aequo\";\n}",
"function colorPlayer(fixPlayerChoice){\n switch (fixPlayerChoice){\n case \"rock\": rockBox.style.background = \"blue\";\n break;\n case \"paper\": paperBox.style.background = \"blue\";;\n break;\n case \"scissors\": scissorsBox.style.background = \"blue\";;\n break;\n }\n}",
"function setUpTurn() {\n if (gameActive) {\n //display current player, create <span> with class of player# & color\n document.getElementById('game_info').innerHTML = \"Current Player: Player \" + activePlayer + \" <span class='player\" + activePlayer + \"'>(\" + playerColor[activePlayer] + \")</span>\";\n }\n}",
"function DefineWinner(ch){\r\n\r\n MChoice=MachineChoice();\r\n Mimg.src=Sources[MChoice];\r\n if(Operations[ch.id][MChoice] > 0){\r\n txt.textContent=\"You win\";\r\n txt.style.color=\"green\";\r\n } else if(Operations[ch.id][MChoice] < 0){\r\n txt.textContent=\"You Lost\";\r\n txt.style.color=\"red\";\r\n }else{\r\n txt.textContent=\"Equality\";\r\n txt.style.color=\"blue\";\r\n }\r\n document.querySelector(\".s-container\").appendChild(Uimg);\r\n document.querySelector(\".s-container\").appendChild(txt);\r\n document.querySelector(\".s-container\").appendChild(Mimg);\r\n document.querySelector(\"#btn\").textContent=\"Click Here to Play Again\";\r\n flag=1; // This flag tells that the user has made a choice and the battle is over.\r\n\r\n}",
"function playerBtnColor(playerSelection) {\n if (playerSelection === \"rock\" && result === \"win\") {\n rock.style.border = \"5px #5cdb5c solid\"\n }\n if (playerSelection === \"paper\" && result === \"win\") {\n paper.style.border = \"5px #5cdb5c solid\"\n }\n if (playerSelection === \"scissors\" && result === \"win\") {\n scissors.style.border = \"5px #5cdb5c solid\"\n }\n if (playerSelection === \"rock\" && result === \"lose\") {\n rock.style.border = \"5px #ff0021 solid\"\n }\n if (playerSelection === \"paper\" && result === \"lose\") {\n paper.style.border = \"5px #ff0021 solid\"\n }\n if (playerSelection === \"scissors\" && result === \"lose\") {\n scissors.style.border = \"5px #ff0021 solid\"\n }\n if (playerSelection === \"rock\" && result === \"draw\") {\n rock.style.border = \"5px #ffa500 solid\"\n }\n if (playerSelection === \"paper\" && result === \"draw\") {\n paper.style.border = \"5px #ffa500 solid\"\n }\n if (playerSelection === \"scissors\" && result === \"draw\") {\n scissors.style.border = \"5px #ffa500 solid\"\n }\n}",
"function setColor(res)\n{\n var color = res.players[username].color;\n $(\"#currentColor\").append('<h3 style=\"text-align: center; font-family:Playball;\">Your Color <span style = \"color:'+ color + '\">\\u2588</span></h3>')\n}",
"function playerTurnBox_update(player) {\n\n playerTurnBox.value = player;\n\n if (player === 'computer') { \n playerTurnBox.style.backgroundColor = \"red\"; \n }\n else if (player === 'user') {\n playerTurnBox.style.backgroundColor = \"green\"; \n }\n else {\n playerTurnBox.style.backgroundColor = \"purple\";\n }\n}",
"setBeakerColor()\n {\n if(this.gameDifficulty === 3)\n {\n let color = this.determineDifficulty2_Color();\n\n }\n else if (this.gameDifficulty === 2)\n {\n\n let color = this.determineDifficulty2_Color();\n }\n else\n {\n\n let color = this.determineDifficulty1_Color();\n\n }\n }",
"function setPlayerColor( player, color ){\r\n\t dgi('errBox').innerHTML = '';\r\n\t dgi('startButton').disabled = false;\r\n\t\tswitch(player){\r\n\t\t\tcase 1: // for player 1\r\n\t\t\t if( color == pColor2 ){ // check if the color chosen matches with color of player 2\r\n\t\t\t dgi('errBox').innerHTML = 'Two players cannot have the same name!';\r\n\t\t\t dgi('startButton').disabled = true;\r\n\t\t\t return false;\r\n\t\t\t }\r\n\t\t\t // set the color\r\n\t\t\t\tpColor1 = color;\r\n\t\t\t\treturn true;\r\n\t\t\t\tbreak;\r\n\t\t\tcase 2:\r\n\t\t\t if( color == pColor1 ){ // check if the color chosen matches with color of player 1\r\n\t\t\t dgi('errBox').innerHTML = 'Two players cannot have the same color!';\r\n\t\t\t dgi('startButton').disabled = true;\r\n\t\t\t return false;\r\n\t\t\t }\r\n\t\t\t // set the color\r\n\t\t\t\tpColor2 = color;\r\n\t\t\t\treturn true;\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\t\t// p1Color is the color shown in the right-side table while the game is being played,\r\n\t\t// set the background color of the table data to the respective colors chosen\r\n\t\tdgi('p1Color').style.backgroundColor = pColor1;\r\n\t\tdgi('p2Color').style.backgroundColor = pColor2;\r\n\t}",
"function victoryScreen() {\n textSize(160);\n fill(victRed, victGreen, victBlue);\n textAlign(CENTER);\n text(\"YOU WIN!\", width / 2, height / 2);\n victoryColorShift();\n resetButton();\n}",
"function aiPlayer(level){\n if (level === game1.ai){\n game1.ai = 0;\n $(\"#easyAI\").css({'background-color':''});\n $(\"#hardAI\").css({'background-color':''});\n } else if (level === 1){\n game1.ai = 1;\n $(\"#easyAI\").css({'background-color':'#FFA340'});\n $(\"#hardAI\").css({'background-color':''});\n } else if (level === 2){\n game1.ai = 2;\n $(\"#hardAI\").css({'background-color':'#FFA340'});\n $(\"#easyAI\").css({'background-color':''});\n }\n}",
"function populateResultDiv(outcome) {\n if (outcome === 'loser') {\n $('#result-div h3').text('SORRY!');\n $('#result-div h5').text('NO CAFFEINE FOR YOU!');\n $('#result-div p').text('Click the Cup to Try Again');\n } else if (outcome === 'espresso') {\n $('#result-div').addClass('lit ' + outcome);\n $('#result-div h3').text('WINNER!');\n $('#result-div h5').text('YOU WON AN ' + outcome.toUpperCase() + '!');\n $('#result-div p').text('Take your Prize and Enjoy your Day');\n } else {\n $('#result-div').addClass('lit ' + outcome);\n $('#result-div h3').text('WINNER!');\n $('#result-div h5').text('YOU WON A ' + outcome.toUpperCase() + '!');\n $('#result-div p').text('Take your Prize and Enjoy your Day');\n }\n }",
"function swapHeadingColor() {\n\n if( curPlayer == human ){\n\n document.getElementById('OHeading').setAttribute('style' , 'background: #44bbaa;') ;\n\n document.getElementById('XHeading').setAttribute('style' , 'background: #5bc538; color: white;') ;\n }\n\n else{\n\n document.getElementById('OHeading').setAttribute('style' , 'background: #585d60; color: white;') ;\n\n document.getElementById('XHeading').setAttribute('style' , 'background: #44bbaa;') ;\n }\n \n}",
"function declareVictory() {\n if (currentPlayer == \"player1\") {\n message.addClass(\"color1\");\n message.html(\"THE LIGHT SIDE OF THE FORCE WINS!\");\n winningSound = new Audio(\"assets/audio/theme.mp3\");\n winningSound.play();\n } else {\n message.addClass(\"color2\");\n message.html(\"THE DARK SIDE OF THE FORCE WINS!\");\n winningSound = new Audio(\"assets/audio/march.mp3\");\n winningSound.play();\n }\n popup.css({\n visibility: \"visible\"\n });\n overlay.addClass(\"on\");\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper to echo strings in the terminal window | function spitt(msg) {
shell.echo(msg);
} | [
"echo(message){\n this.terminal.echo(message);\n }",
"function echo() { //dm\n\t//if ( getCookie(\"dev_mode\") )\n\t{\n\n\t\tfor (var i= 0, txt= \"\"; i<arguments.length; i++) {\n\t\t\tvar delimiter= (i===arguments.length-1)? \"\": \" | \";\n\t\t\ttxt+= arguments[i] + delimiter;\n\t\t}\n\t\tconsole.log(txt);\n\n\t\t//console.log(arguments);\n\t}\n}",
"function display(){\n console.log(chalk.yellow.underline.bold(\"Please use one of the following commands:\"))\n console.log(chalk.blue('\\tconcert-this')+\" to find the bands in the town\")\n console.log(chalk.blue('\\tspotify-this-song') + \" to get the song details\")\n console.log(chalk.blue('\\tmovie-this')+ \" to movie details\")\n console.log(chalk.blue('\\tdo-what-it-says') + \" to allow LIRI talk to to random.txt\")\n console.log(chalk.blue('\\tq') + \" to quit the terminal\\n\")\n}",
"echo(msg) {\r\n this.terminal.echo(apply_color(msg, \"gray\"));\r\n }",
"function terminalPrint(str) {\n var text = htmlDecode(str);\n text = text.split(\"\\n\");\n text.forEach(function (element, index, array) {\n $(\"#console-window-text\").append(\"<p>\" + element + \"</p>\");\n });\n\n // Smoothly scrolls down the terminal\n var scr = $('#terminal-window')[0].scrollHeight;\n $('#terminal-window').animate({scrollTop: scr}, 200);\n}",
"function showOutput(text) {\n $(\"#output\").text(text);\n }",
"function echo(str) {\r\n WScript.echo(str);\r\n}",
"consoleDisplay(message) {\n createConsoleText(message);\n }",
"function showOutput(text) {\n $(\"#output\").text(text);\n }",
"function showOutput(text) {\r\n $(\"#output\").text(text);\r\n }",
"function help(){\n console.log('below are the possible commands: \\n', '\\n', 'quit\\n', 'hello\\n', 'help\\n', 'list\\n', 'add\\n', 'remove\\n', 'edit\\n', 'check\\n', 'uncheck\\n')\n}",
"function showOutput(text) {\n\n $(\"#output\").text(text);\n\n }",
"function echo(str) {\n return str.toUpperCase() + \" ... \" + str + \" ... \" + str.toLowerCase();\n}",
"function printConsole(text){\n console.log(text);\n}",
"function Terminal () {}",
"function help() {\n printLine('The following commands work. Hover them for more information.');\n printLine('' +\n ' <span class=\"yellow\" title=\"Explain the list of commands\">help</span>,' +\n ' <span class=\"yellow\" title=\"Clear the screen for freshness\">clear</span>,' +\n ' <span class=\"yellow\" title=\"List all the files in this directory\">ls</span>,' +\n ' <span class=\"yellow\" title=\"List all links on the website\">tree</span>,' +\n ' <span class=\"yellow\" title=\"Change directory to `dirname`\">cd </span>' +\n '<span class=\"blue\" title=\"Change directory to `dirname`\"><em>dirname</em></span>,' +\n ' <span class=\"yellow\" title=\"Show the contents of `filename`\">cat </span>' +\n '<span class=\"green\" title=\"Show the contents of `filename`\"><em>filename</em></span>'\n );\n printLine('<br>');\n printLine('You can also use the' +\n ' <kbd class=\"cyan\">Up</kbd> and' +\n ' <kbd class=\"cyan\">Down</kbd>' +\n ' keys to navigate through your command history.'\n );\n printLine('You can click on tree nodes if CLI is not your thing.' +\n ' You\\'ll still need to hit <kbd class=\"cyan\">Enter</kbd>.'\n );\n}",
"displayCmd() {\r\n var cmdText = \"Commands \\n\";\r\n for (let i = 0; i < this.cmdOrder.length; ++i) {\r\n cmdText += this.cmdOrder[i] + \": \";\r\n cmdText += keyboardMap[this.cmdKeyCode[this.cmdIdx[this.cmdOrder[i]]]];\r\n cmdText += \"\\n\";\r\n }\r\n this.document.getElementById('commands').innerText = cmdText;\r\n }",
"function echo(string) {\n var allUpper = string.toUpperCase();\n var allLower = string.toLowerCase();\n return allUpper + \"...\" + string + \"...\" + allLower;\n}",
"function echo(string) {\n dots = ' ... ';\n return string.toUpperCase() + dots + string + dots + string.toLowerCase();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets saved regrets from DB and renders on portfolio.ejs view | function getPortfolio(request, response) {
let SQL = 'SELECT * FROM portfolio;';
return client.query(SQL)
.then(result => {
response.render('pages/portfolio', { regret: result.rows })
})
.catch(error => {
request.error = error;
getError(request, response);
});
} | [
"function myPortfolio( req, res ) {\n\n\tvar auth = null;\n\n\tif( req.session.name ) {\n\n\t\tauth = true;\n\n\t}\n\n\tportfolio.find().sort( { date: -1 } ).exec(\n\n\t\tfunction(err, portfolioPost) {\n\n\t\tif (err) {\n\n\t\t\tconsole.log(\"Error \"+err);\n\t\t\tres.send(\"Error \"+err);\n\n\t\t}\n\n\t\tres.render('portfolio',\n\n\t\t{\n\n\t\t\tloggedIn\t: auth,\n\t\t\tportfolios\t: portfolioPost\n\n\t\t});\n\n\t});\n\n}// ends myPortfolio",
"function render() {\n res.render('socList', {\n title: 'Sentinel Project: SOC Manager',\n socs: socs,\n datapoints: resultsDatapoints\n });\n }",
"index(req, res) {\n let plants = Plant.all();\n console.log(plants);\n res.render('plantIndex', { plants: plants });\n }",
"function displayCompanyPage(req, res, next) {\n // Find all of the current companies\n const mysql = req.app.get('mysql');\n let sql_query = `SELECT * FROM Companies`;\n let context = {};\n\n mysql.pool.query(sql_query, (err, rows) => {\n if (err) {\n next(err);\n return;\n }\n\n // Put the mysql data into an array for rendering\n let companyDbData = [];\n for (let i in rows) {\n companyDbData.push({\n companyId: rows[i].companyId,\n companyName: rows[i].companyName,\n dateJoined: rows[i].dateJoined,\n });\n }\n context.companies = companyDbData;\n res.render('add-company', context);\n });\n}",
"function renderPortfolioUpdate(req, res) {\n res.render('pages/portfolio-edit');\n}",
"function getAllCarsAdmin(req,res){\n car\n .find({})\n .exec()\n .then((cars)=>{\n //console.log(cars);\n res.render(\"admin\",{\n content: cars\n });\n })\n .catch((err)=>{\n console.log(err);\n });\n}",
"async index(req, res) {\n //Select statement to retrieve all the lectures created - Chris\n pool.query(`SELECT * FROM lecture`).then(result => {\n const lectures = result.rows;\n //Renders the page lectures containing all of the lectures (object - lectures) - Chris\n res.render('lectures', { lectures })\n })\n }",
"function getAllCars(req,res){\n car\n .find({})\n .exec()\n .then((cars)=>{\n res.render(\"index\",{\n content: cars\n });\n })\n .catch((err)=>{\n console.log(err);\n });\n}",
"showQuotes(req, res){\n Quote.find({}, function(err, quotes){\n console.log(\"Quotes:\", quotes);\n res.render('quotes', {context: quotes});\n });\n }",
"function renderViewPlantsPage(res) {\n\tvar plants = {};\n\tmysql.pool.query('SELECT * FROM Plants', function (err, rows, fields) {\n\t\tif (err) {\n\t\t\tnext(err);\n\t\t\treturn;\n\t\t}\n\t\tplants.results = rows;\n\t\tres.render('plants', plants);\n\t})\n}",
"function saveRegret(request, response) {\r\n let { symbol, name, search_date, search_date_price, current_price, current_date, investment, investment_worth, profit, graph_labels, graph_data } = latestSavedRegretObj;\r\n\r\n let SQL = 'INSERT INTO portfolio(symbol, name, search_date, search_date_price, cur_price, cur_date, investment, investment_worth, profit, graph_labels, graph_data) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11);';\r\n\r\n let values = [symbol, name, search_date, search_date_price, current_price, current_date, investment, investment_worth, profit, graph_labels, graph_data];\r\n\r\n return client.query(SQL, values)\r\n .then(() => response.redirect('/portfolio'))\r\n .catch(error => {\r\n request.error = error;\r\n getError(request, response)\r\n });\r\n}",
"function getSaved(req, res) {\n const conditions = { ...defaultArticleQueryConditions, saved: true };\n Article.find(conditions)\n .sort({ datePublished: 'desc' })\n .then(articles => articles.map(enrichArticle))\n .then(articles => res.render('index', { articles, saved: true }))\n .catch(() => res.stats(404).send('page unavailable'));\n}",
"function getPortfolio(request,response,next) {\n\tconsole.log(\"hit get portfolio name\")\n\tvar id = request.params.id;\n\tdb.User.findById(id)\n\t.exec(function(err,foundUser){\n\t\tconsole.log(foundUser);\n\t\tresponse.json(foundUser.stocks);\n\t});\n}",
"function getPortfolio() {\r\n portfolioEl.innerHTML = \"\";\r\n fetch(\"http://studenter.miun.se/~aslo1900/dt173g_projekt_rest/portfolio.php\")\r\n .then(response => response.json())\r\n .then(data => {\r\n data.forEach(portfolio => {\r\n portfolioEl.innerHTML +=\r\n `<div class=\"portfolio\">\r\n <p>${portfolio.title} -\r\n ${portfolio.description} \r\n <a target=\"_blank\" href=\"${portfolio.url}\"> → Link to website</a>.</p>\r\n </div>`\r\n })\r\n })\r\n}",
"function retrieveFromLocalStorage(){\n console.log('using local storage for Projects data');\n var localStorageData = localStorage.getItem('projectsSourceData');\n var localStorageDataJSON = JSON.parse(localStorageData);\n Projects.loadAll(localStorageDataJSON);\n // portfolioView.initIndexPage();\n }",
"function displayCompanyPage(req, res, next) {\n // Find all of the current companies\n const mysql = req.app.get('mysql');\n let sql_query = `SELECT * FROM Companies ORDER BY dateJoined DESC, companyId DESC`;\n\n // Initialize empty context object with Google user props\n let context = {};\n context.id = req.user.id;\n context.email = req.user.email;\n context.name = req.user.displayName;\n context.photo = req.user.picture;\n context.accessLevel = req.session.accessLevel;\n\n mysql.pool.query(sql_query, (err, rows) => {\n if (err) {\n next(err);\n return;\n }\n\n // Put the mysql data into an array for rendering\n let companyDbData = [];\n for (let i in rows) {\n companyDbData.push({\n companyId: rows[i].companyId,\n companyName: rows[i].companyName,\n dateJoined: rows[i].dateJoined,\n });\n }\n context.companies = companyDbData;\n res.render('companies', context);\n });\n}",
"index(req, res) {\n Cronograma.findAll()\n .then(function (cronogramas) {\n res.status(200).json(cronogramas);\n })\n .catch(function (error) {\n res.status(500).json(error);\n });\n }",
"function showCashDesk(req, res) {\n\n connection.query(Q.GET_INVENTARIS, [], function (err, result) {\n if (err === null) {\n res.render(\"CashDesk.ejs\", {\n products: result\n });\n } else {\n showError(req, res, err);\n }\n });\n\n}",
"showParks(req, res) {\n res.render('allParks', {\n parks: res.locals.parks,\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a team map where key is team id and values are team name and short id | function makeTeamMap(teams) {
var map = {};
for (var i = 0; i < teams.length; i++) {
map[teams[i]._id] = {name : teams[i].team_name, shortID : teams[i].shortID};
}
return map;
} | [
"function createTeamMap(arr) {\n var country = 1\n ,m = {}\n ,j = arr.length\n ,i = 0\n ,team\n ;\n while( i < j ) {\n team = arr[i];\n if (team === \"|\") {\n country += 1;\n } else {\n if ( team in m ) {\n m[team].push(country);\n } else {\n m[team] = [country];\n }\n }\n i += 1;\n }\n return m;\n}",
"function makePlayerMap(players) {\n var playerMap = {};\n for (var i = 0; i < players.length; i++) {\n playerMap[players[i]._id] = {shortID : players[i].shortID, name : players[i].player_name};\n }\n return playerMap;\n}",
"function generateTeams() {\n var playerIds = [];\n while (playerIds.length < 4) {\n var id = _.random(0, names.length - 1);\n if (_.indexOf(playerIds, id) === -1) {\n playerIds.push(id);\n }\n }\n\n return {\n teamA: playerIds.splice(0, 2),\n teamB: playerIds.splice(0, 2)\n };\n}",
"function setTeamInfo(){\n for (var i=0; i<data.setTeams.length; i++){\n var team ={};\n team.teamName = data.setTeams[i];\n team.cash = data.cash;\n team.teamList=[];\n data.teamInfo.push(team);\n }\n}",
"function createTeamCode(team) {\n var lowestLevel = getLowestLevel(team);\n var lowestLevelBOs = team[\"business-objects\"][lowestLevel];\n var guidString = lowestLevelBOs.join(\"-\");\n return [domain, guidString, team.name].join(\"-\").replace(/\\s/g, \"_\");\n}",
"function initTeam() {\n return map(generatePlayer, range(0, 10));\n }",
"function mapTeamsToConferenceKeys(teams) {\n\tvar d = {};\n\tteams.forEach(function(team) {\n\t\td[team.id] = team.division.toUpperCase() + \"-\" + team.sub_division.toUpperCase()\n\t});\n\treturn d;\n}",
"function createTeamIds(fixtures, teams) {\n // Keep a team id Map for adding id attrs to team elements\n var teamIds = {};\n var teamIdCount = 0;\n _.each(fixtures, function(fixture, fixtureIdx) {\n var team1 = resolveTeam(fixture.teamId1, teams);\n var team2 = resolveTeam(fixture.teamId2, teams);\n // ids are used for clicks\n var teamId1 = teamIds[team1];\n if (\"undefined\" === typeof teamId1) {\n teamId1 = teamIds[team1] = teamIdCount++;\n }\n var teamId2 = teamIds[team2];\n if (\"undefined\" === typeof teamId2) {\n teamId2 = teamIds[team2] = teamIdCount++;\n }\n });\n console.log(teamIds);\n return teamIds;\n }",
"teamShortCode(longName) {\n const teams = {\n Angels: \"LAA\",\n Astros: \"HOU\",\n Athletics: \"OAK\",\n Braves: \"ATL\",\n Brewers: \"MIL\",\n Cardinals: \"STL\",\n Cubs: \"CHC\",\n Detroit: \"DET\",\n \"D-backs\": \"ARI\",\n Dodgers: \"LAD\",\n Giants: \"SF\",\n Guardians: \"CLE\",\n \"Blue Jays\": \"TOR\",\n Mariners: \"SEA\",\n Marlins: \"MIA\",\n Milwaukee: \"MIL\",\n Mets: \"NYM\",\n Nationals: \"WSH\",\n Orioles: \"BAL\",\n Padres: \"SD\",\n Phillies: \"PHI\",\n Pirates: \"PIT\",\n Rangers: \"TEX\",\n Rays: \"TB\",\n \"Red Sox\": \"BOS\",\n Reds: \"CIN\",\n Rockies: \"COL\",\n Royals: \"KC\",\n Tigers: \"DET\",\n Twins: \"MIN\",\n \"White Sox\": \"CWS\",\n Yankees: \"NYY\",\n };\n return teams[longName] ? teams[longName] : longName.replace(/ /g, \"_\").toUpperCase().trim();\n }",
"function team_to_spots(team) {\n var spots = new Map();\n\n for (let spot of [Loc.CB, Loc.LM, Loc.CM, Loc.RM, Loc.CF]) {\n spots.set(spot, []);\n }\n\n for (let [id, pl] of team.players) {\n let pl_loc = team.player_loc.get(id);\n let pl_spots = loc_to_spot(pl_loc);\n\n let win = pl.win;\n for (let spot of pl_spots) {\n spots.get(spot).push([win, pl])\n }\n }\n\n var gk_def = 0;\n for (let id of team.place.get(Loc.GK)) {\n gk_def = team.players.get(id).def;\n }\n\n return {spots : spots, gk_def : gk_def };\n}",
"function createPlayerList(team1, team2) {\n\tvar players = {}\n\tfor (p in team1.players) {\n\t\tplayers[team1.players[p]['playerid']] = {\n\t\t\tteamid: team1['teamid'],\n\t\t\tjersey: team1.players[p]['jersey'],\n\t\t\tfirstname: team1.players[p]['firstname'],\n\t\t\tlastname: team1.players[p]['lastname']\n\t\t};\n\t}\n\tfor (p in team2.players) {\n\t\tplayers[team2.players[p]['playerid']] = {\n\t\t\tteamid: team2['teamid'],\n\t\t\tjersey: team2.players[p]['jersey'],\n\t\t\tfirstname: team2.players[p]['firstname'],\n\t\t\tlastname: team2.players[p]['lastname']\n\t\t};\n\t}\n\treturn players;\n}",
"buildCheckoutsMap(checkouts){\n let builtMap = {};\n builtMap[\"Individual\"] = checkouts.individual;\n\n //Check for there to be teams to format and load in, and bail if there is not\n if (checkouts.team == undefined){\n return builtMap;\n }\n\n //dynamically add create the name to pass to the columns and individual\n //teams\n checkouts.team.map(team => {\n builtMap[`Team:_${team.teamId.toString()}`] = team.teamCheckouts;\n });\n\n return builtMap;\n }",
"function setSquadre(t) {\r\n teams = t;\r\n for(var i=0;i < teams.length; i++){\r\n teamsIdByShortName[teams[i].shortName.toLowerCase()] = {\r\n \"id\": teams[i].id,\r\n \"name\": teams[i].name,\r\n \"shortName\": teams[i].shortName\r\n };\r\n\r\n teamsIdByName[teams[i].name] = {\r\n \"id\": teams[i].id,\r\n \"name\": teams[i].name,\r\n \"shortName\": teams[i].shortName.toLowerCase()\r\n };\r\n }\r\n}",
"createTeam() {\n // Create arrays for team names and colours\n const team_names = ['Bears', 'Snakes', 'Rats', 'Cougars', 'Tigers', 'Lions', 'Rabbits', 'Hawks', 'Seagulls', 'Hammers'];\n const colours = ['pink', 'cyan', 'brown', 'orange', 'khaki', 'lightblue', 'blue', 'purple', 'magenta', \t'teal', 'lightseagreen', 'seagreen', 'aquamarine', 'indigo', 'violet', 'darkgreen', 'palegreen', 'darkorange', 'coral', 'tomato'];\n\n // Randomize array offset\n const name_num = Math.floor(Math.random() * team_names.length) + 0;\n const colour_num = Math.floor(Math.random() * colours.length) + 0;\n\n // Set class properties\n this.team_name = team_names[name_num];\n this.colour = colours[colour_num];\n }",
"function Team(units, name) {\n this.units = units;\n this.name = name;\n}",
"function setTeams(){\n var i=0;\n \n while(detailService.list.data.rounds[0].matches[i])\n {\n m.teams.push(\n detailService.list.data.rounds[0].matches[i].team1.name\n );\n m.teams.push(\n detailService.list.data.rounds[0].matches[i].team2.name\n );\n i++;\n }\n \n }",
"function footballTeam (player){\n\tvar teamobj = {}\n\tteamobj.player = player;\n\tteamobj.addInfo =addInfo;\n\tteamobj.arrayOfPlayers= [];\n\tteamobj.increaseLevel=increaseLevel;\n\tteamobj.isAvailable=isAvailable;\n\tteamobj.decrease=decrease;\n\tteamobj.sortPalyerBy=sortPalyerBy;\n\treturn teamobj\n}",
"function extractRelevantTeamData(teams_info) {\n return teams_info.map((team_info) => {\n const { id, name} = team_info.data.data;\n return {\n team_id: id,\n team_name: name,\n };\n });\n}",
"function getTeams() {\n var teams = {};\n // iterate through each region and game of round 1, which includes the seed in the game div\n for(var region = 1; region <= 4; region++) {\n for(var game = 1; game <= 8; game++) {\n var id = region + \"-1-\" + game + \"-\";\n var topEl = document.getElementById(id + \"Top\");\n var bottomEl = document.getElementById(id + \"Bottom\");\n teams[topEl.getElementsByClassName('teamName')[0].innerHTML] =\n parseInt(topEl.getElementsByClassName('seed')[0].innerHTML);\n teams[bottomEl.getElementsByClassName('teamName')[0].innerHTML] =\n parseInt(bottomEl.getElementsByClassName('seed')[0].innerHTML);\n }\n }\n return teams;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get parent path from string ex)"a/b/c"=> "a/b" "a"=> null "a/b/c/"=> "a/b": if allow_empty is false "a/b/c/"=> "a/b/c": if allow_empty is true "a//b/c"=> "a//b" "a/b/c//"=> "a/b": if allow_empty is false "a/b/c//"=> "a/b/c/": if allow_empty is true "a/"=> null: if allow_empty is false "a/"=> "a": if allow_empty is true "/a/b"=> "/a" "/a"=> null "a//b"=> "a": if allow_empty is false "a//b"=> "a/": if allow_empty is true "a/b///"=> "a": if allow_empty is false "a/b///"=> "a/b//": if allow_empty is true | function rawGetParentPath(str, separator, allow_empty)
{
if(!rawIsSafeString(str)){
return '';
}
if(!rawIsSafeEntity(allow_empty)){
allow_empty = false;
}else if('boolean' !== typeof allow_empty){
return '';
}
if(!rawIsSafeString(separator)){
separator = '/';
}
var tmp;
var cnt;
// escape if allow empty
if(allow_empty){
// escape '\' --> '\\'
str = str.replace(/\\/g, '\\\\');
// last word is '/' --> add '\'
if('/' === str[str.length - 1]){
str += '\\';
}
// if '//' --> '/\/'
tmp = '';
for(cnt = 0; cnt < str.length; ++cnt){
tmp += str[cnt];
if('/' === str[cnt] && (cnt + 1) < str.length && '/' === str[cnt + 1]){
tmp += '\\';
}
}
str = tmp;
}
// parse by separator
var parts = str.split(separator);
// remove last elements until it is not empty
while(0 < parts.length && !rawIsSafeString(parts[parts.length - 1])){
parts.pop();
}
// remove last element
if(0 < parts.length){
parts.pop();
}
// remove last elements until it is not empty
while(0 < parts.length && !rawIsSafeString(parts[parts.length - 1])){
parts.pop();
}
// join with separator
var parent = parts.join(separator);
// unescape if allow empty
if(allow_empty && rawIsSafeString(parent)){
// '\' --> '' or '\\' --> '\'
tmp = '';
for(cnt = 0; cnt < parent.length; ++cnt){
if('\\' === parent[cnt]){
++cnt;
if(cnt < parent.length && '\\' === parent[cnt]){
tmp += parent[cnt]; // = '\'
}
}else{
tmp += parent[cnt];
}
}
parent = tmp;
}
return parent;
} | [
"static _normalizeDeepestParentFolderPath(folderPath) {\r\n folderPath = path.normalize(folderPath);\r\n const endsWithSlash = folderPath.charAt(folderPath.length - 1) === path.sep;\r\n const parsedPath = path.parse(folderPath);\r\n const pathRoot = parsedPath.root;\r\n const pathWithoutRoot = parsedPath.dir.substr(pathRoot.length);\r\n const pathParts = [...pathWithoutRoot.split(path.sep), parsedPath.name].filter((part) => !!part);\r\n // Starting with all path sections, and eliminating one from the end during each loop iteration,\r\n // run trueCasePathSync. If trueCasePathSync returns without exception, we've found a subset\r\n // of the path that exists and we've now gotten the correct casing.\r\n //\r\n // Once we've found a parent folder that exists, append the path sections that didn't exist.\r\n for (let i = pathParts.length; i >= 0; i--) {\r\n const constructedPath = path.join(pathRoot, ...pathParts.slice(0, i));\r\n try {\r\n const normalizedConstructedPath = true_case_path_1.trueCasePathSync(constructedPath);\r\n const result = path.join(normalizedConstructedPath, ...pathParts.slice(i));\r\n if (endsWithSlash) {\r\n return `${result}${path.sep}`;\r\n }\r\n else {\r\n return result;\r\n }\r\n }\r\n catch (e) {\r\n // This path doesn't exist, continue to the next subpath\r\n }\r\n }\r\n return undefined;\r\n }",
"function getParentFolder(url)\n{\n // remove last / char\n if (url.lastIndexOf('/') == url.length - 1) {\n url = url.substr(0, url.length - 1);\n }\n\n // no parent\n if (url.lastIndexOf('/') < 0 || url.lastIndexOf('/') == 0) {\n return '';\n }\n\n return url.substr(0, url.lastIndexOf('/'));\n}",
"function CorrectPath(str) {\n let paths = [\"\"];\n for (let i = 0; i < str.length; i++) {\n const dirs = [\"u\", \"d\", \"l\", \"r\"];\n if (str[i] === \"?\") {\n const newPaths = [];\n paths.forEach(path => dirs.forEach(dir => newPaths.push(path + dir)));\n paths = newPaths;\n }\n }\n pathcheck: for (path of paths) {\n let j = 0,\n x = 0,\n y = 0;\n for (let i = 0; i < str.length; i++) {\n let dir = str[i];\n if (dir === \"?\") {\n dir = path[j];\n j++;\n }\n if (dir === \"u\") {\n y--;\n } else if (dir === \"d\") {\n y++;\n } else if (dir === \"l\") {\n x--;\n } else if (dir === \"r\") {\n x++;\n }\n if (x < 0 || x > 4 || y < 0 || y > 4) {\n continue pathcheck;\n }\n }\n if (x === 4 && y === 4) {\n j = 0;\n let correctPath = \"\";\n for (let i = 0; i < str.length; i++) {\n if (str[i] === \"?\") {\n correctPath += path[j];\n j++;\n } else {\n correctPath += str[i];\n }\n }\n return correctPath;\n }\n }\n return \"not possible\";\n}",
"static getParentPath(path) { return Component.splitPath(path)[0] }",
"function normalizeRoute(path, parent) {\n if (!path) return parent ? parent.route : '/'\n if (path[0] == '/') return path // \"/\" signifies an absolute route\n if (parent == null) return path // no need for a join\n return `${parent.route}/${path}` // join\n}",
"function parentPath (path) {\n return generatePath(path)\n .replace(R.NODE_PARENT, '')\n .replace(/\\/$/, '')\n}",
"static splitPath(path) {\n // special case for account path\n if (path === \"/\") return [undefined, \"/\"];\n\n const split = path.split(\"/\");\n const id = split.pop();\n let parent = split.join(\"/\") || \"/\";\n if (!parent) parent = undefined;\n return [parent, id];\n }",
"function rel_path(parent, path){\n\t\tif(typeof parent !== 'string') return false;\n\t\t// empty=root, endsWith('/')=url_path possibility\n\t\treturn parent === '' ? path : parent + (parent.endsWith('/') ? '' : '/') + path;\n\t}",
"normalize(...variants) {\n\n if (variants.length <= 0)\n return null;\n if (variants.length > 0\n && !Object.usable(variants[0]))\n return null;\n if (variants.length > 1\n && !Object.usable(variants[1]))\n return null;\n\n if (variants.length > 1\n && typeof variants[0] !== \"string\")\n throw new TypeError(\"Invalid root: \" + typeof variants[0]);\n let root = \"#\";\n if (variants.length > 1) {\n root = variants[0];\n try {root = Path.normalize(root);\n } catch (error) {\n root = (root || \"\").trim();\n throw new TypeError(`Invalid root${root ? \": \" + root : \"\"}`);\n }\n }\n\n if (variants.length > 1\n && typeof variants[1] !== \"string\")\n throw new TypeError(\"Invalid path: \" + typeof variants[1]);\n if (variants.length > 0\n && typeof variants[0] !== \"string\")\n throw new TypeError(\"Invalid path: \" + typeof variants[0]);\n let path = \"\";\n if (variants.length === 1)\n path = variants[0];\n if (variants.length === 1\n && path.match(PATTERN_URL))\n path = path.replace(PATTERN_URL, \"$1\");\n else if (variants.length > 1)\n path = variants[1];\n path = (path || \"\").trim();\n\n if (!path.match(PATTERN_PATH))\n throw new TypeError(`Invalid path${String(path).trim() ? \": \" + path : \"\"}`);\n\n path = path.replace(/([^#])#$/, \"$1\");\n path = path.replace(/^([^#])/, \"#$1\");\n\n // Functional paths are detected.\n if (path.match(PATTERN_PATH_FUNCTIONAL))\n return \"###\";\n\n path = root + path;\n path = path.toLowerCase();\n\n // Path will be balanced\n const pattern = /#[^#]+#{2}/;\n while (path.match(pattern))\n path = path.replace(pattern, \"#\");\n path = \"#\" + path.replace(/(^#+)|(#+)$/g, \"\");\n\n return path;\n }",
"function normalizeRoute(path, parent) {\n if (path[0] === '/' || path[0] === '') {\n return path; // absolute route\n }\n if (!parent) {\n return path; // no need for a join\n }\n return `${parent.route}/${path}`; // join\n}",
"_parentKey(key){\n return key\n .split(\".\")\n .reduce((parentKey, subKey, idx, arr) =>\n parentKey + ((idx !== arr.length -1) ?`.${subKey}` : \"\"), \"\")\n .replace(/^\\./,\"\");\n }",
"createRoute(path, parentPath) {\n if (path[0] === '/' && path.length === 1) return path;\n if (typeof parentPath === 'undefined') return path;\n if (parentPath[0] === '/' && parentPath.length === 1) return path;\n return `${parentPath}/${path}`;\n }",
"function getParentDir(p) {\n\t\tif(p.length === 0) { return current }\n\t\telse { return exists(p.slice(0, p.length-1)) }\n\t}",
"static function getPathContainer(path : String) {\n\t\tvar delimiter : String = getPathDelimiter(path);\n\t\tif (path.Contains(delimiter)) {\n\t\t\treturn path.Substring(0, path.LastIndexOf(delimiter));\n\t\t}\n\t\treturn path;\n\t}",
"function path(string) {\n return string.replace(/([^:]\\/)\\/+/g, \"$1\");\n}",
"function GetParentDirectoryFromMailingListURI(abURI)\n{\n var abURIArr = abURI.split(\"/\");\n /*\n turn turn \"moz-abmdbdirectory://abook.mab/MailList6\"\n into [\"moz-abmdbdirectory:\",\"\",\"abook.mab\",\"MailList6\"]\n then, turn [\"moz-abmdbdirectory:\",\"\",\"abook.mab\",\"MailList6\"]\n into \"moz-abmdbdirectory://abook.mab\"\n */\n if (abURIArr.length == 4 && abURIArr[0] == \"moz-abmdbdirectory:\" && abURIArr[3] != \"\") {\n return abURIArr[0] + \"/\" + abURIArr[1] + \"/\" + abURIArr[2];\n }\n\n return null;\n}",
"function collapseLeadingSlashes(str) {\n\t for (var i = 0; i < str.length; i++) {\n\t if (str[i] !== '/') {\n\t break\n\t }\n\t }\n\n\t return i > 1\n\t ? '/' + str.substr(i)\n\t : str\n\t}",
"parsePath(url) {\n\t\tvar ret = \"\";\n\n\t\t// In case the url has a protocol, remove it.\n\t\tvar protocolSplit = url.split(\"://\");\n\t\tvar withoutProtocol;\n\t\tif (protocolSplit.length > 1) {\n\t\t\twithoutProtocol = protocolSplit[1];\n\t\t} else {\n\t\t\twithoutProtocol = protocolSplit[0];\n\t\t}\n\n\t\tvar host = withoutProtocol.split(\"?\")[0];\n\t\tvar pathIndex = host.indexOf(\"/\");\n\t\tif (pathIndex !== -1) {\n\t\t\tret = host.substring(pathIndex, host.length);\n\t\t} else {\n\t\t\tret = \"/\";\n\t\t}\n\n\t\treturn ret;\n\t}",
"getParentString() {\n let parent = this.getParent();\n if (!parent) {\n // \n const { parentPath } = this.path;\n if (parentPath) {\n return `[${parentPath.node.type}] ${pathToString(parentPath)}`;\n }\n }\n return parent?.toString();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Class StockDataManager: manage stock data at runtime; data includes StockData, RecentQuotes, Alert... | function StockDataManager() {
this.items = {};
this.count = 0;
} | [
"function StockProvider(){\n /**\n * Maakt een nieuwe YahooAjaxHelper aan en zet dat in de variable yahoo.\n * @type {YahooAjaxHelper} : Geeft een YahooAjaxHelper \"class/object\".\n */\n yahoo = new YahooAjaxHelper();\n\n /**\n * Maakt een nieuwe LocalHelper aan en zet dat in de variable local.\n * @type {LocalHelper} : Geeft een LocalHelper \"class/object\".\n */\n local = new LocalHelper();\n\n /**\n * Dit is om bij te houden het aantal keer dat de methode getdata is aan geroepen,\n * zodat er om en om de yahoo en local helpers worden gereturnt\n * @type {Number} : count begint met 1.\n */\n var count = 1;\n\n /**\n * De functie getData is om een nieuwe yahoo of local helper te returnen .\n * Na elke keer dat de functie wordt aangeroepen gaat de count omhoog.\n * Dan wordt er een if en else gezet, wanneer de getdata 10 keer is aangeroepen (die local mee geeft) geeft hij de yahoo terug.\n * Nadat de functie 20 keer is aangeroepen wordt de count gereset en zo geeft de StockProvider factory om en om de local en yahoo en roept de getStockData functie aan.\n *\n * @param count : het aantal keer dat getdata is opgeroepen.\n */\n function getData(count) {\n /**\n * Eerst 10 keer dat data wordt opgeroepen voor de local;\n * @type {Number} : 10 keer.\n */\n var localCount = 10;\n /**\n * de volgende 10 keer (maximum is dan dus 20 keer) voor de yahoo;\n * @type {Number} : 20e keer.\n */\n var yahooCount = 20;\n /**\n * reset de count terug naar 1\n * @type {Number} : 1 (gereset weer naar het begin)\n */\n var resetCount = 1;\n /**\n * hier wordt de functie getdata aangeroepen voor het returnen van de local of yahoo helper.\n * @return {*} Het hang van de count af wat hij returnt, of de local.getStockData() of de yahoo.getStockData\n */\n this.getData = function () {\n count++;\n if (count <= localCount) {\n return local.getStockData();\n }\n else {\n if (count === yahooCount) {\n count = resetCount;\n }\n return yahoo.getStockData();\n }\n };\n }\n\n /**\n * Wanneer de functie getData wordt opgeroepen geeft hij de count mee.\n */\n getData.call(this, count);\n}",
"function Stock(symbol){\n // this.name = name;\n this.symbol = symbol;\n this.numShares = 0;\n this.data = this.lookupStock();\n this.name = name;\n this.price = price;\n\n}",
"function stockHistory (stockName,startDate,endDate) {\n\tthis.stockName=stockName;\n\tthis.startDate=startDate; // start date of stock history...\n\tthis.endDate=endDate; // end date of stock history...\n\tthis.times=[]; // time series of history\n\tthis.SMA=[]; // RAW SMA data series which matches up with time series\n\tthis.EMA=[]; // RAW EMA data series which matches up with time series\n\tthis.update = function () {\n\t// calls the server explicitly to update this stocks data ....\n\t}\n\tthis.addData = function (data) {\n\t// adds the standard raw data from the server to this stock\n\t}\n\tthis.getPlotData = function () {\n\t// returns the plot data in the format required for plotting\n\t}\n}",
"function Stock(physicalStockRef = \"itemStock\"\n , reservedStockRef = \"itemStockReserved\"\n , refillRef = \"itemStockRefill\"\n , defaultStock = 20\n , alwaysSynchronize = true) {\n // The default availability of any item not in the Stock database\n this.defaultStock = 20;\n\n // The reference for the \"physical stock\" database:\n // the key in localStorage where the stock database is fetched from\n // and stored to.\n this.physicalStockRef = physicalStockRef;\n\n // The reference for the \"reerved stock\" database:\n // the key in localStorage where the database for items reserved to orders\n // is fetched from and stored to.\n this.reservedStockRef = reservedStockRef;\n\n // The reference for the \"refill\" database:\n // the key in localStorage where the database for items marked for restock\n // is fetched from and stored to.\n this.refillRef = refillRef;\n\n // A flag that indicates whether any change to any aspect of\n // the stock should immediately\n // update localStorage to reflect the changes made.\n this.alwaysSynchronize = alwaysSynchronize;\n\n // The physical stock: representing the actual, physical, availability of\n // items\n //\n // physicalStock is represented by a map from itemIds to the quantity of\n // items in stock for that id. If an itemId isn't present in the map.\n // that should be interpreted as the quantity in the stock for that id is\n // this.defaultStock.\n this.physicalStock = JSON.parse(localStorage.getItem(physicalStockRef));\n\n // The reserved stock: representing what items have been allocated to orders.\n // As orders are completed, reserved items will be moved from the\n // reservedStock to the physicalStock.\n //\n // reservedStock is represented by a map {orders: {}, items: {}}\n //\n // orders is a map from table number to a list of [itemId, quantity]-tuples,\n // representing the order for that table.\n //\n // items is a map from itemId to quantity of reserved items of that id\n // across all orders. If an itemId isn't present in items, that should\n // be interpreted as the quantity of reserved items for that id is 0.\n this.reservedStock = JSON.parse(localStorage.getItem(reservedStockRef));\n\n // To-refill: the set of items that management has marked for refill.\n // Represented by a map from itemId to null. If an itemId is present as a\n // key in the map, that indicates that the id is in the set.\n this.toRefill = JSON.parse(localStorage.getItem(refillRef));\n\n // If localStorage doesn't have the physicalStock stored, initialize it.\n if (this.physicalStock === null) {\n this.physicalStock = {};\n localStorage.setItem(physicalStockRef,\n JSON.stringify(this.physicalStock));\n }\n\n // If localStorage doesn't have the reservedStock stored, initialize it.\n if (this.reservedStock === null) {\n this.reservedStock = {orders: {}, items: {}};\n localStorage.setItem(reservedStockRef,\n JSON.stringify(this.reservedStock));\n }\n\n // If localStorage doesn't have the to-refill stored, initialize it.\n if (this.toRefill === null) {\n this.toRefill = {};\n localStorage.setItem(refillRef, JSON.stringify(this.toRefill));\n }\n}",
"function readStock(data){\n foodS = data.val();\n foodObj.updateFoodStock(foodS);\n}",
"getStockList(stockList) {\n console.log(\"AV: getting: \" + stockList);\n var i;\n for (i = 0; i < stockList.length; i++) {\n this.getLatestData(stockList[i]);\n }\n }",
"function init_stocks(){\n \n //init heimdall section\n Heimdall.members.products[\"stocks\"] = {};\n Heimdall.members.products.stocks[\"Locations\"] = [];\n\n Heimdall.members.products.stocks[\"addMenu\"] = stocksAddMenu;\n Heimdall.members.products.stocks[\"generateMenuCode\"] = Heimdall_Stocks.generateMenuCode;\n\n //init the loader of Stock\n loadStaticsStocksData();\n\n return true;\n}",
"function StockHandler() {\n\n // Get stocks from DB and send back in json form\n this.getStocks = function (req, res) {\n\n Stocks\n .find()\n .exec(function (err, result) {\n if (err) { throw err; }\n if (result) {\n res.json(result);\n }\n });\n\n };\n\n // Add stock to DB\n this.addStock = function (req, res) {\n var stockCode = req.body.stockCode.toUpperCase();\n\n Stocks\n .findOne( { 'code': stockCode })\n .exec(function(err, doc) {\n if (err) {\n res.send(null, 500);\n }\n else if (doc) {\n // If stock already exists in DB, don't add it again\n res.json(\"Exists\");\n }\n else {\n // Add stock to DB\n\n // Use Date() to get today's date\n var today = new Date();\n var year = today.getFullYear();\n var month = today.getMonth() + 1;\n var day = today.getDate();\n\n var startDate = year - 1 + '-' + month + '-' + day;\n var endDate = year + '-' + month + '-' + day;\n var apiKey = process.env.QUANDL_API_KEY;\n\n var quandlApiUrl = 'https://www.quandl.com/api/v3/datasets/WIKI/' + stockCode + '.json?api_key=' + apiKey + '&start_date=' + startDate + '&end_date=' + endDate;\n\n getJSON(quandlApiUrl, function (err, data) {\n\n if (data.quandl_error) {\n // Send error reponse back to server\n res.json(\"Error\");\n }\n else {\n var name = data.dataset.name;\n var stockData = data.dataset.data;\n var relevantDataArr = [];\n \n for (var i = stockData.length - 1; i >= 0; i--) {\n var indivDate = stockData[i][0];\n var unixTime = new Date(indivDate).getTime();\n var endPrice = stockData[i][4];\n\n relevantDataArr.push([unixTime, endPrice]);\n }\n\n // Add stock to database\n var newStock = new Stocks();\n newStock.code = stockCode;\n newStock.name = name;\n newStock.data = relevantDataArr;\n\n newStock.save(function(err, doc) {\n if (err) {\n res.send(null, 500);\n }\n\n res.send(newStock);\n\n })\n }\n });\n }\n });\n \n };\n\n // Detete stock from DB\n this.deleteStock = function (req, res) {\n \n var stockCode = req.body.stockCode;\n\n Stocks\n .findOne({ 'code': stockCode })\n .exec(function(err, doc) {\n if (err) {\n res.send(null, 500);\n }\n else {\n doc.remove()\n res.json(stockCode + ' successfully removed.');\n }\n })\n\n };\n\n \n}",
"function getData(stockName){\n \n var stockTag = \"stock-\" + stockName;\n \n // Generating URL's on which Ajax calls will be made\n var companyInfoURL = \"https://api.iextrading.com/1.0/stock/\" + stockName + \"/company\";\n var financeInfoURL = \"https://api.iextrading.com/1.0/stock/\" + stockName + \"/financials\";\n var quoteInfoURL = \"https://api.iextrading.com/1.0/stock/\" + stockName + \"/quote\";\n \n //Displaying the current time, tells the user when the data was last fetched\n var currentTime = new Date().getTime();\n var currentDate = new Date(currentTime);\n $( \"#\" + stockTag + \" .time\").html(currentDate.toLocaleString()); \n \n //Populating the Stock title\n $( \"#\" + stockTag + \" #stockHeading\").html(stockName); \n \n // Getting company information for the specific stock\n $.getJSON({\n url: companyInfoURL, \n success: function(data) {\n $( \"#\" + stockTag + \" #symbol\").html(data.symbol);\n $( \"#\" + stockTag + \" #companyName\").html(data.companyName);\n $( \"#\" + stockTag + \" #industry\").html(data.industry);\n $( \"#\" + stockTag + \" #website\").html(data.website);\n $( \"#\" + stockTag + \" #website\").attr(\"href\", data.website );\n $( \"#\" + stockTag + \" #issueType\").html(data.issueType);\n $( \"#\" + stockTag + \" #ceo\").html(data.CEO);\n $( \"#\" + stockTag + \" #sector\").html(data.sector);\n $( \"#\" + stockTag + \" #exchange\").html(data.exchange);\n \n // Identifying the company name to determine the query term for News API call\n var query = data.companyName;\n var queryArray = query.split(\" \");\n\n /* If the company name is long, it's best to use the stock symbol as the query term,\n instead of the company name as too many words combined will not lead to any search results.\n If the company name is short (less than three words), it's best to take the first term as the \n query term as the second and third words are usually 'holding', 'corporation', 'inc.' etc., \n which don't help. */\n\n if (queryArray.length > 3){\n var queryTerm = data.symbol;\n }else{\n var queryTerm = queryArray[0];\n }\n \n var apiKey = \"419c23ced40b4c5b9f22b7083e86c585\";\n var newsURL = \"https://newsapi.org/v2/everything?q=\" + queryTerm + \"&sortBy=popularity\" + \"&apiKey=\" + apiKey;\n \n // Getting the top 8 most popular articles regarding the company.\n $.getJSON({\n url: newsURL,\n success: function(data) {\n \n /* If the search results in more than 8 articles, the loop below will take the first 8 and break the loop.\n If no results are returned, the no articles will be shown. */ \n if (data.articles.length > 0){\n for (let i = 0; i < data.articles.length; i++){\n $( \"#\" + stockTag + \" #link-\" + i).html(data.articles[i].title);\n $( \"#\" + stockTag + \" #link-\" + i).attr(\"href\", data.articles[i].url);\n if (i >= 7) break;\n }\n } else {\n $( \"#\" + stockTag + \" #link-\" + 0).html(\"No articles found amongst the top sources\");\n }\n }\n })\n }})\n \n \n // Getting financial report information for the specific stock\n $.getJSON({\n url: financeInfoURL, \n success: function(data) {\n $( \"#\" + stockTag + \" #totalRevenue\").html(numeral(data.financials[0].totalRevenue).format('($ 0.0000 a)'));\n $( \"#\" + stockTag + \" #grossProfit\").html(numeral(data.financials[0].grossProfit).format('($ 0.0000 a)'));\n $( \"#\" + stockTag + \" #operatingIncome\").html(numeral(data.financials[0].operatingIncome).format('($ 0.0000 a)'));\n $( \"#\" + stockTag + \" #netIncome\").html(numeral(data.financials[0].netIncome).format('($ 0.0000 a)'));\n $( \"#\" + stockTag + \" #rd\").html(numeral(data.financials[0].researchAndDevelopment).format('($ 0.0000 a)'));\n $( \"#\" + stockTag + \" #liabilities\").html(numeral(data.financials[0].totalLiabilities).format('($ 0.0000 a)'));\n $( \"#\" + stockTag + \" #assets\").html(numeral(data.financials[0].totalAssets).format('($ 0.0000 a)'));\n $( \"#\" + stockTag + \" #report\").html(data.financials[0].reportDate);\n \n }})\n \n // Getting quote information for the specific stock\n $.getJSON({\n url: quoteInfoURL, \n success: function(data) {\n $( \"#\" + stockTag + \" #latestPrice\").html(numeral(data.latestPrice).format('($ 0.00)'));\n $( \"#\" + stockTag + \" #latestVolume\").html(data.latestVolume);\n $( \"#\" + stockTag + \" #latestUpdate\").html(new Date(data.latestUpdate).toLocaleDateString());\n $( \"#\" + stockTag + \" #peRatio\").html(data.peRatio);\n $( \"#\" + stockTag + \" #week52High\").html(numeral(data.week52High).format('($ 0.00)'));\n $( \"#\" + stockTag + \" #week52Low\").html(numeral(data.week52Low).format('($ 0.00)'));\n $( \"#\" + stockTag + \" #marketCap\").html(numeral(data.marketCap).format('($ 0.0000 a)'));\n $( \"#\" + stockTag + \" #ytdChange\").html(numeral(data.ytdChange).format('0.00%'));\n }})\n }",
"function stockObj (){\r\n this.symbol = \"\";\r\n this.company = \"\";\r\n this.price = \"\";\r\n this.quantity = \"\";\r\n this.total = \"\";\r\n this.clientName = \"\";\r\n this.date = \"\";\r\n this.broker = \"\";\r\n this.status = \"\"; //green might indicate this variable has been taken. check if run into problem\r\n}",
"function displayStockData(symbol) {\r\n queryString = `https://www.randyconnolly.com/funwebdev/3rd/api/stocks/history.php?symbol=${symbol}`;\r\n\r\n // fetch stock info\r\n animation2.style.display = \"flex\";\r\n fetch(queryString)\r\n .then(response => {\r\n if (response.ok) { return response.json() }\r\n else { return Promise.reject({ status: response.status, statusTest: response.statusText }) }\r\n })\r\n .then(data => {\r\n animation2.style.display = \"none\";\r\n\r\n //call on function that shows date, open, close, low, high, volume\r\n createStockTable(data);\r\n\r\n //call on function that creates avg, min, max table\r\n stockCalculation(data);\r\n\r\n\r\n //push data into array named financialsStored\r\n financialsStored.push(...data);\r\n\r\n //display chart C\r\n displayChartC(data);\r\n\r\n })\r\n .catch(err => console.log(err));\r\n }",
"function readStock(data){\r\n food=data.val();\r\n FO.updateFoodStock(food);\r\n}",
"function getStockData(ticker) {\r\n\t\treturn new Promise(function(resolve, reject) {\r\n\t\t\tlet url = \"https://www.alphavantage.co/query?function=\";\r\n\t\t\turl += \"TIME_SERIES_DAILY&symbol=\"\r\n\t\t\turl += ticker;\r\n\r\n\t\t\t// If things stop working, switch keys. Likely out of free calls.\r\n\t\t\t// url += \"&apikey=MC4A891THRXU4GAO\";\r\n\t\t\turl += \"&apikey=N0KY93Q4FPKZYQHI\";\r\n\r\n\t\t\tfetch(url)\r\n\t\t\t.then(checkStatus)\r\n\t\t\t.then(function(responseText) {\r\n\t\t\t\tlet stockData = JSON.parse(responseText)[\"Time Series (Daily)\"];\r\n\r\n\t\t\t\tlet date1 = getValidDate(false, stockData);\r\n\t\t\t\tlet date2 = getValidDate(true, stockData);\r\n\r\n\t\t\t\tlet openPrice = parseFloat(stockData[date1][\"1. open\"]);\r\n\t\t\t\tlet closePrice = parseFloat(stockData[date2][\"4. close\"]);\r\n\t\t\t\tlet changeInPrice = ((openPrice - closePrice) / openPrice) * 100;\r\n\r\n\t\t\t\tlet stockObj = {ticker: ticker,\r\n\t\t\t\t\t\t\t\tquantity: 0,\r\n\t\t\t\t\t\t\t\topen: openPrice,\r\n\t\t\t\t\t\t\t\tclose: closePrice,\r\n\t\t\t\t\t\t\t\tchange: changeInPrice};\r\n\r\n\t\t\t\tconsole.log(stockObj);\r\n\t\t\t\tavailableStocks[ticker] = stockObj;\r\n\t\t\t\tbiggestDrops.push(stockObj);\r\n\t\t\t\tresolve(\"Stock Found.\");\r\n\t\t\t})\r\n\t\t\t.catch(function(error) {\r\n\t\t\t\tconsole.log(error.message);\r\n\t\t\t\tresolve(\"Stock not found.\");\r\n\t\t\t});\r\n\t\t});\r\n\t}",
"function Stock(){\n\tthis.storeName = \"\";\n\tthis.storeAdress = \"\";\n\tthis.cds = [];\n\tconsole.log(\"Stock Constructor Called\");\n}",
"function StoreStockData(irisNative){\n // Clear global from previous runs\n irisNative.kill(\"^nyse\");\n\n console.log(\"Storing stock data using Native API...\");\n\n // Get all stock data from all_stocks.csv file into a list\n var array = fs.readFileSync('all_stocks.csv').toString().split(\"\\n\");\n\n // Get start time\n var start = Date.now()/1000;\n\n // Loop through list of stock and store natively\n for (var j = 1; j < array.length; j++){\n irisNative.set(array[j], \"^nyse\", j);\n }\n\n // Get time consuming\n var end = Date.now()/1000;\n var totalConsume = (end - start).toFixed(4);\n console.log(\"Stored natively successfully. Execution time: \" + totalConsume + \"ms\");\n}",
"loadStockHistory(code,totalItems, graphID, callFrom){\r\n \r\n // load chinese stock\r\n if(code.indexOf(\"us\") == -1){\r\n // CN STOCKS, Fund\r\n if (code.indexOf(\"jj\") != -1) {\r\n // type is Chinese Fund\r\n // remove header\r\n if(USE_SKYLINE_CACHE_SERVICE){\r\n var server = SKYLINE_CACHE_SERVER.replace(\"#SYMBOL#\", code).replace('#begin#','0').replace('#end#','1');\r\n } else {\r\n code =code.substring(2,code.length);\r\n var server = \"engine.php?cadd=\" + encodeURIComponent(FUND_SERVER_TENCENT.replace(\"#fundcode#\", code));\r\n }\r\n //console.log(\"parsing URL: \" + server);\r\n var dataHolder = new Array();\r\n $.get(server, function(data) {\r\n //console.log(data);\r\n // clean up\r\n var _cnStockContent = data.substring(data.lastIndexOf(\"[[\")+1,data.lastIndexOf(\"]]\")); \r\n var name = data.substring(data.lastIndexOf(\"name\")+8,data.lastIndexOf(\"}\")-1); \r\n name = JSON.parse(\"\\\"\" + name + \"\\\"\");\r\n \r\n _cnStockContent = _cnStockContent.replaceAll(\"\\\"\", '');\r\n _cnStockContent = _cnStockContent.split(\"], [\");\r\n // packaging\r\n var dataHolder = new Array();\r\n var datalen = _cnStockContent.length;\r\n //fix for fund tomorrow\r\n for (var i = 0; i < datalen; i++) {\r\n //str += formatDate(pdata[0].data[i][0]) + \",\" + pdata[0].data[i][1] + \",\" + pdata[2].data[i][1] + \",\" + (pdata[0].data[i][1] + pdata[2].data[i][1]) + \"\\n\";\r\n _cnStockContent[i] = _cnStockContent[i].replaceAll(\",\\\\[\", '').replaceAll(\"\\\\[\",'');\r\n var tmp = _cnStockContent[i].split(\",\");\r\n dataHolder[i] = [];\r\n dataHolder[i][0] = toUnivfiedMMDDYYYY(tmp[0].trim().insert('/',4).insert('/',7));//fastfind\r\n dataHolder[i][1] = parseFloat(tmp[2]);\r\n dataHolder[i][2] = parseFloat(tmp[2]);\r\n }\r\n //save and send result to main\r\n\r\n //Realtime\r\n\r\n var param = {};\r\n param['type'] = getStockType(code);\r\n param['name'] = name;\r\n param['code'] = code;\r\n param['totalItems'] = totalItems;\r\n param['callFrom'] = callFrom;\r\n saveResults(graphID,dataHolder,param);\r\n \r\n // REALTIME:\r\n \r\n /*\r\n $.get(\"engine.php?cadd=\" + encodeURIComponent('http://qt.gtimg.cn/q=s_sz'+code+',s_sz399300'), function(data) {\r\n // console.log(\"parsing real-time URL: \" +FUND_SERVER + code + \"&indexcode=000300&type=\" + dataPeriod);\r\n var response = data.split(\";\");\r\n var tmpRealtime = response[0].substring(response[0].indexOf(\"\\\"\") , response[0].length - 2).replaceAll(\"\\\"\", '');\r\n tmpRealtime = tmpRealtime.split(\"~\");\r\n console.log(tmpRealtime);\r\n var _date = calcTime('beijing','+8');\r\n var currentPercent = parseFloat(tmpRealtime[5]);\r\n var HistoryCurrentPercent = currentPercent + parseFloat(pdata[0].data[datalen-1][1]);\r\n tmpRealtime = response[1].substring(response[1].indexOf(\"\\\"\") , response[1].length - 2).replaceAll(\"\\\"\", '');\r\n tmpRealtime = tmpRealtime.split(\"~\");\r\n console.log(tmpRealtime);\r\n // str += _date + \",\" + HistoryCurrentPercent + \",\"+ HistoryHS300Percent + \",\" +currentOverall;\r\n \r\n });\r\n */\r\n });\r\n\r\n \r\n } else if (code.contains('if')){\r\n console.log(\"if stocks\");\r\n } else {\r\n // Chinese stock\r\n if(USE_SKYLINE_CACHE_SERVICE)\r\n var server = SKYLINE_CACHE_SERVER.replace(new RegExp(\"#SYMBOL#\", 'g'),code).replace(\"#begin#\",toChineseYYYYMMDD(getDataLength('2y'))).replace(\"#end#\",toChineseYYYYMMDD(getDayInChina()));\r\n else\r\n var server = \"engine.php?cadd=\"+encodeURIComponent(CNSTOCK_HISTORY_SERVER.replace(new RegExp(\"#SYMBOL#\", 'g'),code).replace(\"#begin#\",toChineseYYYYMMDD(getDataLength('2y'))).replace(\"#end#\",toChineseYYYYMMDD(getDayInChina())));\r\n //console.log(\"loading stock \"+server);\r\n $.get(server, function(data) {\r\n // filtering unncessary things\r\n var _cnStockContent = data.substring(data.lastIndexOf(\"[[\")+1,data.lastIndexOf(\"]]\")); \r\n _cnStockContent = _cnStockContent.replaceAll(\"\\\"\", '');\r\n _cnStockContent = _cnStockContent.split(\"]\");\r\n var name = data.substring(data.lastIndexOf(\"qt\"),data.lastIndexOf(\"}\")).split(\",\")[1]; \r\n name = name.replaceAll('\\\"','');\r\n //name =convert2UTF8(name)\r\n name = JSON.parse(\"\\\"\" + name + \"\\\"\");\r\n \r\n // packaging\r\n this.cnStockContent = new Array(_cnStockContent.length);\r\n var initialPrice = parseFloat(_cnStockContent[0].split(\",\")[2]);\r\n for(var i = 0 ; i < _cnStockContent.length; i ++){\r\n _cnStockContent[i] = _cnStockContent[i].replaceAll(\",\\\\[\", '').replaceAll(\"\\\\[\",'');\r\n var tmp = _cnStockContent[i].split(\",\");\r\n this.cnStockContent[i] = [];\r\n this.cnStockContent[i][0] = tmp[0].convert2USDateFromCN();\r\n this.cnStockContent[i][1] = ((parseFloat(tmp[2]) - initialPrice) / initialPrice * 100).toFixed(1)+\"%\" \r\n this.cnStockContent[i][2] = parseFloat(tmp[2]);\r\n }\r\n //save and send result to main\r\n var param = {};\r\n param['type'] = getStockType(code);\r\n param['name'] = name;\r\n param['code'] = code;\r\n param['totalItems'] = totalItems;\r\n param['callFrom'] = callFrom;\r\n\r\n // if stock is valid\r\n if(this.cnStockContent.length>10)\r\n saveResults(graphID,this.cnStockContent,param);\r\n \r\n \r\n });\r\n }//End of Chinese stocks\r\n // Begining of processing us stocks \r\n } else {\r\n // us stocks\r\n if(USE_SKYLINE_CACHE_SERVICE){\r\n var server = SKYLINE_CACHE_SERVER.replace('#SYMBOL#',code).replace(\"#begin#\",getDataLength('2y').toTimeStamp()).replace(\"#end#\",getDayInChina().toTimeStamp());\r\n } else{\r\n code = code.split(\"_\")[1];\r\n var server = \"engine.php?cadd=\" + encodeURIComponent(USSTOCK_HISTORY_SERVER.replace('#SYMBOL#',code).replace(\"#begin#\",getDataLength('2y').toTimeStamp()).replace(\"#end#\",getDayInChina().toTimeStamp()));\r\n }\r\n $.get(server, function(data) {\r\n //parsing yahoo\r\n //console.log(\"loging raw data ------------ \" + code+\" :\" + data); \r\n var _content = '';\r\n try{\r\n _content = JSON.parse(data);\r\n\r\n } catch(e){\r\n smartLog(e.Message,'alarm');\r\n return;\r\n }\r\n var len = _content.chart.result[0]['timestamp'].length;\r\n var initialPrice = parseFloat(_content.chart.result[0]['indicators']['quote'][0]['close'][0]);\r\n var name = code;\r\n \r\n var temp = new Array();\r\n for(var i = 0 ; i < len; i ++){\r\n temp[i] = [];\r\n temp[i][0] = getTime(_content.chart.result[0]['timestamp'][i]);\r\n var c = parseFloat(_content.chart.result[0]['indicators']['quote'][0]['close'][i]);\r\n temp[i][1] = ((c - initialPrice)/initialPrice*100).toFixed(2) + \"%\";\r\n temp[i][2] = c;\r\n }\r\n //console.log(\"loading \"+code+\" complete!\");\r\n // console.log(temp);\r\n var param = {};\r\n param['type'] = getStockType(code);\r\n param['name'] = name;\r\n param['code'] = code;\r\n param['totalItems'] = totalItems;\r\n param['callFrom'] = callFrom;\r\n saveResults(graphID,temp,param);\r\n\r\n });\r\n }\r\n }",
"function getStockTickerUpdate() {\t\n\n\t\t\t// get stock ticker update from server\t\t\t\t\t\n\t stockTickerService.getStockTickers().success(function(data) {\n\n\t \t// config ------\n\t \tvar oldTickers = $scope.stockTikcerArrayTemp; \t\n\t \tvar updateTickers = data;\n\n\t \t// calulate price changes and %\n\t \tupdateTickers = localService.updateTickerArray(updateTickers,oldTickers);\n\n\t \t// Calling Sort method\n\t \t$scope.stockTikcerArray = localService.tickerArraySorting(updateTickers);\n\t \t\n\t }).error(function(data) { \t\n\t alert(\"Unable get update stock ticker\");\n\t });\n\n\t }",
"function getDataFromYQL(thisStock) {\n\t\tvar today = new Date();\n\t\tvar monthNumber = today.getMonth();\n\t\tvar currentMonth = monthNames[monthNumber];\n\t\tvar currentYear = today.getFullYear();\n\t\tvar key = currentMonth + \".\"+ currentYear;\n\n\t\t\t/* Makes sure current date's signals are updated, if not then\n\t\t\t\tuse 1/1/2016's signals */\n\t\tif (!(key in historicalSignalData)){\n\t\t\tmonthNumber = 0;\n\t\t\tcurrentYear = 2016;\n\t\t\tcurrentMonth = monthNames[monthNumber];\n\t\t\tkey = currentMonth + \".\" + currentYear;\n\t\t};\n\t\t$('#signalDate').text(\"Signals from: \" + currentMonth + \" \" + currentYear);\n \tvar url = \"https://query.yahooapis.com/v1/public/yql\";\n\t\t\t//working url https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22MSFT%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=\n \tvar data = encodeURIComponent(\"select * from yahoo.finance.quotes where symbol in ('\" + thisStock + \"')\");\n \t$.getJSON(url, 'q=' + data + \"&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=\")\n .done(function (data) {\n\t\t\t\t\tconsole.log(historicalSignalData[key]);\n \tvar tr = $('<tr/>');\n tr.append(\"<td class='stockGraphSymbol'><button type='button' onclick='showGraph(this.textContent);getYQLNews(this.textContent);'>\" + thisStock + \"</button></td>\");\n \ttr.append(\"<td>\" + data.query.results.quote.Name + \"</td>\");\n \ttr.append(\"<td>\" + historicalSignalData[key][thisStock] + \"</td>\");\n \ttr.append(\"<td>\" + data.query.results.quote.LastTradePriceOnly + \"</td>\");\n\n $('#myTable').append(tr);\n\n \t\t})\n\n .fail(function (jqxhr, textStatus, error) {\n var err = textStatus + \", \" + error;\n $(\"#result\").text('Request failed: ' + err);\n \t});\n\n\t}",
"function stock(symbol) {\r\n\r\n EventEmitter.call(this);\r\n stockEmitter = this;\r\n\r\n var start = \"2014-04-20\";\r\n var end = \"2015-05-04\";\r\n //Connect to the API URL (http://teamtreehouse.com/username.json)\r\n\r\n var request = https.get(\"https://query.yahooapis.com/v1/public/yql\"+\r\n \"?q=select%20*%20from%20yahoo.finance.historicaldata%20\"+\r\n \"where%20symbol%20%3D%20%22\"\r\n +symbol+\"%22%20and%20startDate%20%3D%20%22\"\r\n +start+\"%22%20and%20endDate%20%3D%20%22\"\r\n +end+\"%22&format=json&env=store%3A%2F%2F\"\r\n +\"datatables.org%2Falltableswithkeys\", function (response) {\r\n\r\n var body = \"\";\r\n if (response.statusCode !== 200) {\r\n request.abort();\r\n //Status Code Error\r\n stockEmitter.emit(\"error\", new Error(\"There was an error getting the data for \" + symbol + \". (\" + http.STATUS_CODES[response.statusCode] + \")\"));\r\n\r\n }\r\n\r\n //Read the data\r\n response.on('data', function (chunk) {\r\n body += chunk;\r\n stockEmitter.emit(\"data\", chunk);\r\n });\r\n\r\n\r\n response.on('end', function () {\r\n if(response.statusCode === 200) {\r\n try {\r\n //Parse the data\r\n var stock = JSON.parse(body);\r\n stockEmitter.emit(\"end\", stock);\r\n } catch (error) {\r\n stockEmitter.emit(\"error\", error);\r\n }\r\n }\r\n }).on(\"error\", function(error){\r\n stockEmitter.emit(\"error\", error);\r\n });\r\n });\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Here we setup all the options for the VisJs network diagram were we see what are the default values and configuration | setupOptions() {
this.options = {
nodes: {
shape: 'image',
image: '/images/terminal.png'
},
edges: {
arrows: 'to',
color: '#aaa',
smooth: {
type: 'continuous',
forceDirection: 'none'
}
},
physics: {
enabled: false
},
layout: {
hierarchical: {
direction: 'LR'
}
}
};
} | [
"function drawNetwork({nodes: nodesDataset, edges: edgesDataset}) {\n network = new vis.Network(container, {nodes: nodesDataset, edges: edgesDataset} , options);\n }",
"function initTutorialDefaults() {\n const graph = graphComponent.graph\n \n // configure defaults normal nodes and their labels\n graph.nodeDefaults.style = new ShapeNodeStyle({\n fill: 'darkorange',\n stroke: 'white'\n })\n graph.nodeDefaults.size = new Size(40, 40)\n graph.nodeDefaults.labels.layoutParameter = InteriorLabelModel.CENTER\n \n // configure defaults group nodes and their labels\n graph.groupNodeDefaults.style = new PanelNodeStyle({\n color: 'rgb(214, 229, 248)',\n insets: [18, 5, 5, 5],\n labelInsetsColor: 'rgb(214, 229, 248)'\n })\n graph.groupNodeDefaults.labels.style = new DefaultLabelStyle({\n horizontalTextAlignment: 'center'\n })\n graph.groupNodeDefaults.labels.layoutParameter = InteriorStretchLabelModel.NORTH\n }",
"function initializeGraph() {\n const graph = filteredGraph\n graph.nodeDefaults.style = defaultNodeStyle\n graph.nodeDefaults.size = new Size(80, 30)\n graph.edgeDefaults.style = normalEdgeStyle\n graph.nodeDefaults.labels.style = nodeLabelStyle\n graph.undoEngineEnabled = true\n}",
"function setGraphVizLocs() {\n agentGroup.selectAll(\"polygon\").on('mousedown.drag', null).transition().duration(500)\n .attr(\"transform\", function(d) {\n var x = Math.max(rectLength, Math.min(width - rectLength, d.gv_x));\n var y = Math.max(rectLength, Math.min(height - rectLength, d.gv_y));\n if (isNaN(x) || isNaN(y)) return null;\n return \"translate(\" + x + \",\" + y + \")\";\n });\n\n actsGroup.selectAll(\"circle\").on('mousedown.drag', null).transition().duration(500)\n .attr(\"transform\", function(d) {\n var x = Math.max(radiusLength, Math.min(width - radiusLength, d.gv_x));\n var y = Math.max(radiusLength, Math.min(height - radiusLength, d.gv_y));\n if (isNaN(x) || isNaN(y)) return null;\n return \"translate(\" + x + \",\" + y + \")\";\n });\n\n entsGroup.selectAll(\"rect\").on('mousedown.drag', null).transition().duration(500)\n .attr(\"transform\", function(d) {\n var x = Math.max(rectLength, Math.min(width - rectLength, d.gv_x));\n var y = Math.max(rectLength, Math.min(height - rectLength, d.gv_y));\n if (isNaN(x) || isNaN(y)) return null;\n return \"translate(\" + x + \",\" + y + \")\";\n });\n\n nodeTextGroup.selectAll(\"g\").transition().duration(500)\n .attr(\"transform\", function(d) {\n var x = Math.max(rectLength, Math.min(width - rectLength, d.gv_x));\n var y = Math.max(rectLength, Math.min(height - rectLength, d.gv_y));\n if (isNaN(x) || isNaN(y)) return null;\n return \"translate(\" + x + \",\" + y + \")\";\n });\n \n pathGroup.selectAll(\"path\").transition().duration(500)\n .attr(\"d\", function(d) {\n if (d.type == \"wasGeneratedBy\") {\n return link_wasGeneratedBy(d.source.gv_x, d.source.gv_y, d.target.gv_x, d.target.gv_y, false);\n }\n if (d.type == \"used\") {\n return link_used(d.source.gv_x, d.source.gv_y, d.target.gv_x, d.target.gv_y, false);\n }\n if (d.type == \"associated\") {\n return link_association(d.source.gv_x, d.source.gv_y, d.target.gv_x, d.target.gv_y);\n }\n if (d.type == \"delegated\") {\n return link_delegation(d.source.gv_x, d.source.gv_y, d.target.gv_x, d.target.gv_y);\n }\n if (d.type == \"controlled\") {\n return link_controlled(d.source.gv_x, d.source.gv_y, d.target.gv_x, d.target.gv_y);\n }\n if (d.type == \"e2e_related\") {\n return link_e2e_related(d.source.gv_x, d.source.gv_y, d.target.gv_x, d.target.gv_y, true);\n }\n if (d.type == \"a2e_related\") {\n return link_a2e_related(d.source.gv_x, d.source.gv_y, d.target.gv_x, d.target.gv_y, true);\n }\n });\n\n pathTextGroup.selectAll(\"g\").transition().duration(500)\n .attr(\"transform\", function(d) {\n if (d.source.gv_x > d.target.gv_x) var x = d.target.gv_x + (d.source.gv_x - d.target.gv_x)/2.;\n else var x = d.source.gv_x + (d.target.gv_x - d.source.gv_x)/2.;\n if (d.source.gv_y > d.target.gv_y) var y = d.target.gv_y + (d.source.gv_y - d.target.gv_y)/2.;\n else var y = d.source.gv_y + (d.target.gv_y - d.source.gv_y)/2.;\n if (isNaN(x) || isNaN(y)) return null;\n return \"translate(\" + x + \",\" + y + \")\";\n });\n \n // center the nodes - this needs to be fixed so that it doesn't shift the canvas\n /*\n var g_bbox = allGroup.node().getBoundingClientRect();\n allGroup.transition().duration(500)\n .attr(\"transform\", function(d) {\n return \"translate(\" + (width/2 - g_bbox.width/2) + \",\" + (height/2 - g_bbox.height/2) + \")\";\n });\n */\n\n}",
"renderNetwork() {\n\n const container = document.getElementById('visual-container');\n\n const tactics = this.convertToArray(this.get('store').peekAll('tactic'));\n const mappings = this.convertToArray(this.get('store').peekAll('mapping'));\n const patterns = this.convertToArray(this.get('store').peekAll('pattern'));\n\n const dataSet = dataConverter.dataToDataset(tactics, patterns, mappings);\n\n const options = {\n height: '400px',\n width: '100%',\n physics: {\n enabled: false,\n },\n manipulation: {\n enabled: false,\n },\n layout: {\n hierarchical: {\n enabled: true,\n sortMethod: 'directed',\n nodeSpacing: 230,\n },\n },\n interaction: {\n dragNodes: false,\n zoomView: false,\n dragView: false,\n },\n\n };\n\n // initialize network\n this.set('network', new vis.Network(container, dataSet, options));\n const network = this.get('network');\n\n // set listeners\n network.on('click', (event) => {\n\n // when node is clicked, the node is moving in center of window\n if (event.nodes.length > 0) {\n this.focusNode(event);\n\n // otherwise the overview of the network is shown\n } else {\n this.unFocusNode();\n }\n\n });\n }",
"initializeDefaultStyles() {\n this.graphComponent.graph.nodeDefaults.size = new Size(60, 40)\n this.graphComponent.graph.nodeDefaults.style = new ReactComponentNodeStyle(NodeTemplate)\n this.graphComponent.graph.nodeDefaults.labels.style = new DefaultLabelStyle({\n textFill: '#fff',\n font: new Font('Robot, sans-serif', 14)\n })\n this.graphComponent.graph.edgeDefaults.style = new PolylineEdgeStyle({\n smoothingLength: 25,\n stroke: '5px #242265',\n targetArrow: new Arrow({\n fill: '#242265',\n scale: 2,\n type: 'circle'\n })\n })\n }",
"drawGraph(nodes, connections) {\n this.reset();\n\n const container = document.getElementById(\"infrastructureNetwork_vis\");\n\n // set initial image of each node\n nodes.forEach(function (node) {\n node[\"image\"] = InfrastructureView.buildNodeSVGImage();\n nodes.update(node);\n });\n\n const data = {\n nodes: nodes,\n edges: connections\n };\n\n const options = {\n edges: {\n arrows: {\n to: {\n enabled: true\n }\n },\n arrowStrikethrough: false,\n smooth: {\n enabled: true,\n type: \"dynamic\"\n },\n color: {\n color: \"#000000\"\n },\n length: 300\n },\n interaction: {\n hover: false,\n selectConnectedEdges: false\n },\n manipulation: {\n enabled: false\n },\n layout: {\n // randomSeed: 11235813\n },\n physics: {\n enabled: true,\n solver: \"forceAtlas2Based\"\n }\n };\n\n this.network = new vis.Network(container, data, options);\n }",
"function initDiagram() {\n //set deault values to render diagram\n setDefaults();\n\n //create diagram g\n diagramG = diagram.svg.append('g')\n .attr('width', width)\n .attr('height', height)\n .attr('class', 'eve-vis-g')\n .attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')');\n\n //now we can initialize the diagram\n renderDiagram();\n }",
"function configGraphType() {\n\n graph.scaleX.set(35, 2, '');\n switch(controls.graph_type.value) {\n case 'pos':\n box.title = \"Posición vs. Tiempo\";\n graph.scaleY.set(35, -20, '');\n graph.setLabels(\"\", \"Tiempo [s]\", \"Posición [cm]\");\n break;\n case 'vel':\n box.title = \"Velocidad vs. Tiempo\";\n graph.scaleY.set(35, -5, '');\n graph.setLabels(\"\", \"Tiempo [s]\", \"Velocidad [cm/s]\");\n break;\n case 'accel':\n box.title = \"Aceleración vs. Tiempo\";\n graph.scaleY.set(35, -1, '');\n graph.setLabels(\"\", \"Tiempo [s]\", \"Aceleración [cm/s²]\");\n break;\n }\n\n}",
"function graphGenerateOptions () {\n var options = \"No options are required, default values used.\";\n var optionsSpecific = [];\n var radioButton1 = document.getElementById(\"graph_physicsMethod1\");\n var radioButton2 = document.getElementById(\"graph_physicsMethod2\");\n if (radioButton1.checked == true) {\n if (this.constants.physics.barnesHut.gravitationalConstant != this.backupConstants.physics.barnesHut.gravitationalConstant) {optionsSpecific.push(\"gravitationalConstant: \" + this.constants.physics.barnesHut.gravitationalConstant);}\n if (this.constants.physics.centralGravity != this.backupConstants.physics.barnesHut.centralGravity) {optionsSpecific.push(\"centralGravity: \" + this.constants.physics.centralGravity);}\n if (this.constants.physics.springLength != this.backupConstants.physics.barnesHut.springLength) {optionsSpecific.push(\"springLength: \" + this.constants.physics.springLength);}\n if (this.constants.physics.springConstant != this.backupConstants.physics.barnesHut.springConstant) {optionsSpecific.push(\"springConstant: \" + this.constants.physics.springConstant);}\n if (this.constants.physics.damping != this.backupConstants.physics.barnesHut.damping) {optionsSpecific.push(\"damping: \" + this.constants.physics.damping);}\n if (optionsSpecific.length != 0) {\n options = \"var options = {\";\n options += \"physics: {barnesHut: {\";\n for (var i = 0; i < optionsSpecific.length; i++) {\n options += optionsSpecific[i];\n if (i < optionsSpecific.length - 1) {\n options += \", \"\n }\n }\n options += '}}'\n }\n if (this.constants.smoothCurves.enabled != this.backupConstants.smoothCurves.enabled) {\n if (optionsSpecific.length == 0) {options = \"var options = {\";}\n else {options += \", \"}\n options += \"smoothCurves: \" + this.constants.smoothCurves.enabled;\n }\n if (options != \"No options are required, default values used.\") {\n options += '};'\n }\n }\n else if (radioButton2.checked == true) {\n options = \"var options = {\";\n options += \"physics: {barnesHut: {enabled: false}\";\n if (this.constants.physics.repulsion.nodeDistance != this.backupConstants.physics.repulsion.nodeDistance) {optionsSpecific.push(\"nodeDistance: \" + this.constants.physics.repulsion.nodeDistance);}\n if (this.constants.physics.centralGravity != this.backupConstants.physics.repulsion.centralGravity) {optionsSpecific.push(\"centralGravity: \" + this.constants.physics.centralGravity);}\n if (this.constants.physics.springLength != this.backupConstants.physics.repulsion.springLength) {optionsSpecific.push(\"springLength: \" + this.constants.physics.springLength);}\n if (this.constants.physics.springConstant != this.backupConstants.physics.repulsion.springConstant) {optionsSpecific.push(\"springConstant: \" + this.constants.physics.springConstant);}\n if (this.constants.physics.damping != this.backupConstants.physics.repulsion.damping) {optionsSpecific.push(\"damping: \" + this.constants.physics.damping);}\n if (optionsSpecific.length != 0) {\n options += \", repulsion: {\";\n for (var i = 0; i < optionsSpecific.length; i++) {\n options += optionsSpecific[i];\n if (i < optionsSpecific.length - 1) {\n options += \", \"\n }\n }\n options += '}}'\n }\n if (optionsSpecific.length == 0) {options += \"}\"}\n if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {\n options += \", smoothCurves: \" + this.constants.smoothCurves;\n }\n options += '};'\n }\n else {\n options = \"var options = {\";\n if (this.constants.physics.hierarchicalRepulsion.nodeDistance != this.backupConstants.physics.hierarchicalRepulsion.nodeDistance) {optionsSpecific.push(\"nodeDistance: \" + this.constants.physics.hierarchicalRepulsion.nodeDistance);}\n if (this.constants.physics.centralGravity != this.backupConstants.physics.hierarchicalRepulsion.centralGravity) {optionsSpecific.push(\"centralGravity: \" + this.constants.physics.centralGravity);}\n if (this.constants.physics.springLength != this.backupConstants.physics.hierarchicalRepulsion.springLength) {optionsSpecific.push(\"springLength: \" + this.constants.physics.springLength);}\n if (this.constants.physics.springConstant != this.backupConstants.physics.hierarchicalRepulsion.springConstant) {optionsSpecific.push(\"springConstant: \" + this.constants.physics.springConstant);}\n if (this.constants.physics.damping != this.backupConstants.physics.hierarchicalRepulsion.damping) {optionsSpecific.push(\"damping: \" + this.constants.physics.damping);}\n if (optionsSpecific.length != 0) {\n options += \"physics: {hierarchicalRepulsion: {\";\n for (var i = 0; i < optionsSpecific.length; i++) {\n options += optionsSpecific[i];\n if (i < optionsSpecific.length - 1) {\n options += \", \";\n }\n }\n options += '}},';\n }\n options += 'hierarchicalLayout: {';\n optionsSpecific = [];\n if (this.constants.hierarchicalLayout.direction != this.backupConstants.hierarchicalLayout.direction) {optionsSpecific.push(\"direction: \" + this.constants.hierarchicalLayout.direction);}\n if (Math.abs(this.constants.hierarchicalLayout.levelSeparation) != this.backupConstants.hierarchicalLayout.levelSeparation) {optionsSpecific.push(\"levelSeparation: \" + this.constants.hierarchicalLayout.levelSeparation);}\n if (this.constants.hierarchicalLayout.nodeSpacing != this.backupConstants.hierarchicalLayout.nodeSpacing) {optionsSpecific.push(\"nodeSpacing: \" + this.constants.hierarchicalLayout.nodeSpacing);}\n if (optionsSpecific.length != 0) {\n for (var i = 0; i < optionsSpecific.length; i++) {\n options += optionsSpecific[i];\n if (i < optionsSpecific.length - 1) {\n options += \", \"\n }\n }\n options += '}'\n }\n else {\n options += \"enabled:true}\";\n }\n options += '};'\n }\n\n\n this.optionsDiv.innerHTML = options;\n }",
"function graphGenerateOptions() {\n\t var options = \"No options are required, default values used.\";\n\t var optionsSpecific = [];\n\t var radioButton1 = document.getElementById(\"graph_physicsMethod1\");\n\t var radioButton2 = document.getElementById(\"graph_physicsMethod2\");\n\t if (radioButton1.checked == true) {\n\t if (this.constants.physics.barnesHut.gravitationalConstant != this.backupConstants.physics.barnesHut.gravitationalConstant) {\n\t optionsSpecific.push(\"gravitationalConstant: \" + this.constants.physics.barnesHut.gravitationalConstant);\n\t }\n\t if (this.constants.physics.centralGravity != this.backupConstants.physics.barnesHut.centralGravity) {\n\t optionsSpecific.push(\"centralGravity: \" + this.constants.physics.centralGravity);\n\t }\n\t if (this.constants.physics.springLength != this.backupConstants.physics.barnesHut.springLength) {\n\t optionsSpecific.push(\"springLength: \" + this.constants.physics.springLength);\n\t }\n\t if (this.constants.physics.springConstant != this.backupConstants.physics.barnesHut.springConstant) {\n\t optionsSpecific.push(\"springConstant: \" + this.constants.physics.springConstant);\n\t }\n\t if (this.constants.physics.damping != this.backupConstants.physics.barnesHut.damping) {\n\t optionsSpecific.push(\"damping: \" + this.constants.physics.damping);\n\t }\n\t if (optionsSpecific.length != 0) {\n\t options = \"var options = {\";\n\t options += \"physics: {barnesHut: {\";\n\t for (var i = 0; i < optionsSpecific.length; i++) {\n\t options += optionsSpecific[i];\n\t if (i < optionsSpecific.length - 1) {\n\t options += \", \";\n\t }\n\t }\n\t options += '}}';\n\t }\n\t if (this.constants.smoothCurves.enabled != this.backupConstants.smoothCurves.enabled) {\n\t if (optionsSpecific.length == 0) {\n\t options = \"var options = {\";\n\t } else {\n\t options += \", \";\n\t }\n\t options += \"smoothCurves: \" + this.constants.smoothCurves.enabled;\n\t }\n\t if (options != \"No options are required, default values used.\") {\n\t options += '};';\n\t }\n\t } else if (radioButton2.checked == true) {\n\t options = \"var options = {\";\n\t options += \"physics: {barnesHut: {enabled: false}\";\n\t if (this.constants.physics.repulsion.nodeDistance != this.backupConstants.physics.repulsion.nodeDistance) {\n\t optionsSpecific.push(\"nodeDistance: \" + this.constants.physics.repulsion.nodeDistance);\n\t }\n\t if (this.constants.physics.centralGravity != this.backupConstants.physics.repulsion.centralGravity) {\n\t optionsSpecific.push(\"centralGravity: \" + this.constants.physics.centralGravity);\n\t }\n\t if (this.constants.physics.springLength != this.backupConstants.physics.repulsion.springLength) {\n\t optionsSpecific.push(\"springLength: \" + this.constants.physics.springLength);\n\t }\n\t if (this.constants.physics.springConstant != this.backupConstants.physics.repulsion.springConstant) {\n\t optionsSpecific.push(\"springConstant: \" + this.constants.physics.springConstant);\n\t }\n\t if (this.constants.physics.damping != this.backupConstants.physics.repulsion.damping) {\n\t optionsSpecific.push(\"damping: \" + this.constants.physics.damping);\n\t }\n\t if (optionsSpecific.length != 0) {\n\t options += \", repulsion: {\";\n\t for (var i = 0; i < optionsSpecific.length; i++) {\n\t options += optionsSpecific[i];\n\t if (i < optionsSpecific.length - 1) {\n\t options += \", \";\n\t }\n\t }\n\t options += '}}';\n\t }\n\t if (optionsSpecific.length == 0) {\n\t options += \"}\";\n\t }\n\t if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {\n\t options += \", smoothCurves: \" + this.constants.smoothCurves;\n\t }\n\t options += '};';\n\t } else {\n\t options = \"var options = {\";\n\t if (this.constants.physics.hierarchicalRepulsion.nodeDistance != this.backupConstants.physics.hierarchicalRepulsion.nodeDistance) {\n\t optionsSpecific.push(\"nodeDistance: \" + this.constants.physics.hierarchicalRepulsion.nodeDistance);\n\t }\n\t if (this.constants.physics.centralGravity != this.backupConstants.physics.hierarchicalRepulsion.centralGravity) {\n\t optionsSpecific.push(\"centralGravity: \" + this.constants.physics.centralGravity);\n\t }\n\t if (this.constants.physics.springLength != this.backupConstants.physics.hierarchicalRepulsion.springLength) {\n\t optionsSpecific.push(\"springLength: \" + this.constants.physics.springLength);\n\t }\n\t if (this.constants.physics.springConstant != this.backupConstants.physics.hierarchicalRepulsion.springConstant) {\n\t optionsSpecific.push(\"springConstant: \" + this.constants.physics.springConstant);\n\t }\n\t if (this.constants.physics.damping != this.backupConstants.physics.hierarchicalRepulsion.damping) {\n\t optionsSpecific.push(\"damping: \" + this.constants.physics.damping);\n\t }\n\t if (optionsSpecific.length != 0) {\n\t options += \"physics: {hierarchicalRepulsion: {\";\n\t for (var i = 0; i < optionsSpecific.length; i++) {\n\t options += optionsSpecific[i];\n\t if (i < optionsSpecific.length - 1) {\n\t options += \", \";\n\t }\n\t }\n\t options += '}},';\n\t }\n\t options += 'hierarchicalLayout: {';\n\t optionsSpecific = [];\n\t if (this.constants.hierarchicalLayout.direction != this.backupConstants.hierarchicalLayout.direction) {\n\t optionsSpecific.push(\"direction: \" + this.constants.hierarchicalLayout.direction);\n\t }\n\t if (Math.abs(this.constants.hierarchicalLayout.levelSeparation) != this.backupConstants.hierarchicalLayout.levelSeparation) {\n\t optionsSpecific.push(\"levelSeparation: \" + this.constants.hierarchicalLayout.levelSeparation);\n\t }\n\t if (this.constants.hierarchicalLayout.nodeSpacing != this.backupConstants.hierarchicalLayout.nodeSpacing) {\n\t optionsSpecific.push(\"nodeSpacing: \" + this.constants.hierarchicalLayout.nodeSpacing);\n\t }\n\t if (optionsSpecific.length != 0) {\n\t for (var i = 0; i < optionsSpecific.length; i++) {\n\t options += optionsSpecific[i];\n\t if (i < optionsSpecific.length - 1) {\n\t options += \", \";\n\t }\n\t }\n\t options += '}';\n\t } else {\n\t options += \"enabled:true}\";\n\t }\n\t options += '};';\n\t }\n\n\t this.optionsDiv.innerHTML = options;\n\t}",
"function initializeGraph() {\n const graph = graphComponent.graph;\n // initialize default node/edge styles\n graph.nodeDefaults.style = new NetworkFlowNodeStyle();\n graph.nodeDefaults.size = new Size(60, 30);\n graph.edgeDefaults.style = new NetworkFlowEdgeStyle();\n // enable the undo engine\n graph.undoEngineEnabled = true;\n graph.edgeDefaults.labels.layoutParameter = FreeEdgeLabelModel.INSTANCE.createDefaultParameter();\n graph.edgeDefaults.labels.style = new DefaultLabelStyle({\n font: '11px Arial',\n backgroundStroke: 'skyblue',\n backgroundFill: 'aliceblue',\n insets: [3, 5, 3, 5]\n });\n const decorator = graph.decorator;\n decorator.nodeDecorator.reshapeHandleProviderDecorator.setImplementation(new EmptyReshapeHandleProvider());\n const edgeStyleHighlight = new EdgeStyleDecorationInstaller({\n edgeStyle: new NetworkFlowEdgeStyle(Color.DARK_ORANGE),\n zoomPolicy: StyleDecorationZoomPolicy.WORLD_COORDINATES\n });\n decorator.edgeDecorator.highlightDecorator.setImplementation(edgeStyleHighlight);\n decorator.edgeDecorator.selectionDecorator.hideImplementation();\n decorator.labelDecorator.selectionDecorator.hideImplementation();\n decorator.labelDecorator.focusIndicatorDecorator.hideImplementation();\n}",
"function DrawGraph() {\n RemoveNetwork(\"networkContainer\");\n //initailize the vis network global objects\n VISJS_NODES = new vis.DataSet({});\n VISJS_EDGES = new vis.DataSet({});\n\n VISJS_OPTIONS = {\n physics: false, //don't want wibly wobbley stuff to happen\n layout: { improvedLayout: false } //we let R compute the layout for us since vis.js cant handle layout for large number of nodes\n };\n\n VISJS_DATA = {\n nodes: VISJS_NODES,\n edges: VISJS_EDGES\n };\n\n //Use vis.js to draw each node depending on its type.\n for (var nodeKey in GraphObj.Nodes) {\n var n = GraphObj.Nodes[nodeKey];\n VISJS_NODES.add({\n id: n.Id,\n color: n.color,\n label: n.Label,\n shape: n.shape, //only affects resources. Standards use defualt shape. \n size: 10, //only affects resources since they have no label. \n x: n.X,\n y: n.Y, \n font: {size: n.FontSize}\n });\n }\n\n //Use vis.js to draw the edges between nodes\n for (var edgeKey in GraphObj.Edges) {\n var edge = GraphObj.Edges[edgeKey];\n VISJS_EDGES.add({\n to: edge.source, \n from: edge.target\n });\n }\n\n //Draw the graph. \n var container = document.getElementById(\"networkContainer\");\n VISJS_GRAPH = new vis.Network(container, VISJS_DATA, VISJS_OPTIONS);\n\n VISJS_GRAPH.on(\"click\", function (properties) {\n var nodeID = properties.nodes[0];\n if (nodeID == undefined) return;\n\n var clickedNode = GraphObj.Nodes[nodeID];\n var t = clickedNode.Type;\n\n //handle node click action for standard nodes \n if (t == NodeTypes.CC || t == NodeTypes.SEP || t == NodeTypes.DCI || t == NodeTypes.PE || t == NodeTypes.TOPIC) {\n //perform highlight actions on graph and standards table \n UnighlightAllNodes();\n HighlightNode(nodeID);\n UnhighlightStandardsTableRows();\n HighlightStandardsTableRow(nodeID)\n document.getElementById(nodeID).scrollIntoView();\n\n //Build the aligned resources table\n if (t != NodeTypes.TOPIC) {\n BuildResourcesTable(nodeID);\n }\n } \n UnighlightAllNodes();\n HighlightNode(nodeID);\n });\n\n VISJS_GRAPH.on(\"doubleClick\", function (properties) {\n var nodeID = properties.nodes[0];\n if (nodeID == undefined) return;\n\n NodeDoubleClickActionResult(nodeID); \n });\n\n //Build the standards table\n BuildStandardsTable();\n\n}",
"function tryInitNetworkView(){\n // clear out the old visualisation if needed\n if (visjsobj != undefined){\n visjsobj.destroy();\n }\n // find all tasks from the TryTasks collection\n var trytasks = TryTasks.find();\n var nodes = new Array();\n var ind = 0;\n // iterate the tasks, converting each task into \n // a node object that the visualiser can understand\n trytasks.forEach(function(name){\n // set up a label with the task name\n var label = \"ind: \"+ind;\n if (trytasks.name != undefined){// we have a name\n label = trytasks.name + \" - \" + \" Tryout\";\n console.log(\"the task name:\" + label);\n\n } \n \n // create the node and store it to the nodes array\n nodes[ind] = {\n id:ind, \n label:label, \n }\n ind ++;\n })\n // edges are used to connect nodes together. \n // we don't need these for now...\n edges =[\n ];\n // this data will be used to create the visualisation\n var data = {\n nodes: nodes,\n edges: edges\n };\n // options for the visualisation\n var options = {\n nodes: {\n shape: 'dot',\n }\n };\n // get the div from the dom that we'll put the visualisation into\n container = document.getElementById('tryvisjs');\n // create the visualisation\n visjsobj = new vis.Network(container, data, options);\n}",
"function NodeGraph() {\n const graph = {\n nodes: [\n { id: 1, label: \"Node 1\", title: \"node 1 tootip text\" },\n { id: 2, label: \"Node 2\", title: \"node 2 tootip text\" },\n { id: 3, label: \"Node 3\", title: \"node 3 tootip text\" },\n { id: 4, label: \"Node 4\", title: \"node 4 tootip text\" },\n { id: 5, label: \"Node 5\", title: \"node 5 tootip text\" },\n ],\n edges: [\n { from: 1, to: 2 },\n { from: 1, to: 3 },\n { from: 2, to: 4 },\n { from: 2, to: 5 },\n { from: 3, to: 5 },\n { from: 1, to: 5 },\n { from: 5, to: 1 },\n ],\n };\n\n var options = {\n nodes: {\n shape: \"dot\",\n size: 16,\n },\n physics: {\n forceAtlas2Based: {\n gravitationalConstant: -26,\n centralGravity: 0.005,\n springLength: 230,\n springConstant: 0.18,\n },\n maxVelocity: 146,\n solver: \"forceAtlas2Based\",\n timestep: 0.35,\n stabilization: { iterations: 150 },\n },\n };\n\n const events = {\n select: function (event) {\n var { nodes, edges } =\n event;\n },\n };\n return (\n <Graph\n graph={graph}\n options={options}\n events={events}\n getNetwork={(network) => {\n // if you want access to vis.js network api you can set the state in a parent component using this property\n }}\n />\n );\n}",
"function loadNodeOptions() {\n\n\t\t// TODO: Load the available link options from a config\n\t\tvar nodeOptions = [{\n\t\t\t\t\t\t\tlistIndex : 0,\n\t\t\t\t\t\t\toptionType : \"appPropertiesNode\",\n\t\t\t\t\t\t\tlabel : \"App Properties\",\n\t\t\t\t\t\t\ticon : \"images/AppPropertiesIcon.svg\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlistIndex : 1,\n\t\t\t\t\t\t\toptionType : \"screenNode\",\n\t\t\t\t\t\t\tlabel : \"Screen Node\",\n\t\t\t\t\t\t\ticon : \"images/DefaultScreenIcon.svg\"\n\t\t\t\t\t\t}];\n\n\t\treturn nodeOptions;\n\t}",
"function setGraphics()\n{\n\tvar graph = this.graph;\n\tvar containerId = this.containerId;\n\n\t// define onMouseOver callback function\n\tvar graphics = Viva.Graph.View.svgGraphics(), \n\t\t\t\t\t\thighlightRelatedNodes = function(nodeId, isOn)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// just enumerate all realted nodes and update link color:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tgraph.forEachLinkedNode(nodeId, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfunction(node, link)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvar linkUI = graphics.getLinkUI(link.id);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (linkUI)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// linkUI is a UI object created by graphics below\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlinkUI.attr('stroke', isOn ? 'red' : 'gray');\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t};\n\t// set callback functions\t\n\tgraphics.node(function(node)\n\t{\n\t\t// set images for the nodes\n\t\tvar country = (node.data == null || node.data.split(';')[0] == '')? 'default' : node.data.split(';')[0];\t\t\t\t\t\n\t\n\t\tvar ui = Viva.Graph.svg('image')\n\t\t\t\t\t.attr('width', 16)\n\t\t\t\t\t.attr('height', 16)\n\t\t\t\t\t.link('./img/' + country + '.png');\n\t\t\n\t\t// set onMouseOver/onMouseOut callback functions\t\t\t\n\t\t$(ui).hover(function()\n\t\t\t\t\t\t{\t\t// mouse over\n\t\t\t\t\t\t\t\thighlightRelatedNodes(node.id, true);\n \t\t\t\t\t\t},\n\t\t\t\t\t\tfunction()\n\t\t\t\t\t\t{\t\t// mouse out\n\t\t\t\t\t\t\t\thighlightRelatedNodes(node.id, false);\n\t\t\t\t\t\t});\n\t\t\n\t\t// set onClick callback function\t\t\t\n\t\tui.addEventListener('click', function ()\n\t\t\t\t\t\t\t\t\t{\n \t \tvar d = document.getElementById(containerId).getElementsByClassName(\"info\")[0];\n\t\t\t\t\t\t\t\t\t\tvar content = (node.data == null)? \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"AS: \" + node.id : \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"AS: \" + node.id + \" \" + node.data.substring(0,2) + String.fromCharCode(13) + node.data.substring(3,node.data.length);\n \t \t\t\t\t\t\t\td.firstChild.nodeValue = content;\n \t \t\t});\n\t\t\t\t\t\n\t\treturn ui;\n\t});\n\n\t// call the renderer\n\trenderer = Viva.Graph.View.renderer(graph, { \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tgraphics : graphics,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcontainer : document.getElementById(this.containerId)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t });\n\trenderer.run();\n}",
"function configGraph() {\n vm.graphConfig = {\n tooltips: true,\n labels: false,\n mouseover: function() {},\n mouseout: function() {},\n click: function() {},\n legend: {\n display: true,\n //could be 'left, right'\n position: 'right'\n },\n colors: ['#337AB7', '#5CB85C', '#D9534F'],\n innerRadius: 100,\n isAnimate: true,\n xAxisRotation: -65\n };\n\n // Angular chart config\n vm.graphInfo = {\n series: ['คงเหลือ', 'รายรับ', 'รายจ่าย'],\n data: []\n };\n\n }",
"function constructDot(){\n var Gdot = \"\";\n Gdot += \"graph Gproto {\\n\";\n Gdot += \"\\tsplines=line;\\n\\n\";\n\n // settings\n var includeprotographs = document.getElementById(\"theincludeprotographs\").checked;\n var labelprotographs = document.getElementById(\"thelabelprotographs\").checked;\n var protographcolours = document.getElementById(\"theprotographcolours\").checked;\n\n// var showlabels = true;\n\n // print out the protographs?\n if (includeprotographs){\n Gdot += \"\\t// protographs\\n\";\n for (var n=0;n<Ngraphs;n++){ // loop over all *extant* subgraphs\n if (subgraphNodes[n].length){\n Gdot += \"\\tsubgraph cluster_\"+n+\" {\\n\\t\\tlabel = \\\"Protograph \"+n+\"\\\";\\n\";\n // print the node labels:\n if (labelprotographs){\n for (var i=0;i<subgraphNodes[n].length;i++){ // loop over all nodes in this subgraph\n// Gdot += \"\\t\\t\"+ i +\" [ label = \\\"\"+n+\".\"+ i +\"\\\"];\\n\"; // make lables as \"n.i\"\n// Gdot += \"\\t\\t\"+ i +\" [ label = \\\"\"+ i +\"\\\"];\\n\"; // make labels as \"i\"\n Gdot += \"\\t\\t\"+ i +\" [ label = \\\"\"+ alphabet[n][i] +\"\\\"];\\n\"; // make labels using the nth alphabet\n }\n }\n // print the edges: we need to make these unique wrt other protographs AND the final graph...\n for (var i=0;i<links.length;i++){\n if (links[i].source.subgraph == n && links[i].target.subgraph == n){\n Gdot += \"\\t\\t\"+ links[i].source.index +\"--\"+ links[i].target.index;\n if (protographcolours){\n Gdot += \" [color = \" + colours[n] + \"]\";\n }\n Gdot += \";\\n\";\n }\n }\n Gdot += \"\\t}\\n\";\n }\n }\n } // end includeprotographs\n Gdot += \"}\\n\";\n\n return Gdot;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an arc between two markers | function linkArc(data){
var to = data.toMarker;
var from = data.fromMarker;
bend = data.bend || 1;
var srcXY = map.latLngToLayerPoint( from.getLatLng()),
trgXY = map.latLngToLayerPoint( to.getLatLng() );
var dx = trgXY.x - srcXY.x,
dy = trgXY.y - srcXY.y,
dr = Math.sqrt(dx * dx + dy * dy)*bend;
return "M" + srcXY.x + "," + srcXY.y + "A" + (-dr) + "," + (-dr) + " 0 0,1 " + trgXY.x + "," + trgXY.y;
} | [
"function getCircleArc(r, p1, p2) {\n return `M ${p1.x} ${p1.y} A ${r} ${r}, 0, 0, 1, ${p2.x} ${p2.y}`;\n}",
"function computeArcThroughTwoPoints(p1, p2) {\n var aDen = (p1.x * p2.y - p1.y * p2.x), bDen = aDen;\n var sq1 = p1.squaredNorm(), sq2 = p2.squaredNorm();\n // Fall back to a straight line\n if (aDen == 0)\n return {\n x: 0,\n y: 0,\n ratio: -1\n };\n\n var a = (p1.y * sq2 - p2.y * sq1 + p1.y - p2.y) / aDen;\n var b = (p2.x * sq1 - p1.x * sq2 + p2.x - p1.x) / bDen;\n var x = -a / 2;\n var y = -b / 2;\n var squaredRatio = (a * a + b * b) / 4 - 1;\n // Fall back to a straight line\n if (squaredRatio < 0)\n return {\n x: 0,\n y: 0,\n ratio: -1\n };\n var ratio = Math.sqrt(squaredRatio);\n var out = {\n x: x,\n y: y,\n ratio: ratio > 1000 ? -1 : ratio,\n a: a,\n b: b\n };\n\n return out;\n }",
"function createArcByPoints(p0, p1, r) {\n\tvar d = p0.getDistanceTo(p1);\n\tvar offset = p0.getOffsetTo(p1);\n\tvar theta = Math.acos(d / r);\n\tvar center = new Vector(p);\n\tcenter.addPolar(r, theta + offset.getAngle());\n}",
"function computeArcThroughTwoPoints(p1, p2){\n var aDen = (p1.x * p2.y - p1.y * p2.x), bDen = aDen;\n var sq1 = p1.squaredNorm(), sq2 = p2.squaredNorm();\n // Fall back to a straight line\n if (aDen == 0)\n return {\n x: 0,\n y: 0,\n ratio: -1\n };\n \n var a = (p1.y * sq2 - p2.y * sq1 + p1.y - p2.y) / aDen;\n var b = (p2.x * sq1 - p1.x * sq2 + p2.x - p1.x) / bDen;\n var x = -a / 2;\n var y = -b / 2;\n var squaredRatio = (a * a + b * b) / 4 - 1;\n // Fall back to a straight line\n if (squaredRatio < 0)\n return {\n x: 0,\n y: 0,\n ratio: -1\n };\n var ratio = Math.sqrt(squaredRatio);\n var out = {\n x: x,\n y: y,\n ratio: ratio > 1000? -1 : ratio,\n a: a,\n b: b\n };\n \n return out;\n }",
"function computeArcThroughTwoPoints(p1, p2){\n var aDen = (p1.x * p2.y - p1.y * p2.x), bDen = aDen;\n var sq1 = p1.squaredNorm(), sq2 = p2.squaredNorm();\n // Fall back to a straight line\n if (aDen == 0)\n return {\n x: 0,\n y: 0,\n ratio: -1\n };\n\n var a = (p1.y * sq2 - p2.y * sq1 + p1.y - p2.y) / aDen;\n var b = (p2.x * sq1 - p1.x * sq2 + p2.x - p1.x) / bDen;\n var x = -a / 2;\n var y = -b / 2;\n var squaredRatio = (a * a + b * b) / 4 - 1;\n // Fall back to a straight line\n if (squaredRatio < 0)\n return {\n x: 0,\n y: 0,\n ratio: -1\n };\n var ratio = Math.sqrt(squaredRatio);\n var out = {\n x: x,\n y: y,\n ratio: ratio > 1000? -1 : ratio,\n a: a,\n b: b\n };\n\n return out;\n }",
"function createSmallArc(r, a1, a2) {\n // be careful wrt SVG\n a1 = -a1;\n a2 = -a2;\n\n // compute for an arc of the same angle, but centered around the x-axis\n var\n a = (a2 - a1) / 2.0,\n\n x4 = r * Math.cos(a),\n y4 = r * Math.sin(a),\n x1 = x4,\n y1 = -y4,\n\n q1 = x1 * x1 + y1 * y1,\n q2 = q1 + x1 * x4 + y1 * y4,\n k2 = 4/3 * (Math.sqrt(2 * q1 * q2) - q2) / (x1 * y4 - y1 * x4),\n\n x2 = x1 - k2 * y1,\n y2 = y1 + k2 * x1,\n x3 = x2,\n y3 = -y2,\n\n ar = a + a1,\n cos_ar = Math.cos(ar),\n sin_ar = Math.sin(ar);\n\n return {\n 'x1': r * Math.cos(a1),\n 'y1': r * Math.sin(a1),\n 'x2': x2 * cos_ar - y2 * sin_ar,\n 'y2': x2 * sin_ar + y2 * cos_ar,\n 'x3': x3 * cos_ar - y3 * sin_ar,\n 'y3': x3 * sin_ar + y3 * cos_ar,\n 'x4': r * Math.cos(a2),\n 'y4': r * Math.sin(a2)\n };\n}",
"function drawArc(xArc, yArc, num1, num2) {\n\t\tctx.lineWidth = 3;\n\t\tctx.beginPath();\n\t\tctx.arc(xArc, yArc, r, num1 * Math.PI, num2 * Math.PI);\n\t\tctx.strokeStyle = strokeColor;\n\t\tctx.stroke();\n\t}",
"function drawArc(a, b, c) {\n const orient = b.x * (c.y - a.y) + a.x * (b.y - c.y) + c.x * (a.y - b.y);\n const sweep = (orient > 0) ? 1 : 0;\n const size = Point.distance(b, a);\n return [a.x, a.y + 'A' + size, size, 0, sweep, 1, c.x, c.y].join(',');\n }",
"function arc(c, x, y, r, angleStart, angleEnd) {\n c.beginPath();\n c.arc(x, y, r, angleStart, angleEnd, false)\n c.stroke();\n }",
"function drawArc(e1,e2,a,k,num_arc, coordonnees, first, p){\n\n var x = 155+(a-1)*230,\n y= 140+(4-e1)*50-(e2-e1)*25,\n h = 2+(e2-e1)*50, x1, x2, x3, x4,y1, y2, y3, y4;\n\n if (first){\n first = false;\n\n if (k%2==0){\n\n if (e2<e1){\n coordonnees[num_arc][0] = x-30+50*((k+1)/2)+(e1-e2-1)*15;\n coordonnees[num_arc][1] = y;\n }\n else {\n coordonnees[num_arc][0] = x-30-50*((k+1)/2)-(e1-e2-1)*15;\n coordonnees[num_arc][1] = y;\n }\n }\n\n\n else {\n\n if (e2>=e1){\n coordonnees[num_arc][0] = x+50*((k+1)/2)+(e2-e1-1)*15;\n coordonnees[num_arc][1] = y ;\n }\n\n else {\n coordonnees[num_arc][0] = x-55-50*(k+1)/2-(e2-e1-1)*15+30;\n coordonnees[num_arc][1] = y ;\n }\n }\n var arc_div = document.createElement('div');\n arc_div.className = \"arc\";\n arc_div.id = num_arc;\n document.body.appendChild(arc_div);\n arc_div.onmousedown = function(evt) {\n dragged = true;\n xi = num_arc; xj = 0;\n yi = num_arc; yj = 1;\n }\n\n }\n\n\n if (k%2==0){\n\n if (e2<e1){\n x1 = x4 = x;\n y1 = y+26+(e1-e2-1)*25;\n y4 = y-26-(e1-e2-1)*25;\n line(x,y-h/2, x+8,y-h/2-8);\n line(x,y-h/2, x+8,y-h/2+8);\n noFill();\n bezier(x1, y1, coordonnees[num_arc][0], coordonnees[num_arc][1]+(e1-e2-1)*25+20, coordonnees[num_arc][0], coordonnees[num_arc][1]-(e1-e2-1)*25-20, x4, y4);\n xx = bezierPoint(x1, coordonnees[num_arc][0], coordonnees[num_arc][0], x4, 1/2);\n yy = bezierPoint(y1, coordonnees[num_arc][1]+(e1-e2-1)*25+20, coordonnees[num_arc][1]-(e1-e2-1)*25-20, y4, 1/2);\n }\n else {\n x1 = x4 = x-30;\n y1 = y+24+(e2-e1-1)*25;\n y4 = y-26-(e2-e1-1)*25;\n line(x-38,y-h/2-9, x-30,y-h/2-1);\n line(x-38,y-h/2+7, x-30,y-h/2-1);\n noFill();\n bezier(x1, y1, coordonnees[num_arc][0]-30, coordonnees[num_arc][1]+(e2-e1-1)*25+20, coordonnees[num_arc][0]-30,coordonnees[num_arc][1]-(e2-e1-1)*25-20, x4, y4);\n xx = bezierPoint(x1, coordonnees[num_arc][0]-30, coordonnees[num_arc][0]-30, x4, 1/2);\n yy = bezierPoint(y1, coordonnees[num_arc][1]+(e2-e1-1)*25+20, coordonnees[num_arc][1]-(e2-e1-1)*25-20, y4, 1/2);\n }\n }\n\n else {\n\n if (e2>=e1){\n x1 = x4 = x;\n y1 = y+26+(e2-e1-1)*25;\n y4 = y-26-(e2-e1-1)*25;\n line(x,y-h/2, x+8,y-h/2-8);\n line(x,y-h/2, x+8,y-h/2+8);\n noFill();\n bezier(x1, y1, coordonnees[num_arc][0], coordonnees[num_arc][1]+(e2-e1-1)*25+20, coordonnees[num_arc][0], coordonnees[num_arc][1]-(e2-e1-1)*25-20, x4, y4);\n xx = bezierPoint(x1, coordonnees[num_arc][0], coordonnees[num_arc][0], x4, 1/2);\n yy = bezierPoint(y1, coordonnees[num_arc][1]+(e2-e1-1)*25+20, coordonnees[num_arc][1]-(e2-e1-1)*25-20, y4, 1/2);\n }\n else {\n x1 = x4 = x-30;\n x2 = x3 = x-55-50*(k+1)/2-(e2-e1-1)*15;\n y1 = y+24+(e1-e2-1)*25;\n y4 = y-26-(e1-e2-1)*25;\n line(x-38,y-h/2-9, x-30,y-h/2-1);\n line(x-38,y-h/2+7, x-30,y-h/2-1);\n noFill();\n bezier(x1, y1, coordonnees[num_arc][0]-30, coordonnees[num_arc][1]+(e1-e2-1)*25+20, coordonnees[num_arc][0]-30,coordonnees[num_arc][1]-(e1-e2-1)*25-20, x4, y4);\n xx = bezierPoint(x1, coordonnees[num_arc][0]-30, coordonnees[num_arc][0]-30, x4, 1/2);\n yy = bezierPoint(y1, coordonnees[num_arc][1]+(e1-e2-1)*25+20, coordonnees[num_arc][1]-(e1-e2-1)*25-20, y4, 1/2);\n }\n }\n divs[num_arc].style.top = yy + \"px\";\n divs[num_arc].style.left = xx + \"px\";\n fill(255);\n ellipse(xx, yy, 5,5);\n\n}",
"function Arc2(startPoint,midPoint,endPoint){this.startPoint=startPoint;this.midPoint=midPoint;this.endPoint=endPoint;var temp=Math.pow(midPoint.x,2)+Math.pow(midPoint.y,2);var startToMid=(Math.pow(startPoint.x,2)+Math.pow(startPoint.y,2)-temp)/2.;var midToEnd=(temp-Math.pow(endPoint.x,2)-Math.pow(endPoint.y,2))/2.;var det=(startPoint.x-midPoint.x)*(midPoint.y-endPoint.y)-(midPoint.x-endPoint.x)*(startPoint.y-midPoint.y);this.centerPoint=new Vector2((startToMid*(midPoint.y-endPoint.y)-midToEnd*(startPoint.y-midPoint.y))/det,((startPoint.x-midPoint.x)*midToEnd-(midPoint.x-endPoint.x)*startToMid)/det);this.radius=this.centerPoint.subtract(this.startPoint).length();this.startAngle=Angle.BetweenTwoPoints(this.centerPoint,this.startPoint);var a1=this.startAngle.degrees();var a2=Angle.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees();var a3=Angle.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();// angles correction\nif(a2-a1>+180.0)a2-=360.0;if(a2-a1<-180.0)a2+=360.0;if(a3-a2>+180.0)a3-=360.0;if(a3-a2<-180.0)a3+=360.0;this.orientation=a2-a1<0?Orientation.CW:Orientation.CCW;this.angle=Angle.FromDegrees(this.orientation===Orientation.CW?a1-a3:a3-a1);}",
"function arc(A, B) {\n const a = cartesiand(A),\n b = cartesiand(B);\n const alpha = acos(dot(a, b)), // angle\n w = cross(a, b), // axis direction\n n = sqrt(dot(w, w)); // axis norm\n return !n\n ? { angle: dot(a, b) > 0 ? 0 : 180 }\n : {\n axis: sphericald([w[0] / n, w[1] / n, w[2] / n]),\n angle: alpha * degrees\n };\n}",
"function createSvgArc(x, y, r, startAngle, endAngle) {\n\tif(startAngle > endAngle){\n\t\tvar s = startAngle;\n\t\tstartAngle = endAngle;\n\t\tendAngle = s;\n\t}\n\n\tif (endAngle - startAngle > Math.PI*2) endAngle = Math.PI*1.99999;\n\n\tif (endAngle - startAngle <= Math.PI) largeArc = 0;\n\telse largeArc = 1;\n\n\tvar arc = [\n\t\t'M', x, y,\n\t\t'L', x + (Math.cos(startAngle) * r), y - (Math.sin(startAngle) * r), \n\t\t'A', r, r, 0, largeArc, 0, x + (Math.cos(endAngle) * r), y - (Math.sin(endAngle) * r),\n\t\t'L', x, y\n\t];\n\n\treturn arc.join(' ');\n}",
"function pathArc(ctx, element, offset, spacing, end, circular) {\n const { x , y , startAngle: start , pixelMargin , innerRadius: innerR } = element;\n const outerRadius = Math.max(element.outerRadius + spacing + offset - pixelMargin, 0);\n const innerRadius = innerR > 0 ? innerR + spacing + offset + pixelMargin : 0;\n let spacingOffset = 0;\n const alpha = end - start;\n if (spacing) {\n // When spacing is present, it is the same for all items\n // So we adjust the start and end angle of the arc such that\n // the distance is the same as it would be without the spacing\n const noSpacingInnerRadius = innerR > 0 ? innerR - spacing : 0;\n const noSpacingOuterRadius = outerRadius > 0 ? outerRadius - spacing : 0;\n const avNogSpacingRadius = (noSpacingInnerRadius + noSpacingOuterRadius) / 2;\n const adjustedAngle = avNogSpacingRadius !== 0 ? alpha * avNogSpacingRadius / (avNogSpacingRadius + spacing) : alpha;\n spacingOffset = (alpha - adjustedAngle) / 2;\n }\n const beta = Math.max(0.001, alpha * outerRadius - offset / PI) / outerRadius;\n const angleOffset = (alpha - beta) / 2;\n const startAngle = start + angleOffset + spacingOffset;\n const endAngle = end - angleOffset - spacingOffset;\n const { outerStart , outerEnd , innerStart , innerEnd } = parseBorderRadius$1(element, innerRadius, outerRadius, endAngle - startAngle);\n const outerStartAdjustedRadius = outerRadius - outerStart;\n const outerEndAdjustedRadius = outerRadius - outerEnd;\n const outerStartAdjustedAngle = startAngle + outerStart / outerStartAdjustedRadius;\n const outerEndAdjustedAngle = endAngle - outerEnd / outerEndAdjustedRadius;\n const innerStartAdjustedRadius = innerRadius + innerStart;\n const innerEndAdjustedRadius = innerRadius + innerEnd;\n const innerStartAdjustedAngle = startAngle + innerStart / innerStartAdjustedRadius;\n const innerEndAdjustedAngle = endAngle - innerEnd / innerEndAdjustedRadius;\n ctx.beginPath();\n if (circular) {\n // The first arc segments from point 1 to point a to point 2\n const outerMidAdjustedAngle = (outerStartAdjustedAngle + outerEndAdjustedAngle) / 2;\n ctx.arc(x, y, outerRadius, outerStartAdjustedAngle, outerMidAdjustedAngle);\n ctx.arc(x, y, outerRadius, outerMidAdjustedAngle, outerEndAdjustedAngle);\n // The corner segment from point 2 to point 3\n if (outerEnd > 0) {\n const pCenter = rThetaToXY(outerEndAdjustedRadius, outerEndAdjustedAngle, x, y);\n ctx.arc(pCenter.x, pCenter.y, outerEnd, outerEndAdjustedAngle, endAngle + HALF_PI);\n }\n // The line from point 3 to point 4\n const p4 = rThetaToXY(innerEndAdjustedRadius, endAngle, x, y);\n ctx.lineTo(p4.x, p4.y);\n // The corner segment from point 4 to point 5\n if (innerEnd > 0) {\n const pCenter1 = rThetaToXY(innerEndAdjustedRadius, innerEndAdjustedAngle, x, y);\n ctx.arc(pCenter1.x, pCenter1.y, innerEnd, endAngle + HALF_PI, innerEndAdjustedAngle + Math.PI);\n }\n // The inner arc from point 5 to point b to point 6\n const innerMidAdjustedAngle = (endAngle - innerEnd / innerRadius + (startAngle + innerStart / innerRadius)) / 2;\n ctx.arc(x, y, innerRadius, endAngle - innerEnd / innerRadius, innerMidAdjustedAngle, true);\n ctx.arc(x, y, innerRadius, innerMidAdjustedAngle, startAngle + innerStart / innerRadius, true);\n // The corner segment from point 6 to point 7\n if (innerStart > 0) {\n const pCenter2 = rThetaToXY(innerStartAdjustedRadius, innerStartAdjustedAngle, x, y);\n ctx.arc(pCenter2.x, pCenter2.y, innerStart, innerStartAdjustedAngle + Math.PI, startAngle - HALF_PI);\n }\n // The line from point 7 to point 8\n const p8 = rThetaToXY(outerStartAdjustedRadius, startAngle, x, y);\n ctx.lineTo(p8.x, p8.y);\n // The corner segment from point 8 to point 1\n if (outerStart > 0) {\n const pCenter3 = rThetaToXY(outerStartAdjustedRadius, outerStartAdjustedAngle, x, y);\n ctx.arc(pCenter3.x, pCenter3.y, outerStart, startAngle - HALF_PI, outerStartAdjustedAngle);\n }\n } else {\n ctx.moveTo(x, y);\n const outerStartX = Math.cos(outerStartAdjustedAngle) * outerRadius + x;\n const outerStartY = Math.sin(outerStartAdjustedAngle) * outerRadius + y;\n ctx.lineTo(outerStartX, outerStartY);\n const outerEndX = Math.cos(outerEndAdjustedAngle) * outerRadius + x;\n const outerEndY = Math.sin(outerEndAdjustedAngle) * outerRadius + y;\n ctx.lineTo(outerEndX, outerEndY);\n }\n ctx.closePath();\n}",
"function addArc( startAngle, endAngle, ltlg, radius, backwards ) {\n\n // accumulate the points and return them\n let points = [];\n\n if( Math.round(((2*Math.PI+startAngle)%(Math.PI*2))*20) == Math.round(((2*Math.PI+endAngle)%(Math.PI*2))*20) ) {\n for( var i = 2*Math.PI, adj = Math.PI/40; i >= 0; i -= adj ) {\n var dltlg = ltlg.destPointRad( i % (2*Math.PI), radius);\n points.push( [ dltlg.dlong(), dltlg.dlat() ] );\n }\n points.push( pointAtRadius( ltlg, 2*Math.PI, radius ) );\n }\n else if( 0 ) {\n if( startAngle < endAngle ) {\n for( var i = startAngle, adj = (endAngle-startAngle)/40, ea = Math.round(endAngle*100); Math.round(i*100) <= ea; i -= adj ) {\n var dltlg = ltlg.destPointRad( i, radius );\n points.push( [ dltlg.dlong(), dltlg.dlat() ] );\n }\n\n }\n else {\n for( var i = startAngle, adj = ((_2pi+(startAngle - endAngle))%(_2pi))/40, ea = Math.round(endAngle*100); i >= startAngle || Math.round(i*100) <= ea ; i = roundRad(i +adj) ) {\n var dltlg = ltlg.destPointRad( i, radius );\n points.push( [ dltlg.dlong(), dltlg.dlat() ] );\n }\n }\n }\n else if( startAngle < endAngle ) {\n for( var i = startAngle, adj = (endAngle-startAngle)/40, ea = Math.round(endAngle*100); Math.round(i*100) <= ea; i += adj ) {\n var dltlg = ltlg.destPointRad( i, radius );\n points.push( [ dltlg.dlong(), dltlg.dlat() ] );\n }\n\n }\n else {\n for( var i = startAngle, adj = ((_2pi+(startAngle - endAngle))%(_2pi))/40, ea = Math.round(endAngle*100); i >= startAngle || Math.round(i*100) <= ea ; i = roundRad(i +adj) ) {\n var dltlg = ltlg.destPointRad( i, radius );\n points.push( [ dltlg.dlong(), dltlg.dlat() ] );\n }\n }\n\n return points;\n}",
"function approximateArc(cx, cy, a, b, eta1, eta2){\n if(eta1 < eta2) throw \"approximateArc: eta2 must be bigger than eta1\";\n else if(eta1-eta2 > Math.PI/2){ \n var etamid = eta1 - Math.PI/2;\n approximateArc(cx, cy, a, b, eta1, etamid);\n approximateArc(cx, cy, a, b, etamid, eta2);\n // if a single arc is NOT within acceptable error bounds (0.5), \n // cut it in half and approximate the two sub-arcs\n } else if(bezierError(a, b, eta1, eta2) >= 0.5){\n var etamid = (eta1+eta2)/2;\n approximateArc(cx, cy, a, b, eta1, etamid);\n approximateArc(cx, cy, a, b, etamid, eta2);\n // otherwise, draw the darned thing!\n } else {\n var k = Math.tan((eta1-eta2)/2);\n var alpha = Math.sin(eta1-eta2) * (Math.sqrt(4 + 3*k*k) - 1) / 3;\n \n var p1x = cx + a*Math.cos(eta1),\n p1y = cy + b*Math.sin(eta1),\n p2x = cx + a*Math.cos(eta2),\n p2y = cy + b*Math.sin(eta2),\n c1x = p1x - -a*Math.sin(eta1)*alpha, \n c1y = p1y - b*Math.cos(eta1)*alpha,\n c2x = p2x + -a*Math.sin(eta2)*alpha, \n c2y = p2y + b*Math.cos(eta2)*alpha;\n \n if(!that.openPath) that.moveTo(p1x, p1y);\n that.curveTo(c1x, c1y, c2x, c2y, p2x, p2y);\n }\n }",
"function Arc2(\r\n /** Defines the start point of the arc */\r\n startPoint, \r\n /** Defines the mid point of the arc */\r\n midPoint, \r\n /** Defines the end point of the arc */\r\n endPoint) {\r\n this.startPoint = startPoint;\r\n this.midPoint = midPoint;\r\n this.endPoint = endPoint;\r\n var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);\r\n var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;\r\n var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;\r\n var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);\r\n this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);\r\n this.radius = this.centerPoint.subtract(this.startPoint).length();\r\n this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);\r\n var a1 = this.startAngle.degrees();\r\n var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();\r\n var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();\r\n // angles correction\r\n if (a2 - a1 > +180.0) {\r\n a2 -= 360.0;\r\n }\r\n if (a2 - a1 < -180.0) {\r\n a2 += 360.0;\r\n }\r\n if (a3 - a2 > +180.0) {\r\n a3 -= 360.0;\r\n }\r\n if (a3 - a2 < -180.0) {\r\n a3 += 360.0;\r\n }\r\n this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;\r\n this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);\r\n }",
"function Arc2(\n /** Defines the start point of the arc */\n startPoint, \n /** Defines the mid point of the arc */\n midPoint, \n /** Defines the end point of the arc */\n endPoint) {\n this.startPoint = startPoint;\n this.midPoint = midPoint;\n this.endPoint = endPoint;\n var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);\n var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;\n var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;\n var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);\n this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);\n this.radius = this.centerPoint.subtract(this.startPoint).length();\n this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);\n var a1 = this.startAngle.degrees();\n var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();\n var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();\n // angles correction\n if (a2 - a1 > +180.0) {\n a2 -= 360.0;\n }\n if (a2 - a1 < -180.0) {\n a2 += 360.0;\n }\n if (a3 - a2 > +180.0) {\n a3 -= 360.0;\n }\n if (a3 - a2 < -180.0) {\n a3 += 360.0;\n }\n this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;\n this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);\n }",
"function Arc2(startPoint, midPoint, endPoint) {\n this.startPoint = startPoint;\n this.midPoint = midPoint;\n this.endPoint = endPoint;\n var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);\n var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;\n var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;\n var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);\n this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);\n this.radius = this.centerPoint.subtract(this.startPoint).length();\n this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);\n var a1 = this.startAngle.degrees();\n var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();\n var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();\n // angles correction\n if (a2 - a1 > +180.0)\n a2 -= 360.0;\n if (a2 - a1 < -180.0)\n a2 += 360.0;\n if (a3 - a2 > +180.0)\n a3 -= 360.0;\n if (a3 - a2 < -180.0)\n a3 += 360.0;\n this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;\n this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Invokes the specified nonquery method on the server | invokeNonQuery(methodName, params = null, ...actions) {
// by definition we are not returning anything from these calls so we should not be caching the results
this._useCaching = false;
return this.invokeMethodImpl(methodName, params, actions, null, true);
} | [
"execute(req, res) {\n let msg = req.message\n let method = this[msg.type]\n\n if (method) {\n method.call(this, req, res)\n } else {\n console.error('Method', msg.type, 'not implemented for CollabServer')\n }\n }",
"function noneYaBusiness(){ // Production quality function naming.\n _getRemoteApi(HugeNav.apiServer()); // Invokes our remote Api function using\n } // a Module extension to provide the needed",
"function notImplementedOper(ctx) { ctx.complain(this.name, 'not implemented'); }",
"function executeNoOperations(self, execMode, userCallback) {\n var execId, pendingOps;\n pendingOps = self.impl.getEmptyOperationSet();\n execId = getExecIdForOperationList(self, [], pendingOps);\n run(self, pendingOps, execMode, AO_IGNORE, function onNdbExec(err) {\n onExecute(self, execMode, err, execId, userCallback);\n });\n}",
"function TQueries() {}",
"function TQueries() { }",
"function QueryExecuter()\n{\n}",
"function sendNoop() {\n sendUnauthenticatedRequest(\"noop\", null, null, null, function noop() {});\n}",
"function ETO_InvertibleCmd() { }",
"get remotelyCallable() { return [\"clientRequestForServer\"] }",
"function _callOnClient(method) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n invokeClient.apply(void 0, __spread([method], args));\n}",
"getNonMemberProcedures() {\n var url = `${this.service.server.getUrl()}wa/istsos/services/${this.service.getServiceJSON()[\"service\"]}/offerings/${this.getOfferingJSON()[\"name\"]}/procedures/operations/nonmemberslist`;\n\n let config = {};\n if (this.service.server.getLoginConfig()) {\n config['headers'] = this.service.server.getLoginConfig();\n }\n\n return HttpAPI.get(url, config)\n .then((result) => {\n if (result.success) {\n this.fireEvent('NONMEMBERLIST', result);\n return result;\n } else {\n throw result.message\n }\n }, (error_message) => {\n throw error_message;\n });\n }",
"async function executeQueryWithoutParams(query) {\n return await (await cnn.query(query)).rows[0];\n }",
"cancelQuery()\t{ this._behavior('cancel query'); }",
"function RSExecute(url,method)\r\n\t{\r\n\t\tvar cb, ecb, context;\r\n\t\tvar params = new Array;\r\n\t\tvar pn = 0;\r\n\t\tvar len = RSExecute.arguments.length;\r\n\t\tfor (var i=2; i < len; i++)\r\n\t\t\tparams[pn++] = RSExecute.arguments[i];\r\n\t\t\r\n\t\treturn MSRS.invokeMethod(url,method,params);\r\n\t}",
"static remoteCallConnectedUserByUserName(userName, method, ...args) {\n Assert.assert(method.charAt(0) !== '_', 'Cannot call private methods')\n CommWSUtil.socket.send(JSON.stringify({\n messageType: 'remoteCallConnectedUserByUserName',\n userName,\n method,\n args\n }))\n }",
"handle_NOP() {\n // does nothing\n }",
"NOP(op){}",
"function sendRequest(methodName, args, done, fail) {\n // Generate a random ID for this remote invocation\n var sid = Math.floor(Math.random() * 1000000000).toString(16);\n // Register any callbacks with the nexus so they can be invoked when a response is received\n nexus.add(sid, done, fail);\n // Send a request to the remote, where:\n // - n is the name of the remote function\n // - a is an array of the (hopefully) serializable, non-callback arguments to this method\n send(sid, \"request\", {n: methodName, a: args});\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if at higher priority state | function isHigherPriorityState() {
var options = ISessionScript.getOptions();
var value = options.getOther(options.HighPriorityTransfersPercentageAvailableBandwidth);
var retval = (value == "90");
ISessionScript.debug("isHigherPriorityState()=" + retval);
return retval;
} | [
"isHigh() {\n return this.state === 'high' || this.state === 'pullup';\n }",
"function __checkLevel(currentPriority, stateLevel) {\n if (Array.isArray(stateLevel)) {\n return (//Check if current is whitelisted (state)\n stateLevel.length > 0 &&\n !__insideArray(currentPriority, stateLevel)\n );\n\n } else if (typeof stateLevel === 'string') {\n stateLevel = stateLevel.toLowerCase();//Handle WARN, wArN, etc instead of just warn\n return (//Get numeric value and compare current with state\n typeof (priorities[currentPriority]) === 'number' &&\n typeof (priorities[stateLevel]) === 'number' &&\n (priorities[currentPriority] > priorities[stateLevel])\n );\n\n } else if (typeof stateLevel === 'number') {\n\n return (//Compare current with state\n typeof (priorities[currentPriority]) === 'number' &&\n (priorities[currentPriority] > stateLevel)\n );\n }\n\n return true; //Bail out, level is some unknown type\n }",
"function checkPriority() {\n if (priLoaded){\n doPcodes();\n return;\n } else {\n setTimeout(checkPriority,500);\n }\n}",
"isLow() {\n return this.state === 'low' || this.state === 'pulldown';\n }",
"function OrderedVm_isPrioritized() {\r\n return (this.intVmPriority!=VM_NO_PRIORITY);\r\n }",
"function isPriorityDone() {\n var priorityDone = true,\n priorityWait = config.priorityWait,\n priorityName, i;\n if (priorityWait) {\n for (i = 0; (priorityName = priorityWait[i]); i++) {\n if (!loaded[priorityName]) {\n priorityDone = false;\n break;\n }\n }\n if (priorityDone) {\n delete config.priorityWait;\n }\n }\n return priorityDone;\n }",
"function checkPriority(taskObj, current) {\n\tif (taskObj.getPriority() == current)\n\t\treturn \" checked \";\n}",
"function hasPriority(a, b){\n return operatorPriority(a) >= operatorPriority(b);\n }",
"function isPriorityDone(context) {\n var priorityDone = true,\n priorityWait = context.config.priorityWait,\n priorityName, i;\n if (priorityWait) {\n for (i = 0; (priorityName = priorityWait[i]); i++) {\n if (!context.loaded[priorityName]) {\n priorityDone = false;\n break;\n }\n }\n if (priorityDone) {\n delete context.config.priorityWait;\n }\n }\n return priorityDone;\n }",
"function setHigherPriorityState(state) {\n ISessionScript.debug(\"setHigherPriorityState(\" + state + \")\");\n var options = ISessionScript.getOptions();\n var percentage = null;\n // normal state\n if (state == 0) {\n percentage = \"75\";\n // higher priority state\n } else {\n percentage = \"90\";\n }\n options.setOther(options.HighPriorityTransfersPercentageAvailableBandwidth, percentage);\n options.save();\n return 0;\n}",
"currentPriority(actionContext) {\n const { value: priority, error } = this.priority.tryGetValue(actionContext.state);\n if (error) {\n return -1;\n }\n return priority;\n }",
"get isTop() { return (this.flags & 1 /* Top */) > 0; }",
"isHigherPriority (a, b) {\n return this.heap[a].priority < this.heap[b].priority;\n }",
"getPriority() {\r\n return -50 /* FALLBACK */;\r\n }",
"function is_priority(label) {\n return label.indexOf(\"P-\") == 0 ||\n label == \"I-nominated\" ||\n label == \"I-needs-decision\";\n}",
"_isHigherPriority(i,j) {\n var prioI = ((this._heap[i] && this._heap[i]._priority) ? this._heap[i]._priority : 0);\n var prioJ = ((this._heap[j] && this._heap[j]._priority) ? this._heap[j]._priority : 0);\n return prioI < prioJ;\n }",
"isHigherPriority(i, j) {\n return ((this.heap[i].priority - this.heap[j].priority) > 0);\n }",
"function isPrioritized(status) {\n return (status == \"Prioritize - Approved\" || status == \"Prioritized - Deferred\" || status == \"Prioritized - Denied\" || status == \"To Be Prioritized\");\n}",
"function checkPriority(priority) {\n var intPriority = Number(priority);\n if (!isNaN(intPriority)) {\n return intPriority;\n } else {\n return false;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sets the state for the supplied ED and position. resets the thumbnails to an empty array and sends a request to the datasource for the relevent thumbnails. | setSelectedED(ed,position) {
this.setState( { ed : ed, position: position, thumbnails: [] }, () => { this.requestThumbnails() } );
} | [
"function _initThumbnailsState() {\n return {\n imgs: [],\n firstThumbnailImg: null,\n firstThumbnailBtn: null,\n lastThumbnailImg: null,\n lastTumbnailBtn: null,\n selectedThumbnailImg: null\n };\n }",
"function _initThumbnailsState () {\n return {\n imgs: [],\n firstThumbnailImg: null,\n firstThumbnailBtn: null,\n lastThumbnailImg: null,\n lastTumbnailBtn: null,\n selectedThumbnailImg: null\n };\n }",
"function resetArt() {\n table.empty();\n table.css('opacity', 1);\n hidePreviewImage();\n inputWidth.val(defaultWidth);\n inputHeight.val(defaultHeight);\n makeGrid();\n }",
"function ThumbnailSetPosition( GOMidx, cnt ) {\n var newTop= 0;\n var curTn= G.GOM.items[GOMidx];\n var idx= G.GOM.items[GOMidx].thumbnailIdx;\n var item= G.I[idx];\n \n if( curTn.neverDisplayed ) {\n // thumbnail is built but has never been displayed (=first display)\n var top=curTn.top-G.GOM.clipArea.top;\n if( G.tn.opt.Get('stacks') > 0 ) {\n // we have stacks -> do not display them here. They will be displayed at the end of the display animation\n item.$elt.last().css({ display: 'block'});\n item.$elt.css({ top: top , left: curTn.left });\n }\n else {\n item.$elt.css({ display: 'block', top: top , left: curTn.left });\n }\n newTop=top;\n \n // display the image of the thumbnail when fully loaded\n if( G.O.thumbnailWaitImageLoaded === true ) {\n var gi_imgLoad = ngimagesLoaded( item.$getElt('.nGY2TnImg') );\n gi_imgLoad.on( 'progress', function( instance, image ) {\n if( image.isLoaded ) {\n var idx=image.img.getAttribute('data-idx');\n var albumIdx=image.img.getAttribute('data-albumidx');\n if( albumIdx == G.GOM.albumIdx ) {\n // ignore event if not on current album\n G.I[idx].ThumbnailImageReveal();\n }\n }\n });\n }\n // display the thumbnail\n ThumbnailAppear(GOMidx, cnt);\n\n curTn.displayed=true;\n curTn.neverDisplayed=false;\n }\n else {\n var topOld=G.GOM.cache.containerOffset.top+item.top;\n var top=G.GOM.cache.containerOffset.top+(curTn.top-G.GOM.clipArea.top);\n newTop=curTn.top-G.GOM.clipArea.top;\n var vp=G.GOM.cache.viewport;\n if( G.O.thumbnailDisplayOutsideScreen || ( ( (topOld+curTn.height) >= (vp.t-vp.h) && topOld <= (vp.t+vp.h*2) ) ||\n ( (top+curTn.height) >= (vp.t-vp.h) && top <= (vp.t+vp.h*2) ) ) ) {\n // thumbnail positioned in enlarged viewport (viewport + 2 x viewport height)\n if( curTn.displayed ) {\n // thumbnail is displayed\n if( item.top != curTn.top || item.left != curTn.left ) {\n // set position\n if( G.O.galleryResizeAnimation == true ) {\n // with transition\n var tweenable = new NGTweenable();\n tweenable.tween({\n from: { top: item.top, left: item.left, height: item.height, width: item.width },\n to: { top: newTop, left: curTn.left, height: curTn.height, width: curTn.width },\n attachment: { $e: item.$elt },\n duration: 300,\n delay: cnt * G.tn.opt.Get('displayInterval'),\n easing: 'easeOutQuart',\n step: function (state, att) {\n att.$e.css(state);\n },\n finish: function (state, att) {\n att.$e.css(state);\n this.dispose();\n }\n });\n }\n else {\n // set position without transition\n // item.$elt.css({ top: curTn.top , left: curTn.left });\n item.$elt.css({ top: newTop , left: curTn.left });\n }\n }\n }\n else {\n // re-display thumbnail\n curTn.displayed=true;\n // item.$elt.css({ display: 'block', top: curTn.top , left: curTn.left, opacity:1 });\n item.$elt.css({ display: 'block', top: newTop, left: curTn.left, opacity: 1 });\n ThumbnailAppearFinish(item);\n }\n }\n else {\n // undisplay thumbnail if not in viewport+margin --> performance gain\n curTn.displayed=false;\n item.$elt.css({ display: 'none'});\n }\n }\n item.left=curTn.left;\n item.top=newTop;\n \n // set new size if changed\n if( item.width != curTn.width || item.height != curTn.height ) {\n item.$elt.css({ width: curTn.width , height: curTn.height });\n item.width=curTn.width;\n item.height=curTn.height;\n \n // if( curTn.resizedContentWidth > 0 ) {\n // resize also the content (=image)\n if( item.resizedContentWidth != curTn.resizedContentWidth || item.resizedContentHeight != curTn.resizedContentHeight ) {\n if( item.kind == 'albumUp' ) {\n // item.$getElt('.nGY2GThumbnailAlbumUp').css({'height': curTn.resizedContentHeight, 'width': curTn.resizedContentWidth});\n }\n else {\n item.$getElt('.nGY2GThumbnailImg').css({'height': curTn.resizedContentHeight, 'width': curTn.resizedContentWidth});\n item.$getElt('.nGY2GThumbnailImage').css({'height': curTn.resizedContentHeight, 'width': curTn.resizedContentWidth});\n }\n item.resizedContentWidth=curTn.resizedContentWidth;\n item.resizedContentHeight=curTn.resizedContentHeight;\n }\n }\n \n \n // add counter of remaining (not displayed) images \n if( G.GOM.lastDisplayedIdxNew == GOMidx && G.layout.support.rows ) {\n if( (G.galleryDisplayMode.Get() == 'ROWS' && G.galleryMaxRows.Get() > 0) || (G.galleryDisplayMode.Get() == 'FULLCONTENT' && G.galleryLastRowFull.Get() && G.GOM.lastFullRow != -1) ){\n // number of items\n var nb=G.GOM.items.length - GOMidx -1;\n if( item.albumID != '0' && G.O.thumbnailLevelUp ) {\n nb--;\n }\n }\n if( G.O.thumbnailOpenImage && nb > 0 ) {\n item.$getElt('.nGY2GThumbnailIconsFullThumbnail').html('+'+nb);\n }\n G.GOM.lastDisplayedIdx=GOMidx;\n }\n\n }",
"function setUpThumbs() {\n\tvar $galleryThumbs = $('#thumbs .thumb').draggable();\n\t$thumbsPackery.packery('unbindUIDraggableEvents', $galleryThumbs);\n\t$thumbsPackery.packery('bindUIDraggableEvents', $galleryThumbs);\n\tvar $unusedThumbs = $('#unusedThumbs .thumb').draggable();\n\t$unusedPackery.packery('unbindUIDraggableEvents', $unusedThumbs);\n\t$unusedPackery.packery('bindUIDraggableEvents', $unusedThumbs);\n\taddToggleListeners();\n\tupdatePositions();\n}",
"requestThumbnails() {\n let position = this.state.position;\n let ed = this.state.ed;\n let ts = position == 'start' ? ed.start : ed.end;\n\n this.props.socket.emit('frameSelect',{ ts: ts } );\n }",
"setImages(selectedImageIndex) {\n\n // \"quantize\" the input - if the provided index is out of bounds, bound it\n selectedImageIndex = Math.min( Math.max(selectedImageIndex, 0), this.props.stylePhotos.length - 1);\n\n // determine the first visible image in the gallery\n let firstVisibleImage = this.state.topImageIndex;\n let lastVisibleImage = firstVisibleImage + this.thumbnailsToShow - 1;\n if (selectedImageIndex < firstVisibleImage) { firstVisibleImage = selectedImageIndex; }\n if (selectedImageIndex > lastVisibleImage) { firstVisibleImage = selectedImageIndex - this.thumbnailsToShow + 1; }\n\n // get the main image url and set state\n let mainImage = this.props.stylePhotos[selectedImageIndex].url;\n this.setState({\n selectedImageIndex: selectedImageIndex,\n topImageIndex: firstVisibleImage,\n mainImageUrl: mainImage,\n isLoaded: true\n });\n }",
"function set(row, col, state)\r\n{\r\n\tif (state)\r\n\t\timgFor(row, col).src = imgOn;\r\n\telse\r\n\t\timgFor(row, col).src = imgOff;\r\n}",
"function EPE_ChangeState(newState)\n{\n with (EPE)\n {\n if (!newState) newState = state;\n\n if (newState != 30 && newState != 31) EPE_RemoveSelector();\n\n\n if (state != newState)\n {\n if (state == 93) pad.removeEventListener('mousewheel', EPE_ScaleWithWheel, false);\n if (state == 94) pad.removeEventListener('mousewheel', EPE_RotateWithWheel, false);\n\n\n lastState = state;\n state = newState;\n EPE_ShowStatus(state);\n }\n\n //buttons on editor panel\n //SetClass(bpen, \"pressed\", state == 10 || state == 11);\n //SetClass(beraser, \"pressed\", state == 20 || state == 21);\n //SetClass(bselect, \"pressed\", state == 30 || state == 31);\n //SetClass(bresize, \"pressed\", state == 93);\n //SetClass(brotate, \"pressed\", state == 94);\n //SetClass(bpickcolor, \"pressed\", state == 95);\n\n EPE_ButtonOn(bpen, state == 10 || state == 11);\n EPE_ButtonOn(beraser, state == 20 || state == 21);\n EPE_ButtonOn(bselect, state == 30 || state == 31);\n EPE_ButtonOn(bresize, state == 93);\n EPE_ButtonOn(brotate, state == 94);\n EPE_ButtonOn(bpickcolor, state == 95);\n\n bclear.title = (state == 30 || state == 31) ? \"Clear the selected area\" : \"Clear the entire image\";\n bsave.title = (state == 30 || state == 31) ? \"Save the selected area image to the album\" : \"Save the entire image to the album\";\n\n //editor panel\n editor.style.display = state != 40 ? \"\" : \"none\";\n\n //processor panel\n processor.style.display = state == 40 ? \"\" : \"none\";\n\n //the popup elements\n if (colorTable != null) colorTable.style.display = state == 91 ? \"\" : \"none\";\n if (sizeTable != null) sizeTable.style.display = state == 92 ? \"\" : \"none\";\n\n //change the cursor according to the state.\n switch (state)\n {\n case 10:\n case 11:\n //The color cursor is not applicable to Firefox?\n if (BrowserInfo().browser == \"Firefox\") canvas.style.cursor = \"url('cursor/penff.cur'),pointer\";\n else canvas.style.cursor = \"url('cursor/pen.cur'),pointer\";\n break;\n\n case 20:\n case 21:\n canvas.style.cursor = \"url('cursor/eraser.cur'),pointer\";\n break;\n\n case 95:\n canvas.style.cursor = \"url('cursor/pickcolor.cur'),pointer\";\n break;\n\n case 93:\n canvas.style.cursor = \"url('cursor/resize.cur'),pointer\";\n break;\n\n default:\n canvas.style.cursor = \"pointer\";\n break;\n }\n }\n EPE_SetDrawing();\n}",
"function setFrameItems() {\r\n imagesDict[curFrameId]._wall = toDataURL(image.src)\r\n imagesDict[curFrameId]._mask = toDataURL(mask.src)\r\n imagesDict[curFrameId]._sticker = toDataURL(sticker.src)\r\n}",
"setSymbolArt(state, sa) {\n state.parts = sa.parts\n state.lastId = sa.lastId\n state.selected = {}\n state.requestUpdateColorLayers = {}\n state.requestUpdateVertLayers = {}\n state.equestUpdateTypeLayers = {}\n //start history from a fresh state\n state.undoStack = []\n state.redoStack = []\n }",
"handleReset() {\n this.setState({\n rubiksArray: cubeUtilities.cleanCubeFaceState()\n }, () => {\n this.handleResetPosition();\n this.handleRenderCubeColorPositions();\n });\n }",
"function updateThumbs() {\n\tvar list = document.getElementsByClassName(\"thumb-image\");\n\t\n\tvar sources = ARR_SOURCES[0];\n\tfor (var i = 1; i < ARR_SOURCES.length; i++) {\n\t\tsources += \":\"+ARR_SOURCES[i];\n\t}\n\t\n\tfor(var i = 0; i < ARR_GRAPH_VARS.length; i++) {\n\t\tlist[i].src = \"php/async/graphCreate.php?var=\"+ARR_GRAPH_VARS[i]+\"&mode=thumb&profile=\"+PROFILE+\"&sources=\"+sources+\"&time=\"+timestampBgn+\":\"+timestampEnd;\n\t}\n}",
"visible_thumbs_changed()\n {\n // visible_illusts isn't in any particular order, but should always be contiguous.\n // Start at the first thumb in the list, and walk backwards through thumbs until\n // we reach one that isn't in the list. The thumbnail display can get very long,\n // but visible_illusts is only the ones on screen.\n // Find the earliest thumb in the list.\n if(this.visible_illusts.length == 0)\n return;\n\n let first_thumb = this.visible_illusts[0];\n while(first_thumb != null)\n {\n let prev_thumb = first_thumb.previousElementSibling;\n if(prev_thumb == null)\n break;\n\n if(this.visible_illusts.indexOf(prev_thumb) == -1)\n break;\n\n first_thumb = prev_thumb;\n }\n\n // If the data source supports a start page, update the page number in the URL to reflect\n // the first visible thumb.\n if(this.data_source == null || !this.data_source.supports_start_page || first_thumb.dataset.page == null)\n return;\n\n main_controller.singleton.temporarily_ignore_onpopstate = true;\n try {\n let args = helpers.get_args(document.location);\n this.data_source.set_start_page(args, first_thumb.dataset.page);\n helpers.set_args(args, false, \"viewing-page\");\n } finally {\n main_controller.singleton.temporarily_ignore_onpopstate = false;\n }\n }",
"thumbs_loaded(e)\n {\n this.set_visible_thumbs();\n }",
"static reset(thumbnailContainer) {\n if (!thumbnailContainer) return;\n let thumbs;\n if (thumbnailContainer && thumbnailContainer._children) {\n thumbs = thumbnailContainer._children;\n } else {\n thumbs = thumbnailContainer;\n }\n for (let i = 0; i < thumbs.length; i++) {\n const ch = thumbs[i];\n if (!ch.active) {\n continue;\n }\n ch.active = false;\n Thumbnail.thumbAnimation(ch.element, {position: {z: 0, x: 0}}, 'elementHide', 100);\n }\n\n }",
"resetForNextDest() {\n this.setHintIndex(0);\n this.setPhotoIndex(0);\n this.setReviewIndex(0);\n this.setPhotos([]);\n this.setReviews([]);\n this.setPlaceID(-1);\n }",
"function fetchImageDataAndUpdateState() {\n\n const titleList = images.reduce((newList, img) => [...newList, img.title], []);\n\n hydrateDetailPageImages(titleList, currDetailPage).then(function(detailPage) {\n\n // Update wiki page from our in memory list\n wikiPages[pageID] = detailPage;\n\n // Dispatch our pages list update and set data for the current detail view\n dispatchUpdates(wikiPages, wikiPages[pageID]);\n\n }).catch((e) => {\n console.error('Failed to hydrate image info on details page', e);\n dispatchUpdates(wikiPages, wikiPages[pageID]);\n });\n }",
"function setPiece() {\n var x = $currPiece.data('x');\n var y = $currPiece.data('y');\n var $piece = pieces[$currPiece.data('type')][$currPiece.data('state')];\n var locs = $piece.data('boxes');\n var i, j;\n for (i = 0; i < locs.length; i++) {\n addBox($piece.data('color'), x + locs[i].x, y + locs[i].y);\n }\n $currPiece.remove();\n $currPiece = null;\n for (i = 1; i < grid.length - 1; i++) {\n var remove = true;\n for (j = 1; j < grid[i].length - 1; j++) {\n if (grid[i][j] !== 1) {\n remove = false;\n break;\n }\n }\n if (remove) {\n $('[data-row=\"'+rowName(i)+'\"]').each(removeBox);\n $('[data-row^=\"'+rowName(i-1)+'\"]').each(shiftBox);\n for (j = i; j > 1; j--) {\n grid[j] = grid[j-1];\n }\n grid[1] = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1];\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
call service from a remote node | _call_remote_service(remote, name, fun, args, cb) {
this._find_remote(remote, (err, rn) => {
if (err) return cb(err);
rn.call(name, fun, args, (err, ret) => {
if (err) return cb(err);
return cb(null, ret);
});
});
} | [
"_call_local_service(name, fun, args, cb) {\n if (name in this.services) {\n const rq = {\n type: 'call',\n fun: fun,\n args: args,\n };\n\n return this._req(this.service_socks[name], rq, (rsp) => {\n if (rsp.status != 'ok') return cb(rsp.status);\n return cb(null, rsp.ret);\n });\n }\n return cb('err: no service');\n }",
"function service(){\n\tchef.apply(null,arguments);\n}",
"function run_upstream_service(){\n\n var options = {\n \"success\": \"us_success\",\n \"error\": \"us_error\",\n \"timeout\": 60 * 1000,\n \"geomFormat\": \"GEOJSON\"\n };\n\n var data = {\n \"pNavigationType\": value_selected,\n \"pStartComid\": comid,\n \"pStartMeasure\": fmeasure,\n \"pTraversalSummary\" : \"TRUE\",\n \"pFlowlinelist\" : \"TRUE\",\n \"pStopDistancekm\": 1000,\n \"optNHDPlusDataset\": \"2.1\"\n };\n\n waiting_output();\n rtnStr = WATERS.Services.UpstreamDownstreamService(data, options);\n //this will start the service. If it succeeds, it will call us_success.\n}",
"_get_remote_service(remote, name, cb) {\n this._find_remote(remote, (err, rn) => {\n if (err) return cb(err);\n return rn.request_service(name, (err, d) => {\n if (err) return cb(err);\n return cb(null, d);\n });\n });\n }",
"function serviceCall(serviceName, method, reqParams, callback) {\n\t\tvar serviceResponse = {};\n\t\tvar serviceUrl = 'http://172.25.156.43:8080/eHundi/';\n\t\t/*\n\t\t$http({\n\t\t\t\turl : serviceUrl + serviceName,\n\t\t\t\tdataType : 'json',\n\t\t\t\tmethod : method,\n\t\t\t\tdata : reqParams||'',\n\t\t\t\theaders : {\n\t\t\t\t\"Content-Type\" : \"application/json\"\n\t\t\t\t}\n\t\t\t\t}).then(function(serverResponse, status, headers, config) {\n\t\t\t\t\t//success\n\t\t\t\t\tcallback(serverResponse);\n\t\t\t\t}, function(serverResponseErr, status, headers, config) {\n\t\t\t\t\t//error occured\n\t\t\t\t\t//alert(\"Error occured while connecting to server. Please try again.\");\n\t\t\t\t\tconsole.log(\"Error occured while connecting to server. Please try again.\");\n\t\t\t\t});*/\n\t\t\n\t\tvar serviceUrl = serviceName.split(\"/\")[1];\n\t\t$.getJSON(\"content/mockData/\"+serviceUrl+\".json\").then(function(successData) {\n\t\t\tcallback(successData);\n\t\t}, function(errData) {\n\t\t\talert(\"error occured\");\n\t\t});\n\t}",
"relayService(service, srvType, timeout = 2000) {\n logger.debug(`relayService ${service} ${srvType} ${timeout}`);\n\n delete Meteor.server.method_handlers[service];\n\n let definition = {};\n\n definition[service] = Meteor.wrapAsync((reqData, callback) => {\n logger.debug(`relaying ${service} ${reqData}`);\n\n service = service.replace(/^\\//, ''); // trim initial '/' if any\n const serviceClient = this._nh.serviceClient('/'+service, srvType);\n\n // get service type class\n const Service = rosnodejs.checkService(srvType);\n const ServiceRequest = Service['Request'];\n const available = Promise.await(\n this._nh.waitForService(serviceClient.getService(), timeout)\n );\n if (available) {\n const request = new ServiceRequest(reqData);\n\n logger.debug(`calling ${service} with ${request} ${request.__proto__}`);\n serviceClient.call(request).then((resp) => {\n callback(null, resp);\n }).catch((err) => {\n callback(err);\n });\n } else {\n callback(new Meteor.Error(\n 'timed-out',\n `The request to the service (${service}) timed out.`\n ));\n }\n });\n\n Meteor.methods(definition);\n }",
"invoke(name, args) {\n var eh;\n if (this.log_level > 1) {\n this.log(\"invoke(): \", {name, args});\n }\n eh = (err) => {\n var msg;\n msg = \"\\nWS_RMI_Stub:\";\n msg += {\n id: this.id,\n method: name,\n args: args\n }.toString();\n return new Error(msg);\n };\n return this.connection.send_request(this.id, name, args).catch(eh);\n }",
"function runServiceCall(client, metadata, options, method, payload) {\r\n return new Promise((resolve, reject) => {\r\n client[method](payload, metadata, options, (err, res) => {\r\n if (err) {\r\n reject(errors_1.castGrpcError(err));\r\n }\r\n else {\r\n resolve(res);\r\n }\r\n });\r\n });\r\n}",
"function sendRequest(methodName, args, done, fail) {\n // Generate a random ID for this remote invocation\n var sid = Math.floor(Math.random() * 1000000000).toString(16);\n // Register any callbacks with the nexus so they can be invoked when a response is received\n nexus.add(sid, done, fail);\n // Send a request to the remote, where:\n // - n is the name of the remote function\n // - a is an array of the (hopefully) serializable, non-callback arguments to this method\n send(sid, \"request\", {n: methodName, a: args});\n }",
"function call(method, ...args) {\n\treturn new Promise((resolve, reject) => {\n\t\tconst endpoint = RPC_ENDPOINT + method;\n\t\tdlvConnection.call(endpoint, args, (err, result) => {\n\t\t\tif (err) {\n\t\t\t\taddOutputMessage(\"delve\", `Failed to call ${method}\\n\\terror: ${err}`);\n\t\t\t\treject(err);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tresolve(result);\n\t\t});\n\t});\n}",
"function invoke_discovery() {\n n_sd++;\n\n channel.initialize({\n discover: serviceDiscovery,\n asLocalhost: localHost\n })\n .then((success) => {\n isExecDone(transType);\n if (IDone != 1) {\n invoke_discovery();\n } else {\n tCurr = new Date().getTime();\n logger.info('[Nid:chan:org:id=%d:%s:%s:%d invoke_discovery] pte-exec:completed sent %d transactions (%s) in %d ms, timestamp: start %d end %d,Throughput=%d TPS', Nid, channelName, org, pid, n_sd, transType, tCurr - tLocal, tLocal, tCurr, (n_sd / (tCurr - tLocal) * 1000).toFixed(2));\n evtDisconnect();\n }\n }).catch(err => {\n logger.error('[Nid:chan:org:id=%d:%s:%s:%d invoke_discovery] Failed to send service discovery due to error: ', Nid, channelName, org, pid, err.stack ? err.stack : err)\n process.exit(1)\n });\n}",
"function call_cmd_service_custom(the_cmd){\n init_ros_service_if_url_changed()\n add_cmd_to_user_menu(the_cmd) //doesn't work because jqxmenu broken by design.\n rde.shell(the_cmd)\n}",
"function runServiceCall(client, metadata, options, method, payload) {\n return new Promise((resolve, reject) => {\n client[method](payload, metadata, options || {}, (err, res) => {\n if (err) {\n reject(errors_1.castGrpcError(err));\n }\n else {\n resolve(res);\n }\n });\n });\n}",
"run(sender, fn, args) {\n var argsAsString = RpcHandler.readArgsToString(args);\n var argsPrefix = \"\";\n if (argsAsString) {\n argsPrefix = \", \";\n }\n\n var call = \"interspace.__internal.registeredFunctions.server\" +\n `[\"${fn}\"].fn.call(` +\n `{sender: interspace.clients.byId(\"${sender.uuid}\")}` +\n `${argsPrefix}${argsAsString})`;\n try {\n this._vm.run(call);\n } catch (e) {\n console.error(`ERROR invoking RPC call ${fn}(${argsAsString}):`);\n console.error(e.stack);\n }\n }",
"get remotelyCallable() { return [\"clientRequestForServer\"] }",
"function RemoteCallManager() {}",
"function poolRpc (host, port, path, callback) {\n\tjsonHttpRequest(host, port, '', callback, path);\n}",
"function callRPC(method, params) {\n fakeWindow.emitter.emit('message', {\n data: {\n jsonrpc: '2.0',\n method,\n id: 42,\n params,\n },\n origin: 'https://allowed1.com',\n source: frame,\n });\n }",
"VrackDedicatedConnect(serviceName) {\n let url = `/vrack/${serviceName}/dedicatedConnect`;\n return this.client.request('GET', url);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create a color picker palette for each of the spotlights | function populateColorPickers() {
for (var i = 1; i < 10; i++) {
$( "#spotlight" + i).append("<i id='palette" + i +
"' class='material-icons palette' onClick='openSpotlightControl(" + i + ")'>palette</i>");
$( "#spotlight" + i).append("<span> Spotlight " + i + " <span id='intensity" +
i + "'></span>");
updateIntensityLabel(i);
}
} | [
"function init_colors() {\n\t$('.colorpicker').each(function () {\n\t\tvar id = $(this).attr('id');\n\t\t$(this).spectrum('set', urlObj[id]);\n\t});\n}",
"function createPalette() {\n for (let i = 0; i < colors.length; i++) {\n let color = document.createElement('div')\n palette.appendChild(color).classList.add('color-picker', colors[i])\n }\n theCanvas.style.backgroundColor = selectedColor\n}",
"function setupColorPicker() {\n\t\n\t var colors = ['rgb(255, 128, 0)', 'hsv 100 70 50', 'yellow', 'blanchedalmond', 'red', 'green', 'blue', 'violet'];\n\t\n\t // Setup colorPickers.\n\t $('.js-anno-palette').spectrum({\n\t showPaletteOnly: true,\n\t showPalette: true,\n\t hideAfterPaletteSelect: true,\n\t palette: [colors.slice(0, Math.floor(colors.length / 2)), colors.slice(Math.floor(colors.length / 2), colors.length)]\n\t });\n\t // Set initial color.\n\t $('.js-anno-palette').each(function (i, elm) {\n\t $(elm).spectrum('set', colors[i % colors.length]);\n\t });\n\t\n\t // Setup behavior.\n\t $('.js-anno-palette').off('change').on('change', window.annoPage.displayAnnotation.bind(null, false));\n\t}",
"function setupColorPicker () {\n\t\n\t const colors = [\n\t 'rgb(255, 128, 0)', 'hsv 100 70 50', 'yellow', 'blanchedalmond',\n\t 'red', 'green', 'blue', 'violet'\n\t ]\n\t\n\t // Setup colorPickers.\n\t $('.js-anno-palette').spectrum({\n\t showPaletteOnly : true,\n\t showPalette : true,\n\t hideAfterPaletteSelect : true,\n\t palette : [\n\t colors.slice(0, Math.floor(colors.length / 2)),\n\t colors.slice(Math.floor(colors.length / 2), colors.length)\n\t ]\n\t })\n\t // Set initial color.\n\t $('.js-anno-palette').each((i, elm) => {\n\t $(elm).spectrum('set', colors[ i % colors.length ])\n\t })\n\t\n\t // Setup behavior.\n\t $('.js-anno-palette').off('change').on('change', _displayCurrentReferenceAnnotations)\n\t}",
"function setTilesColorSchemes() {\r\n var arr = [];\r\n arr.push({\"name\" : \"lightblue-white\" , \"backgroundColor\" : \"rgb(23, 137, 230)\" , \"color\" : \"rgba(255, 255, 255, 0.95)\"});\r\n arr.push({\"name\" : \"blue-white\" , \"backgroundColor\" : \"rgb(71, 132, 230)\" , \"color\" : \"rgba(255, 255, 255, 0.95)\"});\r\n arr.push({\"name\" : \"darkblue-white\" , \"backgroundColor\" : \"rgb(58, 111, 180)\" , \"color\" : \"rgba(255, 255, 255, 0.95)\"});\r\n arr.push({\"name\" : \"deepblue-white\" , \"backgroundColor\" : \"rgb(57, 68, 143)\" , \"color\" : \"rgba(255, 255, 255, 0.95)\"});\r\n arr.push({\"name\" : \"tinyblue-white\" , \"backgroundColor\" : \"rgb(58, 74, 180)\" , \"color\" : \"rgba(255, 255, 255, 0.95)\"});\r\n arr.push({\"name\" : \"lightaqua-white\" , \"backgroundColor\" : \"rgb(92, 177, 230)\" , \"color\" : \"rgba(255, 255, 255, 0.95)\"});\r\n arr.push({\"name\" : \"aqua-white\" , \"backgroundColor\" : \"rgb(58, 180, 135)\" , \"color\" : \"rgba(255, 255, 255, 0.95)\"});\r\n arr.push({\"name\" : \"darkaqua-white\" , \"backgroundColor\" : \"rgb(71, 166, 199)\" , \"color\" : \"rgba(255, 255, 255, 0.95)\"});\r\n arr.push({\"name\" : \"lightyellow-white\" , \"backgroundColor\" : \"rgb(240, 201, 44)\" , \"color\" : \"rgba(255, 255, 255, 0.95)\"});\r\n arr.push({\"name\" : \"yellow-white\" , \"backgroundColor\" : \"rgb(245, 163, 0)\" , \"color\" : \"rgba(255, 255, 255, 0.95)\"});\r\n arr.push({\"name\" : \"orange-white\" , \"backgroundColor\" : \"rgb(245, 131, 0)\" , \"color\" : \"rgba(255, 255, 255, 0.95)\"});\r\n arr.push({\"name\" : \"white-lightblue\" , \"backgroundColor\" : \"rgb(255, 255, 255)\" , \"color\" : \"rgb(45, 132, 164)\"});\r\n arr.push({\"name\" : \"white-blue\" , \"backgroundColor\" : \"rgb(255, 255, 255)\" , \"color\" : \"rgb(59, 75, 181)\"});\r\n arr.push({\"name\" : \"white-darkblue\" , \"backgroundColor\" : \"rgb(255, 255, 255)\" , \"color\" : \"rgb(32, 84, 151)\"});\r\n arr.push({\"name\" : \"white-tinyblue\" , \"backgroundColor\" : \"rgb(255, 255, 255)\" , \"color\" : \"rgb(65, 113, 164)\"});\r\n arr.push({\"name\" : \"white-aqua\" , \"backgroundColor\" : \"rgb(255, 255, 255)\" , \"color\" : \"rgb(72, 167, 199)\"});\r\n arr.push({\"name\" : \"white-green\" , \"backgroundColor\" : \"rgb(255, 255, 255)\" , \"color\" : \"rgb(85, 147, 31)\"});\r\n arr.push({\"name\" : \"white-lightred\" , \"backgroundColor\" : \"rgb(255, 255, 255)\" , \"color\" : \"rgb(179, 35, 35)\"});\r\n arr.push({\"name\" : \"white-red\" , \"backgroundColor\" : \"rgb(255, 255, 255)\" , \"color\" : \"rgb(209, 0, 0)\"});\r\n arr.push({\"name\" : \"white-darkred\" , \"backgroundColor\" : \"rgb(255, 255, 255)\" , \"color\" : \"rgb(164, 50, 65)\"});\r\n arr.push({\"name\" : \"white-gray\" , \"backgroundColor\" : \"rgb(255, 255, 255)\" , \"color\" : \"rgb(185, 113, 49)\"});\r\n arr.push({\"name\" : \"white-yellow\" , \"backgroundColor\" : \"rgb(255, 255, 255)\" , \"color\" : \"rgb(240, 201, 45)\"});\r\n arr.push({\"name\" : \"white-pink\" , \"backgroundColor\" : \"rgb(255, 255, 255)\" , \"color\" : \"rgb(104, 48, 136)\"});\r\n arr.push({\"name\" : \"lightgray-white\" , \"backgroundColor\" : \"rgb(218, 126, 44)\" , \"color\" : \"rgba(255, 255, 255, 0.95)\"});\r\n arr.push({\"name\" : \"gray-white\" , \"backgroundColor\" : \"rgb(187, 114, 49)\" , \"color\" : \"rgba(255, 255, 255, 0.95)\"});\r\n arr.push({\"name\" : \"darkgray-white\" , \"backgroundColor\" : \"rgb(224, 107, 0)\" , \"color\" : \"rgba(255, 255, 255, 0.95)\"});\r\n arr.push({\"name\" : \"lime-white\" , \"backgroundColor\" : \"rgb(115, 180, 58)\" , \"color\" : \"rgba(255, 255, 255, 0.95)\"});\r\n arr.push({\"name\" : \"darklime-white\" , \"backgroundColor\" : \"rgb(85, 147, 31)\" , \"color\" : \"rgba(255, 255, 255, 0.95)\"});\r\n arr.push({\"name\" : \"lightgreen-white\" , \"backgroundColor\" : \"rgb(79, 196, 118)\" , \"color\" : \"rgba(255, 255, 255, 0.95)\"});\r\n arr.push({\"name\" : \"darkgreen-white\" , \"backgroundColor\" : \"rgb(58, 180, 58)\" , \"color\" : \"rgba(255, 255, 255, 0.95)\"});\r\n arr.push({\"name\" : \"tinygreen-white\" , \"backgroundColor\" : \"rgb(58, 176, 180)\" , \"color\" : \"rgba(255, 255, 255, 0.95)\"});\r\n arr.push({\"name\" : \"ligthred-white\" , \"backgroundColor\" : \"rgb(229, 76, 41)\" , \"color\" : \"rgba(255, 255, 255, 0.95)\"});\r\n arr.push({\"name\" : \"red-white\" , \"backgroundColor\" : \"rgb(217, 26, 20)\" , \"color\" : \"rgba(255, 255, 255, 0.95)\"});\r\n arr.push({\"name\" : \"darkred-white\" , \"backgroundColor\" : \"rgb(164, 51, 67)\" , \"color\" : \"rgba(255, 255, 255, 0.95)\"});\r\n arr.push({\"name\" : \"ligthpink-white\" , \"backgroundColor\" : \"rgb(200, 70, 201)\" , \"color\" : \"rgba(255, 255, 255, 0.95)\"});\r\n arr.push({\"name\" : \"pink-white\" , \"backgroundColor\" : \"rgb(134, 58, 180)\" , \"color\" : \"rgba(255, 255, 255, 0.95)\"});\r\n arr.push({\"name\" : \"tinypink-white\" , \"backgroundColor\" : \"rgb(104, 48, 137)\" , \"color\" : \"rgba(255, 255, 255, 0.95)\"});\r\n return arr;\r\n }",
"function initiate_color_picker(){\n\t$(\".colorpicker\").spectrum({\n\t showInput: true,\n\t className: \"colorClass\",\n\t showInitial: true,\n\t showPalette: true,\n\t showAlpha: false,\n\t showSelectionPalette: true,\n\t hideAfterPaletteSelect:true,\n\t clickoutFiresChange: false,\n\t maxPaletteSize: 10,\n\t preferredFormat: \"hex\",\n\t localStorageKey: \"colorpicker.local\",\n\t move: function () { },\n\t show: function () {},\n\t beforeShow: function () {},\n\t hide: function (color) {\n\t \tkey = $(this).attr('id');\n\t \tstr = color.toHexString().replace('#','');\n\t \turlObj[key] = str;\n\t \tupdate_Widget();\n\t },\n\t change: function(color) {\n\t \tkey = $(this).attr('id');\n\t \tstr = color.toHexString().replace('#','');\n\t \turlObj[key] = str;\n\t \tupdate_Widget();\n\t \t$(\".color_temp_radio\").attr(\"checked\", false);\n\t \t$(\".color_temp_radio\").button(\"refresh\");\n\t },\n\t /**\n\t * Creates the palette. Each set of [] is one row in the palette.\n\t */\n\t palette: [\n\t \t/*[\"#7b7670\", \"#42ad9e\", \"#FFFFFF\", \"#000000\", \"#ed7c31\"],\n\t \t[\"#000000\", \"#FFFFFF\",\"#0000FF\",\"#FF0000\",\"#00FF00\"],\n\t \t[\"#E6E2AF\", \"#A7A37E\", \"#EFECCA\", \"#046380\", \"#002F2F\"],\n\t \t[\"#FCFFF5\", \"#D1DBBD\", \"#91AA9D\", \"#3E606F\", \"#193441\"],\n\t \t[\"#105B63\", \"#FFFAD5\", \"#FFD34E\", \"#DB9E36\", \"#BD4932\"],*/\n\n\t \t//The default color picker palette\n\t [\"#000000\", \"#0000ff\", \"#FF0FFF\", \"#cccccc\", \"#dadada\",\"#fff\"],\n\t [\"#980000\", \"#f00\", \"#00F\", \"#0F0\", \"#FF0000\",\n\t \"#FFFFF0\", \"rgb(74, 134, 232)\", \"rgb(0, 172, 255)\", \"rgb(153, 0, 255)\", \"rgb(255, 0, 255)\"], \n\t [\"rgb(230, 184, 175)\", \"rgb(244, 204, 204)\", \"rgb(252, 229, 205)\", \"rgb(255, 242, 204)\", \"rgb(217, 234, 211)\", \n\t \"rgb(208, 224, 227)\", \"rgb(201, 218, 248)\", \"rgb(207, 226, 243)\", \"rgb(217, 210, 233)\", \"rgb(234, 209, 220)\", \n\t \"rgb(221, 126, 107)\", \"rgb(234, 153, 153)\", \"rgb(249, 203, 156)\", \"rgb(255, 229, 153)\", \"rgb(182, 215, 168)\", \n\t \"rgb(162, 196, 201)\", \"rgb(164, 194, 244)\", \"rgb(159, 197, 232)\", \"rgb(180, 167, 214)\", \"rgb(213, 166, 189)\", \n\t \"rgb(204, 65, 37)\", \"rgb(224, 102, 102)\", \"rgb(246, 178, 107)\", \"rgb(255, 217, 102)\", \"rgb(147, 196, 125)\", \n\t \"rgb(118, 165, 175)\", \"rgb(109, 158, 235)\", \"rgb(111, 168, 220)\", \"rgb(142, 124, 195)\", \"rgb(194, 123, 160)\",\n\t \"rgb(166, 28, 0)\", \"rgb(204, 0, 0)\", \"rgb(230, 145, 56)\", \"rgb(241, 194, 50)\", \"rgb(106, 168, 79)\",\n\t \"rgb(69, 129, 142)\", \"rgb(60, 120, 216)\", \"rgb(61, 133, 198)\", \"rgb(103, 78, 167)\", \"rgb(166, 77, 121)\",\n\t \"rgb(91, 15, 0)\", \"rgb(102, 0, 0)\", \"rgb(120, 63, 4)\", \"rgb(127, 96, 0)\", \"rgb(39, 78, 19)\", \n\t \"rgb(12, 52, 61)\", \"rgb(28, 69, 135)\", \"rgb(7, 55, 99)\", \"rgb(32, 18, 77)\", \"rgb(76, 17, 48)\"],\n\t ]\n\t});\t\n}",
"function buildColorPicker() {\n var $picker = $('<div>').attr('id', 'picker');\n _.each(paper.pancakeShades, function(color, index) {\n $picker.append(\n $('<a>')\n .addClass('color' + index + (index === 0 ? ' active' : ''))\n .attr('href', '#')\n .attr('title', paper.pancakeShadeNames[index])\n .click(function(e){selectColor(index); e.preventDefault();})\n .css('background-color', color)\n );\n });\n\n var $color = $('<div>')\n .attr('id', 'color')\n .append($picker);\n\n $('#tools #tool-fill').after($color);\n}",
"function setupColorPicker() {\n //Grab pickerarea div\n let palette = document.querySelector(\".pickerarea\");\n\n //Loop to create divs for each color in COLORS\n for (let i = 0; i < NUM_COLORS; i++) {\n\n //Create div\n let cell = document.createElement(\"div\");\n cell.className = \"pickerdiv\";\n\n //Set div background color to color in COLORS\n cell.style.backgroundColor = COLORS[i];\n\n //Event listner for when a color is clicked.\n cell.addEventListener(\"click\", function() {\n //When the color is clicked, set the global currentColor variable to the same color as the div's background color\n currentColor = cell.style.backgroundColor;\n\n //Also change the background color for the div designated to show the current color\n document.querySelector(\".selecteddiv\").style.backgroundColor = currentColor;\n });\n\n //Append each color div to the pickerarea\n palette.appendChild(cell);\n }\n}",
"function createColorPalette() {\n for (let i = 0; i < paletteColors.length; i++) {\n let colorHex = paletteColors[i];\n\n createColorCircleAndAppend(colorHex);\n }\n}",
"function initSliderColors(){\n sliderFill(red);\n sliderFill(green);\n sliderFill(blue);\n}",
"function createColorPalette(colors){\n\n\t\t// create a swatch for each color\n\t\tfor (var i = colors.length - 1; i >= 0; i--) {\n\t\t\tvar $swatch = $(\"<div>\").css(\"background-color\", colors[i])\n\t\t\t\t\t\t\t\t.addClass(\"swatch\");\n\t\t\t$swatch.click(function(){\n\t\t\t\t// add color to the color palette history\n\t\t\t\tcp.history.push($(this).css(\"background-color\"));\n\t\t\t\t// $(this).css(\"border\",\"10px solid black\");\n\n\t\t\t});\n\t\t\tcp.$container.append($swatch);\n\t\t}\n\t}",
"initColorPicker() {\n let control = this,\n colorPicker = control.container.find('.color-picker-hex'),\n options = {},\n fieldId = colorPicker.data('field');\n\n // We check if the color palette parameter is defined.\n if (!_.isUndefined(fieldId) && !_.isUndefined(control.params.fields[fieldId]) && !_.isUndefined(control.params.fields[fieldId].palettes) && _.isObject(control.params.fields[fieldId].palettes)) {\n options.palettes = control.params.fields[fieldId].palettes;\n }\n\n // When the color picker value is changed we update the value of the field\n options.change = function (event, ui) {\n let currentPicker = jQuery(event.target),\n row = currentPicker.closest('.repeater-row'),\n rowIndex = row.data('row'),\n currentSettings = control.getValue();\n\n currentSettings[rowIndex][currentPicker.data('field')] = ui.color.toString();\n control.setValue(currentSettings, true);\n };\n\n // Init the color picker\n if (colorPicker.length !== 0) {\n colorPicker.wpColorPicker(options);\n }\n }",
"function createColorPalette(colors){\n\n // create a swatch for each color\n for (var i = colors.length - 1; i >= 0; i--) {\n var $swatch = $(\"<div>\").css(\"background-color\", colors[i])\n .addClass(\"swatch\");\n $swatch.click(function(){\n // add color to the color palette history\n cp.history.push($(this).css(\"background-color\"));\n });\n cp.$container.append($swatch);\n }\n }",
"function setupColorPicker () {\n\n // Setup colorPickers.\n $('.js-label-palette').spectrum({\n showPaletteOnly : true,\n showPalette : true,\n hideAfterPaletteSelect : true,\n palette : color.getPaletteColors()\n })\n // Set initial color.\n $('.js-label-palette').each((i, elm) => {\n const $elm = $(elm)\n $elm.spectrum('set', $elm.data('color'))\n })\n\n // Setup behavior.\n // Save the color to db, and notify.\n $('.js-label-palette').off('change').on('change', (e) => {\n const $this = $(e.currentTarget)\n const aColor = $this.spectrum('get').toHexString()\n const index = $this.data('index')\n console.log('click color picker:', e, aColor, index)\n\n let labelList = db.getLabelList()\n let label = labelList[core.getCurrentTab()].labels[index]\n if (typeof label === 'string') { // old style.\n label = [ label, aColor ]\n } else {\n label[1] = aColor\n }\n labelList[core.getCurrentTab()].labels[index] = label\n db.saveLabelList(labelList)\n\n // Notify color changed.\n const text = $this.siblings('.js-label').text().trim()\n color.notifyColorChanged({ text : text, color : aColor, annoType : core.getCurrentTab() })\n })\n}",
"function getColorsCreatePalette(){\n cp.$container.html(\" \");\n $.getJSON('/static/coloring/vendors/material/material-colors.json', function(colors){\n var keys = Object.keys(colors);\n for (var i = keys.length - 1; i >= 0; i--) {\n cp.options.push(colors[keys[i]][500]);\n }\n createColorPalette(cp.options);\n });\n }",
"function changeColors() {\n var num = $(\"#num\").slider(\"value\");\n var saturation = $(\"#saturation\").slider(\"value\");\n var lightness = $(\"#lightness\").slider(\"value\");\n var hueMin = $(\"#hue\").slider(\"values\", 0);\n var hueMax = $(\"#hue\").slider(\"values\", 1);\n\n updateValueLabels(num, saturation, lightness, hueMin, hueMax);\n generatePalette(num, saturation, lightness, hueMin, hueMax, format);\n}",
"function EBX_ColorPicker() {\n\n}",
"function initiateDrawColorPicker() {\r\n var colorPickerInputArray = document.querySelectorAll(\r\n \"input.color-input\"\r\n );\r\n var red = document.getElementById(\"redDrawColorSelector\").value;\r\n var green = document.getElementById(\"greenDrawColorSelector\").value;\r\n var blue = document.getElementById(\"blueDrawColorSelector\").value;\r\n colorPickerDisplay = document.getElementById(\"colorDrawDisplay\");\r\n if (colorPickerDisplay && red && green && blue) {\r\n colorPickerDisplay.style.background = `rgba(${red}, ${green}, ${blue}, 1)`;\r\n }\r\n if (colorPickerInputArray && colorPickerInputArray.length > 0) {\r\n for (var i = 0; i < colorPickerInputArray.length; i++) {\r\n colorPickerInputArray[i].addEventListener(\"input\", function () {\r\n red = document.getElementById(\"redDrawColorSelector\").value;\r\n green = document.getElementById(\"greenDrawColorSelector\").value;\r\n blue = document.getElementById(\"blueDrawColorSelector\").value;\r\n colorPickerDisplay = document.getElementById(\"colorDrawDisplay\");\r\n if (colorPickerDisplay && red && green && blue) {\r\n colorPickerDisplay.style.background = `rgba(${red}, ${green}, ${blue}, 1)`;\r\n currentDrawRGBValues = {\r\n red: red,\r\n green: green,\r\n blue: blue,\r\n alpha: \"1\"\r\n };\r\n }\r\n });\r\n }\r\n }\r\n currentDrawRGBValues = {\r\n red: red,\r\n green: green,\r\n blue: blue\r\n };\r\n }",
"function setUpColorPicker() {\n // if color picker instantiated buttons are present already\n // then iteratively remove each button node from the DOM\n [...document.getElementsByClassName(\"color-picker-btn\")].forEach((btn) => {\n btn.remove();\n color_picker_btns = []; // Reinitialize container to empty array\n });\n\n // Get each DOM Element where the color picker button element will be appended to\n let cp_initializer = {\n container: [...document.getElementsByClassName(\"cp-container\")],\n cp_btn_id: [\"start_gdt_btn\", \"end_gdt_btn\", \"bg_color_btn\"],\n cp_target_id: [\"start_gdt\", \"end_gdt\", \"bg_color\"],\n };\n\n for (let i = 0; i < Object.keys(cp_initializer).length; i++) {\n let btn = document.createElement(\"button\");\n\n btn.className = `color-picker-btn`;\n btn.id = cp_initializer[\"cp_btn_id\"][i];\n\n cp_initializer[\"container\"][i].appendChild(btn);\n color_picker_btns.push(btn);\n\n let params = {\n value: \"\",\n valueElement: cp_initializer[\"cp_target_id\"][i],\n styleElement: cp_initializer[\"cp_target_id\"][i],\n buttonHeight: 12,\n hash: true,\n width: 250,\n height: 150,\n position: \"right\",\n borderColor: \"#FFF\",\n insetColor: \"#FFF\",\n backgroundColor: \"#333\",\n padding: 32,\n },\n picker = new jscolor(btn, params);\n\n btn.addEventListener(\"click\", addColorPickerCloseBtn);\n\n // Create a color picker map, mapping the button id to the picker instance\n picker_map[btn.id] = picker;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the given dir has workspace config (new or legacy) | static async isExist(dirPath) {
const jsoncExist = await WorkspaceConfig.pathHasWorkspaceJsonc(dirPath);
if (jsoncExist) {
return true;
}
return _workspaceConfig().default._isExist(dirPath);
} | [
"checkProj(dir) {\n if (fs.existsSync(dir)) {\n if (fs.existsSync(path.join(dir, 'src'))) {\n atom.notifications.addError(`Your directory \"src\" cannot be replaced`);\n return false;\n } else if (fs.existsSync(path.join(dir, 'package.json'))) {\n atom.notifications.addError(`Your directory cannot be initialized`);\n return false;\n }\n }\n return true;\n }",
"findLocalCSConfig() {\n if (!nova.workspace.path) {\n return false;\n }\n\n let found = false;\n const csconf = ['.php_cs.dist', '.php_cs'];\n csconf.forEach((name) => {\n const cfpath = nova.path.join(nova.workspace.path, name);\n const hasConfig = nova.fs.stat(cfpath);\n\n if (hasConfig) {\n found = cfpath;\n }\n });\n\n return found;\n }",
"function isMonorepo(dir) {\n try {\n return !!['package.json', '../../package.json'].find(file => {\n const pkg = JSON.parse(fs.readFileSync(path.resolve(dir, file), 'utf8'));\n return pkg.workspaces;\n });\n } catch (e) {\n // nothing to do\n }\n return false;\n}",
"function checkDir(dir) {\n return dir ? dir : require('../lib/configuration').get('var_path');\n}",
"function checkPath () {\n $scope.alreadyOpen_ws = null;\n var loc = $location.path();\n var index = loc.indexOf('workspace/');\n if (index > -1) {\n var workspaceSubstr = loc.substring(index+10);\n var lastindex = workspaceSubstr.indexOf('/');\n if (lastindex > -1) {\n $scope.alreadyOpen_ws = workspaceSubstr.substring(0, lastindex);\n if ($scope.workspaces) { // only open if workspaces already fetched\n reopenWorkspaceFolder();\n }\n }\n }\n }",
"isComponents(dir) {\n let componentConfig;\n let instanceConfig;\n try {\n componentConfig = legacyLoadComponentConfig(dir);\n } catch (e) {\n // ignore\n }\n try {\n instanceConfig = legacyLoadInstanceConfig(dir);\n } catch (e) {\n // ignore\n }\n if (!componentConfig && !instanceConfig) {\n return false;\n }\n if (instanceConfig && !instanceConfig.component) {\n return false;\n }\n return true;\n }",
"function workspaceChanged() {\n\tvar fileWorkspace = DWfile.read(MM.BC.CONSTANTS.CURRENT_WORKSPACE);\n\tif (globals.currentWorkspace != fileWorkspace) {\n\t\tglobals.currentWorkspace = fileWorkspace;\n\t\treturn true;\n\t}\n\treturn false;\n}",
"function dirCheck(dir) {\n if (!shell.test('-d', dir)) {\n return false;\n } else {\n return true;\n }\n}",
"get exists() {\n // We want to check the Environment's root directory\n return fs.existsSync(this.dir);\n }",
"async checkIfConfigured() {\n this.path = await this._getToolPath()\n return this.path != null\n }",
"hasRepo (name) {\n // Check the existence of the root directory but the repository's\n // spec file as well\n let repoRootDir = path.join(this.reposDir, name);\n return (fs.existsSync(repoRootDir) &&\n fs.existsSync(path.join(repoRootDir, Carmel.Repository.CONFIG.SPEC)));\n }",
"async checkIfConfigured () {\r\n this.path = await this._getToolPath()\r\n return this.path != null\r\n }",
"function isInWorkspace (pathSegment) {\n\tconst workspaceFolder = getWorkspaceFolder();\n\tif (workspaceFolder) {\n\t\tconst pathSegmentUri = workspaceFolder.uri.with({\"path\": pathSegment});\n\t\treturn !vscode.workspace.asRelativePath(pathSegmentUri).startsWith(\"/\");\n\t}\n\treturn false;\n}",
"async function workspaceExists(p, name) {\n const workspaces = await getWorkspaceNames(p);\n\n return workspaces.includes(name);\n}",
"function checkDeploymentDir(targetDir) {\r\n // check if the environment variable exists and does have a value\r\n if (targetDir === undefined || targetDir === '') {\r\n log(formatWarning('The environment variable WORDPRESS_PLUGINS_DIR is not set. Deployment to WordPress will not take place.'));\r\n return false;\r\n }\r\n\r\n // check if the directory defined in WORDPRESS_PLUGINS_DIR exists and is writeable for the current process\r\n try {\r\n fs.accessSync(targetDir, fs.constants.W_OK);\r\n } catch (err) {\r\n log(formatWarning(err.message));\r\n log(formatWarning('Deployment to webserver will not take place.'));\r\n return false;\r\n }\r\n\r\n return true;\r\n}",
"_checkProjectConfig() {\n return this._projectConfig.checkConfig();\n }",
"isDirectoryInProject(directory) {\r\n return directory._inProject === true;\r\n }",
"function hasBuildXML(dir)\n{\n \tvar files =\tfs.readdirSync(dir);\n \t\t\n \tfor(var i = 0; i < files.length; i++)\n \t{\n \t\tif(files[i].indexOf(\"build.xml\") > -1)\n \t\t{\n \t\t\treturn true;\n \t\t}\n \t}\n \t\n \treturn false;\n}",
"function check(dir) {\n const stats = stat(dir);\n if (!stats) {\n throw new Error(`The specified workdir does not exist: ${ dir }`);\n }\n\n if (!stats.isDirectory()) {\n throw new Error(`The specified workdir exists but is not a directory: ${ dir }`);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Values for max_lazy_match, good_match and max_chain_length, depending on the desired pack level (0..9). The values given below have been tuned to exclude worst case performance for pathological files. Better values may be found for specific files. | function DeflateConfiguration(a, b, c, d) {
this.good_length = a; // reduce lazy search above this match length
this.max_lazy = b; // do not perform lazy search above this match length
this.nice_length = c; // quit search above this match length
this.max_chain = d;
} | [
"function DeflateConfiguration(a, b, c, d) {\n\tthis.good_length = a; // reduce lazy search above this match length\n\tthis.max_lazy = b; // do not perform lazy search above this match length\n\tthis.nice_length = c; // quit search above this match length\n\tthis.max_chain = d;\n}",
"function calcMaxRecursionDepth() {\n return min(7, floor(log2(pixelCount)))\n}",
"function DeflateConfiguration(a, b, c, d) {\n \t\tthis.good_length = a; // reduce lazy search above this match length\n \t\tthis.max_lazy = b; // do not perform lazy search above this match length\n \t\tthis.nice_length = c; // quit search above this match length\n \t\tthis.max_chain = d;\n \t}",
"function zip_DeflateConfiguration(a, b, c, d) {\n this.good_length = a; // reduce lazy search above this match length\n this.max_lazy = b; // do not perform lazy search above this match length\n this.nice_length = c; // quit search above this match length\n this.max_chain = d;\n}",
"get depthPacking() {\n\t return Number.parseInt(this.defines.DEPTH_PACKING, 10);\n\t }",
"function GetOptimalBlendedThreshold()\n{\n\treturn \"4\";\n}",
"function maxChunksToDepth(n) {\n if (n === 0)\n return 0;\n return Math.ceil(Math.log2(n));\n}",
"function cross_size(level, max_level) {\r\n return level/2;\r\n}",
"check() {\r\n\t\tvar diffMax = 0;\r\n\t\tvar sizeMax = -1;\r\n\t\tvar nbDiffBig = 0;\r\n\t\tfor (var size=4; size<5000; size++) {\r\n\t\t\tvar coded = this.code(size);\r\n\t\t\tvar w = this.width(coded);\r\n\t\t\tvar diff = Math.abs(size-w);\r\n\t\t\tif (diff > diffMax) {\r\n\t\t\t\tdiffMax = diff;\r\n\t\t\t\tsizeMax = size;\r\n\t\t\t}\r\n\t\t\tif (diff >= 2) {\r\n\t\t\t\tconsole.log(\"=> diff:\", diff, \"@ size=\", size);\r\n\t\t\t\tnbDiffBig ++;\r\n\t\t\t}\r\n\t\t\tif (this.debug) console.log(size, w, coded);\r\n\t\t}\r\n\t\tconsole.log(\"=> nb big diff:\", nbDiffBig,\" diff max:\", diffMax, \" @ size=\", sizeMax);\r\n\t\treturn diffMax;\r\n\t}",
"static get defaultMaxTextures() {\n var _a2;\n return this._defaultMaxTextures = (_a2 = this._defaultMaxTextures) != null ? _a2 : maxRecommendedTextures(32), this._defaultMaxTextures;\n }",
"get maxActiveChunks() {\n return parseInt(this.options.maxActive, 10)\n }",
"numLevels() {\n let maxDimension = Math.max(this.width, this.height);\n let boundary = this.type === 'dzi' ? 1 : this.tileSize;\n let numLevels = 0;\n while (maxDimension >= boundary) {\n maxDimension /= 2;\n numLevels++;\n }\n return numLevels\n }",
"get maxActiveChunks() {\n return parseInt(this.options.maxActive, 10)\n }",
"function computeActualMaxFieldLengths() {\n\tvar actualValue = function(spec) {\n\t\tif (spec) {\n\t\t\t// Option specified.\n\t\t\tif (spec.length == 2) {\n\t\t\t\t// Specified as [min, max].\n\t\t\t\tvar min=spec[0], max=spec[1];\n\t\t\t\treturn min + srandom() * (max-min);\n\t\t\t} else {\n\t\t\t\t// Use raw specified value.\n\t\t\t\treturn spec;\n\t\t\t}\n\t\t}\n\t}\n\t$.each(templates, function(key, val) {\n\t\t// Template-level option.\n\t\tval.actualMaxLength = actualValue(val.maxLength);\n\t\t\n\t\t// Field-level options.\n\t\t$.each(val.fields, function(fkey, fval) {\n\t\t\tfval.actualMaxLength = actualValue(fval.maxLength);\n\t\t});\n\t});\n}",
"possibleLengths() {\n\t\tif (this.v1) return\n\t\treturn this.metadata[this.v2 ? 2 : 3]\n\t}",
"largestOptionLength() {\n const options = [].slice.call(this.options);\n options.push({\n flags: '-h, --help'\n });\n return options.reduce((max, {\n flags\n }) => Math.max(max, flags.length), 0);\n }",
"function getMaxNaivePatternsDepth(patterns) {\r\n return patterns.reduce(function (max, pattern) {\r\n var depth = getNaiveDepth(pattern);\r\n return depth > max ? depth : max;\r\n }, 0);\r\n}",
"static get KEY_MATERIAL_LEN_MAX() {\n return 512;\n }",
"calculateOptimalNumberOfHashes() {\n return (this.numberOfBitsInFilter / this.numberOfHashedItems) * Math.log(2);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
eslintdisableline nounusedvars output information to the warning logging stream. | warn() {} | [
"function logWarning() {\n var _console3;\n\n if (!internalDebugValue && \"production\" === \"test\") {\n return;\n } // eslint-disable-next-line no-console\n\n\n (_console3 = console).warn.apply(_console3, arguments);\n}",
"LogWarning() {}",
"printWarnings() {\n let count = 0;\n\n // Emit warnings for unreachable components, maximum 7 warnings\n for (const id of this.unreachable) {\n console.warn(\"Warning: component \" + id + \" is not reachable\");\n if (++count === 7) break;\n }\n\n count = this.lights.elements.length;\n\n // Emit single warning for more than 8 lights\n if (count > 8) {\n console.warn(\"Warning: WebGL only supports 8 lights, but \" + count\n + \" lights are listed. Only the first 8 will be used\");\n\n // Slice lights array\n this.lights.elements.length = 8;\n }\n\n // Emit warning for material named \"inherit\"\n let material = this.materials.get(\"inherit\");\n if (material != null) {\n console.warn(\"Warning: material named 'inherit' is unusable\");\n }\n\n // Emit warning for texture named \"inherit\"\n let texture = this.textures.get(\"inherit\");\n if (texture != null) {\n console.warn(\"Warning: texture named 'inherit' is unusable\");\n }\n\n texture = this.textures.get(\"none\");\n if (texture != null) {\n console.warn(\"Warning: texture named 'none' is unusable\");\n }\n }",
"static warn() {\n var str;\n str = Util.toStrArgs('Warning:', arguments);\n Util.consoleLog(str);\n }",
"function warning (message) {\n print.warning(message)\n }",
"function warn(message) {\n console.log(\"Compiler Warning: \" + message);\n}",
"function _parserPrintWarning(prefix, msg, source){//FIXME\r\n\t\tif ( errorLevel <= 2 ) console.warn(parser.parserCreatePrintMessage(prefix,msg, source));\r\n\t}",
"function _warn(message) {\n _log('warning', message);\n}",
"function restoreWarnings (t) {\n console.warn = t.context.warn\n}",
"function unused(unusedArg) {\r\n\t\tvar unusedVariable;\r\n\t\t/*jshint -W098 */\r\n\t\t/* FAIL disable warning number not working with grunt-contrib-jshint */\r\n\t\tvar hideUnused;\r\n\t}",
"function emitWarningIfNeeded(set) {\n if ('HTTP' === set || 'HTTP2' === set) {\n process.emitWarning('Setting the NODE_DEBUG environment variable ' +\n 'to \\'' + set.toLowerCase() + '\\' can expose sensitive ' +\n 'data (such as passwords, tokens and authentication headers) ' +\n 'in the resulting log.');\n }\n}",
"function warn() {\n log.apply(null, [ STRINGS.WARNING ].concat( new$Array( arguments ) ))\n }",
"function hello2() {\n const bye = \"bye\";\n\n /**\n * For disable the es-lint on the line\n * Please put the below comment\n * now instead of the error we will have the warning for below 2\n */\n // eslint-disable-next-line\n console.log(\"this is sample \", bye);\n\n /**\n * disabling a particular rule for the eslint\n */\n // eslint-disable-next-line quotes\n console.log(\"this is sample \", 2323232);\n\n const a = 95;\n\n console.log(`vaylue for the a the `, a);\n}",
"function showWarn() {Config.LogLevel = LogLevels.WARN;}",
"warnDev(...args) {\n if (process.env.NODE_ENV === 'production') {\n return;\n }\n self.warn(...[ '\\n⚠️ ', ...args, '\\n' ]);\n }",
"warn(...args) {\n console.warn(this.getColorOn() + args.join(\" \"));\n }",
"function warn(msg) {\n console.log(TAG + \" \" + colors.bold.black.bgYellow(\"WARNING\") + \" \" + msg);\n}",
"function skipWarnings(output) {\n if (output.substr(0, 8) === 'Warning:' || output.substr(0, 12) === 'Cloning into') output = '';\n return output;\n}",
"warn(...args) {\n return this.log('warn', ...args);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
TODO: DAFTAR MENU JURUSAN 1. menampilkan menu Jurusan | function menuJurusan() {
console.log(`
===========================================================
Silahkan pilih opsi di bawah ini
[1] daftar Jurusan
[2] cari Jurusan
[3] tambah Jurusan
[4] hapus Jurusan
[5] kembali
===========================================================
`);
rl.question('masukan salah satu no. dari opsi diatas: ', (answer) => {
switch (answer) {
case "1":
daftarJurusan();
break;
case "2":
cariJurusan();
break;
case '3':
tambahJurusan();
break;
case '4':
hapusJurusan();
break;
case '5':
mainMenu();
break;
default:
break;
}
// rl.close();
});
} | [
"function Venus() {}",
"function printMenu() {\n console.log(\"\\n<====== PENDAFATARAN SISWA BARU ======>\");\n console.log(\"<====== SMKN 1 RPL ======>\");\n console.log(\"\\n<====== Menu ======>\");\n console.log(\"1. Registrasi\");\n console.log(\"2. Input Nilai\");\n console.log(\"3. Lihat Profil\");\n console.log(\"4. Informasi Kelulusan\");\n console.log(\"5. keluar\");\n }",
"function updateMenuTitles(menuMap) {\n\t\t\t\tupdateLocaleMenu(menuMap);\n\t\t\t\tif(surveyCurrentSpecial!= null && surveyCurrentSpecial != '') {\n//\t\t\t\t\tmenubuttons.set(menubuttons.section /*,stui_str(\"section_special\") */);\n\t\t\t\t\t//menubuttons.set(menubuttons.section,stui_str(\"special_\"+surveyCurrentSpecial));\n\t\t\t\t\tswitch(surveyCurrentSpecial) {\n\t\t\t\t\t\tcase \"r_vetting_json\":\n\t\t\t\t\t\t\t$('#section-current').html(stui_str('Dashboard'));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t$('#section-current').html(stui_str(\"special_\"+surveyCurrentSpecial));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tsetDisplayed(titlePageContainer, false);\n\t\t\t\t} else if(!menuMap) {\n\t\t\t\t\t//menubuttons.set(menubuttons.section);\n\t\t\t\t\tsetDisplayed(titlePageContainer, false);\n//\t\t\t\t\tmenubuttons.set(menubuttons.page, surveyCurrentPage); \n\t\t\t\t} else {\n\t\t\t\t\tif(menuMap.sectionMap[window.surveyCurrentPage]) {\n\t\t\t\t\t\tsurveyCurrentSection = surveyCurrentPage; // section = page\n\t\t\t\t\t\t//menubuttons.set(menubuttons.section, menuMap.sectionMap[surveyCurrentSection].name);\n\t\t\t\t\t\t$('#section-current').html(menuMap.sectionMap[surveyCurrentSection].name);\n\t\t\t\t\t\tsetDisplayed(titlePageContainer, false); // will fix title later\n\t\t\t\t\t} else if(menuMap.pageToSection[window.surveyCurrentPage]) {\n\t\t\t\t\t\tvar mySection = menuMap.pageToSection[window.surveyCurrentPage];\n\t\t\t\t\t\t//var myPage = mySection.pageMap[window.surveyCurrentPage];\n\t\t\t\t\t\tsurveyCurrentSection = mySection.id;\n\t\t\t\t\t\t//menubuttons.set(menubuttons.section, mySection.name);\n\t\t\t\t\t\t$('#section-current').html(mySection.name);\n\t\t\t\t\t\tsetDisplayed(titlePageContainer, false); // will fix title later\n//\t\t\t\t\t\tmenubuttons.set(menubuttons.page, myPage.name);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//menubuttons.set(menubuttons.section, stui_str(\"section_general\"));\n\t\t\t\t\t\t$('#section-current').html(stui_str(\"section_general\"));\n\t\t\t\t\t\tsetDisplayed(titlePageContainer, false);\n//\t\t\t\t\t\tmenubuttons.set(menubuttons.page);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t/*if(surveyCurrentSpecial=='' || surveyCurrentSpecial===null) {\n\t\t\t\t\tdojo.byId('st-link').href = dojo.byId('title-locale').href = '#locales//'+surveyCurrentPage+'/'+surveyCurrentId;\n\t\t\t\t} else {\n\t\t\t\t\tdojo.byId('st-link').href = dojo.byId('title-locale').href = '#locales///';\n\t\t\t\t}*/\n\t\t\t}",
"function salirMenu() {\n if (confirm(\"¿Esta seguro de que quiere salir al menu?\")) {\n for (var mini in Game.global.control) {\n mini.haGanado = false\n }\n this.music.stop();\n Game.state.start('Menu');\n }\n }",
"function salirMenu() {\r\n if (confirm(\"¿Esta seguro de que quiere salir al menu?\")) {\r\n for (var mini in Game.global.control) {\r\n mini.haGanado = false\r\n }\r\n this.music.stop();\r\n Game.state.start('Menu');\r\n }\r\n }",
"function salirMenu() {\n if(confirm(\"¿Esta seguro de que quiere salir al menu?\")) {\n for (var mini in Game.global.control){\n mini.haGanado=false\n }\n this.music.stop();\n if(this.cascada.isPlaying)\n this.cascada.stop();\n Game.state.start('Menu');\n }\n }",
"function tampil_menu(){\r\n\r\n // yang mana nav nya?\r\n let a = document.getElementById('nav')\r\n\r\n // yang mana tombol menu nya?\r\n let b = document.getElementById('tombol-menu')\r\n\r\n // tampilkan nav\r\n a.style.display = 'block'\r\n\r\n // hilangkan tombol menu\r\n b.style.display = 'none'\r\n}",
"setMenu( aDom, aMenu ) {\n \tif( this.debug ) this.debug( aDom, aMenu );\nalert(\"a\")\n/*\n\t\t// Criando os menus superiores\n\t\t$i = 0;\n\t\tforeach( $gl_System -> Menu -> Item as $aRow ) {\n\t\t $aRow = json_decode($aRow);\n\t\t print(\"\n\t\t<a id='{$aRow->id}' href='{$gl_System -> URL }{$aRow->href}' aria-label='{$aRow->text}' class='link-item'>\n\t\t<div class='header-item'>{$aRow->menu}</div>\n\t\t</a>\\n\");\n\t\t $i ++;\n\t\t if( $i >= $gl_System -> Menu -> Show )\n\t\t break;\n\t\t} <nav id='id_mnu_system' class=\"header__items\">\n\t\t <div class=\"header-item \">\n\t\t <div>Mais\n\t\t <span class=\"header-item__more-icon\">\n\t\t <svg class=\"arrow-icon down\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" x=\"0px\" y=\"0px\" width=\"512px\" height=\"512px\" viewBox=\"0 0 512 512\" enable-background=\"new 0 0 512 512\" preserveAspectRatio=\"xMinYMin meet\">\n\t\t <g><g transform=\"translate(261.928932, 262.000000) rotate(45.000000) translate(-261.928932, -262.000000) translate(76.928932, 77.000000)\">\n\t\t <g><path d=\"M146.537,223.463l277.301,0c11.343,0,20.537,9.197,20.536,20.541l0.001, 30.81 c-0.001,11.345-9.197,20.541-20.539,20.541l-328.654,0c-5.671, 0-10.805-2.299-14.521-6.015 c-3.718-3.719-6.017-8.853-6.017-14.523l0-328.654c0.001-11.342, 9.197-20.538,20.541-20.539l30.809,0 c11.344,0,20.541,9.197,20.541,20.537l-0.001, 277.301L146.537,223.463z\"> </path></g>\n\t\t <g><path d=\"M146.537,223.463l277.301,0c11.343,0,20.537,9.197,20.536,20.541l0.001, 30.81 c-0.001,11.345-9.197,20.541-20.539,20.541l-328.654,0c-5.671, 0-10.805-2.299-14.521-6.015 c-3.718-3.719-6.017-8.853-6.017-14.523l0-328.654c0.001-11.342, 9.197-20.538,20.541-20.539l30.809,0 c11.344,0,20.541,9.197,20.541,20.537l-0.001, 277.301L146.537,223.463z\"> </path></g></g>\n\t\t </g>\n\t\t </svg></span>\n\t\t </div>\n\t\t <div class=\"menu-more-items header__fade-menu-dropdown\">\n\t\t<?php\n\t\t// Criando os menus superiores\n\t\t$i = 0;\n\t\tforeach( $gl_System -> Menu -> Item as $aRow ) {\n\t\t if( $i >= $gl_System -> Menu -> Show ) {\n\t\t $aRow = json_decode($aRow);\n\t\t print(\"\n\t\t<a id='{$aRow->id}' href='{$gl_System->URL}{$aRow->href}' aria-label='{$aRow->text}' class='menu-more-items__item'>\n\t\t<div>{$aRow->link}</div>\n\t\t</a>\\n\");\n\t\t }\n\t\t $i++;\n\t\t}\n\t\tunset($i);\n\t\t?>\n\n\t\t </div>\n\t\t </div>\n\t\t </nav>*/\n\n\t}",
"function menuOptions() {}",
"function ativarAtalhoMenu() {\n\t\t\n\t\t//abrir/fechar menu\n\t\t$(document)\n\t\t\t.on('keydown', 'body, input[type=\"text\"], textarea, select, #menu-filtro', 'alt+z', function() {\n\t\t\t\n\t\t\t\tif( $('.navbar-toggle').css('display') !== 'none' ) \n\t\t\t\t\t$('.navbar-toggle').click();\n\n\t\t\t})\n\t\t\t.on('keydown', 'body, input[type=\"text\"], textarea, select, #menu-filtro', 'pause', function() {\n\t\t\t\n\t\t\t\tif( $('.navbar-toggle').css('display') !== 'none' ) \n\t\t\t\t\t$('.navbar-toggle').click();\n\t\t\t});\n\t\t\n\t\t/**\n\t\t * Abrir submenu de acordo com o item passado.\n\t\t * @param {int} submenu\n\t\t */\n//\t\tfunction abrirSubmenu(submenu) {\n//\t\t\t\n//\t\t\tif ( $('#menu').hasClass('aberto') ) {\n//\t\t\t\t\n//\t\t\t\t$('#menu-itens button:nth-child('+submenu+')')\n//\t\t\t\t\t.click();\n//\t\t\t\t\n//\t\t\t\tsetTimeout(function() { \n//\t\t\t\t\t$('#menu-filtro-itens ul li:first-child a').focus(); \n//\t\t\t\t}, 500);\n//\t\t\t}\n//\t\t}\n//\t\t\n//\t\t//abrir submenu Admin\n//\t\t$('body, #menu-filtro').bind('keydown', 'alt+1', function() {\n//\t\t\tabrirSubmenu(1);\n//\t\t});\n\t\t\n\t}",
"fungsiMakan() {\n return `Blubuk kelas parent di ambil alih blubuk ini`;\n }",
"function DWMenu() {}",
"function pegaMenus()\n{\n\ttry\n\t{YAHOO.util.Event.removeListener(YAHOO.admin.container.panelEditor.close, \"click\");}\n\tcatch(e){}\n\tcore_pegaDados(\"buscando menus...\",\"../php/menutemas.php?funcao=pegaMenus2&idioma=\"+idiomaSel(),\"montaArvore\");\n}",
"function mainMenuShow () {\n $ (\"#menuButton\").removeAttr (\"title-1\");\n $ (\"#menuButton\").attr (\"title\", htmlSafe (\"Stäng menyn\")); // i18n\n $ (\"#menuButton\").html (\"×\");\n $ (\".mainMenu\").show ();\n}",
"function menuMataKuliah() {\nconsole.log(`\n===========================================================\nSilahkan pilih opsi di bawah ini\n[1] daftar mata kuliah\n[2] cari mata kuliah\n[3] tambah mata kuliah\n[4] hapus mata kuliah\n[5] kembali\n===========================================================\n`);\n\n rl.question('masukan salah satu no. dari opsi diatas: ', (answer) => {\n switch (answer) {\n case \"1\":\n daftarMataKuliah();\n break;\n case \"2\":\n cariMataKuliah();\n break;\n case '3':\n tambahMataKuliah();\n break;\n case '4':\n hapusMataKuliah();\n break;\n case '5':\n mainMenu();\n break;\n\n default:\n break;\n }\n\n // rl.close();\n });\n\n}",
"function mo_menu_trai_trang_chu()\n{\n\tmenu = document.getElementById('menuRight');\n\tif (menu != '' && menu != undefined) {\n\t\tif(document.getElementById('mnDanhMuc')) document.getElementById(\"mnDanhMuc\").style.display=\"none\";\n\t\tif(document.getElementById('mnRight-closeBtn')) document.getElementById(\"mnRight-closeBtn\").style.display=\"block\";\n\t}\n\tshow_hide_block('menuRight');\n\t// show_hide_block('mnRight-closeBtn');\n\tvar v_height = window.innerHeight;\n\tif (document.getElementById('div_scroll')) {\n\t\tdocument.getElementById('div_scroll').style.height = (v_height-150) + 'px';\n\t}\n\ttouchScroll();\n}",
"function maranatha_activate_menu() {\n\n\tvar $header_menu_raw_list, $header_menu_raw_items;\n\n\t// Continue if menu not empty\n\tif ( ! jQuery( '#maranatha-header-menu-content' ).children().length ) {\n\t\treturn;\n\t}\n\n\t// Make copy of menu contents before Superfish modified\n\t// Original markup works better with MeanMenu (less Supersubs and styling issues)\n\tif ( ! jQuery( $maranatha_header_menu_raw ).length ) { // not done already\n\t\t$maranatha_header_menu_raw = jQuery( '<div></div>' ); // Create empty div\n\t\t$header_menu_raw_list = jQuery( '<ul></ul>' ); // Create empty list\n\t\t$header_menu_raw_items = jQuery( '#maranatha-header-menu-content' ).html(); // Get menu items\n\t\t$header_menu_raw_list = $header_menu_raw_list.html( $header_menu_raw_items ); // Copy items to empty list\n\t\t$maranatha_header_menu_raw = $maranatha_header_menu_raw.html( $header_menu_raw_list ); // Copy list to div\n\t}\n\n\t// Regular Menu (Superfish)\n\tjQuery( '#maranatha-header-menu-content' ).supersubs( { // Superfish dropdowns\n\t\tminWidth: 14.5,\t// minimum width of sub-menus in em units\n\t\tmaxWidth: 14.5,\t// maximum width of sub-menus in em units\n\t\textraWidth: 1\t// extra width can ensure lines don't sometimes turn over due to slight rounding differences and font-family\n\t} ).superfish( {\n\t\tdelay: 150,\n\t\tdisableHI: false,\n\t\tanimation: {\n\t\t\topacity: 'show',\n\t\t\t//height:'show'\n\t\t},\n\t\tspeed: 0, // animation\n\t\tonInit: function() {\n\n\t\t\t// Responsive Menu (MeanMenu) for small screens\n\t\t\t// Replaces regular menu with responsive controls\n\t\t\t// Init after Superfish done because Supersubs needs menu visible for calculations\n\t\t jQuery( $maranatha_header_menu_raw ).meanmenu( {\n\t\t \tmeanMenuContainer: '#maranatha-header-mobile-menu',\n\t\t\t\tmeanScreenWidth: maranatha_mobile_width, // use CSS media query to hide #maranatha-header-menu-content at same size\n\t\t \tmeanRevealPosition: 'right',\n\t\t \tmeanRemoveAttrs: true, // remove any Superfish classes, duplicate item ID's, etc.\n\t\t \tmeanMenuClose: '<i class=\"' + maranatha_main.mobile_menu_close + '\"></i>',\n\t\t \tmeanExpand: '+',\n\t\t \tmeanContract: '-',\n\t\t \t//removeElements: '#maranatha-header-menu-inner' // toggle visibility of regular\n\t\t } );\n\n\t\t\t// Set open/close height same as logo and position top same as logo, so vertically centered\n\t\t\t// Also insert search into mobile menu\n\t\t\t// And again on resize in case logo changes height of bar\n\t\t\tmaranatha_activate_mobile_menu();\n\t\t\tjQuery( window ).resize(function() {\n\t\t\t\tmaranatha_activate_mobile_menu();\n\t\t\t} );\n\n\t\t},\n\t\tonBeforeShow: function() {\n\n\t\t\t// Make dropdowns on right open to the left if will go off screen\n\t\t\t// This considers that the links may have wrapped and dropdowns may be mobile-size\n\n\t\t\tvar $link, $dropdown, $dropdown_width, $offset;\n\n\t\t\t// Detect if is first-level dropdown and if not return\n\t\t\tif ( jQuery( this, '#maranatha-header-menu-content' ).parents( 'li.menu-item' ).length != 1 ) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Top-level link hovered on\n\t\t\t$link = jQuery( this ).parents( '#maranatha-header-menu-content > li.menu-item' );\n\n\t\t\t// First-level dropdown\n\t\t\t$dropdown = jQuery( '> ul', $link );\n\n\t\t\t// First-level dropdown width\n\t\t\t$dropdown_width = $dropdown.outerWidth();\n\t\t\t$dropdown_width_adjusted = $dropdown_width - 20; // compensate for left alignment\n\n\t\t\t// Remove classes first in case don't need anymore\n\t\t\t$link.removeClass( 'maranatha-dropdown-align-right maranatha-dropdown-open-left' );\n\n\t\t\t// Get offset between left side of link and right side of window\n\t\t\t$offset = jQuery( window ).width() - $link.offset().left;\n\n\t\t\t// Is it within one dropdown length of window's right edge?\n\t\t\t// Add .maranatha-dropdown-align-right to make first-level dropdown not go off screen\n\t\t\tif ( $offset < $dropdown_width_adjusted ) {\n\t\t\t\t$link.addClass( 'maranatha-dropdown-align-right' );\n\t\t\t}\n\n\t\t\t// Is it within two dropdown lengths of window's right edge?\n\t\t\t// Add .maranatha-dropdown-open-left to open second-level dropdowns left: https://github.com/joeldbirch/superfish/issues/98\n\t\t\tif ( $offset < ( $dropdown_width_adjusted * 2 ) ) {\n\t\t\t\t$link.addClass( 'maranatha-dropdown-open-left' );\n\t\t\t}\n\n\t\t},\n\n\t} );\n\n}",
"function menuHandler() {\n console.log('menuHandler');\n\n agent.add('Questi sono alcuni dei modi in cui posso aiutarti nella tua visita al nostro store online')\n agent.add(new Suggestion(`Esplorazione delle categorie`));\n agent.add(new Suggestion(`Ricerca prodotto specifico`));\n agent.add(new Suggestion(`Suggerimento prodotto`));\n}",
"function showMenu() {\n console.info(\n `\\nYou can choose for these commands:\\n\\n` +\n `exit, quit: Exits the program\\n`+\n `menu, help: Shows this menu\\n` +\n `larare: Show table Teachers and their info\\n`+\n `kompetens: Shows how the teachers competence changed during the payreview\\n`+\n `lon: Shows how the teachers salary changed during the payreview\\n`+\n `sok: <searchString> search teachers table\\n`+\n `nylon: <acronym> <lon> choose a teacher and change their salary\\n\\n`\n );\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
intervals = insertInterval([[1, 3], [5, 7], [8, 12]], [4, 6]); result = ""; for(i=0; i < intervals.length; i++) result += "[" + intervals[i][0] + ", " + intervals[i][1] + "] "; console.log("Intervals after inserting the new interval: " + result); intervals = insertInterval([[1, 3], [5, 7], [8, 12]], [4, 10]); result = ""; for(i=0; i < intervals.length; i++) result += "[" + intervals[i][0] + ", " + intervals[i][1] + "] "; console.log("Intervals after inserting the new interval: " + result); intervals = insertInterval([[2, 3], [5, 7]], [1, 4]); result = ""; for(i=0; i < intervals.length; i++) result += "[" + intervals[i][0] + ", " + intervals[i][1] + "] "; console.log("Intervals after inserting the new interval: " + result); Given a list of intervals, mergeIntervals all the overlapping intervals to produce a list that has only mutually exclusive intervals. | mergeIntervals (intervals)
{
if( intervals.length < 2 )
{
return intervals
}
intervals.sort((a, b) => a.start - b.start);
const merged = [];
let start = intervals[0].start,
end = intervals[0].end;
for (let i = 1; i < intervals.length; i++)
{
const interval = intervals[i];
if (interval.start <= end)
{ // overlapping intervals, adjust the 'end'
end = Math.max(interval.end, end);
}
else
{ // non-overlapping interval, add the previous interval and reset
merged.push(new Interval(start, end));
start = interval.start;
end = interval.end;
}
}
// add the last interval
merged.push(new Interval(start, end));
return merged;
} | [
"insertInterval (intervals, new_interval)\n {\n const merged = [];\n\n let newStart = new_interval[0]\n let newEnd = new_interval[1]\n\n let i = 0\n while( i < intervals.length && intervals[i][1] <= newStart )\n {\n merged.push( intervals[i] )\n i++\n }\n\n if( intervals[i][1] === newStart )\n {\n newStart = intervals[i][0]\n }\n\n while( i < intervals.length && intervals[i][0] <= newEnd )\n {\n newEnd = Math.max( newEnd, intervals[i][1] )\n i++\n }\n\n merged.push( [newStart, newEnd] )\n\n while( i < intervals.length )\n {\n merged.push( intervals[i] )\n i++\n }\n\n return merged;\n }",
"function mergeOverlappingIntervals(intervals) {\n // sort by STARTING val in ASCENDING order\n let sortedIntervals = intervals.sort((a,b) => a[0] - b[0]);\n const mergedIntervals = [];\n let currInterval = sortedIntervals[0];\n // need to have at least 1 interval in our mergedIntervals array to make comparision to\n // (modifications to currentInterval will be reflected in mergedIntervals)\n mergedIntervals.push(currInterval);\n\n for (const nextInterval of sortedIntervals) {\n // don't care about starting variable of currentInterval\n const [ _, currentIntervalEnd ] = currInterval;\n const [ nextIntervalStart, nextIntervalEnd ] = nextInterval;\n\n // compare new interval to currentInterval (represents the previous interval that was potentially merged)\n // there's OVERLAP\n if (currentIntervalEnd >= nextIntervalStart) {\n // reassign ending value in current interval as needed\n currInterval[1] = Math.max(currentIntervalEnd, nextIntervalEnd)\n }\n // NO overlap\n else {\n currInterval = nextInterval;\n mergedIntervals.push(currInterval)\n }\n }\n return mergedIntervals;\n}",
"function merge(intervals) {\n\n /*\n - Sort Intervals\n - Go through the list of Intervals:\n If the end time of the current interval is >==\n to the start time of the next, then the intervals need to be merged\n */\n if (intervals.length === 0) {\n return intervals;\n }\n\n intervals.sort((a, b) => {\n return a[0] - b[0];\n });\n\n const mergedIntervals = [];\n let startTime = intervals[0][0];\n let endTime = intervals[0][1];\n\n\n for (let i = 0; i < intervals.length; i++) {\n let nextStartTime = undefined;\n let nextEndTime = undefined;\n\n if (i !== intervals.length - 1) {\n nextStartTime = intervals[i+1][0];\n nextEndTime = intervals[i+1][1];\n }\n\n//Check that current interval is not the last\n//and end time greater than or equal to start time of next interval\n if (nextStartTime !== undefined && endTime >= nextStartTime) {\n endTime = Math.max(endTime, nextEndTime);\n } else {\n mergedIntervals.push([startTime, endTime]);\n startTime = nextStartTime;\n endTime = Math.max(endTime, nextEndTime);\n }\n }\n\n return mergedIntervals;\n}",
"function mergeIntervals(intervals)\n{\n // Test if the given set has at least one interval\n if (intervals.length <= 0)\n return intervals;\n\n // Create an empty stack of intervals\n var stack = [], last;\n\n // sort the intervals based on start time\n intervals.sort(function(a,b) {\n return a['start'] - b['start'];\n });\n\n // console.log(intervals);\n\n // push the first interval to stack\n stack.push(intervals[0]);\n\n // Start from the next interval and merge if necessary\n for (var i = 1, len = intervals.length ; i < len; i++ ) {\n // get interval from last item\n last = stack[stack.length - 1];\n\n // if current interval is not overlapping with stack top,\n // push it to the stack\n if (last['end'] <= intervals[i]['start']) {\n stack.push( intervals[i] );\n }\n \n // Otherwise update the ending time of top if ending of current \n // interval is more\n else if (last['end'] < intervals[i]['end']) {\n last['end'] = intervals[i]['end']; \n \n stack.pop();\n stack.push(last);\n }\n }\n\n // console.log(stack);\n\n return stack;\n}",
"function nonOverlappingIntervals(set, newInterval){\n var newSet = new Array();\n var head = newInterval[0];\n var tail = newInterval[1];\n var merge_head = -1;\n var merge_tail = -1;\n var isMerged = false;\n for (var i in set) {\n if( (set[i][0] < head && set[i][1] < head) ||\n (set[i][0] > tail && set[i][1] > tail) ){\n if(merge_head != -1 && merge_tail != -1){\n newSet.push([merge_head, merge_tail]);\n console.log([merge_head, merge_tail]);\n isMerged = true;\n }\n newSet.push(set[i]);\n console.log(set[i]);\n continue;\n }\n else{\n if(set[i][0] < head && set[i][1] >= head && set[i][1] < tail){\n merge_head = set[i][0];\n merge_tail = tail;\n }\n else if(set[i][0] < head && set[i][1] >= tail){\n merge_head = set[i][0];\n merge_tail = set[i][1];\n }\n else if(set[i][0] >= head && set[i][0] <= tail && set[i][1] >= tail) {\n merge_head = (merge_head == -1 ? head : merge_head);\n merge_tail = set[i][1];\n }\n else {\n merge_head = (merge_head == -1 ? head : merge_head);\n merge_tail = tail;\n }\n }\n }\n if(!isMerged){\n newSet.push([merge_head, merge_tail]);\n console.log([merge_head, merge_tail]);\n isMerged = true;\n }\n return newSet;\n}",
"function insertInterval(arr, newInterval) {\n let intervals = arr; \n let reverseSortedIntervals = [];\n let newInt = newInterval; \n\n if (intervals.length < 1) {\n return [newInterval]\n }\n\n if (intervals.length === 1) {\n if (newInterval[0] < intervals[0][0]) {\n let newSecondInterval = intervals[0];\n intervals.pop();\n intervals.push(newInterval);\n intervals.push(newSecondInterval);\n } else {\n intervals.push(newInterval);\n }\n }\n\n // we sort the intervals array from latest end time to earliest end time, \n // inserting the new interval whenever appropriate.\n // big O of this part is O(n) due to us having to push into the \n // reverseSortedIntervals arr n times.\n while (intervals.length> 0) {\n if (newInt !== null) {\n // if the new interval start time is less than the 1st entry in the\n // intervals array, it is pushed into the reverseSortedIntervals \n // array first\n if (newInt[0]>=intervals[intervals.length-1][0]) {\n reverseSortedIntervals.push(newInt);\n newInt = null;\n } else {\n reverseSortedIntervals.push(intervals.pop());\n }\n } else {\n reverseSortedIntervals.push(intervals.pop());\n }\n }\n\n intervals = reverseSortedIntervals;\n let mergedIntervals = [];\n\n // bigO = O(n)\n while (intervals.length > 1) {\n let intervalA = intervals[intervals.length-1];\n let intervalB = intervals[intervals.length-2];\n\n // if end time of intervalA is greater than the start time of interval B, \n // we have overlap\n if (intervalB[0] < intervalA[1]) {\n // get the endTime of new merged interval\n let endTime = Math.max(intervalA[1], intervalB[1]);\n\n // replace intervalB value with the value of the new merged interval\n intervalB = [intervalA[0], endTime];\n\n // replace the old value of intervalB in the intervals array with the \n // new interval B \n intervals[intervals.length-2] = intervalB;\n\n // pop off intervalA from the intervals array\n intervals.pop();\n } else {\n // we do not have overlap, so we pop off the end value in intervals \n // and push it into mergedIntervals\n mergedIntervals.push(intervals.pop())\n }\n }\n\n // at this point the length of the intervals array is just one, so we just pop\n // it into the merged intervals array \n mergedIntervals.push(intervals.pop());\n\n return mergedIntervals\n}",
"function insert(intervals, new_interval) {\n let merged = [];\n let i = 0;\n\n // skip and add to output) all intervals that come before the 'new_interval'\n while (i < intervals.length && intervals[i][1] < new_interval[0]) {\n merged.push(intervals[i]);\n i += 1;\n }\n\n // merge all intervals that overlap with 'new_interval'\n while (i < intervals.length && intervals[i][0] <= new_interval[1]) {\n new_interval[0] = Math.min(intervals[i][0], new_interval[0]);\n new_interval[1] = Math.max(intervals[i][1], new_interval[1]);\n i += 1;\n }\n\n // insert the new_interval\n merged.push(new_interval);\n\n // add all the remaining intervals to the output\n while (i < intervals.length) {\n merged.push(intervals[i]);\n i += 1;\n }\n\n return merged;\n}",
"function merge(intervals){\n if(intervals.length < 2) return intervals\n intervals.sort((a,b)=> a[0] - b[0])\n for (let i = 1; i < intervals.length; i++){\n let curr = intervals[i]\n let prev = intervals[i - 1]\n if(curr[0] <= prev[1]){\n interval[i] = [Math.min(prev[0], curr[0]), Math.max(prev[1], curr[1])]\n intervals.splice(i - 1, 1)\n i --\n }\n }\n return intervals\n}",
"function removeIntervals(nums, intervals) {\n if (nums.length === 0) return [];\n\n intervals.sort((a, b) => a[0] - b[0])\n //intervals = qs(intervals);\n let mergedIntervals = [];\n\n let currIntervalStart = intervals[0][0];\n let currIntervalEnd = intervals[0][1];\n for (let i = 1; i < intervals.length; i++) {\n // is the start of the curr within the last interval\n let [currStart, currEnd] = intervals[i];\n\n // replace both with a merged version with \n if (currStart <= lastEnd) {\n currIntervalEnd = Math.max(currEnd, currIntervalEnd);\n } else {\n mergedIntervals.push([currIntervalStart, currIntervalEnd]);\n currIntervalStart = currStart;\n currIntervalEnd = currEnd;\n }\n }\n mergedIntervals.push([currIntervalStart, currIntervalEnd]);\n\n mergedIntervals.forEach(int => {\n let [s, e] = int;\n while (s < e) {\n nums[s] = undefined;\n s++;\n }\n })\n\n // [1,3,3,4,u,u,6,u,u,u,1]\n let lastValidIdx = 0;\n for (let i = 0; i < nums.length; i++) {\n if (nums[i] !== undefined) {\n [nums[i], nums[lastValidIdx]] = [nums[lastValidIdx], nums[i]];\n lastValidIdx++\n }\n }\n\n return nums.slice(0, lastValidIndex);\n}",
"function insertInterval(intervals, newInterval){\n let len = intervals.length;\n let i = 0;\n let result = [];\n if(len === 0) result.push(newInterval);\n\n while(i < len && intervals[i][1] < newInterval[0]){\n result.push(intervals[i]);\n i++;\n }\n \n if(i == len)result.push(newInterval);\n\n while(i < len && intervals[i][0] <= newInterval[1]){\n newInterval[0] = Math.min(intervals[i][0], newInterval[0]);\n newInterval[1] = Math.max(intervals[i][1], newInterval[1]);\n i++;\n }\n result.push(newInterval);\n while(i < len){\n result.push(intervals[i]);\n i++;\n }\n return result;\n}",
"function mergeInterval(intervals, newInterval) {\n var A = intervals;\n var B = [newInterval];\n\n var pA = 0;\n var pB = 0;\n\n while ()\n}",
"function MergeIntervals(clip_intervals, max_distance_apart) {\n var num_intervals = clip_intervals.length;\n if(num_intervals == 0) {\n return [];\n }\n\n // Sorting the intervals places candidates for merging in adjacent slots in\n // the array.\n var sorted_intervals = SortIntervalsByStart(clip_intervals);\n var merged_intervals = [];\n\n // This loop calculates the distance between each pair of candidate intervals,\n // and merges them if the distance is smaller than |max_distance_apart|. \n merged_intervals[0] = sorted_intervals[0];\n var num_merged_intervals = 1;\n for(var interval_idx = 0; interval_idx < num_intervals - 1; interval_idx++) {\n var left_interval = merged_intervals[num_merged_intervals - 1];\n var right_interval = sorted_intervals[interval_idx + 1];\n\n // Check to merge.\n var distance_apart = right_interval.start - left_interval.stop;\n if(distance_apart <= max_distance_apart) {\n var new_start = left_interval.start;\n\n // This handles the case when one interval is entirely within a bigger \n // interval. \n var new_stop = Math.max(left_interval.stop, right_interval.stop);\n var new_interval = { start: new_start, stop: new_stop };\n\n // We need to replace the most recent interval with the newly merged \n // interval, or there will be duplicates.\n merged_intervals[num_merged_intervals - 1] = { start: new_start, stop: new_stop };\n }\n else {\n // We don't merge, so we can just append the right interval.\n merged_intervals[num_merged_intervals] = right_interval;\n num_merged_intervals++;\n }\n }\n\n return merged_intervals;\n }",
"mergeIntervals(basicIntervals, complexIntervals, shiftArray){\n\n let cmp = (int1, int2) => {\n return int1.start - int2.start;\n };\n\n // sort intervals by start index\n basicIntervals = basicIntervals.sort(cmp);\n complexIntervals = complexIntervals.sort(cmp);\n\n let eliminateDuplication = sortedArr => {\n return sortedArr.filter( ( currVal, currIndex ) => {\n let compPrev = () => {\n let prevVal = sortedArr[ currIndex - 1 ];\n\n return currVal.start === prevVal.start && currVal.end === prevVal.end;\n };\n\n return currIndex === 0 || !compPrev();\n } );\n };\n\n // same intervals would be repeated based on text mining results\n // handle such cases by removing any duplication of intervals\n basicIntervals = eliminateDuplication( basicIntervals );\n complexIntervals = eliminateDuplication( complexIntervals );\n\n if ( shiftArray ) {\n this.applyShift( basicIntervals, shiftArray );\n this.applyShift( complexIntervals, shiftArray );\n }\n\n let basicIndex = 0;\n let complexIndex = 0;\n let retVal = [];\n\n while ( basicIndex < basicIntervals.length && complexIndex < complexIntervals.length ) {\n let basicInt = basicIntervals[basicIndex];\n let complexInt = complexIntervals[complexIndex];\n\n // push a complex object for the part of complex interval that intersects no basic interval\n if ( basicInt.start > complexInt.start ) {\n let complexObj = {\n start: complexInt.start,\n end: Math.min(basicInt.start, complexInt.end),\n classes: [ complexInt.class ]\n };\n\n retVal.push(complexObj);\n\n // update the beginining of complex interval since we just covered some\n complexInt.start = complexObj.end;\n\n // if the whole complex interval is covered pass to the next one\n // this would happen if complex interval does not include any basic interval\n if ( complexInt.end === complexObj.end ) {\n complexIndex++;\n continue;\n }\n }\n\n let basicObj = {\n start: basicInt.start,\n end: basicInt.end,\n classes: [ basicInt.class ]\n };\n\n // if basic interval is covered by complex interval it makes an intersection\n // so it should have the complex class as well\n if ( basicInt.start >= complexInt.start && basicInt.end <= complexInt.end ) {\n basicObj.classes.push( complexInt.class );\n complexInt.start = basicInt.end;\n\n // we are done with this intersection pass to the next one\n if ( complexInt.start >= complexInt.end ) {\n complexIndex++;\n }\n }\n\n retVal.push(basicObj);\n\n // pass to next basic interval\n basicIndex++;\n }\n\n let iterateRemaningIntervals = ( index, intervals ) => {\n while ( index < intervals.length ) {\n let interval = intervals[index];\n retVal.push({\n start: interval.start,\n end: interval.end,\n classes: [ interval.class ]\n });\n index++;\n }\n };\n\n // iterate through the remaining intervals\n iterateRemaningIntervals( basicIndex, basicIntervals );\n iterateRemaningIntervals( complexIndex, complexIntervals );\n\n return retVal;\n }",
"function parseInput(string){\n\n//value error\n if(string == null){\n return (\"ValueError\")\n }\n\n//initialize variables\n let newIntervals = [];\n const result = [];\n let intervalObjects = [];\n\n//initialize splitString function\n splitString(string);\n\n//split number string into separated strings\nfunction splitString (string) {\n let newArray = string.split(',')\n for(let i=0; i<newArray.length; i++){\n newIntervals.push(replaceDashes(newArray[i]))\n // console.log(\"newIntervals\", newIntervals)\n }\n}\n\n// helper function replace dashes to commas\nfunction replaceDashes(string){\n let newString = string.toString().replace(/-/g,\",\").split(\",\");\n return newString;\n}\n\n//create array of parse interval objects\n for(let i=0; i<newIntervals.length; i++){\n let newInt = new Interval(newIntervals[i][0], newIntervals[i][1]);\n intervalObjects.push(newInt);\n // console.log(intervalObjects);\n }\n\n//array of objects to array of arrays to be used in merging algorithm\n let mergeArray = intervalObjects.map(obj => Object.values(obj));\n\n//Part 3: Merge Intervals\n function merge(mergeArray) {\n // console.log(\"merge\", mergeArray)\n \n if (mergeArray.length <2) return mergeArray;\n\n //sort the intervals in ascending order\n mergeArray.sort((a,b)=> a[0] - b[0]);\n //starting interval to compare\n let prev = mergeArray[0];\n //loop through entire intervals array\n for(let i=1; i<mergeArray.length; i++){\n if(prev[1] >= mergeArray[i][0]){\n prev = [prev[0], Math.max(prev[1], mergeArray[i][1])];\n } else{\n result.push(prev);\n prev = mergeArray[i];\n }\n }\n result.push(prev);\n};\nmerge(mergeArray);\nreturn result;\n}",
"function ensureNotOverlapping(intervals, comparator) {\n if(intervals.length <= 1) {\n return intervals;\n }\n const result = [intervals.shift()];\n for(const interval of intervals) {\n const pendingIntervals = [interval];\n while(pendingIntervals.length > 0) {\n const pendingInterval = pendingIntervals.pop();\n const overlappingInterval = result.find((interval) => overlaps(interval, pendingInterval, comparator));\n if(!overlappingInterval) {\n result.push(pendingInterval);\n continue;\n }\n result.splice(result.indexOf(overlappingInterval), 1);\n const newIntervals = applyIntervals(overlappingInterval, pendingInterval, comparator);\n for(const interval of newIntervals) {\n pendingIntervals.push(interval);\n }\n }\n }\n\n result.sort((a, b) => {\n return comparator(a.min, b.min);\n });\n const mergedResult = [result.shift()];\n for(let interval of result) {\n const last = mergedResult[mergedResult.length - 1];\n if(isAdjacent(last, interval, comparator) && _.isEqual(last.ref, interval.ref)) {\n mergedResult.pop();\n const mergedInterval = mergeAdjacentIntervals(last, interval, comparator);\n mergedInterval.ref = last.ref;\n mergedResult.push(mergedInterval);\n }\n else {\n mergedResult.push(interval);\n }\n }\n\n return mergedResult;\n}",
"function mergeArrayWithOverlappingIntervals(inputArray) {\n let mergedArray = []\n\n for (let inputPair of inputArray) {\n const { first: currentStart, second: currentEnd } = inputPair;\n const lastMergedIndex = mergedArray.length - 1\n const { first: mergedStart, second: mergedEnd } = mergedArray[lastMergedIndex] || {}\n\n if (!mergedStart && !mergedEnd || currentStart > mergedEnd) {\n mergedArray.push(new Pair(currentStart, currentEnd))\n } else if (currentStart <= mergedEnd && currentEnd > mergedEnd) {\n mergedArray[lastMergedIndex].second = currentEnd\n }\n }\n\n return mergedArray\n}",
"function groupIntervals(intervals, comparator) {\n var numIntervals = intervals.length;\n var order = new Array(numIntervals);\n for (var i = 0; i < numIntervals; i++) {\n order[i] = i;\n }\n order = order.sort(function (a, b) {\n return intervals[a].start - intervals[b].start ||\n intervals[a].end - intervals[b].end;\n });\n\n // Now order is order in which to process intervals so their start/end coordinates increase\n // Use this sorting for detecting duplicities\n var matching = [];\n var result = new Array(numIntervals);\n var numResult = 0;\n for (var j = 0; j < numIntervals;) {\n var index = order[j];\n var interval1 = intervals[index];\n matching[0] = interval1; // Put it into a group with itself\n var toGroup = [];\n toGroup[0] = interval1;\n for (var k = j + 1; k < numIntervals; k++) {\n var interval2 = intervals[order[k]];\n if (\n interval1.start !== interval2.start ||\n interval1.end !== interval2.end) {\n break;\n }\n toGroup.push(interval2);\n }\n var matches = new Array(toGroup.length);\n while(toGroup.length > 0) {\n var first = toGroup[0];\n matches[0] = true; // Ourselves\n var numMatches = 1;\n for(var ii=1; ii<toGroup.length; ii++)\n {\n var isMatch = comparator(toGroup[ii], first);\n matches[ii] = isMatch;\n if (isMatch) {\n numMatches++;\n }\n }\n if (numMatches > 1) {\n result[numResult] = new Interval(\n first.start,\n first.stop,\n first.text + \" (\" + numMatches + \")\",\n first.overlap,\n first.color,\n first.url,\n // All grouped go in\n toGroup.filter(function(element, i) { return matches[i] }));\n }\n else {\n result[numResult] = first;\n }\n numResult++;\n // Filter the grouped out\n toGroup = toGroup.filter(function(element, i) { return !matches[i]});\n }\n j = k; // Skip to the first ungrouped\n }\n return result.slice(0, numResult);\n}",
"findIntersection (intervals_a, intervals_b)\n {\n const result = [];\n\n let aIndex = 0, bIndex = 0\n\n while( aIndex < intervals_a.length && bIndex < intervals_b.length )\n {\n const aStart = intervals_a[aIndex][0],\n aEnd = intervals_a[aIndex][1],\n bStart = intervals_b[bIndex][0],\n bEnd = intervals_b[bIndex][1]\n\n if( bStart <= aEnd && aStart <= bEnd )\n {\n result.push( [Math.max(aStart, bStart), Math.min(aEnd, bEnd)] )\n aIndex++\n }\n else if( aStart <= bEnd && bStart <= aEnd )\n {\n result.push( [Math.max(aStart, bStart), Math.min(aEnd, bEnd)] )\n bIndex++\n }\n\n if( aEnd < bStart )\n {\n aIndex++\n }\n else if( bEnd < aStart )\n {\n bIndex++\n }\n }\n\n return result;\n}",
"function unionOfIntervals(intervals) {\n if (intervals.length === 0) return [];\n return tr.b.mergeRanges(intervals.map(x => ({ min: x.start, max: x.end })), 1e-6, function (ranges) {\n return {\n start: ranges.reduce((acc, x) => Math.min(acc, x.min), ranges[0].min),\n end: ranges.reduce((acc, x) => Math.max(acc, x.max), ranges[0].max)\n };\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function: parse description: performs parse by Esprima parser, calls recursive expand() on parsed string and codeArray parameters: none return: null | function parse(){
var syntax = esprima.parse(editor.getValue());
codeArray = [];
expand(syntax.body, codeArray, 0);
} | [
"function parser(ast){\n var isTextNode = ast.type === 3;\n\n var $var = '_$var_' + ( ast.tag || 'text' ) + `_${uuid++}_`;\n codes.push(`var ${$var} = [];`);\n\n var parentVar = stack[stack.length - 1] || $root;\n //var parentAST = stackAST[stackAST.length - 1];\n\n stack.push($var);\n //stackAST.push(ast);\n\n if( !isTextNode ) {\n\n ast.children.forEach((child, i)=>{\n if( child.type === 3 ) {\n codes.push(`${$var}.push(${JSON.stringify(child.text)});`); \n } else if( child.type === 1 ) {\n if( child.tag == 'js' ) {\n if( child.children.length ) {\n codes.push(`${child.children[0].text}`);\n }\n } else {\n parser(child);\n }\n }\n });\n\n }\n\n stack.length -= 1;\n //stackAST.length -= 1;\n\n //if( ast.tag === 'js' ) return;\n\n //if( stack.length )\n codes.push(`${parentVar}.push(${program}(\"${ast.tag}\", ${JSON.stringify(ast.attrsMap)}, ${$var}));`);\n //else \n // codes.push(`${program}(\"${ast.tag}\", ${JSON.stringify(ast.attrsMap)}, ${$var});`);\n }",
"function Parser() {}",
"function parseText(code, parameters) {\n var prop,\n syntax,\n esprimaReport = \"\",\n reports = {\n 'whitelist': [],\n 'blacklist': []\n };\n \n // auxiliary function: checks if object is empty\n function isEmpty(obj) {\n for (prop in obj) {\n if (obj.hasOwnProperty(prop)) {\n return false;\n }\n }\n return true;\n }\n \n // checks for vague structural constructs\n function checkStructure(object, structure) {\n var key, child, tempList;\n \n visitor.call(null, object);\n for (key in object) {\n if (object.hasOwnProperty(key)) {\n child = object[key];\n if (typeof child === 'object' && child !== null) {\n tempList = ancestors.concat(object.type);\n traverse(child, tempList, visitor);\n // call checkStructure at every leaf\n } else {\n checkStructure(ancestors);\n }\n }\n }\n }\n \n // traverses syntax tree created by esprima; at every leaf calls checkStructure to analyze code structure\n // repurposed from an esprima example script\n function traverse(object, ancestors, visitor) {\n var key, child, tempList;\n\n visitor.call(null, object);\n for (key in object) {\n if (object.hasOwnProperty(key)) {\n child = object[key];\n if (typeof child === 'object' && child !== null) {\n tempList = ancestors.concat(object.type);\n traverse(child, tempList, visitor);\n // call checkStructure at every leaf\n } else {\n checkStructure(ancestors);\n }\n }\n }\n }\n \n function checkList(list, node) { \n /*\n //this is commented out, but provides extra information on the whitelist/blacklist elements\n var excerpt;\n excerpt = content.substring(node.range[0], node.range[1]);\n\n if (excerpt.length > 20) {\n excerpt = excerpt.substring(0, 20) + '...';\n }\n */\n\n parameters[list][node.type] = true;\n \n reports[list].push({\n 'type': node.type,\n 'location': node.loc.start.line\n });\n }\n \n // if each nested structure in parameters.structure is fulfilled, mark the main structure's integrity as 'true'\n function verifyStructure() {\n var component, key;\n parameters.structure.integrity = true;\n \n for (key in parameters.structure.components) {\n component = parameters.structure.components[key];\n if (component.integrity !== true) {\n parameters.structure.integrity = false;\n }\n }\n }\n \n // reset the parameters (at the end of parseText, so that it can be run fresh in the next call)\n function resetParameters() {\n var key;\n for (key in parameters.whitelist) {\n parameters.whitelist[key] = false;\n }\n for (key in parameters.blacklist) {\n parameters.blacklist[key] = false;\n }\n parameters.structure.integrity = false;\n parameters.structure.components.some(function (component) {\n component.integrity = false;\n });\n }\n \n // generates a string, stored in esprimaReport, providing feedback on the code in terms of the whitelist, blacklist, and structure\n function assembleReport() {\n var key, element, component, errorBool = false;\n \n //assemble whitelist report\n esprimaReport = esprimaReport.concat('Whitelist: <br>');\n for (element in parameters.whitelist) {\n if (parameters.whitelist[element] !== true) {\n errorBool = true;\n esprimaReport = esprimaReport.concat('  Error: You are missing a ' + element + '.');\n }\n }\n if (!errorBool) {\n esprimaReport = esprimaReport.concat('  No issues!<br>');\n } else {\n esprimaReport = esprimaReport.concat('<br>');\n }\n \n //assemble blacklist report\n esprimaReport = esprimaReport.concat('Blacklist:');\n if (reports.blacklist.length > 0) {\n esprimaReport = esprimaReport.concat('<br>');\n reports.blacklist.forEach(function (element) {\n esprimaReport = esprimaReport.concat('  Error: You have a ' + element.type + ' on line ' + element.location + '.<br>');\n });\n } else {\n esprimaReport = esprimaReport.concat(' No issues! <br>');\n }\n \n //assemble structure report\n esprimaReport = esprimaReport.concat('Structure: <br>');\n if (parameters.structure.integrity) {\n esprimaReport = esprimaReport.concat('  No issues! <br>');\n } else {\n parameters.structure.components.some(function (component, index) {\n if (index === 0) {\n esprimaReport = esprimaReport.concat('  Error: You are missing a ');\n }\n component.array.forEach(function (element, index) {\n esprimaReport = esprimaReport.concat(element);\n if (index < component.array.length - 1) {\n esprimaReport = esprimaReport.concat(' enclosing a ');\n }\n });\n if (index < component.array.length - 1) {\n esprimaReport = esprimaReport.concat(', followed by a <br>');\n }\n });\n esprimaReport = esprimaReport.concat('.<br>');\n }\n }\n \n // if var code is empty\n if (!code) {\n return \"Waiting for your input...<br>\";\n }\n \n // if esprima throws an error, catch and pass it to the html\n try{\n syntax = esprima.parse(code, { tolerant: true, loc: true, range: true });\n }\n catch(err){\n return err + \"<br\";\n }\n \n traverse(syntax, [], function (node) {\n var rule;\n for (rule in parameters.whitelist) {\n if (node.type === rule) {\n checkList('whitelist', node);\n }\n }\n for (rule in parameters.blacklist) {\n if (node.type === rule) {\n checkList('blacklist', node);\n }\n }\n });\n verifyStructure();\n assembleReport();\n resetParameters();\n \n return esprimaReport;\n }",
"function _Parser() {\n\t}",
"parse () {\n this._ast = Parser.parse(this.regex)\n }",
"parse(rawInputList) {\n // TODO: check that the input list contains only valid symbols\n // we have a list of input symbols (must be terminated with the end\n // character for our parsing to work) and a stack representing the\n // current state of the AST, which naturally starts out with the start\n // symbol (which represents the full sentence and the head of the AST)\n let baseInput = Immutable.List(rawInputList).push(this.END);\n let baseStack = Immutable.Stack.of(this.START);\n // our output will be an abstract syntax tree, the root node of which\n // is the start symbol\n let baseTree = new Baobab(new util.TreeNode(this.START), {\n // Baobab options\n // baobab publishes updates async by default; using promises or\n // callbacks would make the code really messy so just disable that\n asynchronous: false,\n // there's no difference by including immutability but it fits\n // the theme here\n immutable: true\n });\n\n /**\n * Parses the given input (Immutable.List) using the given stack\n * (Immutable.Stack) and uses this to build up the given abstract\n * syntax tree (Baobab), returning null if the given input symbols\n * cannot be generated by this parser's grammar.\n * The given tree should be a Baobab cursor; if you have a Baobab tree\n * just access its \"root\" field.\n * The root of the given tree should have the same value\n * as the element at the top of the stack (i.e. the given tree gets\n * built recursively.\n */\n let parseHelper = (input, stack, tree) => {\n // console.log(tree.get());\n if (stack.isEmpty()) {\n // done parsing\n // if the original input was valid, input should be no more\n // than the end symbol\n if (input.equals(Immutable.List.of(this.END))) {\n return tree;\n } else {\n return null;\n }\n } else {\n let topStackSymbol = stack.first();\n let topInputSymbol = input.first();\n\n if (topStackSymbol === topInputSymbol) {\n // if the stack and input symbols match, they can be\n // removed; the current node in the tree is a leaf, so\n // move on to its sibling\n return parseHelper(\n input.shift(),\n stack.pop(),\n util.siblingNode(tree));\n } else if (topStackSymbol === this.EMPTY) {\n // an empty symbol can simply be removed from the stack\n // because it is, well, empty\n // the empty symbol is a leaf, so move on to its sibling\n // -- which will be the sibling of its parent because the\n // empty sibling is always the only child of its parent\n // and, therefore, the rightmost sibling thereof\n return parseHelper(\n input,\n stack.pop(),\n util.siblingNode(tree));\n } else {\n // look up the matching rule in the parse table and place\n // the right side thereof on the stack\n let rule = this.parseTable\n .get(topStackSymbol)\n .get(topInputSymbol);\n return parseHelper(\n input,\n stack.pop().pushAll(rule.right),\n // also add all the symbols on the right side to the\n // tree and move into the leftmost new child (which\n // happens by default when you drill down into a tree)\n util.addChildren(tree, rule.right.toArray())\n .select('children')\n .down()\n .leftmost());\n }\n }\n };\n return parseHelper(baseInput, baseStack, baseTree.root);\n }",
"parse(text, start = null, on_error = null) {\r\n return this.parser.parse(text, start, on_error);\r\n }",
"function AST(){}",
"parseAsync(text,extra){\r\n\t\treturn new Promise(function(ok,err){\r\n\t\t\t/**\r\n\t\t\t * Pseudo-labels\r\n\t\t\t**/\r\n\t\t\tconst $DOC_TEXT=1,\r\n\t\t\t\t$TAG=2,$TAG_COLON=3,$TAG_KEY=4,\r\n\t\t\t\t$VALUE_TEXT=5,$VALUE_TAG=6,$VALUE_ERR=7,\r\n\t\t\t\t$SEC_START=8,$SEC_BODY=9;\r\n\t\t\t\r\n\t\t\tfunction innerParseAsync(next,text,ps,extra){\r\n\t\t\t\t//Avoid redefining this all over the place\r\n\t\t\t\tlet m;\r\n\t\t\t\t\r\n\t\t\t\tswitch(next){\r\n\t\t\t\t\tcase $DOC_TEXT:\r\n\t\t\t\t\t\tif(ps.val){\r\n\t\t\t\t\t\t\tps.doc.push(ps.val);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse{\r\n\t\t\t\t\t\t\tif(ps.pos>=text.length){\r\n\t\t\t\t\t\t\t\tok(new Document(ps.doc,1,0));\r\n\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif((m=maybe(text,ps,DOC_TEXT)) && m[0]){\r\n\t\t\t\t\t\t\tps.doc.push(new Text(\r\n\t\t\t\t\t\t\t\tm[0].replace(DOC_REPL,normalize),\r\n\t\t\t\t\t\t\t\tps.line,ps.col\r\n\t\t\t\t\t\t\t));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tps.callstack.push($DOC_TEXT);\r\n\t\t\t\t\t\t//next=$TAG;break;\r\n\t\t\t\t\t\r\n\t\t\t\t\tcase $TAG:\r\n\t\t\t\t\t\tps.val=null;\r\n\t\t\t\t\t\tif(text[ps.pos]!=\"{\"){\r\n\t\t\t\t\t\t\t//\"return\" null\r\n\t\t\t\t\t\t\tnext=ps.callstack.pop();\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tps.tagstack.push(\r\n\t\t\t\t\t\t\tps.toptag={\r\n\t\t\t\t\t\t\t\tkeys:[],vals:[],pos:[],\r\n\t\t\t\t\t\t\t\tline:ps.line,col:ps.col++,p:ps.pos++\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t/*\r\n\t\t\t\t\t\tEither TAG or TAG_COLON can fall through to \r\n\t\t\t\t\t\t TAG_KEY, but TAG_COLON can be \"called\" more than\r\n\t\t\t\t\t\t once per tag parsing circuit, and thus can be\r\n\t\t\t\t\t\t potentially more efficient. TAG is only more\r\n\t\t\t\t\t\t efficient for tags like {tag}\r\n\t\t\t\t\t\t*/\r\n\t\t\t\t\t\tnext=$TAG_KEY;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\r\n\t\t\t\t\tcase $TAG_COLON:\r\n\t\t\t\t\t\tmaybe(text,ps,SPACE);\r\n\t\t\t\t\t\tif(text[ps.pos]==\":\"){\r\n\t\t\t\t\t\t\tif(index(ps.toptag.keys,ps.val)!==null){\r\n\t\t\t\t\t\t\t\terr(new ParseError(DUPLICATE,ps.line,ps.col));\r\n\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tps.toptag.keys.push(ps.val);\r\n\t\t\t\t\t\t\t++ps.pos;\r\n\t\t\t\t\t\t\t++ps.col;\r\n\t\t\t\t\t\t\tmaybe(text,ps,SPACE);\r\n\t\t\t\t\t\t\tps.callstack.push($TAG_KEY);\r\n\t\t\t\t\t\t\tnext=$VALUE_TEXT;\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tps.toptag.pos.push(ps.val);\r\n\t\t\t\t\t\tps.val=null;\r\n\t\t\t\t\t\t//next=$TAG_KEY;break;\r\n\t\t\t\t\t\r\n\t\t\t\t\tcase $TAG_KEY:\r\n\t\t\t\t\t\tif(ps.val){\r\n\t\t\t\t\t\t\tps.toptag.vals.push(ps.val);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tmaybe(text,ps,SPACE);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t//No need to check for pos<=tl because VALUE_* will\r\n\t\t\t\t\t\t// catch any in-tag EOF error\r\n\t\t\t\t\t\tif(text[ps.pos]==\"}\"){\r\n\t\t\t\t\t\t\t++ps.pos;\r\n\t\t\t\t\t\t\t++ps.col;\r\n\t\t\t\t\t\t\tconst tag=ps.tagstack.pop();\r\n\t\t\t\t\t\t\tps.toptag=ps.tagstack[ps.tagstack.length-1];\r\n\t\t\t\t\t\t\tps.val=ps.build(\r\n\t\t\t\t\t\t\t\ttag.keys,tag.vals,tag.pos,\r\n\t\t\t\t\t\t\t\ttag.line,tag.col,tag.p,\r\n\t\t\t\t\t\t\t\textra\r\n\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t\tnext=ps.callstack.pop();\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t//Once the value is determined, goto TAG_COLON\r\n\t\t\t\t\t\tps.callstack.push($TAG_COLON);\r\n\t\t\t\t\t\t//next=$VALUE_TEXT;break;\r\n\t\t\t\t\t\r\n\t\t\t\t\tcase $VALUE_TEXT:\r\n\t\t\t\t\t\tif(m=maybe(text,ps,QUOTED_TEXT)){\r\n\t\t\t\t\t\t\tlet tr,qr;\r\n\t\t\t\t\t\t\tif(m[1]){\r\n\t\t\t\t\t\t\t\ttr=m[1];\r\n\t\t\t\t\t\t\t\tqr=DQ_REPL;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if(m[2]){\r\n\t\t\t\t\t\t\t\ttr=m[2];\r\n\t\t\t\t\t\t\t\tqr=SQ_REPL;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if(m[3]){\r\n\t\t\t\t\t\t\t\ttr=m[3];\r\n\t\t\t\t\t\t\t\tqr=BQ_REPL;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tps.val=new Text(\r\n\t\t\t\t\t\t\t\ttr.replace(qr,normalize),\r\n\t\t\t\t\t\t\t\tps.line,ps.col\r\n\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if(m=maybe(text,ps,UNQUOTED_TEXT)){\r\n\t\t\t\t\t\t\tps.val=new Text(\r\n\t\t\t\t\t\t\t\tm[0].replace(UNQ_REPL,normalize),\r\n\t\t\t\t\t\t\t\tps.line,ps.col\r\n\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse{\r\n\t\t\t\t\t\t\tps.callstack.push($VALUE_TAG);\r\n\t\t\t\t\t\t\tnext=$TAG;\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t//Successful, return to next block\r\n\t\t\t\t\t\tnext=ps.callstack.pop();\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\r\n\t\t\t\t\tcase $VALUE_TAG:\r\n\t\t\t\t\t\tif(ps.val){\r\n\t\t\t\t\t\t\t//Successful, return to next block\r\n\t\t\t\t\t\t\tnext=ps.callstack.pop();\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t//next=$SEC_START;break;\r\n\t\t\t\t\t\r\n\t\t\t\t\tcase $SEC_START:\r\n\t\t\t\t\t\t//Sections are the last checked value - if it's not\r\n\t\t\t\t\t\t// there, it MUST be an error\r\n\t\t\t\t\t\tif(text[ps.pos]!='['){\r\n\t\t\t\t\t\t\t/*\r\n\t\t\t\t\t\t\tSnow errors are very predictable, so check for\r\n\t\t\t\t\t\t\tcommon mistakes. By this point, we know the next\r\n\t\t\t\t\t\t\tcharacter is one of the start of quoted text, ],\r\n\t\t\t\t\t\t\t}, EOF, or whitespace. Whitespace is an error in\r\n\t\t\t\t\t\t\tthe parsing logic, but is predictable. If it's\r\n\t\t\t\t\t\t\tnot any of these, it's completely unknown what's\r\n\t\t\t\t\t\t\twrong.\r\n\t\t\t\t\t\t\t*/\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t//check for EOF\r\n\t\t\t\t\t\t\tif(ps.pos>=text.length){\r\n\t\t\t\t\t\t\t\terr(new ParseError(\r\n\t\t\t\t\t\t\t\t\tUNCLOSED_TAG,\r\n\t\t\t\t\t\t\t\t\tps.toptag.line,ps.toptag.col\r\n\t\t\t\t\t\t\t\t));\r\n\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tconst c=text[ps.pos];\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tswitch(c){\r\n\t\t\t\t\t\t\t\tcase '\"':\r\n\t\t\t\t\t\t\t\t\terr(new ParseError(\r\n\t\t\t\t\t\t\t\t\t\tUNCLOSED_DQ,\r\n\t\t\t\t\t\t\t\t\t\tps.line,ps.col\r\n\t\t\t\t\t\t\t\t\t));\r\n\t\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t\tcase \"'\":\r\n\t\t\t\t\t\t\t\t\terr(new ParseError(\r\n\t\t\t\t\t\t\t\t\t\tUNCLOSED_SQ,\r\n\t\t\t\t\t\t\t\t\t\tps.line,ps.col\r\n\t\t\t\t\t\t\t\t\t));\r\n\t\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t\tcase '`':\r\n\t\t\t\t\t\t\t\t\terr(new ParseError(\r\n\t\t\t\t\t\t\t\t\t\tUNCLOSED_BQ,\r\n\t\t\t\t\t\t\t\t\t\tps.line,ps.col\r\n\t\t\t\t\t\t\t\t\t));\r\n\t\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t\tcase ']':\r\n\t\t\t\t\t\t\t\t\tconst p=ps.secstack.pop();\r\n\t\t\t\t\t\t\t\t\terr(new ParseError(\r\n\t\t\t\t\t\t\t\t\t\tMIXED,\r\n\t\t\t\t\t\t\t\t\t\tp.line,p.col-1\r\n\t\t\t\t\t\t\t\t\t));\r\n\t\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t\tcase \"}\":\r\n\t\t\t\t\t\t\t\t\terr(new ParseError(\r\n\t\t\t\t\t\t\t\t\t\tNO_VALUE,\r\n\t\t\t\t\t\t\t\t\t\tps.coloncol,ps.colonline\r\n\t\t\t\t\t\t\t\t\t));\r\n\t\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t\tcase \":\":\r\n\t\t\t\t\t\t\t\t\terr(new ParseError(\r\n\t\t\t\t\t\t\t\t\t\tCOLON,\r\n\t\t\t\t\t\t\t\t\t\tps.line,ps.col\r\n\t\t\t\t\t\t\t\t\t));\r\n\t\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tif(/\\s/m.test(c)){\r\n\t\t\t\t\t\t\t\terr(new ParseError(\r\n\t\t\t\t\t\t\t\t\t\"Expected a value, found whitespace. \"+\r\n\t\t\t\t\t\t\t\t\t\"There's a problem with the API's \"+\r\n\t\t\t\t\t\t\t\t\t\"parser code.\",ps.line,ps.col\r\n\t\t\t\t\t\t\t\t));\r\n\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t//reserved for cosmic ray errors\r\n\t\t\t\t\t\t\terr(new ParseError(\r\n\t\t\t\t\t\t\t\t'Something went horribly wrong. '+\r\n\t\t\t\t\t\t\t\t'Expected value, got \"'+(\r\n\t\t\t\t\t\t\t\t\ttext.slice(ps.pos,ps.pos+8)+\r\n\t\t\t\t\t\t\t\t\t(ps.pos+8>=text.length)?\"\":\"...\"\r\n\t\t\t\t\t\t\t\t)+'\"',ps.line,ps.col\r\n\t\t\t\t\t\t\t));\r\n\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t++ps.pos;\r\n\t\t\t\t\t\t++ps.col;\r\n\t\t\t\t\t\tps.secstack.push([]);\r\n\t\t\t\t\t\t//next=$SEC_BODY;break;\r\n\t\t\t\t\t\r\n\t\t\t\t\tcase $SEC_BODY:\r\n\t\t\t\t\t\tconst ss=ps.secstack[ps.secstack.length-1];\r\n\t\t\t\t\t\tif(ps.val!==null){\r\n\t\t\t\t\t\t\tss.push(ps.val);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif((m=maybe(text,ps,SEC_TEXT)) && m[0]){\r\n\t\t\t\t\t\t\tss.push(new Text(\r\n\t\t\t\t\t\t\t\tm[0].replace(SEC_REPL,normalize),\r\n\t\t\t\t\t\t\t\tps.line,ps.col\r\n\t\t\t\t\t\t\t));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif(ps.pos>=text.length){\r\n\t\t\t\t\t\t\terr(new ParseError(\r\n\t\t\t\t\t\t\t\tUNCLOSED_SECTION,ps.line,ps.col\r\n\t\t\t\t\t\t\t));\r\n\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif(text[ps.pos]==']'){\r\n\t\t\t\t\t\t\t++ps.pos;\r\n\t\t\t\t\t\t\t++ps.col;\r\n\t\t\t\t\t\t\tps.val=new Section(ss,ps.line,ps.col,ps.pos);\r\n\t\t\t\t\t\t\t//sections must come from the value circuit\r\n\t\t\t\t\t\t\tnext=ps.callstack.pop();\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tps.callstack.push($SEC_BODY);\r\n\t\t\t\t\t\tnext=$TAG;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tnextTick(function(){\r\n\t\t\t\t\tinnerParseAsync(next,text,ps,extra);\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tconst bom=(text.length>0 && text[0]==\"\\ufeff\")|0;\r\n\t\t\tnextTick(function(){\r\n\t\t\t\tinnerParseAsync($DOC_TEXT,text,{\r\n\t\t\t\t\tpos:bom,\r\n\t\t\t\t\tline:1,\r\n\t\t\t\t\tcol:bom,\r\n\t\t\t\t\tcolonline:1,\r\n\t\t\t\t\tcoloncol:0,\r\n\t\t\t\t\tdoc:[],tagstack:[],secstack:[],toptag:null,\r\n\t\t\t\t\tval:null,callstack:[]\r\n\t\t\t\t},extra);\r\n\t\t\t});\r\n\t\t});\r\n\t}",
"function qaParser(str){\n\n\n str = str.trim();\n\n /* cuts metadata from input str and removes unnecessary beginning \" */\n let meta = str.slice(str.indexOf('|'), str.lastIndexOf('|') + 1);\n\n /* cuts text string from input str and removes unnecessary ending \" */\n let string = str.slice(str.lastIndexOf('|') + 1, -1);\n\n\n let aReg = /\\|Q(\\d*):(\\d):Q(\\d*)\\|/i;\n let qReg = /\\|Q(\\d*)\\|/i;\n let qfReg = /\\|Q(\\d*)\\?(\\w*)\\|/i;\n\n let question = {\n text : \"\",\n answers : [],\n stepID : 0\n };\n\n let answer = {\n text : \"\",\n questionID : 0,\n answerID : 0,\n stepID : 0\n };\n\n\n if(meta.match(qReg)){\n question.text = string;\n question.stepID = qReg.exec(meta)[1];\n nodes[0].push(question);\n // return question;\n }\n\n if(meta.match(qfReg)){\n let opt = qfReg.exec(meta)\n question.text = string;\n question.stepID = opt[1];\n question.final = opt[2] == 'FT';\n delete question.answers;\n nodes[0].push(question);\n // return answer;\n }\n\n if(meta.match(aReg)){\n let opt = aReg.exec(meta);\n answer.text = string;\n answer.questionID = opt[1];\n answer.answerID = opt[2];\n answer.stepID = opt[3];\n nodes[1].push(answer);\n // return answer;\n }\n\n // return null;\n}",
"function parse_and_compile(string) {\n \n // machine_code is array for machine instructions\n const machine_code = [];\n \n // insert_pointer keeps track of the next free place\n // in machine_code\n let insert_pointer = 0;\n\n // three insert functions (nullary, unary, binary instructions)\n function add_nullary_instruction(op_code) {\n machine_code[insert_pointer] = op_code;\n insert_pointer = insert_pointer + 1;\n }\n // unary instructions have one argument (constant or address)\n function add_unary_instruction(op_code, arg_1) {\n machine_code[insert_pointer] = op_code;\n machine_code[insert_pointer + 1] = arg_1;\n insert_pointer = insert_pointer + 2;\n }\n // binary instructions have two arguments\n function add_binary_instruction(op_code, arg_1, arg_2) {\n machine_code[insert_pointer] = op_code;\n machine_code[insert_pointer + 1] = arg_1;\n machine_code[insert_pointer + 2] = arg_2; \n insert_pointer = insert_pointer + 3;\n }\n // ternary instructions have three arguments\n function add_ternary_instruction(op_code, arg_1, arg_2, arg_3) {\n machine_code[insert_pointer] = op_code;\n machine_code[insert_pointer + 1] = arg_1;\n machine_code[insert_pointer + 2] = arg_2; \n machine_code[insert_pointer + 3] = arg_3; \n insert_pointer = insert_pointer + 4;\n }\n \n // to_compile stack keeps track of remaining compiler work:\n // these are function bodies that still need to be compiled\n let to_compile = null;\n function no_more_to_compile() {\n return is_null(to_compile);\n }\n function pop_to_compile() {\n const next = head(to_compile);\n to_compile = tail(to_compile);\n return next;\n }\n function push_to_compile(task) {\n to_compile = pair(task, to_compile);\n }\n \n // to compile a function body, we need an index table\n // to get the environment indices for each name\n // (parameters, globals and locals)\n // Each compile function returns the max operand stack\n // size needed for running the code. When compilation of \n // a function body is done, the function continue_to_compile \n // writes the max operand stack size and the address of the\n // function body to the given addresses.\n\n function make_to_compile_task(\n function_body, max_stack_size_address, \n address_address, index_table) {\n return list(function_body, max_stack_size_address, \n address_address, index_table);\n }\n function to_compile_task_body(to_compile_task) {\n return list_ref(to_compile_task, 0);\n }\n function to_compile_task_max_stack_size_address(to_compile_task) {\n return list_ref(to_compile_task, 1);\n }\n function to_compile_task_address_address(to_compile_task) {\n return list_ref(to_compile_task, 2);\n }\n function to_compile_task_index_table(to_compile_task) {\n return list_ref(to_compile_task, 3);\n }\n\n // index_table keeps track of environment addresses\n // assigned to names\n function make_empty_environment_index_table() {\n return null;\n }\n \n function extend_environment_index_table(t, s) {\n return is_null(t) \n ? list(pair(s, 0))\n : pair(pair(s, tail(head(t)) + 1), t);\n }\n \n function index_of(t, s) {\n return is_null(t)\n ? error(s, \"name not found:\")\n : head(head(t)) === s \n ? tail(head(t))\n : index_of(tail(t), s);\n }\n\n // mapping from property names (strings) to \n // integers, each uniquely identifying the property.\n const IDP = make_table();\n let next_idp = 0; // next free ID in IDP\n \n function get_IDP(string) {\n if (lookup(string, IDP) === undefined) {\n insert(string, next_idp, IDP);\n next_idp = next_idp + 1;\n } else {}\n return lookup(string, IDP);\n }\n \n // mapping from record signatures (strings with all\n // property names in alphabetical order) to integers, \n // each uniquely identifying the record type.\n const IDR = make_table();\n let next_idr = 0; // next free ID in IDR\n \n function get_IDR(string) {\n if (lookup(string, IDR) === undefined) {\n insert(string, next_idr, IDR);\n next_idr = next_idr + 1;\n } else {}\n return lookup(string, IDR);\n }\n \n // index_table (called p in Notes 07) is an array\n // indexed using idr's, containing arrays indexed\n // using idp's, containing the index of the property\n // with idp in records of the idr kind.\n const record_index_table = [];\n \n function put_index_in_record_index_table(idr, idp, the_index) {\n if (record_index_table[idr] === undefined) {\n record_index_table[idr] = [];\n } else {}\n record_index_table[idr][idp] = the_index;\n }\n // a small complication: the toplevel function\n // needs to return the value of the last statement\n let toplevel = true;\n \n function continue_to_compile() {\n while (! is_null(to_compile)) {\n const next_to_compile = pop_to_compile();\n const address_address = \n to_compile_task_address_address(next_to_compile);\n machine_code[address_address] = insert_pointer;\n const index_table = \n to_compile_task_index_table(next_to_compile);\n const max_stack_size_address =\n to_compile_task_max_stack_size_address(\n next_to_compile);\n const body = to_compile_task_body(next_to_compile);\n const max_stack_size =\n compile(body, index_table, true);\n machine_code[max_stack_size_address] = \n max_stack_size;\n toplevel = false;\n }\n }\n \n function local_names(stmt) {\n if (is_sequence(stmt)) {\n const stmts = sequence_statements(stmt);\n return is_empty_sequence(stmts)\n ? null\n : append(\n local_names(first_statement(stmts)),\n local_names(make_sequence(\n\t\t rest_statements(stmts))));\n } else {\n return is_constant_declaration(stmt)\n ? list(constant_declaration_name(stmt))\n : null;\n }\n }\t \n \n // compile_arguments compiles the arguments and\n // computes the maximal stack size needed for \n // computing the arguments. Note that the arguments\n // themselves accumulate on the operand stack, which\n // explains the \"i + compile(...)\"\n function compile_arguments(exprs, environment_index_table) {\n let i = 0;\n let s = length(exprs);\n let max_stack_size = 0;\n while (i < s) {\n max_stack_size = math_max(i + \n compile(head(exprs), \n environment_index_table, \n false),\n max_stack_size);\n i = i + 1;\n exprs = tail(exprs);\n }\n return max_stack_size;\n }\n \n function compile_boolean_operation(expr, environment_index_table) {\n if (boolean_operator_name(expr) === \"&&\") {\n return compile(make_conditional_expression(\n first_operand(\n operands(expr)),\n first_operand(\n rest_operands(\n operands(expr))),\n false), \n environment_index_table,\n false);\n } else {\n return compile(make_conditional_expression(\n first_operand(\n operands(expr)),\n true,\n first_operand(\n rest_operands(\n operands(expr)))),\n environment_index_table,\n false);\n }\n }\n \n function compile_conditional_expression(expr, environment_index_table,\n insert_flag) {\n const m_1 = compile(cond_expr_pred(expr), \n environment_index_table, false);\n add_unary_instruction(JOF, NaN);\n const JOF_address_address = insert_pointer - 1;\n const m_2 = compile(cond_expr_cons(expr), \n environment_index_table, insert_flag);\n let GOTO_address_address = NaN;\n if (!insert_flag) {\n add_unary_instruction(GOTO, NaN);\n GOTO_address_address = insert_pointer - 1;\n } else {}\n machine_code[JOF_address_address] = insert_pointer;\n const m_3 = compile(cond_expr_alt(expr), \n environment_index_table, insert_flag);\n if (!insert_flag) {\n machine_code[GOTO_address_address] = insert_pointer;\n } else {}\n return math_max(m_1, m_2, m_3);\n }\n \n function compile_primitive_application(expr, environment_index_table) {\n const op = primitive_operator_name(expr);\n const ops = operands(expr);\n const operand_1 = first_operand(ops);\n if (op === \"!\") {\n const max_stack_size = compile(operand_1, \n environment_index_table, false);\n add_nullary_instruction(NOT);\n return max_stack_size;\n } else {\n const operand_2 = first_operand(rest_operands(ops));\n const op_code = op === \"+\" ? PLUS\n : op === \"-\" ? MINUS\n : op === \"*\" ? TIMES\n : op === \"/\" ? DIV\n : op === \"===\" ? EQUAL\n : op === \"<\" ? LESS\n : op === \"<=\" ? LEQ\n : op === \">\" ? GREATER\n : op === \">=\" ? GEQ\n : error(op, \"unknown operator:\");\n const m_1 = compile(operand_1, environment_index_table, false);\n const m_2 = compile(operand_2, environment_index_table, false);\n add_nullary_instruction(op_code);\n return math_max(m_1, 1 + m_2);\n }\n }\n \n function compile_application(expr, environment_index_table) { \n const max_stack_operator = compile(operator(expr),\n environment_index_table, false);\n const max_stack_operands = compile_arguments(operands(expr),\n environment_index_table);\n add_unary_instruction(CALL, length(operands(expr)));\n return math_max(max_stack_operator, max_stack_operands + 1);\n }\n \n function compile_function_definition(expr, environment_index_table) {\n const body = function_definition_body(expr);\n const locals = local_names(body);\n const parameters = \n map(x => name_of_name(x), function_definition_parameters(expr));\n const extended_index_table =\n accumulate((s, it) => extend_environment_index_table(it, s),\n environment_index_table,\n append(reverse(locals), \n reverse(parameters)));\n add_ternary_instruction(LDF, NaN, NaN, \n length(parameters) + length(locals));\n const max_stack_size_address = insert_pointer - 3;\n const address_address = insert_pointer - 2;\n push_to_compile(make_to_compile_task(\n body, max_stack_size_address, \n address_address, extended_index_table));\n return 1;\n }\n \n function compile_sequence(expr, environment_index_table, insert_flag) {\n const statements = sequence_statements(expr);\n if (is_empty_sequence(statements)) {\n return 0;\n } else if (is_last_statement(statements)) {\n return compile(first_statement(statements), \n environment_index_table, insert_flag);\n } else {\n const m_1 = compile(first_statement(statements), \n environment_index_table, false);\n add_nullary_instruction(POP);\n const m_2 = compile(make_sequence(rest_statements(statements)), \n environment_index_table, insert_flag);\n return math_max(m_1, m_2);\n }\n }\n \n function compile_constant_declaration(expr, environment_index_table) {\n const name = constant_declaration_name(expr);\n const index = index_of(environment_index_table, name);\n const max_stack_size = compile(constant_declaration_value(expr),\n environment_index_table, false);\n add_unary_instruction(ASSIGN, index);\n add_nullary_instruction(LDCU);\n return max_stack_size;\n }\n \n // we compile away blocks by putting them in \n // applications of nullary functions:\n // { stmt } => ( () => { stmt } )()\n \n function compile_block(expr, index_table) {\n const body = block_body(expr);\n if (is_return_statement(body) ||\n (is_sequence(body) &&\n filter(is_return_statement, \n sequence_statements(body)) !== null)) {\n error(expr, \n \"current limitation: no return in try-catch allowed\");\n } else {\n return compile(\n make_application(\n make_function_definition(null, block_body(expr)),\n null),\n index_table,\n false);\n }\n }\n \n function compile_object_access(expr, environment_index_table) {\n const max_stack_size = compile(object_access_object(expr),\n environment_index_table, false);\n const idp = get_IDP(head(tail(object_access_property(expr))));\n add_unary_instruction(LDCN, idp);\n add_nullary_instruction(DOT);\n return max_stack_size + 1;\n }\n \n function compile_object_expression(expr, environment_index_table) {\n let bindings = object_expression_bindings(expr);\n const unsorted_property_names =\n map(x => head(tail(head(x))), bindings);\n const sorted_property_names =\n merge_sort(unsorted_property_names);\n // calculates the index of property name s in \n // sorted_property_names\n function record_index(s) {\n function ind(ss, i) {\n return head(ss) === s ? i : ind(tail(ss), i + 1);\n }\n return ind(sorted_property_names, 0);\n }\n // computes a unique string from the properties\n const signature =\n accumulate((s, ss) => s + \",\" + ss, \"\", sorted_property_names);\n const idr = get_IDR(signature);\n let i = 0;\n let s = length(bindings);\n let max_stack_size = 0;\n while (i < s) {\n const property_name = head(tail(head(head(bindings))));\n const idp = get_IDP(property_name);\n add_unary_instruction(LDCN, idp);\n put_index_in_record_index_table(idr, idp, record_index(property_name));\n max_stack_size = math_max(i * 2 + \n compile(tail(head(bindings)), \n environment_index_table, \n false),\n max_stack_size);\n i = i + 1;\n bindings = tail(bindings);\n }\n add_binary_instruction(RCD, s, idr);\n return max_stack_size; \n }\n \n function compile_try_catch_statement(expr, environment_index_table, insert_flag) {\n add_unary_instruction(TRY, NaN);\n const catch_address_address = insert_pointer - 1;\n const max_stack_size_1 = \n compile(try_catch_statement_try_statement(expr),\n environment_index_table, false);\n add_nullary_instruction(ENDTRY);\n let GOTO_address_address = NaN;\n\n add_unary_instruction(GOTO, NaN);\n GOTO_address_address = insert_pointer - 1;\n\n machine_code[catch_address_address] = insert_pointer;\n const catch_name = name_of_name(try_catch_statement_exception_name(expr));\n const extended_index_table = \n extend_environment_index_table(environment_index_table, catch_name);\n const max_stack_size_2 =\n compile(try_catch_statement_catch_statement(expr),\n extended_index_table, false);\n\n machine_code[GOTO_address_address] = insert_pointer;\n\n return math_max(max_stack_size_1, max_stack_size_2);\n }\n \n function compile_throw_statement(expr, environment_index_table) {\n const max_stack_size =\n compile(throw_statement_expression(expr), \n environment_index_table, false);\n add_nullary_instruction(THROW);\n return max_stack_size;\n }\n\n function compile(expr, environment_index_table, insert_flag) {\n let max_stack_size = 0;\n if (is_number(expr)) {\n add_unary_instruction(LDCN, expr);\n max_stack_size = 1;\n } else if (is_boolean(expr)) {\n add_unary_instruction(LDCB, expr); \n max_stack_size = 1;\n } else if (is_undefined_expression(expr)) {\n add_nullary_instruction(LDCU); \n max_stack_size = 1;\n } else if (is_boolean_operation(expr)) {\n max_stack_size = \n compile_boolean_operation(expr, environment_index_table);\n } else if (is_conditional_expression(expr)) {\n max_stack_size = \n compile_conditional_expression(expr, \n environment_index_table, insert_flag);\n insert_flag = false;\n } else if (is_primitive_application(expr)) {\n max_stack_size = \n compile_primitive_application(expr, environment_index_table);\n } else if (is_application(expr)) {\n max_stack_size = \n compile_application(expr, environment_index_table);\n } else if (is_function_definition(expr)) {\n max_stack_size =\n compile_function_definition(expr, environment_index_table);\n } else if (is_name(expr)) {\n add_unary_instruction(LD, index_of(environment_index_table, \n name_of_name(expr)));\n max_stack_size = 1;\n } else if (is_sequence(expr)) {\n max_stack_size =\n compile_sequence(expr, environment_index_table, insert_flag);\n insert_flag = false;\n } else if (is_constant_declaration(expr)) {\n max_stack_size =\n compile_constant_declaration(expr, environment_index_table);\n } else if (is_return_statement(expr)) {\n max_stack_size = compile(return_statement_expression(expr), \n environment_index_table, false);\n } else if (is_block(expr)) {\n max_stack_size = compile_block(expr, environment_index_table);\n } else if (is_object_expression(expr)) {\n max_stack_size = \n compile_object_expression(expr, environment_index_table);\n } else if (is_object_access(expr)) {\n max_stack_size = \n compile_object_access(expr, environment_index_table);\n } else if (is_try_catch_statement(expr)) {\n max_stack_size = \n compile_try_catch_statement(expr, environment_index_table, insert_flag);\n } else if (is_throw_statement(expr)) {\n max_stack_size = \n compile_throw_statement(expr, environment_index_table);\n } else {\n error(expr, \"unknown statement:\");\n }\n \n // handling of return\n if (insert_flag) {\n if (is_return_statement(expr)) {\n add_nullary_instruction(RTN);\n } else if (toplevel && \n (is_self_evaluating(expr) ||\n is_undefined_expression(expr) ||\n is_application(expr) ||\n is_primitive_application(expr) ||\n is_object_access(expr) || \n is_try_catch_statement(expr) ||\n is_block(expr))\n ) {\n add_nullary_instruction(RTN);\n } else {\n add_nullary_instruction(LDCU);\n max_stack_size = max_stack_size + 1;\n add_nullary_instruction(RTN);\n } \n } else {}\n return max_stack_size;\n }\n\n const program = parse(string);\n \n add_nullary_instruction(START);\n add_ternary_instruction(LDF, NaN, NaN, \n length(local_names(program)));\n const LDF_max_stack_size_address = insert_pointer - 3;\n const LDF_address_address = insert_pointer - 2;\n add_unary_instruction(CALL, 0);\n add_nullary_instruction(DONE);\n \n const locals = reverse(local_names(program));\n const program_names_index_table =\n accumulate((s, it) => extend_environment_index_table(it, s),\n make_empty_environment_index_table(),\n locals);\n \n push_to_compile(make_to_compile_task(\n program, \n LDF_max_stack_size_address, \n LDF_address_address, \n program_names_index_table));\n continue_to_compile();\n \n const div_by_zero_error_address = insert_pointer;\n \n compile(parse(\"throw {DivisionByZero: true};\"), null, false);\n\n display(IDP, \"IDP:\");\n display(IDR, \"IDR:\");\n \n return list(machine_code, record_index_table, \n div_by_zero_error_address);\n \n}",
"parse(superBlock, tokenizer) {\n throw new Error(\"parse function not implemented!\");\n }",
"parseBravaScript(code) {\n //console.log(code + '\\n Parse operation complete');\n const processedArray = {};\n const params = {};\n const steps = {};\n let currentStep = '';\n let prevStep = '';\n \n // Regexes\n const stripSpaces = /\"[^\"]*\"|\\S+/gm; // Strips spaces\n code = code.replace(/:/g,''); // Strips colons\n\n let rawCodeArray = code.match(stripSpaces);\n //console.log(rawCodeArray);\n //this.setState({parsed: processedArray.join('\\n')});\n var heaterArray = [];\n var whenArray = [];\n\n rawCodeArray.forEach((element, index) => {\n //console.log(`${element} at ${index}`);\n\n switch (element) {\n case 'param':\n // Retrieve parameters\n params[rawCodeArray[this.getChild(index)]] = rawCodeArray[this.getGrandchild(index)];\n break;\n\n case 'step':\n // Get the steps\n currentStep = rawCodeArray[this.getChild(index)];\n steps[currentStep] = {};\n\n if (prevStep !== currentStep) {\n whenArray = [];\n heaterArray = [];\n }\n \n break;\n\n case 'when':\n // Get the exit conditions\n var exitConditionParams = (this.formatSeconds(rawCodeArray[index+3])) ? \n {timeSpent : (this.formatSeconds(rawCodeArray[index+3]))} : \n {probeTemp : rawCodeArray[index+3]};\n\n exitConditionParams.then = rawCodeArray[index+5];\n\n whenArray.push(exitConditionParams); \n steps[currentStep].when = whenArray;\n break;\n\n case 'then':\n // Get the exit step\n break;\n\n case 'heater':\n // Get the heater arrays\n var lampArray = [];\n\n if (rawCodeArray[index+1] !== \"off\") {\n lampArray = [\n parseInt(rawCodeArray[index+1]),\n parseInt(rawCodeArray[index+2]),\n parseInt(rawCodeArray[index+3]),\n parseInt(rawCodeArray[index+4]),\n parseInt(rawCodeArray[index+5]),\n parseInt(rawCodeArray[index+6]),\n parseInt(rawCodeArray[index+8].split('s',1)) ? parseInt(rawCodeArray[index+8].split('s',1)) : 0\n ];\n } else {\n lampArray = [0,0,0,0,0,0,\n parseInt(rawCodeArray[index+3].split('s',1)) ? parseInt(rawCodeArray[index+3].split('s',1)) : 0\n ]\n }\n\n heaterArray.push(lampArray);\n steps[currentStep].heaters = heaterArray;\n break;\n\n case 'for':\n // Get the heater timings\n break;\n\n default:\n break;\n }\n prevStep = currentStep;\n \n });\n\n processedArray.params = params;\n processedArray.steps = steps;\n \n // Convert the JS object into JSON, display the results\n var jsonString = JSON.stringify(processedArray, undefined, 4);\n var syntaxJsonString = this.syntaxHighlight(jsonString);\n this.setState({parsed: syntaxJsonString});\n this.setState({procedureObject: processedArray});\n }",
"function Parser() {\n}",
"function read_expression(orig){\n text=orig;\n var result = null;\n var stack = [];\n while (text.length > 0){\n result = re_match(' *', text);\n text = result[1];\n\n result = re_match('\\\\(', text);\n text = result[1];\n if (result[0] !== null){\n stack.push(new LeftPar());\n continue;\n }\n\n result = re_match('[0-9]+', text);\n text = result[1];\n if (result[0] !== null){\n // NOTE: assuming int for now. add more later.\n stack.push(ConstantTextMake(parseInt(result[0])));\n continue;\n }\n\n result = read_dotted_name(text);\n text = result[1];\n if (result[0] !== null){\n stack.push(result[0]);\n continue;\n }\n\n result = re_match(',',text);\n text = result[1];\n if (result[0] !== null){\n stack.push(result[0]);\n continue;\n }\n result = re_match(OPERATORS_PATTERN,text);\n text = result[1];\n if (result[0] !== null){\n stack.push(new Operator(result[0]));\n continue;\n }\n result = re_match('\\\\)',text);\n text = result[1];\n if (result[0] !== null){\n var text_node = build_text_node(stack);\n if (text_node !== null){\n stack.push(text_node);\n }\n continue;\n }\n\n result = re_match(':', text);\n if (result[0] !== null){\n text = ':'+text;\n break;\n }\n\n }\n\n stack.unshift(new LeftPar());\n var exps = build_text_node(stack);\n if (exps.values.length !== 1){\n return [null, orig];\n }\n\n expression = exps.values[0];\n return [expression, text];\n}",
"function Node_parser(){\n}",
"function parse_and_compile(string) {\n // machine_code is array for machine instructions\n const machine_code = [];\n\n // insert_pointer keeps track of the next free place\n // in machine_code\n let insert_pointer = 0;\n\n // three insert functions (nullary, unary, binary instructions)\n function add_nullary_instruction(op_code) {\n machine_code[insert_pointer] = op_code;\n insert_pointer = insert_pointer + 1;\n }\n // unary instructions have one argument (constant or address)\n function add_unary_instruction(op_code, arg_1) {\n machine_code[insert_pointer] = op_code;\n machine_code[insert_pointer + 1] = arg_1;\n insert_pointer = insert_pointer + 2;\n }\n // binary instructions have two arguments\n function add_binary_instruction(op_code, arg_1, arg_2) {\n machine_code[insert_pointer] = op_code;\n machine_code[insert_pointer + 1] = arg_1;\n machine_code[insert_pointer + 2] = arg_2;\n insert_pointer = insert_pointer + 3;\n }\n // ternary instructions have three arguments\n function add_ternary_instruction(op_code, arg_1, arg_2, arg_3) {\n machine_code[insert_pointer] = op_code;\n machine_code[insert_pointer + 1] = arg_1;\n machine_code[insert_pointer + 2] = arg_2;\n machine_code[insert_pointer + 3] = arg_3;\n insert_pointer = insert_pointer + 4;\n }\n\n // to_compile stack keeps track of remaining compiler work:\n // these are function bodies that still need to be compiled\n let to_compile = null;\n function no_more_to_compile() {\n return is_null(to_compile);\n }\n function pop_to_compile() {\n const next = head(to_compile);\n to_compile = tail(to_compile);\n return next;\n }\n function push_to_compile(task) {\n to_compile = pair(task, to_compile);\n }\n\n // to compile a function body, we need an index table\n // to get the environment indices for each name\n // (parameters, globals and locals)\n // Each compile function returns the max operand stack\n // size needed for running the code. When compilation of\n // a function body is done, the function continue_to_compile\n // writes the max operand stack size and the address of the\n // function body to the given addresses.\n\n function make_to_compile_task(\n function_body,\n max_stack_size_address,\n address_address,\n index_table\n ) {\n return list(\n function_body,\n max_stack_size_address,\n address_address,\n index_table\n );\n }\n function to_compile_task_body(to_compile_task) {\n return list_ref(to_compile_task, 0);\n }\n function to_compile_task_max_stack_size_address(to_compile_task) {\n return list_ref(to_compile_task, 1);\n }\n function to_compile_task_address_address(to_compile_task) {\n return list_ref(to_compile_task, 2);\n }\n function to_compile_task_index_table(to_compile_task) {\n return list_ref(to_compile_task, 3);\n }\n\n // index_table keeps track of environment addresses\n // assigned to names\n function make_empty_index_table() {\n return null;\n }\n function extend_index_table(t, s) {\n return is_null(t) ? list(pair(s, 0)) : pair(pair(s, tail(head(t)) + 1), t);\n }\n function index_of(t, s) {\n return is_null(t)\n ? error(s, \"name not found:\")\n : head(head(t)) === s\n ? tail(head(t))\n : index_of(tail(t), s);\n }\n\n // a small complication: the toplevel function\n // needs to return the value of the last statement\n let toplevel = true;\n\n function continue_to_compile() {\n while (!is_null(to_compile)) {\n const next_to_compile = pop_to_compile();\n const address_address = to_compile_task_address_address(next_to_compile);\n machine_code[address_address] = insert_pointer;\n const index_table = to_compile_task_index_table(next_to_compile);\n const max_stack_size_address = to_compile_task_max_stack_size_address(\n next_to_compile\n );\n const body = to_compile_task_body(next_to_compile);\n const max_stack_size = compile(body, index_table, true);\n machine_code[max_stack_size_address] = max_stack_size;\n toplevel = false;\n }\n }\n\n function local_names(stmt) {\n if (is_sequence(stmt)) {\n const stmts = sequence_statements(stmt);\n return is_empty_sequence(stmts)\n ? null\n : append(\n local_names(first_statement(stmts)),\n local_names(make_sequence(rest_statements(stmts)))\n );\n } else {\n return is_constant_declaration(stmt)\n ? list(constant_declaration_name(stmt))\n : null;\n }\n }\n\n // compile_arguments compiles the arguments and\n // computes the maximal stack size needed for\n // computing the arguments. Note that the arguments\n // themselves accumulate on the operand stack, which\n // explains the \"i + compile(...)\"\n function compile_arguments(exprs, index_table) {\n let i = 0;\n let s = length(exprs);\n let max_stack_size = 0;\n while (i < s) {\n max_stack_size = math_max(\n i + compile(head(exprs), index_table, false),\n max_stack_size\n );\n i = i + 1;\n exprs = tail(exprs);\n }\n return max_stack_size;\n }\n\n function compile_boolean_operation(expr, index_table) {\n if (boolean_operator_name(expr) === \"&&\") {\n return compile(\n make_conditional_expression(\n first_operand(operands(expr)),\n first_operand(rest_operands(operands(expr))),\n false\n ),\n index_table,\n false\n );\n } else {\n return compile(\n make_conditional_expression(\n first_operand(operands(expr)),\n true,\n first_operand(rest_operands(operands(expr)))\n ),\n index_table,\n false\n );\n }\n }\n\n function compile_conditional_expression(expr, index_table, insert_flag) {\n const m_1 = compile(cond_expr_pred(expr), index_table, false);\n add_unary_instruction(JOF, NaN);\n const JOF_address_address = insert_pointer - 1;\n const m_2 = compile(cond_expr_cons(expr), index_table, insert_flag);\n let GOTO_address_address = NaN;\n if (!insert_flag) {\n add_unary_instruction(GOTO, NaN);\n GOTO_address_address = insert_pointer - 1;\n } else {\n }\n machine_code[JOF_address_address] = insert_pointer;\n const m_3 = compile(cond_expr_alt(expr), index_table, insert_flag);\n if (!insert_flag) {\n machine_code[GOTO_address_address] = insert_pointer;\n } else {\n }\n return math_max(m_1, m_2, m_3);\n }\n\n function compile_primitive_application(expr, index_table) {\n const op = primitive_operator_name(expr);\n const ops = operands(expr);\n const operand_1 = first_operand(ops);\n if (op === \"!\") {\n const max_stack_size = compile(operand_1, index_table, false);\n add_nullary_instruction(NOT);\n return max_stack_size;\n } else {\n const operand_2 = first_operand(rest_operands(ops));\n const op_code =\n op === \"+\"\n ? PLUS\n : op === \"-\"\n ? MINUS\n : op === \"*\"\n ? TIMES\n : op === \"/\"\n ? DIV\n : op === \"===\"\n ? EQUAL\n : op === \"<\"\n ? LESS\n : op === \"<=\"\n ? LEQ\n : op === \">\"\n ? GREATER\n : op === \">=\"\n ? GEQ\n : error(op, \"unknown operator:\");\n const m_1 = compile(operand_1, index_table, false);\n const m_2 = compile(operand_2, index_table, false);\n add_nullary_instruction(op_code);\n return math_max(m_1, 1 + m_2);\n }\n }\n\n function compile_application(expr, index_table) {\n const max_stack_operator = compile(operator(expr), index_table, false);\n const max_stack_operands = compile_arguments(operands(expr), index_table);\n add_unary_instruction(CALL, length(operands(expr)));\n return math_max(max_stack_operator, max_stack_operands + 1);\n }\n\n function compile_function_definition(expr, index_table) {\n const body = function_definition_body(expr);\n const locals = local_names(body);\n const parameters = map(\n x => name_of_name(x),\n function_definition_parameters(expr)\n );\n const extended_index_table = accumulate(\n (s, it) => extend_index_table(it, s),\n index_table,\n append(reverse(locals), reverse(parameters))\n );\n add_ternary_instruction(LDF, NaN, NaN, length(parameters) + length(locals));\n const max_stack_size_address = insert_pointer - 3;\n const address_address = insert_pointer - 2;\n push_to_compile(\n make_to_compile_task(\n body,\n max_stack_size_address,\n address_address,\n extended_index_table\n )\n );\n return 1;\n }\n\n function compile_sequence(expr, index_table, insert_flag) {\n const statements = sequence_statements(expr);\n if (is_empty_sequence(statements)) {\n return 0;\n } else if (is_last_statement(statements)) {\n return compile(first_statement(statements), index_table, insert_flag);\n } else {\n const m_1 = compile(first_statement(statements), index_table, false);\n add_nullary_instruction(POP);\n const m_2 = compile(\n make_sequence(rest_statements(statements)),\n index_table,\n insert_flag\n );\n return math_max(m_1, m_2);\n }\n }\n\n function compile_constant_declaration(expr, index_table) {\n const name = constant_declaration_name(expr);\n const index = index_of(index_table, name);\n const max_stack_size = compile(\n constant_declaration_value(expr),\n index_table,\n false\n );\n add_unary_instruction(ASSIGN, index);\n add_nullary_instruction(LDCU);\n return max_stack_size;\n }\n\n function compile(expr, index_table, insert_flag) {\n let max_stack_size = 0;\n if (is_number(expr)) {\n add_unary_instruction(LDCN, expr);\n max_stack_size = 1;\n } else if (is_boolean(expr)) {\n add_unary_instruction(LDCB, expr);\n max_stack_size = 1;\n } else if (is_undefined_expression(expr)) {\n add_nullary_instruction(LDCU);\n max_stack_size = 1;\n } else if (is_boolean_operation(expr)) {\n max_stack_size = compile_boolean_operation(expr, index_table);\n } else if (is_conditional_expression(expr)) {\n max_stack_size = compile_conditional_expression(\n expr,\n index_table,\n insert_flag\n );\n insert_flag = false;\n } else if (is_primitive_application(expr)) {\n max_stack_size = compile_primitive_application(expr, index_table);\n } else if (is_application(expr)) {\n max_stack_size = compile_application(expr, index_table);\n } else if (is_function_definition(expr)) {\n max_stack_size = compile_function_definition(expr, index_table);\n } else if (is_name(expr)) {\n add_unary_instruction(LD, index_of(index_table, name_of_name(expr)));\n max_stack_size = 1;\n } else if (is_sequence(expr)) {\n max_stack_size = compile_sequence(expr, index_table, insert_flag);\n insert_flag = false;\n } else if (is_constant_declaration(expr)) {\n max_stack_size = compile_constant_declaration(expr, index_table);\n } else if (is_return_statement(expr)) {\n max_stack_size = compile(\n return_statement_expression(expr),\n index_table,\n false\n );\n } else {\n error(expr, \"unknown expression:\");\n }\n\n // handling of return\n if (insert_flag) {\n if (is_return_statement(expr)) {\n add_nullary_instruction(RTN);\n } else if (\n toplevel &&\n (is_self_evaluating(expr) ||\n is_undefined_expression(expr) ||\n is_application(expr) ||\n is_primitive_application(expr))\n ) {\n add_nullary_instruction(RTN);\n } else {\n add_nullary_instruction(LDCU);\n max_stack_size = max_stack_size + 1;\n add_nullary_instruction(RTN);\n }\n } else {\n }\n return max_stack_size;\n }\n\n const program = parse(string);\n add_nullary_instruction(START);\n add_ternary_instruction(LDF, NaN, NaN, length(local_names(program)));\n const LDF_max_stack_size_address = insert_pointer - 3;\n const LDF_address_address = insert_pointer - 2;\n add_unary_instruction(CALL, 0);\n add_nullary_instruction(DONE);\n\n const locals = reverse(local_names(program));\n const program_names_index_table = accumulate(\n (s, it) => extend_index_table(it, s),\n make_empty_index_table(),\n locals\n );\n\n push_to_compile(\n make_to_compile_task(\n program,\n LDF_max_stack_size_address,\n LDF_address_address,\n program_names_index_table\n )\n );\n continue_to_compile();\n return machine_code;\n}",
"static parseSequence(sequence, context) {\n var e, i, isQuoted, len, output, ref, value;\n output = [];\n len = sequence.length;\n ({i} = context);\n i += 1;\n // [foo, bar, ...]\n while (i < len) {\n context.i = i;\n switch (sequence.charAt(i)) {\n case '[':\n // Nested sequence\n output.push(this.parseSequence(sequence, context));\n ({i} = context);\n break;\n case '{':\n // Nested mapping\n output.push(this.parseMapping(sequence, context));\n ({i} = context);\n break;\n case ']':\n return output;\n case ',':\n case ' ':\n case \"\\n\":\n break;\n default:\n // Do nothing\n isQuoted = ((ref = sequence.charAt(i)) === '\"' || ref === \"'\");\n value = this.parseScalar(sequence, [',', ']'], ['\"', \"'\"], context);\n ({i} = context);\n if (!isQuoted && typeof value === 'string' && (value.indexOf(': ') !== -1 || value.indexOf(\":\\n\") !== -1)) {\n try {\n // Embedded mapping?\n value = this.parseMapping('{' + value + '}');\n } catch (error) {\n e = error;\n }\n }\n // No, it's not\n output.push(value);\n --i;\n }\n ++i;\n }\n throw new ParseMore('Malformed inline YAML string ' + sequence);\n }",
"function parseCode(editor) {\n\n\n localStorage.setItem(\"code\", editor.getValue());\n const intermediateParsedCode = [];\n let errorMessage = \"\";\n\n const lines = editor.getValue().split(\"\\n\");\n\n for (let i = 0; i < lines.length; i++) {\n const value = lines[i];\n if (value.trim().length > 0) {\n try {\n const result = {};\n\n result[\"code\"] = PARSERINTERMEDIATE.parse(value);\n result[\"lineNumber\"] = i + 1;\n intermediateParsedCode.push(result);\n }\n catch (err) {\n errorMessage = errorMessage + \"intermediateParse: \" + \"(\" + (i + 1) + \", \" + err.location.start.column + \"): \" + err.message + \"\\n\";\n }\n }\n\n }\n\n //lineCartesian(0, 0, 0, 0, 0, 0, Pr, 0, 0)\n\n\n const substitutedIntermediateParsedCode = intermediateParsedCode.map((element) => {\n\n const code = element.code;\n let substitutedStatement = \"\";\n\n substitutedStatement = substitutedStatement + code.name + \"(\"\n\n const args = []\n for (let arg of code.arguments) {\n\n\n if (arg.type === \"variable\") {\n if (arg.value in definedParameters)\n args.push(definedParameters[arg.value]);\n else\n errorMessage = errorMessage + \"line \" + element.lineNumber + \": parameter \" + arg.value + \" doesn't exist\\n\";\n }\n else if (arg.type === \"REL\")\n args.push(\"R\" + arg.value)\n else if (arg.type == \"overrides\") {\n const keys = Object.keys(arg);\n\n const overrideStrings = [];\n\n for (let key of keys)\n if (key !== \"type\")\n overrideStrings.push(key + \"=\" + arg[key].value);\n\n\n args.push(\"[\" + overrideStrings.join(\",\") + \"]\");\n\n }\n else if (arg.type === \"expression\") {\n const regex = /`.*`/g;\n\n\n const variablesToReplace = arg.value.match(regex);\n\n let result = arg.value;\n\n if (variablesToReplace !== null) {\n for (let elem of variablesToReplace) {\n if (elem.slice(1, -1) in definedParameters)\n result = result.replace(elem, definedParameters[elem.slice(1, -1)]);\n else\n errorMessage = errorMessage + \"line \" + element.lineNumber + \": parameter \" + elem.slice(1, -1) + \" doesn't exist\\n\";\n\n }\n }\n\n args.push(result);\n }\n\n else if (arg.type === \"range\") {\n\n args.push(\"'\" + arg.value.join(\", \") + \"'\");\n }\n else\n args.push(arg.value);\n }\n\n substitutedStatement = substitutedStatement + args.join(\", \") + \")\";\n\n\n return { \"code\": substitutedStatement, \"lineNumber\": element.lineNumber };\n\n })\n\n\n const parsedCode = Array(lines.length).fill({});\n\n for (let intermediateLine of substitutedIntermediateParsedCode) {\n try {\n\n const parsedCodeObj = PARSER.parse(intermediateLine.code);\n parsedCodeObj[\"lineNumber\"] = intermediateLine.lineNumber;\n parsedCode[intermediateLine.lineNumber - 1] = parsedCodeObj;\n }\n catch (err) {\n errorMessage = errorMessage + \"finalParse: \" + \"(\" + (intermediateLine.lineNumber) + \", \" + err.location.start.column + \"): \" + err.message + \"\\n\";\n\n }\n }\n\n\n if (errorMessage.length > 0) {\n alert(errorMessage);\n return [];\n }\n else\n return parsedCode;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Replace repeater values in a field def with the concrete field name. | function replaceRepeaterInFieldDef(fieldDef, repeater) {
fieldDef = replaceRepeat(fieldDef, repeater);
if (fieldDef === undefined) {
// the field def should be ignored
return undefined;
}
if (fieldDef.sort && isSortField(fieldDef.sort)) {
var sort = replaceRepeat(fieldDef.sort, repeater);
fieldDef = __assign({}, fieldDef, (sort ? { sort: sort } : {}));
}
return fieldDef;
} | [
"function replaceRepeaterInFieldDef(fieldDef, repeater) {\n var field = fieldDef.field;\n if (fielddef_1.isRepeatRef(field)) {\n if (field.repeat in repeater) {\n return tslib_1.__assign({}, fieldDef, { field: repeater[field.repeat] });\n } else {\n log.warn(log.message.noSuchRepeatedValue(field.repeat));\n return null;\n }\n } else {\n // field is not a repeat ref so we can just return the field def\n return fieldDef;\n }\n}",
"function replaceRepeaterInFieldDef(fieldDef, repeater) {\n var field = fieldDef.field;\n if (fielddef_1.isRepeatRef(field)) {\n if (field.repeat in repeater) {\n return tslib_1.__assign({}, fieldDef, { field: repeater[field.repeat] });\n }\n else {\n log.warn(log.message.noSuchRepeatedValue(field.repeat));\n return null;\n }\n }\n else {\n // field is not a repeat ref so we can just return the field def\n return fieldDef;\n }\n}",
"function replaceRepeaterInFieldDef(fieldDef, repeater) {\n\t fieldDef = replaceRepeat(fieldDef, repeater);\n\t if (fieldDef === undefined) {\n\t // the field def should be ignored\n\t return undefined;\n\t }\n\t if (fieldDef.sort && sort.isSortField(fieldDef.sort)) {\n\t var sort$$1 = replaceRepeat(fieldDef.sort, repeater);\n\t fieldDef = tslib_1.__assign({}, fieldDef, (sort$$1 ? { sort: sort$$1 } : {}));\n\t }\n\t return fieldDef;\n\t}",
"function replaceRepeaterInFieldDef(fieldDef, repeater) {\n fieldDef = replaceRepeat(fieldDef, repeater);\n if (fieldDef === undefined) {\n // the field def should be ignored\n return undefined;\n }\n else if (fieldDef === null) {\n return null;\n }\n if ((0,_channeldef__WEBPACK_IMPORTED_MODULE_2__.isSortableFieldDef)(fieldDef) && (0,_sort__WEBPACK_IMPORTED_MODULE_4__.isSortField)(fieldDef.sort)) {\n const sort = replaceRepeat(fieldDef.sort, repeater);\n fieldDef = Object.assign({}, fieldDef, (sort ? { sort } : {}));\n }\n return fieldDef;\n}",
"function updateIdAndName( field ) {\n\t\t\t\tfield.id += '_' + uniqid();\n\t\t\t\tfield.name += ' ' + i18n.copy;\n\t\t\t\tif ( field.hasOwnProperty( 'fields' ) ) {\n\t\t\t\t\tfield.fields = field.fields.map( updateIdAndName );\n\t\t\t\t}\n\t\t\t\treturn field;\n\t\t\t}",
"function replacer(currentFields, scope, dictionary, s, field) {\n\tlet parts = field.split('.'),\n\t\tv = currentFields;\n\tfor (let i=0; i<parts.length; i++) {\n\t\tv = v[parts[i]];\n\t\tif (v == null) return ''; // eslint-disable-line eqeqeq\n\n\t\t//allow field values to be <Text /> nodes\n\t\tif (v && v.nodeName === Text) {\n\t\t\treturn translate(v.attributes.id, scope, dictionary, v.attributes.fields, v.attributes.plural, v.attributes.fallback);\n\t\t}\n\t}\n\t// allow for recursive {{config.xx}} references:\n\tif (typeof v==='string' && v.match(/\\{\\{/)) {\n\t\tv = template(v, currentFields);\n\t}\n\treturn v;\n}",
"function replaceRepeat(o, repeater) {\n if (isRepeatRef(o.field)) {\n if (o.field.repeat in repeater) {\n // any needed to calm down ts compiler\n return __assign({}, o, { field: repeater[o.field.repeat] });\n }\n else {\n warn(message.noSuchRepeatedValue(o.field.repeat));\n return undefined;\n }\n }\n return o;\n }",
"function applyFieldReplacements(doc, text) {\n // Find any field name replacements.\n var fieldMatches = text.match(/\\[(.*?)\\]/g);\n var updatedText = text;\n $.each(fieldMatches, function eachMatch(i, fieldToken) {\n var dataVal;\n // Cleanup the square brackets which are not part of the field name.\n var field = fieldToken.replace(/\\[/, '').replace(/\\]/, '');\n dataVal = indiciaFns.getValueForField(doc, field);\n updatedText = updatedText.replace(fieldToken, dataVal);\n });\n return updatedText;\n }",
"function replacer(s, field) {\n\tlet parts = field.split('.'),\n\t\tv = currentFields;\n\tfor (let i=0; i<parts.length; i++) {\n\t\tv = v[parts[i]];\n\t\tif (v == null) return ''; // eslint-disable-line eqeqeq\n\t}\n\t// allow for recursive {{config.xx}} references:\n\tif (typeof v==='string' && v.match(/\\{\\{/)) {\n\t\tv = template(v, currentFields);\n\t}\n\treturn v;\n}",
"function getRepeatingFieldName( fieldId, parentHtmlId ) {\n\t\tvar repeatFieldName = '';\n\t\tif ( parentHtmlId.indexOf( 'frm_section' ) > -1 ) {\n\t\t\t// The HTML id provided is the frm_section HTML id\n\t\t\tvar repeatSecParts = parentHtmlId.replace( 'frm_section_', '' ).split( '-' );\n\t\t\trepeatFieldName = 'item_meta[' + repeatSecParts[0] + '][' + repeatSecParts[1] + '][' + fieldId +']';\n\t\t} else {\n\t\t\t// The HTML id provided is the field div HTML id\n\t\t\tvar fieldDivParts = parentHtmlId.replace( 'frm_field_', '').replace( '_container', '').split('-');\n\t\t\trepeatFieldName = 'item_meta[' + fieldDivParts[1] + '][' + fieldDivParts[2] + '][' + fieldId +']';\n\t\t}\n\n\t\treturn repeatFieldName;\n\t}",
"function replacer(s, field) {\n var parts = field.split('.'),\n v = currentFields;\n for (var i = 0; i < parts.length; i++) {\n v = v[parts[i]];\n if (v == null) {return '';} // eslint-disable-line eqeqeq\n }\n // allow for recursive {{config.xx}} references:\n if (typeof v === 'string' && v.match(/\\{\\{/)) {\n v = template(v, currentFields);\n }\n return v;\n}",
"function replaceField(fld, typ) {\n $(fld).clone(true).attr('type', typ).insertAfter(fld).prev().remove();\n}",
"function replaceRepeat(o, repeater) {\n if ((0,_channeldef__WEBPACK_IMPORTED_MODULE_2__.isRepeatRef)(o.field)) {\n if (o.field.repeat in repeater) {\n // any needed to calm down ts compiler\n return Object.assign({}, o, { field: repeater[o.field.repeat] });\n }\n else {\n _log__WEBPACK_IMPORTED_MODULE_3__.warn(_log__WEBPACK_IMPORTED_MODULE_3__.message.noSuchRepeatedValue(o.field.repeat));\n return undefined;\n }\n }\n return o;\n}",
"function refreshDerivedName(nameField) {\n\n let nameFullText = \"\";\n let nameText = \"\";\n if (nameField.Title !== \"\") nameFullText += \" \" + titleCase(currentResult.result.Name.Title);\n if (nameField.Name.FirstName !== \"\") nameFullText += \" \" + titleCase(currentResult.result.Name.Name.FirstName);\n if (nameField.Name.MiddleName !== \"\") nameFullText += \" \" + titleCase(currentResult.result.Name.Name.MiddleName);\n if (nameField.Name.ExtraName !== \"\") nameFullText += \" \" + titleCase(currentResult.result.Name.Name.ExtraName);\n if (nameField.Surname !== \"\") nameFullText += \" \" + titleCase(currentResult.result.Name.Surname);\n if (nameField.Name.FirstName !== \"\") nameText += \" \" + titleCase(currentResult.result.Name.Name.FirstName);\n if (nameField.Name.MiddleName !== \"\") nameText += \" \" + titleCase(currentResult.result.Name.Name.MiddleName);\n if (nameField.Name.ExtraName !== \"\") nameText += \" \" + titleCase(currentResult.result.Name.Name.ExtraName);\n nameField.Text = nameFullText.substr(1);\n nameField.Name.Text = nameText.substr(1);\n\n return nameField;\n}",
"function getExplicitFieldReplacement(key, data) {\n if (!key.startsWith(FIELD_PREFIX)) {\n return;\n }\n const fieldName = key.substring(FIELD_PREFIX.length);\n return data.get(fieldName, '');\n}",
"_generateFieldName() {\n let cleanedCollectionName = this.linkConfig.collection._name.replace(\n /\\./g,\n '_'\n );\n let defaultFieldPrefix = this.linkName + '_' + cleanedCollectionName;\n\n switch (this.strategy) {\n case 'many-meta':\n return `${defaultFieldPrefix}_metas`;\n case 'many':\n return `${defaultFieldPrefix}_ids`;\n case 'one-meta':\n return `${defaultFieldPrefix}_meta`;\n case 'one':\n return `${defaultFieldPrefix}_id`;\n }\n }",
"function getField$1(_,ctx){if(!_.$field)return null;var k='f:'+_.$field+'_'+_.$name;return ctx.fn[k]||(ctx.fn[k]=field(_.$field,_.$name));}",
"editNameFields(field, name) {\n field === \"First name\" ? this.firstName.setValue(name) : this.lastName.setValue(name);\n }",
"function setField(selector,field,str){\n if(str == undefined){\n str = \"\";\n }\n if((field instanceof Array) || (field instanceof Object) ){ // don't append field value if it's an array or object\n selector.append(str);\n return selector;\n }\n if(field == undefined){ // if the field is undefined then simply return the selector\n return selector;\n }\n else{\n selector.append(\"<b>\" + str + \"</b>\" + \" \" + field); // append the field value to selector\n return selector;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
constructor Initialize a new instance for `PdfGridStyle` class. | function PdfGridStyle(){var _this=_super.call(this)||this;_this.gridBorderOverlapStyle=exports.PdfBorderOverlapStyle.Overlap;_this.bAllowHorizontalOverflow=false;_this.gridHorizontalOverflowType=exports.PdfHorizontalOverflowType.LastPage;return _this;} | [
"function PdfGridStyle() {\n var _this = _super.call(this) || this;\n _this.gridBorderOverlapStyle = PdfBorderOverlapStyle.Overlap;\n _this.bAllowHorizontalOverflow = false;\n _this.gridHorizontalOverflowType = PdfHorizontalOverflowType.LastPage;\n return _this;\n }",
"function PdfGrid() {\n var _this = _super.call(this) || this;\n /**\n * @hidden\n * @private\n */\n _this.gridSize = new SizeF(0, 0);\n /**\n * @hidden\n * @private\n */\n _this.isRearranged = false;\n /**\n * @hidden\n * @private\n */\n _this.pageBounds = new RectangleF();\n /**\n * @hidden\n * @private\n */\n _this.listOfNavigatePages = [];\n /**\n * @hidden\n * @private\n */\n _this.flag = true;\n /**\n * @hidden\n * @private\n */\n _this.columnRanges = [];\n /**\n * @hidden\n * @private\n */\n _this.currentLocation = new PointF(0, 0);\n /**\n * @hidden\n * @private\n */\n _this.breakRow = true;\n return _this;\n }",
"function PdfGridCellStyle() {\n var _this = _super.call(this) || this;\n /**\n * @hidden\n * @private\n */\n _this.gridCellBorders = PdfBorders.default;\n return _this;\n }",
"function PdfGridCellStyle(){var _this=_super.call(this)||this;/**\n * @hidden\n * @private\n */_this.gridCellBorders=PdfBorders[\"default\"];return _this;}",
"function PdfGrid(){var _this=_super.call(this)||this;/**\n * @hidden\n * @private\n */_this.gridSize=new SizeF(0,0);/**\n * Check the child grid is ' split or not'\n */_this.isGridSplit=false;/**\n * @hidden\n * @private\n */_this.isRearranged=false;/**\n * @hidden\n * @private\n */_this.pageBounds=new RectangleF();/**\n * @hidden\n * @private\n */_this.listOfNavigatePages=[];/**\n * @hidden\n * @private\n */_this.parentCellIndex=0;_this.tempWidth=0;/**\n * @hidden\n * @private\n */_this.breakRow=true;_this.splitChildRowIndex=-1;/**\n * The event raised on `begin cell lay outing`.\n * @event\n * @private\n */ //public beginPageLayout : Function;\n/**\n * The event raised on `end cell lay outing`.\n * @event\n * @private\n */ //public endPageLayout : Function;\n_this.hasRowSpanSpan=false;_this.hasColumnSpan=false;_this.isSingleGrid=true;return _this;}",
"init() {\n this.prepareGrid();\n this.configureCells();\n }",
"function Grid() {\n _classCallCheck(this, Grid);\n\n this.setup();\n }",
"function Grid() {\n $.jqplot.ElemContainer.call(this);\n // Group: Properties\n \n // prop: drawGridlines\n // wether to draw the gridlines on the plot.\n this.drawGridlines = true;\n // prop: background\n // css spec for the background color.\n this.background = '#fffdf6';\n // prop: borderColor\n // css spec for the color of the grid border.\n this.borderColor = '#999999';\n // prop: borderWidth\n // width of the border in pixels.\n this.borderWidth = 2.0;\n // prop: shadow\n // wether to show a shadow behind the grid.\n this.shadow = true;\n // prop: shadowAngle\n // shadow angle in degrees\n this.shadowAngle = 45;\n // prop: shadowOffset\n // Offset of each shadow stroke from the border in pixels\n this.shadowOffset = 1.5;\n // prop: shadowWidth\n // width of the stoke for the shadow\n this.shadowWidth = 3;\n // prop: shadowDepth\n // Number of times shadow is stroked, each stroke offset shadowOffset from the last.\n this.shadowDepth = 3;\n // prop: shadowAlpha\n // Alpha channel transparency of shadow. 0 = transparent.\n this.shadowAlpha = '0.07';\n this._left;\n this._top;\n this._right;\n this._bottom;\n this._width;\n this._height;\n this._axes = [];\n // prop: renderer\n // Instance of a renderer which will actually render the grid.\n this.renderer = $.jqplot.CanvasGridRenderer;\n this.rendererOptions = {};\n this._offsets = {top:null, bottom:null, left:null, right:null};\n }",
"function PdfGridRowStyle() {\n //\n }",
"function Grid() {\n this.setup();\n }",
"constructor() {\n this.doc = new TextDocument();\n this.cdp = this.doc;\n this.cTable = undefined;\n this._setupStyles();\n var left = DirectionType.left;\n var right = DirectionType.right;\n TableCellStyle.defaultPadding = {\n left: '1.5mm',\n right: '1.5mm',\n }\n Paragraph.defaultStyle = this.standardStyle;\n }",
"function PdfGridLayoutFormat(baseFormat) {\n var _this = this;\n if (typeof baseFormat === 'undefined') {\n _this = _super.call(this) || this;\n }\n else {\n _this = _super.call(this, baseFormat) || this;\n }\n return _this;\n }",
"function Grid() {\n $.jqplot.ElemContainer.call(this);\n // Group: Properties\n \n // prop: drawGridlines\n // wether to draw the gridlines on the plot.\n this.drawGridlines = true;\n // prop: gridLineColor\n // color of the grid lines.\n this.gridLineColor = '#cccccc';\n // prop: gridLineWidth\n // width of the grid lines.\n this.gridLineWidth = 1.0;\n // prop: background\n // css spec for the background color.\n this.background = '#fffdf6';\n // prop: borderColor\n // css spec for the color of the grid border.\n this.borderColor = '#999999';\n // prop: borderWidth\n // width of the border in pixels.\n this.borderWidth = 2.0;\n // prop: drawBorder\n // True to draw border around grid.\n this.drawBorder = true;\n // prop: shadow\n // wether to show a shadow behind the grid.\n this.shadow = true;\n // prop: shadowAngle\n // shadow angle in degrees\n this.shadowAngle = 45;\n // prop: shadowOffset\n // Offset of each shadow stroke from the border in pixels\n this.shadowOffset = 1.5;\n // prop: shadowWidth\n // width of the stoke for the shadow\n this.shadowWidth = 3;\n // prop: shadowDepth\n // Number of times shadow is stroked, each stroke offset shadowOffset from the last.\n this.shadowDepth = 3;\n // prop: shadowColor\n // an optional css color spec for the shadow in 'rgba(n, n, n, n)' form\n this.shadowColor = null;\n // prop: shadowAlpha\n // Alpha channel transparency of shadow. 0 = transparent.\n this.shadowAlpha = '0.07';\n this._left;\n this._top;\n this._right;\n this._bottom;\n this._width;\n this._height;\n this._axes = [];\n // prop: renderer\n // Instance of a renderer which will actually render the grid,\n // see <$.jqplot.CanvasGridRenderer>.\n this.renderer = $.jqplot.CanvasGridRenderer;\n // prop: rendererOptions\n // Options to pass on to the renderer,\n // see <$.jqplot.CanvasGridRenderer>.\n this.rendererOptions = {};\n this._offsets = {top:null, bottom:null, left:null, right:null};\n }",
"function Grid() {\n $.jqplot.ElemContainer.call(this);\n // Group: Properties\n\n // prop: drawGridlines\n // wether to draw the gridlines on the plot.\n this.drawGridlines = true;\n // prop: gridLineColor\n // color of the grid lines.\n this.gridLineColor = '#cccccc';\n // prop: gridLineWidth\n // width of the grid lines.\n this.gridLineWidth = 1.0;\n // prop: background\n // css spec for the background color.\n this.background = '#fffdf6';\n // prop: borderColor\n // css spec for the color of the grid border.\n this.borderColor = '#999999';\n // prop: borderWidth\n // width of the border in pixels.\n this.borderWidth = 2.0;\n // prop: drawBorder\n // True to draw border around grid.\n this.drawBorder = true;\n // prop: shadow\n // wether to show a shadow behind the grid.\n this.shadow = true;\n // prop: shadowAngle\n // shadow angle in degrees\n this.shadowAngle = 45;\n // prop: shadowOffset\n // Offset of each shadow stroke from the border in pixels\n this.shadowOffset = 1.5;\n // prop: shadowWidth\n // width of the stoke for the shadow\n this.shadowWidth = 3;\n // prop: shadowDepth\n // Number of times shadow is stroked, each stroke offset shadowOffset from the last.\n this.shadowDepth = 3;\n // prop: shadowColor\n // an optional css color spec for the shadow in 'rgba(n, n, n, n)' form\n this.shadowColor = null;\n // prop: shadowAlpha\n // Alpha channel transparency of shadow. 0 = transparent.\n this.shadowAlpha = '0.07';\n this._left;\n this._top;\n this._right;\n this._bottom;\n this._width;\n this._height;\n this._axes = [];\n // prop: renderer\n // Instance of a renderer which will actually render the grid,\n // see <$.jqplot.CanvasGridRenderer>.\n this.renderer = $.jqplot.CanvasGridRenderer;\n // prop: rendererOptions\n // Options to pass on to the renderer,\n // see <$.jqplot.CanvasGridRenderer>.\n this.rendererOptions = {};\n this._offsets = {top:null, bottom:null, left:null, right:null};\n }",
"function PdfGridLayoutFormat(baseFormat){return _super.call(this,baseFormat)||this;}",
"constructor(gridSize, gridColumns, gridRows, gridMin) {\n this.gridSize = gridSize\n this.gridColumns = gridColumns\n this.gridRows = gridRows\n this.gridMin = gridMin\n this.rects = []\n this.currentRects = [{\n x: 0,\n y: 0,\n w: this.gridColumns,\n h: this.gridRows\n }]\n }",
"constructor(gridSize, gridColumns, gridRows, gridMin) {\n this.gridSize = gridSize\n this.gridColumns = gridColumns\n this.gridRows = gridRows\n this.gridMin = gridMin\n this.rects = []\n this.currentRects = [{ x: 0, y: 0, w: this.gridColumns, h: this.gridRows }]\n }",
"initGridCanvas() {\n this.gridCanvas = createCanvas('grid');\n this.containerElement.appendChild(this.gridCanvas);\n }",
"function PdfGridColumn(grid){/**\n * The `width` of the column.\n * @default 0\n * @private\n */this.columnWidth=0;this.grid=grid;}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set speed of both wheels where 1 is the maximum speed and 1 is the maximum in reverse. | setSpeedCoeff(left, right) {
this.leftWheel = this.servoStop + (this.servoSpeedSpread * left) * this.leftServoCoeff;
this.rightWheel = this.servoStop + (this.servoSpeedSpread * right) * this.rightServoCoeff;
} | [
"setMotorSpeed () {\n var tickDelta = this.tickDelta()\n\n switch (true) {\n case (tickDelta <= 3):\n this.motor.speed = SPEEDS.SINGLE_KERNEL\n break\n case (tickDelta > 3 && tickDelta <= 8):\n //this.motor.speed = SPEEDS.VERY_SLOW\n this.motor.speed = SPEEDS.SLOW\n break\n case (tickDelta > 8 && tickDelta <= 16):\n //this.motor.speed = SPEEDS.SLOW\n this.motor.speed = SPEEDS.FAST\n break\n case (tickDelta > 16 && tickDelta <= 32):\n //this.motor.speed = SPEEDS.MEDIUM\n this.motor.speed = SPEEDS.VERY_FAST\n break\n case (tickDelta > 32 && tickDelta <= 48):\n this.motor.speed = SPEEDS.VERY_FAST\n break\n case (tickDelta > 48):\n this.motor.speed = SPEEDS.VERY_FAST\n break\n }\n }",
"set speedMultiplier(value) {}",
"function setSpeed(side, speed) {\n\n const scaled = speed/100 * 82 + 18\n\n if (side == LEFT) {\n pwm.setPwm(0, 0, Math.round(dutyCycle * scaled / 100));\n } else if (side == RIGHT) {\n pwm.setPwm(1, 0, Math.round(dutyCycle * scaled / 100));\n }\n}",
"set wheelDampingRate(value) {}",
"function setSpeed() {}",
"function setspeed (motora, motorb)\n{\n motorspeed = {a:motora, b:motorb};\n}",
"setRightSpeed(speed) {\n this.rightSpeed = speed;\n }",
"function setSpeed(speed){\n for (m in motors){\n ms.setMotorSpeed(motors[m], speed);\n }\n //currentSpeed = speed;\n console.log(\"Speed set to\" + speed);\n }",
"set speedUS(speed) {\r\n this.speed = speed * 1.6;\r\n }",
"function resetSpeed(){\n MAX_SPEED = STARTING_SPEED;\n }",
"changeSpeed() {\n\n // ternary operator to choose from +1 and -1\n var sign = Phaser.Math.Between(0, 1) == 0 ? -1 : 1;\n\n // random number between -gameOptions.rotationVariation and gameOptions.rotationVariation\n var variation = Phaser.Math.FloatBetween(-gameOptions.rotationVariation, gameOptions.rotationVariation);\n\n // new rotation speed\n this.newRotationSpeed = (this.currentRotationSpeed + variation) * sign;\n\n // setting new rotation speed limits\n this.newRotationSpeed = Phaser.Math.Clamp(this.newRotationSpeed, -gameOptions.maxRotationSpeed, gameOptions.maxRotationSpeed);\n }",
"function set_motor_speed(index, value)\r\n{\r\n\tif (value == 0) {\r\n\t\tstop_motor(index);\r\n\t}\r\n\tvar prev_state = motor_states[index];\r\n\tif (value > 0 && prev_state != \"f\")\t\t\tset_motor_forward(index);\r\n\telse if (value < 0 && prev_state != \"r\")\tset_motor_reverse(index);\r\n\tsend_motor_noreply(\"p \" + index + \" \" + Math.abs(value));\r\n}",
"setSpeed(speed) {\n this.speed = speed;\n }",
"setSpeed() {\n var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;\n\n if (!this._lottie) {\n return;\n }\n\n this._lottie.setSpeed(value);\n }",
"set targetSpeed(targetSpeed) {\n this._targetSpeed = targetSpeed;\n if (targetSpeed === this.speed) {\n this.acceleration = 0;\n }\n else {\n const direction = Math.sign(targetSpeed - this.speed);\n this.acceleration = direction * (targetSpeed === 0 ? MAX_DECEL : MAX_ACCEL);\n }\n }",
"setDownSpeed(speed) {\n this.downSpeed = speed;\n }",
"function setSlowMovement() {\r\n setSpeed(stateConstants.SPEED.SLOW);\r\n}",
"setSpeed(value) {\n\t\tthis.moveSpeed = value;\n\t\tthis.speed = Math.round((6.66666666667 * GAME_SPEED) / this.moveSpeed);\n\t}",
"motionRight() {\n this.speed = this.maxSpeed;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update informations about a previously saved Jenkins | function updateJenkins(jenkins_id,jenkins_name, jenkins_url){
var db = getDatabase();
var res = "";
db.transaction(function(tx) {
var rs = tx.executeSql('UPDATE jenkins_data SET jenkins_name=?, jenkins_url=? WHERE id=?;', [jenkins_name,jenkins_url,jenkins_id]);
if (rs.rowsAffected > 0) {
res = "OK";
} else {
res = "Error";
}
}
);
return res;
} | [
"function saveJenkinsJobs(event) {\r\n\r\n var jenkinsJobsToSave = [];\r\n var selectedJenkinsJobs = document.getElementById(\"selectedJenkinsJobs\").getElementsByTagName(\"li\");\r\n\r\n var length = selectedJenkinsJobs.length;\r\n for (var i = 0; i < length; i++) {\r\n var jobId = selectedJenkinsJobs[i].id;\r\n var liString = 'li-';\r\n if (jobId.startsWith(liString)) {\r\n jobId = jobId.substring(liString.length);\r\n }\r\n var jobName = getJenkinsJobFromIndex(jobId);\r\n jenkinsJobsToSave.push(jobName);\r\n }\r\n\r\n var jenkinsSetup = getJenkinsSetupFromPageFields();\r\n jenkinsSetup.jobs = jenkinsJobsToSave;\r\n var background = chrome.extension.getBackgroundPage();\r\n background.buildbot.refreshJobs(jenkinsSetup);\r\n\r\n chrome.storage.local.set({\r\n jenkinsJobs: jenkinsJobsToSave,\r\n }, function () {\r\n // Update status to let user know options were saved.\r\n var status = document.getElementById('configJobsStatus');\r\n status.textContent = 'Jenkins Jobs saved.';\r\n setTimeout(function () {\r\n status.textContent = '';\r\n }, 6000);\r\n });\r\n}",
"function doUpdate() {\n $ionicDeploy.update().then(function(res) {\n logger.success('Ionic Deploy: Update Success! ', res);\n }, function(err) {\n logger.error('Ionic Deploy: Update error! ', err);\n }, function(prog) {\n logger.info('Ionic Deploy: Progress... ', prog);\n });\n }",
"updateProject() {\n console.log(chalk.blue('We are now making the final touches!'))\n const status = new Spinner(chalk.white('Please wait...'))\n status.start()\n setTimeout(() => {\n fs.readFile('package.json', 'utf-8', (err, data) => {\n if (err) throw err\n\n const newValue = data\n .replace(/\"name\": \"wasa-boilerplate\"/g, `\"name\": \"${this.name}\"`)\n .replace(/\"author\": \"Wait And See Agency\"/g, `\"author\": \"${username()}\"`)\n\n fs.writeFile('package.json', newValue, 'utf-8', (error) => {\n if (error) {\n throw error\n } else {\n status.stop()\n console.log(chalk.green('Project install complete, you\\'re all set !'))\n }\n })\n })\n }, 1000)\n }",
"update() {\n Spark.put(`/settings/${Spark.teamsPrefix}/${this.team.id}/name`, this.form)\n .then(() => {\n Bus.$emit('updateTeam');\n Bus.$emit('updateTeams');\n });\n }",
"function save_edits(){\n\n\t\t\t////////////////////////////////////\n\t\t\t// Saves data from different tabs //\n\t\t\t////////////////////////////////////\n\n\t\t\t//Basic\n\t\t\tvar oldMachName = $(\"#settingsModal\").data(\"currentMachName\");\n\t\t\tvar newMachName = $(\"#settingsMachineNameBox\").val();\n\t\t\tvar plat = $(\"#settingsPlatformSelect option:selected\").val();\n\t\t\tvar os = $(\"#settingsOsSelect option:selected\").val();\n\t\t\t//find the right box and change the content in it\n\t\t\tvar machToEditIndex;\n\t\t\t$.each(window.boxes, function(index, value){\n\t\t\t\tif(oldMachName === value.name){\n\t\t\t\t\tmachToEditIndex = index;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t});\n\t\t\twindow.boxes[machToEditIndex][\"name\"] = newMachName;\n\t\t\twindow.boxes[machToEditIndex][\"platform\"] = plat;\n\t\t\twindow.boxes[machToEditIndex][\"os_version\"] = os;\n\t\t\trender_machine_cards();\n\n\n\t\t}",
"function updateRecentlyEditedComponents() {\n\n }",
"save() {\n\t\t\tupdate(bs => {\n\t\t\t\tStorage.local.put('commander', bs);\n\t\t\t\treturn bs;\n\t\t\t});\n\t\t}",
"function updateSolveStatus(newStatus) {\n let key = `${document.title}/status`;\n window.localStorage.setItem(key, newStatus);\n}",
"commit() {\r\n const newAngularJsonContent = JSON.stringify(this.workspace, null, 2);\r\n this.host.overwrite('/angular.json', newAngularJsonContent);\r\n }",
"_saveChanges(e) {\n const { envPath, obj, model, t } = this.props;\n const { currentEnvVars } = this.state;\n\n e.preventDefault();\n\n const patches = currentEnvVars.getPatches(envPath);\n const promise = k8sPatch(model, obj, patches);\n this.handlePromise(promise).then((res) => {\n this.setState({\n currentEnvVars: new CurrentEnvVars(res, currentEnvVars.isContainerArray, envPath),\n dirty: false,\n errorMessage: null,\n stale: false,\n success: t('public~Successfully updated the environment variables.'),\n });\n });\n }",
"function getLastStableBuildDetails(jenkinsUrl,buildNumber,jobName){\n\n var xmlhttp = new XMLHttpRequest();\n var url = jenkinsUrl+\"/job/\"+jobName+\"/\"+buildNumber+\"/api/json\";\n\n //console.log(\"Get Job build info for build: \"+buildNumber+\" to url: \"+url)\n\n var lastBuildDetails;\n\n xmlhttp.onreadystatechange = function() {\n if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {\n fillLastStableBuildModel(xmlhttp.responseText);\n }\n }\n xmlhttp.open(\"GET\", url, true);\n xmlhttp.send(); \n }",
"_setJenkinsConfig(newConfig) {\n config.jenkinsConfig = newConfig;\n }",
"function updateAdministration() {\n\n\n\n\t}",
"function saveInfo(){\n this.start();\n this.then(function(){\n this.thenOpen(node_js_collector,{\n method: \"POST\",\n data: JSON.stringify(patch_note_info),\n headers: {\n \"Content-Type\":\"application/json\"\n }\n },function(response){\n this.echo(\"POSTED: \");\n this.echo(JSON.stringify(response));\n this.exit();\n });\n });\n this.run();\n}",
"function saveJobsInfo(data) {\r\n let query = `UPDATE ${table.SUBMIT_LIST} \r\n SET job_names=\"${data.jobList}\", job_levels=\"${data.levelList}\" \r\n WHERE uid=${data.userId}`\r\n\r\n return new Promise((resolve, reject) => {\r\n db.query(query, (error, result, fields) => {\r\n if (error) {\r\n reject({ message: message.INTERNAL_SERVER_ERROR })\r\n } else {\r\n visitModel.checkVisitSession(db, data.userId, 0).then((result) =>{\r\n resolve()\r\n })\r\n }\r\n })\r\n })\r\n}",
"save() {\n\t\tconst tools = this.state.tools;\n\n\t\t// If tool has valid ID then PUT, no ID do a POST (new record)\n\t\tconst method = tools._id ? 'put' : 'post';\n\n\t\t// PUT URL : POST URL\n\t\tconst url = tools._id ? `${BASE_URL}/${tools._id}` : BASE_URL;\n\t\taxios[method](url, tools).then((resp) => {\n\t\t\t// resp.data returns the data returned from the webservice\n\t\t\tconst list = this.getUpdatedList(resp.data);\n\t\t\tthis.setState({ tools: initialState.tools, list });\n\t\t});\n\t}",
"function update() {\n updateGym(id, name, address1, address2, town, county, openingHours)\n .then(() => {\n alert(\"Gym Information updated!\");\n })\n .catch((error) => {\n alert(error.message);\n });\n }",
"_updateProject() {\n const projectJsonFile = path.resolve(this.outputFolder, \"package.json\");\n const projectJson = JSON.parse(fs.readFileSync(projectJsonFile));\n projectJson.name = this.projectFolder;\n const userInfo = os.userInfo();\n projectJson.author = `${userInfo.username} <${userInfo}@localhost>`;\n\n fs.writeFileSync(projectJsonFile, JSON.stringify(projectJson, null, 2));\n }",
"updateWorkspace () {\n this.setState({dialogWorkspace: false});\n Utils.setItem(\"@workspace\", this.state.workspace);\n this.props.updateWorkspace(this.state.workspace);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the product data percent & names | function calculatePercentsAndNames() {
// Get local storage products
var products = JSON.parse(localStorage.getItem('products'));
var percents = [];
var names = [];
// Calculate the percents for each product
for (var i = 0; i < products.length; i++) {
var percent = Math.floor((products[i].clicks / products[i].timesShown) * 100);
if (isNaN(percent)) {
percent = 0;
}
percents.push(percent);
names.push(products[i].name);
}
return [percents, names];
} | [
"function calcPercentage(){\n for (var i = 0; i < allProducts.length; i++) {\n var percentage;\n if (allProducts[i].views === 0){\n percentage = 0;\n }\n else {\n percentage = parseInt(Math.floor((allProducts[i].clicks / allProducts[i].views) * 100));\n }\n return percentage;\n }\n}",
"function allGenderProportion(){\n\tmaleProportion = ((allMale/allData)*100).toFixed(2);\n\tfemaleProportion = ((allFemale/allData)*100).toFixed(2);\n\tdocument.getElementById(\"maleCount\").innerHTML = maleProportion + \"%\";\n\tdocument.getElementById(\"femaleCount\").innerHTML = femaleProportion + \"%\";\n}",
"percentageSupplied () {\n return this.collectedSupply / this.yearDemand\n }",
"function set_percentage()\n\t\t{\n\t\tfor (var each in $scope.DATA)\n\t\t\t{\n\t\t\tvar ar = $scope.DATA[each];\n\t\t\tvar total = 0;\n\t\t\t//calc total\n\t\t\tar.map(function(el){total = total+el['totalOrders']});\n\t\t\tar.map(function(el)\n\t\t\t\t{\n\t\t\t\tif (!total){el['percentage'] =0;return false;};\n\t\t\t\tel['percentage'] = $filter('number')((el['totalOrders']/total)*100,1);\n\t\t\t\t})\n\t\t\t}\n\t\t}",
"calculatePercentages()\n {\n // 1. loop thru each element in array of expenses \n this.data.allItems['exp'].forEach(function(cur) {\n cur.calcPercentage(this.data.totals.inc);\n });\n }",
"getRainProbability(data) {\n if (data.precipProbability === 0) {\n return 'dry';\n }\n return (data.precipProbability * 100).toFixed(0) + '%';\n }",
"function add_percent_to_obj(data) {\n\tlet total = 0;\n\tfor (let key in data) {\n\t\ttotal += data[key];\n\t}\n\n\tfor (let key in data) {\n\t\tdata[key] = data[key] + ' (' + (data[key] / total * 100).toFixed(1) + '%' + ')';\n\t}\n\treturn data;\n}",
"getPercentage(index, data) {\n let output = (data.fitArray[index]/data.total)*100;\n return output;\n }",
"function calcPercentageClicked() {\n for (var product in ProductItem.productItemArray) {\n var currentObject = ProductItem.productItemArray[product];\n if (currentObject.numTimesDisplayed === 0) {\n currentObject.percentageClicked = 0;\n } else {\n currentObject.percentageClicked = 100 * (currentObject.numTimesClicked / currentObject.numTimesDisplayed);\n }\n }\n}",
"function deprication_sum(price, percent) {\n price = price/100\n return price*percent\n}",
"eggPercentage():Number {\n // get eggs in stock\n let eggs = 0;\n let percentage = 0;\n if(this.eggs instanceof Array && this.batchInformation) {\n let { length } = this.eggs;\n if(length >= 1) {\n eggs = this.eggs[(this.eggs.length - 1)][0][4];\n if(eggs) {\n percentage = Math.round(eggs/(this.batchInformation.population[0].population) * 100);\n }\n }\n }\n\n return percentage;\n }",
"calcPercent(propUnitPrice, setUnitPrice) {\n let npcRange = this.npc.type[this.typeToBuy];\n console.log(`npc range is ${npcRange}`);\n let percentOfBudget = Phaser.Math.Between(npcRange[0], npcRange[1]);\n console.log(`seventy five percent of budget is ${percentOfBudget}`);\n let budget = percentOfBudget/.75;\n console.log(`budget is ${budget}`);\n let percent = setUnitPrice/budget;\n console.log(`percent is ${percent}`)\n return percent;\n\n }",
"function percentagePhD( data ){\n return( (_.reduce(\n _.pluck( _.where( data, {Level: \"Doctoral\"} ), \"AWARDS\"),//list for _.reduce\n function( memo, awardNum){ //iteratee for _.reduce\n return( memo + awardNum);\n }) / totalDegrees(data) * 100) //after total number of doctoral is found, divide by total and * 100\n );\n}",
"function scaleDataPercent(data){\n var sum = 0;\n for(var d in data){\n sum += data[d].percent;\n }\n for(var d in data){\n data[d].percent = parseInt(((data[d].percent / sum) * 100).toFixed(2));\n }\n return data;\n}",
"function percentageReport() {\n return ([(((allRocks().length)/(totalCells()))*100).toFixed(2), ((allCurrents().length/(totalCells()))*100).toFixed(2)]);\n }",
"function mainPercentOff(){\n var retailPrice = $(\".productView-price .price.price--rrp.retail-price\").text().replace(\"$\",\"\");\n var salePrice = $(\".productView-price .price.price--withoutTax\").text().replace(\"$\",\"\");\n var percent = (retailPrice - salePrice) / retailPrice * 100;\n var percentOffFinal = Math.round(percent);\n $(\".percent-saved\").text('('+percentOffFinal+'%)');\n }",
"function someStatistics(products) {\n const count = products.length;\n let statsHash = {\n //count: products.length,\n volumeMin: products[0].volume,\n volumeAverage: 0,\n volumeMax: products[0].volume,\n\n priceMin: products[0].price,\n priceAverage: 0,\n priceMax: products[0].price,\n\n weightMin: products[0].weight,\n weightAverage: 0,\n weightMax: products[0].weight,\n\n priceVolumeRatioMin: products[0].priceVolumeRatio,\n priceVolumeRatioAverage: 0,\n priceVolumeRatioMax: products[0].priceVolumeRatio\n };\n\n products = products.reduce((hash, product) => {\n hash.volumeAverage += product.volume;\n hash.volumeMin = Math.min(hash.volumeMin, product.volume);\n hash.volumeMax = Math.max(hash.volumeMax, product.volume);\n \n hash.priceAverage += product.price;\n hash.priceMin = Math.min(hash.priceMin, product.price);\n hash.priceMax = Math.max(hash.priceMax, product.price);\n \n hash.weightAverage += product.weight;\n hash.weightMin = Math.min(hash.weightMin, product.weight);\n hash.weightMax = Math.max(hash.weightMax, product.weight);\n \n hash.priceVolumeRatioAverage += product.priceVolumeRatio;\n hash.priceVolumeRatioMin = Math.min(hash.priceVolumeRatioMin, product.priceVolumeRatio);\n hash.priceVolumeRatioMax = Math.max(hash.priceVolumeRatioMax, product.priceVolumeRatio);\n\n return hash;\n }, statsHash);\n\n statsHash.volumeAverage = Math.round(statsHash.volumeAverage / count);\n statsHash.priceAverage = Math.round(statsHash.priceAverage / count);\n statsHash.weightAverage = Math.round(statsHash.weightAverage / count);\n statsHash.priceVolumeRatioAverage = statsHash.priceVolumeRatioAverage / count;\n statsHash.count = count;\n\n return statsHash;\n}",
"function calcMetaDataField_percent(data,params,field)\n{\n // only use the first target & targetVal\n\n var target = field.target[0]; // these are always arrays coming in\n var targetVals = field.targetVal;\n\n var dataTarget = normalizeDataItem(data,target);\n var percent = 0;\n\n if(dataTarget.length) {\n\tvar count = 0;\n\tfor(var i=0; i < dataTarget.length; i++) {\n\t for(var j=0; j < targetVals.length; j++) {\n\t\tif(dataTarget[i] == targetVals[j]) {\n\t\t count++;\n\t\t break; // don't allow double counting if the same targetVal\n\t\t} // is used multiple times\n\t }\n\t}\n\tpercent = (count/dataTarget.length) * 100;\n }\n\n return(percent);\n}",
"function percent(totaleDati){\n var fatturato = 0; //Variabile vuota pari a 0, dove aggiungero il risulato e riporterò fuori con il return\n for (var i = 0; i < totaleDati.length; i++) {\n var datoSingolo = totaleDati[i];\n var valoreDato = datoSingolo.amount;\n fatturato += parseInt(valoreDato);\n }\n return fatturato;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create cost plus quote tool. Simplified to only Fuel and Wage Expense consideration. | function costPlusQuote() {
if (distanceInMiles >= 100) {
quote = (wageExpense + fuelExpense) * margins[3];
return quote
} else if (distanceInMiles >= 500) {
quote = (wageExpense + fuelExpense) * margins[2];
return quote
} else if (distanceInMiles >= 1000) {
quote = (wageExpense + fuelExpense) * margins[1];
return quote
} else {
quote = (wageExpense + fuelExpense) * margins[0];
return quote
}
} | [
"function createComputedCost(grid) {\n const computed = document.createElement(\"span\");\n computed.classList.add(\"computed-cost\");\n const computedCost = document.createTextNode(\"\");\n computed.appendChild(computedCost);\n grid.appendChild(computed);\n}",
"function building(cost, exp) {\n\t\tcost *= 4 * mult('Resourceful', -5);\n\t\treturn log(income(true) * trimps() * (exp - 1) / cost + 1) / log(exp);\n\t}",
"function calcCost() {\r\n\t\t\t\tvar TSA = calcTSA();\r\n\t\t\t\tvar Time = calcTime();\r\n\t\t\t\tvar glue = calcGlue();\r\n\t\t\t\treturn ((TSA*Time*Glue)*1.1)\r\n\t\t\t}",
"calculateCost() {\n let costs = ezmoney.fromNumber(0, 'EUR', 2, ezmoney.roundUp);\n if (!util_1.isNullOrUndefined(this.cameraman)) {\n const cameramanCosts = ezmoney.fromNumber(this.cameraman.calculateCost(), 'EUR', 2, ezmoney.roundUp);\n costs = ezmoney.add(costs, cameramanCosts);\n }\n if (!util_1.isNullOrUndefined(this.equipmentItems) && this.equipmentItems.length !== 0) {\n this.equipmentItems.forEach(item => {\n const equipmentItemCosts = ezmoney.fromNumber(item.calculateCost(), 'EUR', 2, ezmoney.roundUp);\n costs = ezmoney.add(costs, equipmentItemCosts);\n });\n }\n return ezmoney.toNumber(costs);\n }",
"function createHueristicCost(grid) {\n const hueristic = document.createElement(\"span\");\n hueristic.classList.add(\"hueristic-cost\");\n const hueristicCost = document.createTextNode(\"\");\n hueristic.appendChild(hueristicCost);\n grid.appendChild(hueristic);\n}",
"function CostObject(taxCA, taxME, shipping, price_liveAmerican, price_tailAmerican, price_liveRock, price_tailRock) {\n this.shipping = shipping;\n this.taxCA = taxCA;\n this.taxME = taxME;\n this.price_liveAmerican = price_liveAmerican;\n this.price_tailAmerican = price_tailAmerican;\n this.price_liveRock = price_liveRock;\n this.price_tailRock = price_tailRock;\n}",
"calculateAdvancedCost() {\n var scale = this.isMonthly ? 1 : 1 / 12; // divide by 12 if the user input yearly numbers \n this.cost = parseInt( ( parseInt(this.monthlyRentCost) + parseInt(this.homeInsuranceCost) + parseInt(this.utilitiesCost)) * scale);\n // this.cost = this.cost.toFixed(2);\n\n this.eventAggregator.publish('update', {name: 'Housing', value: this.cost});\n }",
"function CostTce() {\n\tthis.name = \"\";\n\tthis.linkIds = []; // String array\n\tthis.conditions = []; // TceConditon array\n\tthis.tollStructures = []; // TollStructure array\n}",
"function finalCostCalculation() {\n\tfinalCost = base + memoryParseCost + strogeParseCost + deliveryParseCost;\n\ttotalCost.innerText = finalCost;\n\tfinalPrice.innerText = finalCost;\n}",
"function displayAddNewTaxiCost() {\n \n }",
"function Cost(gameResource, equip) {\n preBuy();\n game.global.buyAmt = 1;\n var price = parseFloat(getBuildingItemPrice(gameResource, equip.Resource, equip.Equip, 1));\n if (equip.Equip) price = Math.ceil(price * (Math.pow(1 - game.portal.Artisanistry.modifier, game.portal.Artisanistry.level)));\n postBuy();\n return price;\n}",
"function food(name,type,region,product,nutrient_content,importance,crop_type){\r\n //identifying objects and there attributes\r\n this.name = name;\r\n this.type = type;\r\n this.region = region;\r\n this.product = product;\r\n this.nutrient_content=nutrient_content;\r\n this.importance=importance;\r\n this.crop_type=crop_type;\r\n //defining an object and a method\r\n this.cost= function price(a){\r\n //allows the value of the function to be revealed out of the function\r\n return this.name + ' costs ' + a + 'a kilogram';\r\n }\r\n \r\n\r\n}",
"function Tool(toolName, toolType, energyCost, count, toolTipWidth = 128, toolTipHeight = 16) {\n Item.call(this, toolName, toolType, count, toolTipWidth, toolTipHeight);\n\n this.energyCost = energyCost;\n}",
"function printCost(shape,size,metal) {\n\t\t\t\n\t\t// Nested if statements to determine cost for shape, size and metals\n\t\tvar silver_price_grm = 2.80;\n\t\tvar bronze_price_grm = .25;\n\n\t\t// CIRCLE\n\t\tif(shape == \"circle\") {\n\t\t\t//(pendantCost for small silver circle\n\t\t\tif (size == \"sm\") {\n\t\t\t\tif (metal == \"silver\") {\n\t\t\t\t\tpendantCost = 20;\n\t\t\t\t} \n\t\t\t\t//(pendantCost for small bronze circle\n\t\t\t\telse if (metal == \"bronze\") {\n\t\t\t\t\tpendantCost = 12;\n\t\t\t\t}\n\t\t\t} \n\n\t\t\t//(pendantCost for medium silver circle\n\t\t\telse if (size == \"md\") {\n\t\t\t\tif (metal == \"silver\") {\n\t\t\t\t\tpendantCost = 25;\n\t\t\t\t} \n\t\t\t\t//(pendantCost for medium bronze circle\n\t\t\t\telse if (metal == \"bronze\") {\n\t\t\t\t\tpendantCost = 15;\t\n\t\t\t\t}\n\t\t\t} \n\n\t\t\t//(pendantCost for large silver circle\n\t\t\telse if (size ==\"lg\") {\n\t\t\t\tif (metal == \"silver\") {\n\t\t\t\t\tpendantCost = 30;\n\t\t\t\t} \n\t\t\t\t//(pendantCost for large bronze circle\n\t\t\t\telse if (metal == \"bronze\") {\n\t\t\t\t\tpendantCost = 18;\n\t\t\t\t}\n\t\t\t}\n\t\t} \n\n\t\t//(pendantCost for small silver square\n\t\telse if (shape == \"square\") {\n\t\t\tif(size == \"sm\") {\n\t\t\t\tif (metal == \"silver\") {\n\t\t\t\t\tpendantCost = 20;\n\t\t\t\t} \n\t\t\t\t//(pendantCost for small bronze square\n\t\t\t\telse if (metal == \"bronze\") {\n\t\t\t\t\tpendantCost = 12;\n\t\t\t\t}\n\t\t\t} \n\n\t\t\t//(pendantCost for medium silver square\n\t\t\telse if (size == \"md\") {\n\t\t\t\tif (metal == \"silver\") {\n\t\t\t\t\tpendantCost = 25;\n\t\t\t\t} \n\t\t\t\t//(pendantCost for medium bronze square\n\t\t\t\telse if (metal == \"bronze\") {\n\t\t\t\t\tpendantCost = 15;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//(pendantCost for large silver square\n\t\t\telse if (size ==\"lg\") {\n\t\t\t\tif (metal == \"silver\") {\n\t\t\t\t\tpendantCost = 30;\n\t\t\t\t} \n\t\t\t\t//(pendantCost for large bronze square\n\t\t\t\telse if (metal == \"bronze\") {\n\t\t\t\t\tpendantCost = 18;\n\t\t\t\t}\n\t\t\t}\n\t\t} \n\n\t\telse if (shape == \"heart\") {\n\t\t\t//(pendantCost for small silver heart\n\t\t\tif(size == \"sm\") {\n\t\t\t\tif (metal == \"silver\") {\n\t\t\t\t\tpendantCost = 20;\n\t\t\t\t} \n\t\t\t\t//(pendantCost for small bronze heart\n\t\t\t\telse if (metal == \"bronze\") {\n\t\t\t\t\tpendantCost = 12;\t\t\t\t\n\t\t\t\t}\n\t\t\t} \n\t\t\t//(pendantCost for medium silver heart\n\t\t\telse if (size == \"md\") {\n\t\t\t\tif (metal == \"silver\") {\n\t\t\t\t\tpendantCost = 25;\t\t\t\t\n\t\t\t\t} \n\t\t\t\t//(pendantCost for medium bronze heart\n\t\t\t\telse if (metal == \"bronze\") {\n\t\t\t\t\tpendantCost = 15;\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t\t//(pendantCost for large silver heart\n\t\t\telse if (size ==\"lg\") {\n\t\t\t\tif (metal == \"silver\") {\n\t\t\t\t\tpendantCost = 30;\n\t\t\t\t}\n\t\t\t\t//(pendantCost for large bronze heart\n\t\t\t\telse if (metal == \"bronze\") {\n\t\t\t\t\tpendantCost = 18;\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Call the round penny function\n\t\tpendantCost = roundPenny(pendantCost);\n\n\t\t// Print the cost of the pendant\n\t\t$('#output').html(pendantCost);\n\n\t\t// Pass selected pendant cost value to id on paypal form\n\t\t$('#paypalPrice').val(pendantCost);\n\n\t}",
"function createProductCostNode(itemCost) {\n var div = document.createElement(\"div\")\n div.setAttribute(\"class\", \"productCost\")\n var span = document.createElement(\"span\")\n span.appendChild(document.createTextNode(\"$\"+itemCost))\n div.appendChild(span)\n return div\n}",
"function ChargeTool(charge) {\n this.charge = charge;\n}",
"function CalculateLineCost(linenum) {\n var product_code, category_code, product, i, j, k, m, n;\n var heightin, widthin; \n var wsheight; // the height of the printed sign in inches\n var wswidth; // the width of the printed sign in inches\n var printwidth; // the width of the media in inches\n var printlength; // the length of the media in inches\n var wsperimeter; // the linear dimension of the sign perimeter in ft\n var wsarea; // the area of one side of the sign in sqft\n var quantity; // the number of signs to print\n var waste_sqft_per_sign; // material wasted per sign (if optimum quantity was purchased)\n var cost_discountable;\n var cost_nondiscountable;\n var cost_waste;\n var cost_options;\n var sign_sqfootage;\n var printed_sqfootage;\n var waste_sqfootage;\n var total_sqfootage;\n var line_discountable_cost;\n var a1;\n var popup, input_items, the_option_id, data, the_option_name; \n var varcost, fixedcost, equation, extra_days, option_set, laminate_product_code;\n var array_length, item_found, option_cost; \n var cost_per_piece, cost_line_total; \n var number_of_options;\n var laminate_print_width, laminate_print_length; \n var laminate_cost_discountable, laminate_cost_nondiscountable, laminate_cost_waste;\n\n // COMPUTE SQUARE FOOTAGE, WASTE AND PERIMETER AMOUNTS\n // ===================================================\n\n product_code = document.getElementById(\"pr\" + linenum).value\n category_code = document.getElementById(\"cat\" + linenum).value\n\n // Identify the array index for that product.\n product = 0;\n for (j = 1; j <= numberOfProducts; j++) {\n if (productArray[j][CodeIdx] == product_code) {\n product = j;\n break;\n }\n }\n if (product == 0) {\n ClearDetails(linenum);\n return;\n }\n\n // if product is a fixture (e.g. stand, accessory or frame) no printing is involved\n // so calculations are much simpler\n if (!isPrintableCategory(category_code)) {\n quantity = parseFloat(document.getElementById(\"quantity\" + linenum).value);\n\n //This is the discountable portion of the fixture cost \n cost_discountable = parseFloat(productArray[product][CostDiscIdx]) * quantity;\n discountable_cost_global += cost_discountable;\n\n //This is the non-discountable portion of the fixture cost \n cost_nondiscountable = parseFloat(productArray[product][CostNonIdx]) * quantity;\n nondiscountable_cost_global += cost_nondiscountable;\n\n //Line cost.\n line_discountable_cost = cost_discountable;\n cost_line_total = cost_discountable + cost_nondiscountable;\n cost_per_piece = cost_line_total / quantity;\n\n // Save information in hidden fields so they get submitted to PHP by the form and saved in database.\n a1 = new ToFmt(0.0);\n document.getElementById(\"wastearea\" + linenum).value = strltrim(a1.fmtF(9,3));\n a1 = new ToFmt(0.0);\n document.getElementById(\"wastecost\" + linenum).value = strltrim(a1.fmtF(9,2));\n a1 = new ToFmt(cost_per_piece);\n document.getElementById(\"piececost\" + linenum).innerHTML = \"$\" + strltrim(a1.fmtF(9,2));\n a1 = new ToFmt(cost_line_total);\n document.getElementById(\"totlinecost\" + linenum).innerHTML = \"$\" + strltrim(a1.fmtF(9,2));\n a1 = new ToFmt(line_discountable_cost);\n document.getElementById(\"lindct\" + linenum).value = \"$\" + strltrim(a1.fmtF(9,2));\n a1 = new ToFmt(0.0); \n document.getElementById(\"sqft\" + linenum).value = strltrim(a1.fmtF(9,3));\n a1 = new ToFmt(0.0); \n document.getElementById(\"printedarea\" + linenum).value = strltrim(a1.fmtF(9,3));\n a1 = new ToFmt(0.0); \n document.getElementById(\"inkcost\" + linenum).value = strltrim(a1.fmtF(9,3));\n\n return(0.0); // returning printed square footage of 0 for fixture\n }\n\n heightin = document.getElementById(\"heighti\" + linenum);\n widthin = document.getElementById(\"widthi\" + linenum);\n wsheight = parseFloat(heightin.value);\n wswidth = parseFloat(widthin.value);\n printwidth = productArray[product][PrintWidthIdx];\n printlength = productArray[product][PrintLengthIdx];\n\n // Work out perimeter (in linear feet) and square footage of the printed sign\n wsperimeter = ((wsheight + wswidth) * 2) / 12;\n wsarea = (wsheight/12) * (wswidth/12);\n\n // Find out how many signs to print.\n quantity = parseFloat(document.getElementById(\"quantity\" + linenum).value);\n sign_sqfootage = wsarea * quantity;\n printed_sqfootage = sign_sqfootage; // gets doubled below, if sign is printed on back side (BS option)\n\n // Calculate amount of material wasted (in sq ft) per sign. Assume for this calculation\n // that the customer ordered the optimum optimum multiples of their sign.\n waste_sqft_per_sign = ComputeWaste(printlength, printwidth, wsheight, wswidth);\n waste_sqfootage = waste_sqft_per_sign * quantity * parseFloat(wastefactor);\n waste_sqfootage_test = waste_sqft_per_sign * quantity * 1.0;\n\n // Work out total square footage of media used (sign + waste).\n total_sqfootage = sign_sqfootage + waste_sqfootage;\n\n//alert(\"printed sqft = \" + sign_sqfootage + \" wasted sqft = \" + waste_sqfootage + \" true waste = \" + waste_sqfootage_test + \" total sqft = \" + total_sqfootage);\n\n\n // COMPUTE COST OF MEDIA AND PRINTING\n // ==================================\n\n //This is the discountable portion of the media cost \n cost_discountable = parseFloat(productArray[product][CostDiscIdx]) * sign_sqfootage;\n discountable_cost_global += cost_discountable;\n\n //This is the non-discountable portion of the media cost \n cost_nondiscountable = parseFloat(productArray[product][CostNonIdx]) * sign_sqfootage;\n nondiscountable_cost_global += cost_nondiscountable;\n\n //Waste cost of media.\n cost_waste = parseFloat(productArray[product][CostWasteIdx]) * waste_sqfootage;\n waste_cost_global += cost_waste;\n\n //This is the cost of the ink. It is non-discountable and system-wide (not product-specific).\n cost_ink = inkcost * sign_sqfootage;\n ink_cost_global += cost_ink;\n\n//alert(\"costs: discountable = \" + cost_discountable + \" non-discountable = \" + cost_nondiscountable + \" waste = \" + cost_waste + \" ink = \" + cost_ink);\n\n // COMPUTE COST OF FINISHING OPTIONS\n // =================================\n\n cost_options = 0;\n number_of_options = 0;\n\n // we treat lamination separately from other options because it is priced like a medium\n cost_lamination = 0; \n cost_lamination_discountable = 0; \n\n // Identify each finishing option which has been requested.\n popup = document.getElementById(\"finishing-popup-\" + linenum);\n input_items = popup.getElementsByTagName(\"input\");\n for (i = 0; i < input_items.length; i++) {\n if (input_items[i].checked) {\n number_of_options++;\n the_option_id = input_items[i].id; // e.g. AF-X-1\n // Find the_option_name, which is the_option_id with the -linenum removed e.g. AF-X\n data = the_option_id.split('-');\n the_option_name = data[0] + \"-\" + data[1];\n\n // Go through finishingOptionArray and find that option and its values;\n for (k = 1; k <= numberOfFinishingOptions; k++) {\n if (finishingOptionArray[k][FinOptCodeIdx] == the_option_name) {\n varcost = parseFloat(finishingOptionArray[k][FinOptVariableCostIdx]);\n fixedcost = parseFloat(finishingOptionArray[k][FinOptFixedCostIdx]);\n equation = finishingOptionArray[k][FinOptUnitsIdx];\n extra_days = finishingOptionArray[k][FinOptExtraTimeIdx];\n batch_day = finishingOptionArray[k][FinOptBatchDayIdx];\n option_set = finishingOptionArray[k][FinOptSetIdx];\n laminate_product_code = finishingOptionArray[k][FinOptLaminateProductCodeIdx];\n break;\n }\n }\n\n // Keep track of all finishing options used in this order, and if they require extra days.\n array_length = optionsRequestedArray.length;\n item_found = false;\n for (m = 0; m < array_length; m++) {\n if (the_option_name == optionsRequestedArray[m][0]) item_found = true;\n }\n if (!item_found) {\n optionsRequestedArray[m] = new Array();\n optionsRequestedArray[m][0] = the_option_name;\n optionsRequestedArray[m][1] = extra_days;\n optionsRequestedArray[m][2] = batch_day;\n //alert(\"Finishing option \" + the_option_name + \" requires \" + extra_days + \" extra days. Batch day is \" + batch_day);\n }\n\n // Calculate cost of that option and add to the total cost of options.\n switch (equation) {\n case \"PF\": // Perimeter Footage\n option_cost = ((wsperimeter * varcost) + fixedcost) * quantity;\n cost_options += option_cost;\n //alert(\"Line: \" + linenum + \"\\n\\nOption: \" + the_option_name + \"\\n\\nEquation: PF\\n\\nPerimeter: \" + wsperimeter + \"\\n\\nVariable: \" + varcost + \"\\n\\nFixed: \" + fixedcost + \"\\n\\nQuantity: \" + quantity + \"\\n\\nCOST: \" + option_cost);\n break;\n case \"SF\": // Square Footage\n\t if (option_set == 'LAMINATION') \n\t {\n\n\t // If this option uses a laminate product (.e.g it's not a -X option)...\n laminate = 0;\n\t if (laminate_product_code.length > 0) \n\t {\n\t // Get the costing information from the product array for the selected laminate.\n // Identify the array index for that product.\n for (n = 1; n <= numberOfProducts; n++) {\n if (productArray[n][CodeIdx] == laminate_product_code) {\n\t\t laminate = n;\n break;\n }\n }\n }\n\t // Read out the information.\n\t if ((laminate <= numberOfProducts) && (laminate != 0))\n\t {\n\t /*\n\t laminate_print_width = productArray[laminate][PrintWidthIdx];\n\t laminate_print_length = productArray[laminate][PrintLengthIdx];\n\t laminate_cost_discountable = productArray[laminate][CostDiscIdx];\n\t laminate_cost_nondiscountable = productArray[laminate][CostNonIdx];\n\t laminate_cost_waste = productArray[laminate][CostWasteIdx];\n\t alert(\n\t\t\"Lamination option \" + the_option_name + \n\t\t\" uses product \" + laminate_product_code + \n\t\t\" which is \" + laminate_print_width + \n\t\t\" x \" + laminate_print_length + \n\t\t\" and disc = \" + laminate_cost_discountable + \n\t\t\" nondisc = \" + laminate_cost_nondiscountable + \n\t\t\" waste = \" + laminate_cost_waste);\n\t\t*/\n\n\t // This is the discountable portion of the laminate cost \n\t // TO DO: cost out double-sided laminate (right now we don't notice if it's double-sided)\n laminate_cost_discountable = parseFloat(productArray[laminate][CostDiscIdx]) * sign_sqfootage;\n discountable_cost_global += laminate_cost_discountable;\n\n // This is the non-discountable portion of the laminate cost \n\t // TO DO: cost out double-sided laminate (right now we don't notice if it's double-sided)\n laminate_cost_nondiscountable = parseFloat(productArray[laminate][CostNonIdx]) * sign_sqfootage;\n nondiscountable_cost_global += laminate_cost_nondiscountable;\n \n // Waste cost of laminate. \n\t // TO DO: Calculate the actual waste for the laminate instead of assuming it is same as product waste.\n\t // (Laminate and product may have different widths.)\n laminate_cost_waste = parseFloat(productArray[laminate][CostWasteIdx]) * waste_sqfootage;\n waste_cost_global += laminate_cost_waste;\n\n\t\t/*\n\t\talert(\"Lamination option \" + the_option_name + \n\t\t \" uses product \" + laminate_product_code + \n\t\t \" Nondiscountable = \" + laminate_cost_nondiscountable +\n\t\t \" Discountable = \" + laminate_cost_discountable +\n\t\t \" Waste = \" + laminate_cost_waste);\n\t */\n\n\t\t// We track the lamination cost separately from other finishing costs, because it has disc/nondisc portions.\n\t\toption_cost = 0;\n cost_options += option_cost;\n lamination_cost = laminate_cost_discountable + laminate_cost_nondiscountable + laminate_cost_waste;\n cost_lamination += lamination_cost; \n cost_lamination_discountable += laminate_cost_discountable; \n\t }\n\t }\n\t else\n\t {\n option_cost = ((wswidth/12 * wsheight/12 * varcost) + fixedcost) * quantity;\n cost_options += option_cost;\n //alert(\"Line: \" + linenum + \"\\n\\nOption: \" + the_option_name + \"\\n\\nEquation: SF\\n\\nWidth (ft): \" + wswidth/12 + \"\\n\\nLength (ft): \" + wsheight/12 + \"\\n\\nVariable: \" + varcost + \"\\n\\nFixed: \" + fixedcost + \"\\n\\nQuantity: \" + quantity + \"\\n\\nCOST: \" + option_cost);\n\t }\n break;\n case \"BS\": // Back Side\n // Charge the printing and ink cost for the back side, but not the media cost.\n // Don't multiply cost_disc + cost_non + cost_ink by quantity, as they already include quantity in them.\n option_cost = ((cost_discountable + cost_nondiscountable) * varcost) + (fixedcost * quantity) + cost_ink;\n cost_options += option_cost;\n printed_sqfootage = printed_sqfootage * 2.0;\n //alert(\"Line: \" + linenum + \"\\n\\nOption: \" + the_option_name + \"\\n\\nEquation: BS\" + \"\\n\\nDiscountable Cost: \" + cost_discountable + \"\\n\\nNon-discountable Cost: \" + cost_nondiscountable + \"\\n\\nVariable: \" + varcost + \"\\n\\nFixed: \" + fixedcost + \"\\n\\nQuantity: \" + quantity + \"\\n\\nCOST: \" + option_cost);\n break;\n case \"EA\": // Each\n // Calculate the number of (fixed) and the cost of (variable) an item added to a sign. \n option_cost = fixedcost * varcost * quantity;\n cost_options += option_cost;\n //alert(\"Line: \" + linenum + \"\\n\\nOption: \" + the_option_name + \"\\n\\nEquation: EA\\n\\nVariable: \" + varcost + \"\\n\\nFixed: \" + fixedcost + \"\\n\\nQuantity: \" + quantity + \"\\n\\nCOST: \" + option_cost);\n break;\n default:\n alert(\"The order page could not identify how to price one of the finishing items you selected on line \" + linenum + \". Please call us at (604) 881-0363 to let us know this has happened so that we can manually quote your order and fix the order page. We apologize for the inconvenience.\")\n break;\n } // end switch\n\n } // end of if that option is checked\n\n } // end of for all options\n\n options_cost_global += cost_options;\n\n // TO DO: Check whether this variable gets used for calculations later. May be able to delete it or zero it out.\n //line_discountable_cost = cost_discountable + cost_options; \n line_discountable_cost = cost_discountable + cost_lamination_discountable; \n\n // COMPUTE COST OF MEDIA AND PRINTING\n // ==================================\n\n //Line cost.\n cost_line_total = cost_discountable + cost_nondiscountable + cost_waste + cost_options + cost_ink + cost_lamination;\n cost_per_piece = cost_line_total / quantity;\n\n if (isPrintableCategory(category_code) && (category_code != 'GFLOOR') && (number_of_options == 0)) {\n ie8_alert_global = true;\n }\n\n // Save information in hidden fields so they get submitted to PHP by the form and saved in database.\n a1 = new ToFmt(waste_sqfootage);\n document.getElementById(\"wastearea\" + linenum).value = strltrim(a1.fmtF(9,3));\n a1 = new ToFmt(cost_waste);\n document.getElementById(\"wastecost\" + linenum).value = strltrim(a1.fmtF(9,2));\n a1 = new ToFmt(cost_ink);\n document.getElementById(\"inkcost\" + linenum).value = strltrim(a1.fmtF(9,2));\n a1 = new ToFmt(cost_per_piece);\n document.getElementById(\"piececost\" + linenum).innerHTML = \"$\" + strltrim(a1.fmtF(9,2));\n a1 = new ToFmt(cost_line_total);\n document.getElementById(\"totlinecost\" + linenum).innerHTML = \"$\" + strltrim(a1.fmtF(9,2));\n a1 = new ToFmt(line_discountable_cost);\n document.getElementById(\"lindct\" + linenum).value = \"$\" + strltrim(a1.fmtF(9,2));\n a1 = new ToFmt(sign_sqfootage); \n document.getElementById(\"sqft\" + linenum).value = strltrim(a1.fmtF(9,3));\n a1 = new ToFmt(printed_sqfootage); \n document.getElementById(\"printedarea\" + linenum).value = strltrim(a1.fmtF(9,3));\n\n /*\n alert(\n \"CALCULATE LINE COST\\n\\nTotal Sq.Ft.: \" + total_sqfootage + \"\\n\" +\n \"Sign Sq.Ft.:\" + sign_sqfootage + \"\\n\" +\n \"Printed Sq.Ft.:\" + printed_sqfootage + \"\\n\" +\n \"Waste Sq.Ft.:\" + waste_sqfootage + \"\\n\" +\n \"Material Cost(Disc):\" + cost_discountable + \"\\n\" +\n \"Material Cost(Non-Disc):\" + cost_nondiscountable + \"\\n\" +\n \"Waste Cost:\" + cost_waste + \"\\n\" +\n \"Option Cost:\" + cost_options \n );\n */\n\n return(printed_sqfootage);\n }",
"function createBuyOrder() {\n logger.info('Calculate price and amount for Buy');\n\n TRADE.api_query('trades', {\n \"pair\": CURRENCY_PAIR\n }, (res) => {\n // Orders statistics\n res = JSON.parse(res);\n\n let getPricesByPeriod = _.reduce(res[CURRENCY_PAIR], function(result, value) {\n let condition = getPassedTime(parseFloat(value.date)) < AVG_PRICE_PERIOD * 60;\n if (condition) result.push(parseFloat(value.price));\n return result;\n }, []);\n\n let avgPrice = _.sum(getPricesByPeriod) / getPricesByPeriod.length;\n\n let myNeedPrice = avgPrice - avgPrice * (STOCK_FEE + PROFIT);\n let myAmount = SPENDING_LIMIT / myNeedPrice;\n\n logger.warn('Buy info: ', JSON.stringify({ avgPrice, myNeedPrice, myAmount }, null, 2));\n\n TRADE.api_query('pair_settings', {}, (res) => {\n let quantity = JSON.parse(res)[CURRENCY_PAIR].min_quantity;\n\n if (myAmount >= quantity) {\n logger.info('Creating BUY order');\n\n TRADE.api_query('order_create', {\n 'pair': CURRENCY_PAIR,\n 'quantity': myAmount,\n 'price': myNeedPrice,\n 'type': 'buy'\n }, (res) => {\n res = JSON.parse(res);\n if (res.result === true && _.isEmpty(res.error)) logger.info(`Buy order created. id: ${res.order_id}`);\n else logger.error('Something went wrong, got error when try to buy');\n wait();\n });\n } else {\n logger.warn('WARN. Have no money to create Buy Order');\n wait();\n }\n });\n });\n}",
"calculateAdvancedTaxCost() {\n var scale = this.isMonthly ? 1 : 1 / 12; // divide by 12 if the user input yearly numbers\n this.cost = parseInt( ( parseInt(this.stateTaxCost) + parseInt(this.federalTaxCost) + parseInt(this.otherTaxCost)) * scale);\n // this.cost = this.cost.toFixed(2);\n\n this.eventAggregator.publish('update', {name: 'Taxes', value: this.cost});\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write a function to check number is Armstrong or not. Test Cases : ``` Input 1: 153 Output: The 153 is Armstrong. Input 2: 11 Output: The 11 is not Armstrong. ``` | function Armstrong(number){
let digit=0;
for(i=0;i<number.length;i++){
digit += Number(number[i]*number[i]*number[i]);
}
if(digit == number){
return "Armstrong";
}
else{
return "not Armstrong";
}
} | [
"isArmstrong() {\n\n\t\tvar num = prompt(\"Enter a number\");\n\t\tvar input_num = parseInt(num);\n\t\tvar numLength = num.length;\n\t\tvar sum = 0;\n\t\tfor(var i = 0; i < numLength; i++)\n\t\t{\n\t\t\tvar container = 1;\n\t\t\tvar int_num = parseInt(num.charAt(i));\n\t\t\tfor(var j = 0; j < numLength; j++)\n\t\t\t{\n\t\t\t\tcontainer = container * int_num;\n\t\t\t}\n\t\t\tsum = sum + container;\n\t\t}\n\t\tif(input_num == sum) {\n\t\t\tdocument.write(sum + \" is Armstrong Number\");\n\t\t}\n\t\telse {\n\t\t\tdocument.write(input_num + \" is not Armstrong Number\");\n\t\t}\n\t}",
"function isArmstrong(num)\r\n{\r\n\tn = parseInt(num);\r\n\tsum = 0;\r\n\twhile(n > 0)\r\n\t{\r\n\t\tmod = n % 10;\r\n\t\tsum = sum+mod*mod*mod;\r\n\t\tn = parseInt(n/10);\r\n\t}\r\n\tif(sum==num)\r\n\t\treturn(\"Armstrong\");\r\n\telse\r\n\t\treturn(\"Not Armstrong\");\r\n\t\r\n}",
"function isArmstrong(number) {\n\treturn digitCubesSum(number) == number;\n}",
"function isArmstrongNumber(n) {\n let sum = 0; // holds sum of nth power digits\n const strArr = n.toString().split(\"\"); // convert number to string array\n const nthPower = strArr.length; // exponent\n\n // loop strArr and sum exponents of the digits\n // note: still string array so convert to numbers using Number()\n for (let i = 0; i < strArr.length; i++) {\n // console.log(Number(strArr[i]));\n sum = sum + Math.pow(Number(strArr[i]), nthPower);\n }\n // compare if Armstrong number or not\n if (sum === n) {\n return true;\n } else {\n return false;\n }\n}",
"function armstr()\r\n{\r\nvar arm=0,a,b,c,d,num;\r\nnum=Number(document.getElementById(\"no_input\").value);\r\n\r\ntemp=num;\r\nwhile(temp>0)\r\n{\r\na=temp%10;\r\ntemp=parseInt(temp/10);\r\narm=arm+a*a*a;\r\n}\r\nif(arm==num)\r\n{\r\nalert(\"Armstrong number\");\r\n}\r\nelse\r\n{\r\nalert(\"Not Armstrong number\");\r\n}\r\n}",
"function armstrong_number(num){\n let r,sum = 0,temp;\n temp = num;\n while(num > 0){\n r = num % 10;\n sum = sum+(r*r*r);\n num = Math.floor(num/10);\n }\n num = temp;\n if(temp === sum){\n console.log(`${num} is an armstrong number`);\n } else {\n console.log(`${num} is not an armstrong number`);\n }\n}",
"function getArmstrongNumber(n) {\n let sumOfCubesOfDigits = 0;\n let strN = String(n);\n\n for (let myChar of strN) {\n sumOfCubesOfDigits += Math.pow(parseInt(myChar), 3);\n }\n\n if (sumOfCubesOfDigits === n) {\n return `${n} is an Armstrong number`;\n } else {\n return `${n} is NOT an Armstrong number`;\n }\n}",
"function armstrong(num) {\n let square = 0;\n let array = [],\n n;\n let temp = num;\n for (i = 0; i < 3; i++) {\n n = num % 10;\n array.push(n);\n num = Math.floor(num / 10);\n }\n array.reverse();\n for (let i = 0; i < array.length; i++) {\n square = square + (array[i] * array[i] * array[i])\n }\n if (temp === square) {\n return 'Number is Amstrong'\n } else {\n return 'Number not armstrong';\n }\n}",
"function armstrongChk(userNum){\n\n let armstNum=0;\n\n if(isNaN(userNum)===false) {\n\n userNum = userNum.toString();\n }\n \n for (i=0 ; i<userNum.length ; i++) {\n\n armstNum += Math.pow(parseInt(userNum.charAt(i)),userNum.length);\n \n }\n \n\n if (armstNum === parseInt(userNum)) {\n\n return true;\n }else {\n\n return false;\n }\n}",
"function findArmstrongs(range) {\n\tfor (let j = 0; j < range; j++) {\n\t\tif (isArmstrong(j)) {\n\t\t\tconsole.log(j + \" is an Armstrong number.\");\n\t\t}\n\t}\n}",
"function checkArmStrong(num){\n\tvar sum = 0;\n\n\tfor (var i = 0; i < num.length; i++){\n\t\tvar cubes = cube(parseInt(num[i], 10));\n\t\tsum += cubes;\n\t}\n\tconsole.log(sum);\n\n\tif (sum === parseInt(num)){\n\t\tdisplay.textContent = \"This is an ArmStrong number\";\n\t\tdisplay.style.backgroundColor = 'red';\n\t}else{\n\t\tdisplay.textContent = \"This is not an ArmStrong number\";\n\t\tdisplay.style.backgroundColor = 'red';\n\t}\n}//end of function checkArmStrong",
"function identifyArmstrongNumbers(num1, num2) {\n let armstrongNumbers = [];\n\n for (let i = num1; i<num2+1; i++) {\n let d1 = Math.floor(i/10000);\n let d2 = Math.floor(i/1000%10);\n let d3 = Math.floor(i/100%10);\n let d4 = Math.floor(i%100/10);\n let d5 = Math.floor(i%10);\n \n let q = Number(i.toString().length);\n\n if ((Math.pow(d1, q) + Math.pow(d2, q) + Math.pow(d3, q) + Math.pow(d4, q) + Math.pow(d5, q)) === Number(`${d1}${d2}${d3}${d4}${d5}`)) {\n armstrongNumbers.push(i);\n }\n }\n\n return armstrongNumbers;\n}",
"function findArmstrongNumbers(num1, num2) {\n // num1 and num2 are Numberslet ans = [];\n const Armstrong = n => {\n let arr = n.toString().split(\"\").map(el => parseInt(el))\n let sumn = 0;\n for (let i = 0; i <= arr.length - 1; i++) {\n sumn += arr[i] ** arr.length;\n }\n return sumn;\n }\n for(let idx = num1; idx <= num2; idx++){\n let anumber = Armstrong(idx);\n if(anumber === idx){\n ans.push(idx)\n }\n }\n return ans\n}",
"function three_digit_armstrong_number()\r\n{\r\n console.log(\"_________________________________________\");\r\n console.log(\"Find the armstrong numbers of 3 digits :\");\r\n for (var i = 1; i < 10; ++i)\r\n {\r\n for (var j = 0; j < 10; ++j)\r\n {\r\n for (var k = 0; k < 10; ++k)\r\n {\r\n var pow = (Math.pow(i,3) + Math.pow(j,3) + Math.pow(k,3));\r\n var plus = (i * 100 + j * 10 + k);\r\n if (pow == plus)\r\n {\r\n\r\n console.log(pow);\r\n }\r\n }\r\n }\r\n }\r\n }",
"function identifyArmstrongNumbers(num1, num2) {\n let armstrongNumbers = [];\n\n for (let i = num1; i <= num2; i++) {\n let digits = i.toString().split('');\n let sum = 0;\n digits.forEach(function(digit) {\n let product = 1;\n for (let x = 0; x < digits.length; x++) {\n product *= digit;\n }\n sum += product;\n });\n if (sum === i) {\n armstrongNumbers.push(i);\n }\n }\n\n return armstrongNumbers;\n}",
"function identifyArmstrongNumbers(num1, num2) {\n\n let armstrongNumbers = [];\n \n for(let num=num1; num<=num2; num++) {\n \n let sum = 0;\n let strNum = num.toString();\n let power = strNum.length;\n \n for(let i=0; i<power; i++)\n sum += Math.pow(strNum[i].valueOf(), power);\n \n if(sum === num)\n armstrongNumbers.push(num);\n }\n\n return armstrongNumbers;\n}",
"function mod10_validation(num){\r\n if( !num ) return false;\r\n num = num.replace(/-/g,'');\r\n \r\n var calc, i, check, checksum = 0, r = [2,1]; // alternating routing table (cnofigured for credit cards)\r\n \r\n // iterate on all the numbers in 'num'\r\n for( i=num.length-1; i--; ){\r\n calc = num.charAt(i) * r[i % r.length];\r\n // handle cases where it's a 2 digits number\r\n calc = ((calc/10)|0) + (calc % 10);\r\n checksum += calc;\r\n }\r\n check = (10-(checksum % 10)) % 10; // make sure to get '0' if checksum is '10'\r\n checkDigit = num % 10;\r\n \r\n return check == checkDigit;\r\n }",
"function identifyArmstrongNumbers(num1, num2) {\n if (0 <= num1 || num2 < 10) {\n for (a = 0; a < 10; a++) {\n let power1 = Math.pow(a, 1);\n let sum = a;\n if (power1 == sum) {\n console.log(power1);\n }\n }\n }\n\n if (10 <= num1 || num2 < 100) {\n for (a = 0; a < 10; a++) {\n for (b = 0; b < 10; b++) {\n let power2 = Math.pow(a, 2) + Math.pow(b, 2);\n let sum2 = a * 10 + b;\n if (power2 == sum2) {\n console.log(power2);\n }\n }\n }\n }\n\n if (100 <= num1 || num2 < 1000) {\n for (a = 0; a < 10; a++) {\n for (b = 0; b < 10; b++) {\n for (c = 0; c < 10; c++) {\n let power3 = Math.pow(a, 3) + Math.pow(b, 3) + Math.pow(c, 3);\n let sum3 = a * 100 + b * 10 + c;\n if (power3 == sum3) {\n console.log(power3);\n }\n }\n }\n }\n }\n\n if (1000 <= num1 || num2 < 10000) {\n for (a = 0; a < 10; a++) {\n for (b = 0; b < 10; b++) {\n for (c = 0; c < 10; c++) {\n for (d = 0; d < 10; d++) {\n let power4 =\n Math.pow(a, 4) + Math.pow(b, 4) + Math.pow(c, 4) + Math.pow(d, 4);\n let sum4 = a * 1000 + b * 100 + c * 10 + d;\n if (power4 == sum4) {\n console.log(power4);\n }\n }\n }\n }\n }\n }\n\n if ((num1, num2 <= 99999)) {\n for (a = 0; a < 10; a++) {\n for (b = 0; b < 10; b++) {\n for (c = 0; c < 10; c++) {\n for (d = 0; d < 10; d++) {\n for (e = 0; e < 10; e++) {\n let power5 =\n Math.pow(a, 5) +\n Math.pow(b, 5) +\n Math.pow(c, 5) +\n Math.pow(d, 5) +\n Math.pow(e, 5);\n let sum5 = a * 10000 + b * 1000 + c * 100 + d * 10 + e;\n if (power5 == sum5) {\n console.log(power5);\n }\n }\n }\n }\n }\n }\n }\n}",
"function palindrom(n){\n let number = n;\n let lastIndex = 0;\n let result = 0;\n\n while(n){\n lastIndex = n % 10; \n result = result * 10 + lastIndex; \n n = Math.floor(n / 10);\n } \n if (result === number){\n return true;\n } else {\n return false;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Changes the visibility of a insert form, using the table name. | function toggleInsertForm(table){
var obj = ge(table+"_insertDiv");
var display = obj.style.display;
if( display == 'none'){
obj.style.display = 'block';
}else{
obj.style.display = 'none';
}
} | [
"function setVisibility() {\r\n var table = document.getElementById('activitiesTable');\r\n table.style.visibility = 'visible';\r\n}",
"function showSettingTable(){\r\n document.getElementById(\"setting_table\").style.visibility = \"visible\";\r\n}",
"function showTable() {\n $addItem.show();\n $myTable.show();\n $itemForm.hide();\n }",
"function addNew () {\n $( \"#table\" ).hide();\n $( \"#form\" ).show();\n}",
"function loadTable(){\n document.getElementById('add-player').style.display = 'none'\n document.getElementById('edit-players').style.display = 'block'\n}",
"function updateTableVisibility(t) {\n\t\tif (t.numberOfRows.getNum > 0) {\n\t\t\tdocument.getElementById('transactionTable').classList.remove('elementHidden');\n\t\t\tdocument.getElementById('secHighestTrans').classList.remove('elementHidden');\n\t\t} else {\n\t\t\tdocument.getElementById('transactionTable').classList.add('elementHidden');\n\t\t\tdocument.getElementById('secHighestTrans').classList.add('elementHidden');\n\t\t}\n\t}",
"_toggleInsert() {\n if (this.formValid()) {\n this.$insert.removeClass('disabled');\n } else {\n this.$insert.addClass('disabled');\n }\n }",
"function showTable(){\n formLoaded = false;\n tableLoaded = true;\n forms.css('display','none');\n tables.css('display','block');\n buttonContainer.css('display','block');\n}",
"function showTable(TABLE) {\n TABLE.classList.remove('table-hidden');\n TABLE.classList.add('table-shown');\n }",
"function showCreditsTable(){\r\n document.getElementById(\"credits_table\").style.visibility = \"visible\";\r\n}",
"function accountsTableDisplay() {\n accountsView.style.display = \"block\";\n addAccountView.style.display = \"none\";\n editDeleteAccountView.style.display = \"none\";\n editAccountView.style.display = \"none\";\n}",
"function showScoreboardTable(){\r\n document.getElementById(\"scoreboard_table\").style.visibility = \"visible\";\r\n}",
"showTableDialog() {\n if (this.tableDialogModule && !this.isReadOnlyMode && this.viewer) {\n this.tableDialogModule.show();\n }\n }",
"function showInsert() {\n console.log( 'Field insertion (CTRL + INS)' );\n if( $('.insert').is(':visible') ) {\n $('.insert').hide();\n $('#i1_insert').prop('checked', true);\n $('#i2_insert').prop('checked', true);\n document.getElementById('subfields_insert').value = '';\n subfields = '';\n insert = {id: '', i1: '', i2: ''};\n document.getElementById('field_insert').value = insert.id;\n $(\"#\" + focus_previous ).focus();\n }\n else {\n $('.insert').show();\n $('#field_insert').focus(); \n } \n}",
"function showTable() {\n table.show();\n showPreviewButton();\n }",
"function showTable() {\n $( \"#table\" ).show();\n $( \"#form\" ).hide();\n clear();\n}",
"function displayUserUpdateForm() {\n UpdateUserForm.style.display = 'block';\n // UpdateUserForm.style.opacity = 1;\n UserTable.style.opacity = 0.3;\n}",
"function toggleInsert() {\n if (trjs.param.modeinsert === false) {\n $('#mode-insert').prop('checked', true);\n trjs.param.modeinsert = true;\n $('#insertreplacemode').text(trjs.messgs.insertreplacemodeInsert);\n } else {\n $('#mode-insert').prop('checked', false);\n trjs.param.modeinsert = false;\n $('#insertreplacemode').text(trjs.messgs.insertreplacemodeReplace);\n }\n trjs.param.saveStorage();\n }",
"function displayReservationField() {\n tableNumber = this.id;\n table = tables[tableNumber];\n noTables.style.display = 'none';\n checkForm.style.display ='none';\n reserveForm.style.display = 'flex';\n reserveButton.setAttribute('tableNumber', table.tableNumber);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Toggle displaying given element. If element is invisible make it visible with given display type. If Element is visible make it invisible. If animate is true, will use expand/collapse animation when bringing element in/out of view. | function toggleDisplayWithDisplayType(idOfElement, displayType, animate){
var element = document.getElementById(idOfElement);
if(!element){
return;
}
if(!displayType){
displayType = "block";
}
if (!animate) {
element.style.display = element.style.display == 'none' ? displayType : 'none';
return;
}
if (element.style.display == 'none') {
Animation.rollIn(element, function() {element.style.display = displayType;} );
return;
}
Animation.rollOut(element);
} | [
"function toggle_display(elem) {\n if (elem.css('display') === 'none') {\n elem.css('display', 'block');\n } else {\n elem.css('display', 'none');\n }\n }",
"function toggle_display(elem) {\n if (elem.css('display') === 'none') {\n elem.css('display', 'block');\n } else {\n elem.css('display', 'none');\n }\n}",
"function toggleDisplay(element)\n{\n\tif(!element)\n\t\treturn;\n\tif (element.style.display == \"none\") \n\t{\n\t\tif(currentlyVisible)\n\t\t\tcurrentlyVisible.style.display = \"none\";\n\t\t\n\t\telement.style.display = \"block\";\n\t\tcurrentlyVisible = element;\n\n\t}\n\telse element.style.display = \"none\";\t\n}",
"function toggleVisibility(elem) {\n // If the element is visible, hide it\n if (elem.classList.contains('is-visible')) {\n hide(elem);\n return;\n }\n\n // Otherwise, show it\n show(elem);\n}",
"function showHideElement(element, display, showElement) {\n if (showElement) {\n element.classList.remove(\"collapsed\");\n element.classList.add(display);\n } else {\n element.classList.add(\"collapsed\");\n element.classList.remove(display);\n }\n}",
"function toggleAndShow(element) {\n toggle(element);\n makeVisible(element);\n}",
"static toggleDisplay(element, condition) {\n condition ? (element.style.display = 'block') : (element.style.display = 'none');\n }",
"toggleDisplay(element,displayCondition){\n\t\t\tif (displayCondition){\n\t\t\t\telement.style.display=\"block\"; \n\t\t\t}\n\t\t\telse{\n\t\t\t\telement.style.display=\"none\"; \n\t\t\t}\n\t\t}",
"function toggleElementVisibility(elementID, show)\n{\n if (show == null)\n {\n show = !isElementVisible(elementID);\n }\n \n if(show == true)\n {\n showElement(elementID);\n }\n else\n hideElement(elementID);\n}",
"function toggleVisibility(element) {\n\n if (element.style.display === 'none') {\n element.style.display = 'block';\n }\n else {\n element.style.display = 'none';\n }\n}",
"function toggle_visibility(elem) {\n if ($(elem).css('display') == 'none') {\n $(elem).css('display', 'block')\n } else {\n $(elem).css('display', 'none')\n }\n}",
"show() {\n if (this.hasAttr('hidden')) this.removeAttr('hidden');\n\n if (this.data.display === 'visibility') {\n this._el.style.visibility = 'visible';\n } else {\n this._el.style.display = this.data.display || 'block';\n }\n }",
"toggleVisible() {\n\t\tvar e = document.getElementById(this.elem);\n\n\t\tif(e.style.display == \"block\") {\n\t\t\te.style.display = \"none\";\n\t\t}\n\t\telse {\n\t\t\te.style.display = \"block\";\n\t\t}\n\t}",
"show() {\n if (this.hasAttr('hidden'))\n this.removeAttr('hidden');\n if (this.data['display'] === 'visibility') {\n this._el.style.visibility = 'visible';\n }\n else {\n this._el.style.display = this.data.display || 'block';\n }\n }",
"function setElementDisplay(element, display) {\n element.style.display = display;\n }",
"function show(display) {\n return function (element) {\n Object.defineProperty(element, \"show\", {\n value: function () {\n this.element.style.display = display;\n }\n });\n };\n}",
"function showElement(element) {\n\n hideElement(element, false);\n}",
"function toggleElementDisplay(element) {\r\n // The first setTimeout method will run first and the next one after that\r\n // to bring back the mega menu content\r\n setTimeout(function() {\r\n element.style.display === \"none\"\r\n ? (element.style.display = \"\")\r\n : (element.style.display = \"none\");\r\n }, 100);\r\n setTimeout(function() {\r\n element.style.display === \"none\"\r\n ? (element.style.display = \"\")\r\n : (element.style.display = \"none\");\r\n }, 400);\r\n}",
"function changeElementDisplay(elem, display){\n\telem.style.display = display;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Max sockets by default is 5, but we want more than that. Set os limits | function configureMaxSockets(http){
http.globalAgent.maxSockets = pound.userOptions.globalAgentMaxSockets;//Infinity;
} | [
"function connectionPoolSize() {\n // A factor that's based on the type of storage.\n const MEM_FACTOR = 1;\n\n return (os.cpus().length * 2) + MEM_FACTOR;\n}",
"constructor() {\n this.maxClients = 4;\n }",
"function get_pool_sockets(pool) {\n if (pool.getProductAttribute(\"sockets\")) {\n // this can be either a ReadOnlyPool or a Pool, so deal with attributes as appropriate.\n var attribute = pool.getProductAttribute(\"sockets\");\n if (\"getValue\" in attribute) {\n var sockets = attribute.getValue();\n }\n else {\n var sockets = attribute;\n }\n\n if (sockets == 0) {\n return Infinity;\n }\n else {\n return parseInt(sockets);\n }\n }\n else {\n return Infinity;\n }\n}",
"function setMaxListeners() {\n\t\t// WARNING: this may have unintended side-effects. Dangerous, as this temporarily changes the global state for all modules, not just this module.\n\t\teventEmitter.prototype._maxListeners = 100;\n\t}",
"set maxPoolSize(value) {\n assert && assert(value === Number.POSITIVE_INFINITY || Number.isInteger(value) && value >= 0, 'maxPoolSize should be a non-negative integer or infinity');\n maxPoolSize = value;\n }",
"function setLimit(n) {\n switch (n) {\n case 5:\n justSystem = fiveLimit;\n break;\n case 7:\n justSystem = sevenLimit;\n break;\n case 11:\n justSystem = elevenLimit;\n break;\n case 13:\n justSystem = thirteenLimit;\n break;\n default:\n postError('Tuning not available.\\nValid arguments: 5, 7, 11, 13');\n }\n}",
"function getMaxOS() {\n return self.maxOS;\n }",
"function getMaxOS() {\r\n return self.maxOS;\r\n }",
"set maxPoolSize(value) {\n assert && assert(value === Number.POSITIVE_INFINITY || Number.isInteger(value) && value >= 0, 'maxPoolSize should be a non-negative integer or infinity');\n this._maxPoolSize = value;\n }",
"function resetMaxListeners() {\n\t\teventEmitter.prototype._maxListeners = 11;\n\t}",
"function adjustCorruptionSockets(group) {\n\tvar max = 0;\n\tif (equipped[group].max_sockets > 0 && corruptsEquipped[group].name != group) {\n\t\tmax = ~~equipped[group].max_sockets;\n\t\tif (equipped[group].ethereal > 0 || equipped[group].sockets > 0 || equipped[group].rarity == \"rw\" || equipped[group].rarity == \"common\" || equipped[group].type == \"quiver\") { max = 0 }\n\t\tif (max != corruptsEquipped[group].sockets) {\n\t\t\tcharacter.sockets -= corruptsEquipped[group].sockets\n\t\t\tcorruptsEquipped[group].sockets = max\n\t\t\tcharacter.sockets += max\n\t\t}\n\t}\n\tif (max == 0 && equipped[group].name != \"none\" && corruptsEquipped[group].name == \"+ Sockets\") { corrupt(group, group) }\n\tupdateStats()\n}",
"function setMaxBufferSize(value) {\n if (!Number.isFinite(value) || value <= 0) {\n throw new Error(`max buffer size must be a positive number.`);\n }\n maxBufferSize = value;\n}",
"async setWaitlistLimit(limit) {\n if (this.limit === undefined) throw new this.ConnectionError();\n this.limit = limit;\n }",
"function getSocketsLength() {\n return Object.keys(sockets).length - freeSlot.length;\n}",
"get maxResources() {\n const contextLimit = this.node.tryGetContext(exports.STACK_RESOURCE_LIMIT_CONTEXT);\n return contextLimit !== undefined ? parseInt(contextLimit, 10) : MAX_RESOURCES;\n }",
"function caml_sys_const_max_wosize () { return (0x7FFFFFFF/4) | 0;}",
"static get defaultMaxListeners () {\n throw new $err.NotImplemented('AsyncEventEmitter does not support defaultMaxListeners');\n }",
"function SetLimited(net, fLimited = true) {\n if (net == NET_UNROUTABLE)\n return;\n // LOCK(cs_mapLocalHost)\n vfLimited[net] = fLimited;\n}",
"get _maxListeners() {\n const data = weakMap.get(this);\n if (data) {\n return data.maxListeners;\n } else {\n return 10;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List all locations the API key has access to. The API key belongs to a particular account and has access to all locations of the account. This function returns a list of locations that the API key has access to. Calls the following HTTP API: `GET /locations/` For example: ```javascript import as Qminder from 'qminderapi'; Qminder.setKey('API_KEY_HERE'); const locationList = await Qminder.locations.list(); ``` | static list() {
return api_base_1.default.request('locations/').then((locations) => {
return locations.data.map(each => new Location_1.default(each));
});
} | [
"function getLocations(){\n AuthActions.locations.getAll()\n .then(locations => setLocations(locations))\n }",
"async getLocations () {\n if (!API_URL || !API_KEY) {\n console.error('Missing API_URL or API_KEY');\n throw new BadGatewayError();\n }\n\n // We could do some proper request mapping here but\n const response = await rp(`${API_URL}?key=${API_KEY}&location=${this.currentLocation.latitude},${this.currentLocation.longitude}&radius=${this.radius}&keyword=coffee`);\n this.locations = response.results.map((location) => {\n return {\n name: location.name,\n open: location.opening_hours.open_now,\n latitude: location.geometry.location.lat,\n longitude: location.geometry.location.lng,\n };\n });\n }",
"function getLocations() {\n $.get(\"/api/users/\" + localStorage.getItem(\"userId\"))\n .then(res => renderLocationList(res.Locations));\n }",
"async function getLocations() {\n return await locations.find().toArray()\n }",
"GetAllLocations() {\n return location_queries.GetAllLocations(this.pool);\n }",
"getLocationList() {\n return async function() {\n let locationNames = await this._model.find({}, 'locationName -_id');\n let filteredNames = [];\n \n // Take out duplicate location names, and the N/A one for the admin.\n locationNames.forEach(user => filteredNames.indexOf(user.locationName) === -1 ? filteredNames.push(user.locationName) : undefined);\n //filteredNames.splice(filteredNames.indexOf(\"N/A\"), 1); UNCOMMENT TO REMOVE ADMIN ACCOUNT\n return filteredNames;\n }.bind(this)();\n }",
"function get_loc() {\n var tmp_loc = JSON.parse(localStorage.getItem(\"locations\"));\n\n all_locations = _.pairs(tmp_loc);\n\n //console.info(\"All Locations: \" + all_locations);\n}",
"function getAllLocationsCallback(response){\n\tconsole.log(response.results.forEach(function(locations){\n\t\tconsole.log(locations.name);\n\t}))\n}",
"getLocations() {\n const locations = localStorage.getItem('locations');\n return JSON.parse(locations);\n }",
"get locations() { return this.locations_.values(); }",
"async function getAppointmentsForAllLocations() {}",
"function listLocationsForCustomer(axios, token, criteria, format) {\n var query = randomSeedQuery();\n if (criteria) {\n query += createPagingQuery(criteria);\n }\n return restAuthGet(axios, \"customers/\" + token + \"/locations\" + query);\n}",
"function getLocations() {\n return $.ajax({\n type: \"get\",\n async: false,\n url: '/mapapi/getAllLocation'\n });\n}",
"function listLocationsForArea(axios, token, criteria, format) {\n var query = randomSeedQuery();\n if (criteria) {\n query += createPagingQuery(criteria);\n }\n return restAuthGet(axios, \"areas/\" + token + \"/locations\" + query);\n}",
"async function getLocationsWithExtendedLocations() {\n const subscriptionId = \"a1ffc958-d2c7-493e-9f1e-125a0477f536\";\n const includeExtendedLocations = true;\n const options = {\n includeExtendedLocations,\n };\n const credential = new DefaultAzureCredential();\n const client = new SubscriptionClient(credential);\n const resArray = new Array();\n for await (let item of client.subscriptions.listLocations(subscriptionId, options)) {\n resArray.push(item);\n }\n console.log(resArray);\n}",
"function fetchAllLocations() {\r\n\t\tLocationService.fetchAllLocation()\r\n\t\t\t.then(\r\n\t\t\t\t\tfunction (locations) {\r\n\t\t\t\t\t\tself.locations = locations;\t\t\t\t\r\n\t\t\t\t\t}, \r\n\t\t\t\t\tfunction (errResponse) {\r\n\t\t\t\t\t\tconsole.log('Error while fetching branches');\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t}",
"function getLocations(bounds) {\n\n const url = \"/api/v1/stores?lat1=\" + bounds.getNorthEast().lat() + \"&lat2=\"\n + bounds.getSouthWest().lat() + \"&lng1=\" + bounds.getNorthEast().lng()\n + \"&lng2=\" + bounds.getSouthWest().lng();\n\n // Query the backend to refresh results.\n $.getJSON(url, updateView);\n}",
"function listLocationsForArea(store, token, criteria, format) {\n var axios = createCoreApiCall(store);\n var api = API.Areas.listLocationsForArea(axios, token, criteria, format);\n return loaderWrapper(store, api);\n}",
"async function getLocations() {\n const res = await fetch(\"/api/v1/stores\");\n const data = await res.json();\n\n const locations = data.data.map(loc => {\n return {\n type: \"Feature\",\n geometry: {\n type: 'Point',\n coordinates: [loc.location.coordinates[0], loc.location.coordinates[1]]\n },\n properties: {\n storeId: loc.stordId,\n icon: 'shop'\n }\n }\n });\n\n loadMap(locations);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determines the next available user ID. | function nextUserId() {
return ++userSeq;
} | [
"function nextID (callback) {\n \n users.findOne({}).sort({userID: -1}).exec(function(err, user) {\n if (err) {\n throw err;\n } else {\n if (user) {\n callback(user.userID + 1);\n } else {\n callback(0);\n }\n }\n });\n}",
"async function getNewUserID() {\n const field = \"User_ID\";\n const table = \"User\";\n const results = await dbms.dbquery(`SELECT MAX(${field}) FROM ${table};`);\n const maxId = results[0][`MAX(${field})`];\n if (maxId == null) return 0;\n return maxId + 1;\n}",
"function createUserId(){\n while (true){\n var id = '_' + Math.random().toString(36).substr(2, 9);\n if(database.users.find((user) => user.id == id)==null){\n return id\n }\n }\n}",
"function getFreeId() {\n while(entities[nextId] !== undefined) {\n nextId++;\n }\n return nextId++;\n}",
"async getNextBlock () {\n const result = await this.db.query(QUERY_GET_ID_SEQ, { seqName: this.seqName })\n if (!_.isArray(result) || _.isEmpty(result)) {\n throw new Error(`null or empty result for ${this.seqName}`)\n }\n this._nextId = --result[0][0]\n this._availableId = result[0][1]\n }",
"function getNextUserHanlder() {\n let index = parseInt($($modalInfoContainer).find('input[name=\"current-user-index\"]').val()) + 1;\n if (index < users.length) {\n let nextUser = users[index];\n writingUserInfoIntoModal(nextUser, index);\n }\n }",
"function defineFirstPlayer() {\n\tactualIndexOfUsersId = Math.floor(Math.random() * usersId.length);\n\treturn usersId[actualIndexOfUsersId];\n}",
"function getNewUserId() {\n userCount++;\n return \"user\" + userCount;\n}",
"function nextUser(users, userId){\n userId = parseInt(userId);\n if(userId >= users.length - 1){\n displayUserModal(users, users[0], 0);\n } else {\n displayUserModal(users, users[userId + 1], userId + 1);\n }\n }",
"function getNextId() {\n\t\tvar maxId = 0;\n\t\t_.forEach($scope.d, function(bulletin) {\n\t\t\tif(bulletin.id > maxId) {\n\t\t\t\tmaxId = bulletin.id;\n\t\t\t}\n\t\t});\n\t\tmaxId++;\n\t\treturn maxId;\n\t}",
"async getNextPlayerId() {\n this.currentPlayerNum++;\n return `player__${this.currentPlayerNum}`;\n }",
"function getNextKey(){\n\t\"use strict\";\n\t// Make copy of nextKey to return\n\tvar aliasKey = nextKey;\n\t// Generate next key and increase values in database\n\tvar incrNext = Math.floor(Math.random() * 100) + 1;\n\tnextKey += incrNext;\n\t// Set the next key value in database\n\tNextKey.findOneAndUpdate({}, {$set: {keyid: nextKey} }, function (err){\n\t\tif (err){\n\t\t\tconsole.log(\"ERROR\");\n\t\t}\n\t});\n\treturn aliasKey.toString(36);\n}",
"async function getCreatorId ({\n numUsers,\n executeAll,\n executeOne,\n numCreatorNodes\n}) {\n const walletIndexToUserIdMap = await addAndUpgradeUsers(\n numUsers,\n executeAll,\n executeOne\n )\n\n return walletIndexToUserIdMap[CREATOR_INDEX]\n}",
"function getNextId()\n{\n let id = 0;\n for (id = 0; id <= maxId; id++)\n {\n // If this ID is not used, return it\n if (!(id in costs))\n {\n return id;\n }\n }\n return id;\n}",
"function getNextId(currentId, filecount, callback) {\n prefs.get(Constants.Key.choose_random, function (is_random) {\n if (isdef(is_random) && is_random === true) {\n callback(randomMinMax(0, filecount - 1));\n } else {\n if (!isdef(currentId)) {\n callback(0);\n } else {\n var newId = currentId + 1;\n if (newId > (filecount - 1)) {\n newId -= filecount;\n }\n callback(newId);\n }\n }\n },\n // optional flag to return even if the result would be \"undefined\"\n true);\n}",
"function generateRandomUserId() {\n userid = Math.floor(Math.random()*9000000000) + 10000;\n return userid;\n}",
"static getNextPasswordId() {\n return Math.max(AzkabanService.passwords.map(password => password.id)) + 1;\n }",
"function genUserID() {\n\treturn Math.random() + ':' + Math.random();\n}",
"nextID() {\n this._ctx.groupCount++;\n this._ctx.currentID = `${this._ctx.groupID}-${this._ctx.groupCount}`;\n return this._ctx.currentID;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the ID of the document associated with a given verification code, or null if no document matches the given code. | static lookupVerificationCode(session, code) {
if (!code) {
return null;
}
// >>>>> NOTICE <<<<<
// This should be implemented on your application as a SELECT on your
// "document table" by the verification code column, which should be an
// indexed column.
if (session['Codes/' + code]) {
return session['Codes/' + code];
}
return null;
} | [
"static lookupVerificationCode(session, code) {\n\t\tif (!code) {\n\t\t\treturn null;\n\t\t}\n\t\t// >>>>> NOTICE <<<<<\n\t\t// This should be implemented on your application as a SELECT on your\n\t\t// \"document table\" by the verification code column, which should be an\n\t\t// indexed column.\n\t\tif (session[`Codes/${code}`]) {\n\t\t\treturn session[`Codes/${code}`];\n\t\t}\n\t\treturn null;\n\t}",
"static getVerificationCode(session, fileId) {\n\n // >>>>> NOTICE <<<<<\n // This should be implemented on your application as a SELECT on your\n // \"document table\" by the ID of the document, returning the value of the\n // verification code column.\n if (session['Files/' + fileId + '/Code']) {\n return session['Files/' + fileId + '/Code'];\n }\n return null;\n }",
"static getVerificationCode(session, fileId) {\n\t\t// >>>>> NOTICE <<<<<\n\t\t// This should be implemented on your application as a SELECT on your\n\t\t// \"document table\" by the ID of the document, returning the value of the\n\t\t// verification code column.\n\t\tif (session[`Files/${fileId}/Code`]) {\n\t\t\treturn session[`Files/${fileId}/Code`];\n\t\t}\n\t\treturn null;\n\t}",
"getByCode(code) {\n let mongo = new Mongo();\n return mongo.query(COLLECTION, {\n 'code': code\n }).then(ret => {\n if (ret && ret.length >= 1) {\n return ret[0];\n }\n return null;\n });\n }",
"function find_ca_id() {\n\t\t\tif (all_ca_info && doc.id) {\n\t\t\t\tfor (let id in all_ca_info) {\n\t\t\t\t\tfor (let pos in all_ca_info[id]._issued_msps) {\n\t\t\t\t\t\tif (all_ca_info[id]._issued_msps[pos] && all_ca_info[id]._issued_msps[pos].id === doc.id) {\n\t\t\t\t\t\t\treturn id;\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\treturn 'unknown';\n\t\t}",
"generateCode() {\n var ID = Math.random()\n .toString(36)\n .substr(2, 9);\n this.code = ID; // for testing purposes\n var docRef = db.collection(\"appointments\").doc(ID);\n return docRef\n .get()\n .then(doc => {\n if (doc.exists) {\n return true;\n } else {\n this.code = ID;\n return false;\n }\n })\n .catch(function (error) {\n alert(error);\n });\n }",
"function findPasscodeId(theCode) {\n return db(\"passcode\").select(\"id\").where({ \"passcode.code\": theCode });\n}",
"async function getOrganizationByCode(code) {\n\treturn new Promise((resolve, reject) => {\n\t\ttry {\n\t\t\tdb.collection(\"organizations\").findOne({ inviteCode: code }, function (\n\t\t\t\terr,\n\t\t\t\tresult\n\t\t\t) {\n\t\t\t\tif (err) throw err;\n\t\t\t\tresolve(result);\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treject(err);\n\t\t}\n\t});\n}",
"__getDocumentId (input) {\n\n\t\tswitch (typeof input) {\n\t\t\tcase `string`: return input;\n\t\t\tcase `object`:\n\t\t\t\tif (input === null) { return null; }\n\t\t\t\tif (mongoose.Types.ObjectId.isValid(input)) { return input; }\n\t\t\t\tif (input._id) { return input._id; }\n\t\t\t\treturn null;\n\t\t\tdefault: return null;\n\t\t}\n\n\t}",
"function findInvoice(invoiceNo) {\n try {\n // Looks for invoice in the Invoices folder.\n const invoice = DriveApp.getFolderById('1fheoM0D86nabYbw0CYy9HGnoqs8d004M').getFilesByName(`${invoiceNo}.pdf`)\n let id\n while (invoice.hasNext()) {\n const file = invoice.next()\n id = file.getId()\n }\n if (id) return id \n \n // Looks for the invoice in the entire Drive folder if not yet found.\n const search = DriveApp.searchFiles(`title contains \"${invoiceNo}\"`)\n while (search.hasNext()) { \n const file = search.next()\n const name = file.getName()\n // Make sure the file has the characters 'inv', the way Blake stores invoices originally.\n const match = name.match('Inv.')\n if (match) {\n return file.getId()\n }\n } \n } catch (error) {\n console.log(error)\n addError(error)\n }\n}",
"async getDocumentByCode ( p_auth, p_document_code, p_document_id, p_document_name, p_document_ext ) {\n const AUTHORIZATION = `${p_auth.token_type} ${p_auth.access_token}`\n const PATH = 'Med_get_documento_b24'\n const documentBlob = await RNFetchBlob.config({ fileCache : true, })\n .fetch('GET', `${ BASE_API_URL }${ BASE_PATH_URL }${ PATH }?p_docu_cod_clave=${ p_document_code }`, {\n Authorization: AUTHORIZATION, 'Content-Type': CONTENT_TYPE,\n })\n .then((res) => {\n let status = res.info().status;\n if(status == 200) {\n // the conversion is done in native code //let base64Str = res.base64() //console.log(base64Str) // the following conversions are done in js, it's SYNC //let text = res.text()\n let json = res.json()\n return json\n } \n else { /* handle other status codes */ }\n })\n .catch((errorMessage, statusCode) => {\n console.log(errorMessage, statusCode)\n })\n const { fs } = RNFetchBlob\n const DownloadDir = Platform.OS === 'ios' ? fs.dirs['MainBundleDir'] : fs.dirs['SDCardDir'] + '/EducApp/Documentos'\n if (Platform.OS === 'android') { RNFetchBlob.fs.mkdir(DownloadDir) }\n const NEW_FILE_PATH = `${ DownloadDir }/${p_document_id}_${p_document_name}.${p_document_ext}`\n RNFetchBlob.fs.createFile(NEW_FILE_PATH, documentBlob.retorno, 'base64')\n return NEW_FILE_PATH \n }",
"async getByCode(code) {\n\t\treturn await CoreHelpers.MongoFuncHelper.$getByCode(this.model, code);\n\t}",
"function getDocumentByID(_type,__id,_cb){\n\tcollection[_type].findOne({_id:makeMongoID(__id)},function(e,_doc){\n\t\t//does error handling happen here?\n\t\tif(!e) _cb(null,_doc)\n\t\telse _cb(e);\n\t})\n\n}",
"async function getEmailTemplateByCode (code) {\n let template = await EmailTemplate.findOne({templateCode: code})\n if(template){\n return template\n }\n\n}",
"findEmoteId(emoteCode) {\n for (const emoteSet of Object.values(this._data)) {\n for (const emote of emoteSet) {\n if (EmoteSetList_1._testEmoteCode(emote.code, emoteCode)) {\n return emote.id;\n }\n }\n }\n return undefined;\n }",
"getByCode (code) {\n if (this._codes[code]) {\n return this._codes[code]\n } else {\n return code\n }\n }",
"async function save_verification_code(verification_code_str, user_email_str, database)\n {\n const COLLECTION_NAME_FOR_STORED_CODES = \"codes\";\n \n let database_results_array =\n await database.collection(COLLECTION_NAME_FOR_STORED_CODES).find( {email : user_email_str} ).toArray();\n\n // IF THERE IS CURRENTLY NO CODE ENTRY FOR THE USER\n if(database_results_array.length === 0)\n {\n database.collection(COLLECTION_NAME_FOR_STORED_CODES).insertOne\n ( code_obj_factory(verification_code_str, \"\", user_email_str) );\n }\n \n // OTHERWISE, THE USER ALREADY EXISTS IN THE 'codes' COLLECTION\n else\n {\n database.collection(COLLECTION_NAME_FOR_STORED_CODES).updateOne( {email : user_email_str},\n { $set : {verification_code : verification_code_str} } );\n }\n }",
"function verifyCode(req, res, next) {\n var query = VerifyCode.where( 'key', new RegExp('^'+req.params.v+'$', 'i') );\n query.findOne(function (err, verifyCode) {\n if (!err && verifyCode) {\n updateUserEmailStatus(req, res, next, verifyCode);\n } else {\n return next(new restify.NotAuthorizedError(VERIFY_FAIL));\n }\n });\n }",
"function findVerificationCode(text) {\n let match = verificationCodeRegExp.exec(text);\n return match && match[0];\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the renderer dimensions to the max dimension of the canvas. This assumes a 1:1 aspect ratio but improves the output resolution. | updateRenderDimensions(window) {
const maxDimension = Math.max(this.renderer.domElement.clientWidth, this.renderer.domElement.clientHeight);
// Set the pixel ratio to set the correct resolution for high PPI displays.
this.renderer.setPixelRatio(window.devicePixelRatio);
this.renderer.setSize(maxDimension, maxDimension, false);
} | [
"setActualSize() {\n this.renderer.setActualSize();\n }",
"setRendererSize(w, h) {\n this.drawableObject.activate()\n this.drawableObject.view.setViewSize(w,h);\n\n var ctx = this.drawableElement.getContext('2d');\n ctx.canvas.style.width = '';\n ctx.canvas.style.height = '';\n }",
"function updateRendererSize(){\n renderer.setSize(width, height);\n camera.aspect = width / height;\n camera.updateProjectionMatrix();\n }",
"updateMaxCanvasRegion() {\n this.maxCanvasRegion.width = this.windowWidth;\n this.maxCanvasRegion.height = this.windowHeight;\n if (this.node === document.body)\n return;\n const containerRect = this.node.getBoundingClientRect();\n this.maxCanvasRegion.width = containerRect.width;\n this.maxCanvasRegion.height = containerRect.height;\n }",
"updateMaxCanvasRegion() {\n this.maxCanvasRegion.width = this.windowWidth;\n this.maxCanvasRegion.height = this.windowHeight;\n if (this.node === document.body)\n return;\n const containerRect = this.node.getBoundingClientRect();\n this.maxCanvasRegion.width = containerRect.width;\n this.maxCanvasRegion.height = containerRect.height;\n }",
"function setCanvasDimensions() {\n\tcanvas.setDimensions({ width: window.innerHeight, height: window.innerHeight });\n}",
"resize() {\n const scale = settings.devCamera ? settings.viewportPreviewScale : 1;\n let { width, height } = getRenderBufferSize();\n width *= scale;\n height *= scale;\n this.renderTargetA.setSize(width, height);\n this.renderTargetB.setSize(width, height);\n this.renderTargetC.setSize(width, height);\n this.transitionPass.resize(width, height);\n this.finalPass.resize(width, height);\n }",
"setRendererSize(w,h) {\n\n }",
"function Update_Canvas_Height_Width() {\n // var Container_Main_Canvas_Width = document.getElementById(\"Canvas_Row\").clientWidth;\n // var Container_Main_Canvas_Height = document.getElementById(\"fractal_canvas\").width;\n // document.querySelector('#fractal_canvas').width = Container_Main_Canvas.offsetWidth;\n // document.querySelector('#fractal_canvas').height = Math.round(Container_Main_Canvas.width * aspect);\n\n\n\n //this changes the canvas as the page is adjusted, should keep the aspect ratio\n canvas.style.width = '100%';\n canvas.style.height = '100%';\n canvas.width = canvas.offsetWidth;\n canvas.height = canvas.offsetHeight;\n //renderer.setSize(canvas.width, canvas.height);\n\n}",
"function adjustCanvasSize() {\n CANVAS.width = CANVAS_WIDTH;\n CANVAS.height = window.innerHeight;\n}",
"function set_canvas_size()\n\t{\n\t\tsize.width = 0;\n\t\tsize.height = 0;\n\n\t\tfeed_string( false );\n\t\trender.setSize( size.width, size.height );\n\t}",
"resize() {\n // const scale = settings.devCamera ? settings.viewportPreviewScale : 1;\n let { width, height } = getRenderBufferSize();\n\n // width *= scale;\n // height *= scale;\n this.renderTargetTransitionA.setSize(width, height);\n this.renderTargetTransitionB.setSize(width, height);\n this.renderTargetDenoise.setSize(width, height);\n this.renderTargetDenoisePrev.setSize(width, height);\n this.renderTargetDenoiseCombined.setSize(width, height);\n this.transitionPass.resize(width, height);\n this.denoisePass.resize(width, height);\n this.copyPass.resize(width, height);\n this.finalPass.resize(width, height);\n }",
"resize() {\n this.texturePool.setScreenSize(this.renderer.view);\n }",
"function resizeCanvas() {\n ch = ((h = canvas.height = innerHeight - 32) / 2) | 0;\n cw = ((w = canvas.width = innerWidth) / 2) | 0;\n updateDisplay = true;\n }",
"function setCanvasSize() {\n // Get the smaller dimension to use as limit to set canvas size\n let minD = Math.min(CANVAS_CONTAINER_HEIGHT, CANVAS_CONTAINER_WIDTH);\n\n // Check if there is the extra space needed to fit the drawer else reduce canvas size\n if (window.innerWidth - DRAWER_WIDTH < minD) {\n minD = window.innerWidth - DRAWER_WIDTH;\n }\n\n // Set canvas width and height to that value\n CANVAS_WIDTH = minD;\n CANVAS_HEIGHT = minD;\n\n // Set CSS width/height\n // This will create the box that will contain the canvas\n canvas.style.width = CANVAS_WIDTH + \"px\";\n canvas.style.height = CANVAS_HEIGHT + \"px\";\n\n // Scale for dpi for retina display\n // This will set the width and height for the canvas coordinate system\n canvas.width = Math.floor(CANVAS_WIDTH * DPI);\n canvas.height = Math.floor(CANVAS_HEIGHT * DPI);\n\n // Scale the canvas accordingly\n canvasCtx.scale(DPI, DPI);\n}",
"function setSize() {\n parentWidth = $(\"#demo\").width();\n let size = parentWidth < windowHeight - 200 ? parentWidth : windowHeight - 200;\n resizeCanvas(size, size);\n}",
"setSize(width, height) {\r\n const fovX = 40;\r\n const aspect = width / height;\r\n const fovY = Math.max(15, fovX / aspect);\r\n this.camera.aspect = aspect;\r\n this.camera.fov = fovY;\r\n this.camera.updateProjectionMatrix();\r\n this.renderer.setSize(width, height);\r\n }",
"function setCanvasSize() {\n\tcontext.canvas.width = window.innerWidth - (window.innerWidth * 0.1);\n\tcontext.canvas.height = window.innerHeight - (window.innerWidth * 0.15);\n}",
"updateCanvasSize() {\n this.canvas.width = this.config.container.clientWidth;\n this.canvas.height = this.config.container.clientHeight;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a configuration of a taco, containing baseLayer, mixins, etc., save it to our state array and locally in our cookie | saveTaco (config, cameFromHistory = false) {
// Update saved tacos
const newTacos = this.state.tacos.concat([new Taco(config)])
this.setState({ tacos: newTacos })
// On github pages cookies don't work!!!
Cookies.set(COOKIE_KEY, newTacos)
this.props.onSave(newTacos)
this.props.onSave(newTacos)
if (cameFromHistory === true)
this.props.history.replace("/", null)
} | [
"saveStateToCookie() {\n cookies = cookies || new Cookies();\n\n const stateToSave = {};\n STATE_KEYS_SAVE.forEach(key => {\n stateToSave[key] = this.state[key];\n });\n\n cookies.set(STORYTELLER_COOKIE, stateToSave, {\n path: '/',\n expires: new Date(COOKIE_EXP),\n });\n }",
"function SaveConfiguration() {\n var cookievalue = '';\n\n // get added wms layers\n var wmslayers = mapPanel.layers.queryBy(function (record, id) { return record.get(\"layer\").CLASS_NAME.indexOf(\"WMS\") > -1 && !record.get(\"layer\").isBaseLayer; });\n var count = wmslayers.getCount();\n if (count > 0) {\n cookievalue += 'wms,';\n for (i = 0; i < count; i++) {\n cookievalue += Ext.util.JSON.encode(wmslayers.itemAt(i).data); // werkt niet! Een layer blijkt te complex om te serializeren... (\"too much recursion\")\n if (i < count - 1) { cookievalue += ','; }\n }\n cookievalue += ';';\n }\n\n // TODO: get wmsSourcesStore?\n // TODO: get current zoom values?\n\n // save cookie\n Set_Cookie('mapconfig', cookievalue, '', '/', '', '');\n if (Get_Cookie('mapconfig')) {\n msg('Configuratie bewaren', 'Configuratie is bewaard.\\n\\n' + cookievalue);\n }\n else {\n msg('Configuratie bewaren', 'Configuratie is NIET bewaard.\\n\\nZijn cookies uitgeschakeld in uw browser?');\n }\n}",
"function saveConfiguration() {\n // save the current configuration in the \"chair\" object\n updateChairObject();\n // update local storage\n updateLocalStarage(\"chair\", chair);\n}",
"saveState() {\n fs.writeFileSync(this.options.tmpFile, JSON.stringify(this.state));\n }",
"static _saveConfig() {\n console.log(\"Enregistre le json de config des casques\",Casque.configJson);\n fs.writeFileSync(window.machine.jsonCasquesConfigPath, JSON.stringify(Casque.configJson,undefined, 2));\n }",
"function saveState(canvas) {\n\tundoList.push(canvas.toDataURL());\n}",
"writeConfigToCookies() { \r\n\r\n var configString = \"\";\r\n\r\n configString += this.isCookieLatestBackup() ? \"1\" : \"0\";\r\n\r\n var currentConfig, currentZone, currentDir;\r\n for(var config = 0; config < NUM_INTERSECTION_CONFIGS; config++) {\r\n\r\n if(!PROJECT.getIntersectionByIndex(config).isEnabled())\r\n continue;\r\n else\r\n configString += this._break_char + this.getConfigId(config);\r\n\r\n currentConfig = PROJECT.getIntersectionByIndex(config);\r\n for(var zone = MIN_EFFECTIVE_ZONE; zone < NUM_ZONES; zone++) {\r\n\r\n if(!currentConfig.getZoneByIndex(zone).isEnabled()) {\r\n continue;\r\n }\r\n\r\n currentZone = currentConfig.getZoneByIndex(zone);\r\n for(var dir = 0; dir < 4; dir++) {\r\n currentDir = currentZone.getDirectionByIndex(dir);\r\n\r\n configString += this.TMtoCHAR(zone, dir, currentDir.getSharedLeft(), currentDir.getSharedRight(),\r\n currentDir.getchannelizedRight(), currentDir.getThrough(), currentDir.getLeftTurn(),\r\n currentDir.getRightTurn(), 0);\r\n }\r\n }\r\n }\r\n\r\n this._cookie = configString;\r\n\r\n var date = new Date();\r\n date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000));\r\n var expires = \"; expires=\" + date.toUTCString();\r\n document.cookie = this._cookie_id + \"=\" + this._cookie + expires + \"; path=/\";\r\n }",
"function save_state() {\n\tvar json_state = JSON.stringify(state, null, 2);\n\tvar f = new File(\"state.json\", \"write\");\n\tf.writestring(json_state);\n\tf.close();\n}",
"function saveState () {\n console.log('saving state to ' + cfg.filePath)\n cfg.write(state.saved, function (err) {\n if (err) console.error(err)\n update()\n })\n}",
"static saveState() {\n\t\t//Cookie data\n\t\tvar cdata = \"\";\n\t\t//Get the cards\n\t\tvar cards = CardManager.getCardsOrdered();\n\t\t//Check each card\n\t\tfor(var i = 0; i < cards.length; i++) {\n\t\t\t//Add the card name to the list\n\t\t\tcdata += cards[i].getAttribute(\"cardname\") + \",\";\n\t\t}\n\t\t//Save the cookie\n\t\tdocument.cookie = \"cardstate=\" + cdata.substring(0, cdata.length - 1);\n\t\t//Log\n\t\tconsole.log(\"Card state saved as \" + cdata.substring(0, cdata.length - 1));\n\t}",
"function saveState() {\n LS.setData('commute-storage', [\n vm.state.originA,\n vm.state.originB,\n vm.state.destination,\n vm.state.mileageRate,\n vm.state.hourlyRate,\n vm.state.milesPerGallon,\n vm.state.gasPrice,\n vm.state.maintenance,\n vm.state.tires,\n vm.state.insurance,\n vm.state.licenseRegTaxes,\n vm.state.depreciation,\n vm.state.finance,\n vm.state.advancedToggle\n ]);\n // reset state, which will use local storage data\n setState();\n }",
"persistState() {\n\t\tsessionStorage.ta = JSON.stringify({\n\t\t\trooms: this.getCurrentRoom().name,\n\t\t\tcurrentItem: this.currentItem ? this.currentItem : '',\n\t\t\tlastTransition: this.lastTransition ? this.lastTransition : '',\n\t\t});\n\t}",
"function saveSettings(){\n\t\tvar checkboxes = document.querySelectorAll('.accordion-header input[type=\"checkbox\"]');\n\t\tvar toSave = {};\n\t\t[].forEach.call(checkboxes,\tfunction (el) {\n\t\t\tvar id = el.parentNode.id;\n\t\t\tvar checked = el.checked;\n\t\t\ttoSave[id] = checked;\n\t\t});\n\t\t// console.log(\"Saving block preferences\", toSave);\n\t\tlocalStorage['__' + language + '_hidden_blocks'] = JSON.stringify(toSave);\n\t}",
"function saveState() {\n // https://www.w3schools.com/js/js_cookies.asp\n function setCookie(cname, cvalue, exdays) {\n var d = new Date();\n d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));\n var expires = \"expires=\" + d.toUTCString();\n document.cookie = cname + \"=\" + cvalue + \";\" + expires + \";path=/\";\n }\n cookie = JSON.stringify(state.selectedSections);\n setCookie('ycui_' + state.semester, cookie, 256);\n }",
"function saveAccordionState(enabledAccordions) {\n elements.enabledAccordions = enabledAccordions;\n localStorage['sunjer_enabledAccordions'] = enabledAccordions;\n}",
"function saveConfig(){\n\t\tconsole.log(config)\n\t\tlocalStorage.config = JSON.stringify(config)\n\t}",
"save(state) {\n fs.writeFileSync(this.stateFile, JSON.stringify(state), \"utf8\");\n }",
"saveState() {\n this.turtleStateStack.push(new TurtleState(this.state.pos, this.state.dir));\n }",
"saveCurrentStateData() {\n // Create temporary object for later use\n let data = {};\n // Add the current expand all state to the object\n data.expandAll = this.state.expandAll;\n // Create an empty sections array to hold\n // the current state sections\n data.sections = [];\n // Check if sections exist in state\n if (!this.state || !this.state.sections) return;\n // Loop through each section in the state\n this.state.sections.forEach(section => {\n // Add the open/close state of the current section to\n // the temporary saved state object\n data.sections.push({\n uniqueIdentifier: section.sectionUniqueIdentifier,\n open: section.sectionOpen,\n });\n });\n // Save the current state of the section with it's unqiue hash\n store.set(this.uniqueIdentifier, data);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check for delay in start of new year due to length of adjacent years | function hebrew_delay_2(year)
{
var last, present, next;
last = hebrew_delay_1(year - 1);
present = hebrew_delay_1(year);
next = hebrew_delay_1(year + 1);
return ((next - present) == 356) ? 2 :
(((present - last) == 382) ? 1 : 0);
} | [
"function hebrew_delay_2(year) {\n var last, present, next;\n last = hebrew_delay_1(year - 1);\n present = hebrew_delay_1(year);\n next = hebrew_delay_1(year + 1);\n return ((next - present) == 356) ? 2 : (((present - last) == 382) ? 1 : 0);\n}",
"function hebrew_delay_2(year)\n\t{\n\t var last, present, next;\n\n\t last = hebrew_delay_1(year - 1);\n\t present = hebrew_delay_1(year);\n\t next = hebrew_delay_1(year + 1);\n\n\t return ((next - present) == 356) ? 2 :\n\t (((present - last) == 382) ? 1 : 0);\n\t}",
"function hebrew_delay_2(year)\n{\n var last, present, next;\n\n last = hebrew_delay_1(year - 1);\n present = hebrew_delay_1(year);\n next = hebrew_delay_1(year + 1);\n\n return ((next - present) == 356) ? 2 :\n (((present - last) == 382) ? 1 : 0);\n}",
"function hebrewDelay2(year) {\n var last, present, next;\n\n last = hebrewDelay1(year - 1);\n present = hebrewDelay1(year);\n next = hebrewDelay1(year + 1);\n\n return ((next - present) === 356) ? 2 :\n (((present - last) === 382) ? 1 : 0);\n }",
"function _isNextYear(d1, d2) {\n return d2.getFullYear() - d1.getFullYear() === 1;\n }",
"function checkIfInInterval(year) {\n var result;\n if (year >= 1900 && year <= 2018) {\n result = true;\n } else {\n result = false;\n }\n return result;\n}",
"fineLifeSpanLeftFromBdayTEST() {\n this.year += 79;\n let thisDate = new SpaceClock(2018, 3, 16, 0, 0, 0, 0);\n let now = thisDate.makeDate();\n let remains = (this.makeDate() - now) / 1000;\n let result = (remains)\n this.year -= 79;\n\n return result;\n }",
"function getMissingYearSequences(arr_years) {\n\n var idx = -1;\n var is_new_missing_sequence = true;\n var arr_return = [];\n\n //loop through if the first year (1910) is less than the most recent (2019)\n while( num_start_year < num_end_year ){\n\n //find the index of the starting year\n //if its not found then....\n if( findIndex(arr_years, num_start_year) == -1 ) {\n\n\n var arr_missing_sequence = [];\n\n //if we have a new sequence of missing number increment index so that\n // we can create a new entry in to the arr_return\n if(is_new_missing_sequence) {\n idx++;\n } else {\n //get a reference to the existing missing years\n arr_missing_sequence = arr_return[idx];\n }\n\n //include the year in the missing sequence group\n arr_missing_sequence.push(num_start_year);\n\n //overwrite the existing or create new entry depending on the idx\n arr_return[idx] = arr_missing_sequence;\n \n //if this if statement fires true again we want this false so it doesn't create a new group\n is_new_missing_sequence = false;\n\n } else {\n //however if we have a new valid year the next invalid year will be a new sequence\n is_new_missing_sequence = true; \n }\n\n num_start_year ++;\n\n }\n\n return arr_return;\n\n}",
"function durYear(first, last) {\n return (Math.abs(last.getTime() - first.getTime()) / (1000 * 3600 * 24 * 365));\n}",
"checkYear(year) {\n if (year.length !== 4 || year > 2019 || year < 1800) return false;\n return true;\n }",
"function afterYear (citation, year) { return citation.year >= year; }",
"function _isPrevYear(d1, d2) {\n return _isNextYear(d2, d1);\n }",
"function beforeYear (citation, year) { return citation.year <= year; }",
"function daysSinceYearBegun(dy, mn, yr) \n {\n mn--;\n // Add the number of days passed + 1 if the current year is a leap year.\n return arrComulativeDays[mn] + dy + (mn > 2 && isGregorianLeapYear(yr));\n }",
"function CheckYear(year) \n { \n return (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) ? 1 : 0;\n }//End CheckYear",
"function withinYear(date1,date2){\n \tdate1Val = date1[0]*1000000+date1[1]*1000+date1[2];\n \tdate2Val = date2[0]*1000000+date2[1]*1000+date2[2];\n \tnextYearVal = date1Val + 1*1000000;\n\n \treturn date2Val < nextYearVal;\n }",
"function analyzeYear(year){\n var flag = false;\n\n if(year % 4 == 0 && year % 100 != 0){\n flag = true;\n } else if(year % 400 == 0){\n flag = true;\n } else{\n flag = false;\n }\n return flag;\n }",
"function yearsUntilRetirement(year, firstName) {\n var age = calculateAge(year);\n var retirement = 65 - age;\n console.log(firstName + ' retires in ' + retirement + ' years.');\n}",
"function checkYear(start, current) \n{\n\tif (start.value > current.value )\n\t{\n\t\talert(\"Current year can't be greater than enrollment year.\");\n\t\treturn false;\n\t}\n\t\n\treturn true;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.