query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
sequencelengths
19
20
metadata
dict
Source of Test generating stack trace is expensive, so using a getter will help defer this until we need it
get source() { return test.stack; }
[ "get stack() {\n \t\treturn extractStacktrace(this.errorForStack, 2);\n \t}", "function _getCallerDetails() {\n var originalFunc = Error.prepareStackTrace\n\n var callerfile\n var line\n try {\n var err = new Error()\n var currentfile\n\n Error.prepareStackTrace = function (err, stack) {\n return stack\n }\n let shifted = err.stack.shift()\n currentfile = shifted.getFileName()\n\n while (err.stack.length) {\n shifted = err.stack.shift()\n callerfile = shifted.getFileName()\n\n if (currentfile !== callerfile) break\n }\n\n const trackedLine = shifted.toString()\n const regex = /^(.*) \\((.*):(\\d+):(\\d+)\\)$/\n //\n const match = regex.exec(trackedLine)\n line = {\n function: match[1] === 'Object.<anonymous>' ? 'none/root' : match[1],\n filepath: match[2],\n line: match[3],\n column: match[4],\n }\n } catch (e) {}\n\n Error.prepareStackTrace = originalFunc\n\n return line\n}", "function getStackTrace() {\n let stack;\n try {\n throw new Error();\n } catch (e) {\n e.task = task;\n Zone.longStackTraceZoneSpec.onHandleError(\n delegate,\n current,\n target,\n e\n );\n stack = e.stack;\n }\n return stack;\n }", "function stacktrace()\n{\n\tvar stackstring = \"stacktrace: \";\n\tvar history = [];\n\tvar func = arguments.callee.caller;\n\n\twhile (func !== null)\n\t{\n\t\tvar funcName = getFuncName(func);\n\t\tvar funcArgs = getFuncArgs(func);\n\t\tvar caller = func.caller;\n\t\tvar infiniteLoopDetected = history.indexOf(funcName) !== -1;\n\t\tvar historyTooLong = history.length > 50;\n\t\tvar callerIsSelf = (caller === func);\n\n\t\tif ( infiniteLoopDetected || historyTooLong || callerIsSelf)\n\t\t\tbreak;\n\n\t\tstackstring += funcName + funcArgs + \"\\n\\n\";\n\t\thistory.push(funcName);\n\t\tfunc = caller;\n\t}\n\n\treturn stackstring;\n}", "function traceCaller(numberOfCalls, stack) {\n let n;\n if (numberOfCalls === undefined || numberOfCalls < 0) n = 1;\n n = numberOfCalls + 1;\n let line = stack.split('\\n')[n];\n const start = line.indexOf('(/');\n line = line.substring(start + 1, line.length - 1);\n const baseDir = path.join(__dirname, '../');\n if (line.indexOf(baseDir) > -1) {\n return line.replace(baseDir, '');\n }\n return line;\n }", "function lookupThisFileCaller() {\n return callerLookup(__filename);\n}", "function getStack() {\n return settings.getStack();\n}", "get name() {\n return this.stack.name;\n }", "static sourcePosition() {\n var _a;\n const stackObj = {};\n Error.captureStackTrace(stackObj, Resource.sourcePosition);\n // Parse out the source position of the user code. If any part of the match is missing, return undefined.\n const { file, line, col } = ((_a = Resource.sourcePositionRegExp.exec(stackObj.stack)) === null || _a === void 0 ? void 0 : _a.groups) || {};\n if (!file || !line || !col) {\n return undefined;\n }\n // Parse the line and column numbers. If either fails to parse, return undefined.\n //\n // Note: this really shouldn't happen given the regex; this is just a bit of defensive coding.\n const lineNum = parseInt(line, 10);\n const colNum = parseInt(col, 10);\n if (Number.isNaN(lineNum) || Number.isNaN(colNum)) {\n return undefined;\n }\n return {\n uri: url.pathToFileURL(file).toString(),\n line: lineNum,\n column: colNum,\n };\n }", "static getStackFrame(id) {\n return stacks[id]\n }", "function traceCaller(n) {\n\t\tif (isNaN(n) || n < 0) n = 1;\n\t\tn += 1;\n\t\tlet s = (new Error()).stack\n\t\t\t\t, a = s.indexOf('\\n', 5);\n\t\twhile (n--) {\n\t\t\ta = s.indexOf('\\n', a + 1);\n\t\t\tif (a < 0) {\n\t\t\t\ta = s.lastIndexOf('\\n', s.length);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tlet b = s.indexOf('\\n', a + 1);\n\t\tif (b < 0) b = s.length;\n\t\ta = Math.max(s.lastIndexOf(' ', b), s.lastIndexOf('/', b));\n\t\tb = s.lastIndexOf(':', b);\n\t\ts = s.substring(a + 1, b);\n\t\treturn '[' + s + ']';\n\t}", "function inferCaller(stack) {\n\tfor (var index = stack.length; index > 0; index--)\n\t\tif (stack[index - 1].getFileName() == __filename)\n\t\t\treturn stack[index];\n}", "getSourceFile() {\r\n if (this._context == null)\r\n return undefined;\r\n const file = this.compilerObject.file;\r\n return file == null ? undefined : this._context.compilerFactory.getSourceFile(file, { markInProject: false });\r\n }", "function getStackInfo(stackIndex) {\n // get call stack, and analyze it\n // get all file, method, and line numbers\n var stacklist = new Error().stack.split('\\n').slice(3)\n\n // stack trace format:\n // http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi\n // do not remove the regex expresses to outside of this method (due to a BUG in node.js)\n var stackReg = /at\\s+(.*)\\s+\\((.*):(\\d*):(\\d*)\\)/gi\n var stackReg2 = /at\\s+()(.*):(\\d*):(\\d*)/gi\n\n var s = stacklist[stackIndex] || stacklist[0]\n var sp = stackReg.exec(s) || stackReg2.exec(s)\n\n if (sp && sp.length === 5) {\n return {\n method: sp[1],\n relativePath: path.relative(PROJECT_ROOT, sp[2]),\n line: sp[3],\n pos: sp[4],\n file: path.basename(sp[2]),\n stack: stacklist.join('\\n'),\n }\n }\n}", "static getActiveStackFrame() {\n return active\n }", "function stackTrace(fn) {\r\n if (!fn) fn = arguments.caller.callee;\r\n var list = [];\r\n while (fn && list.length < 10) {\r\n list.push(fn);\r\n fn = fn.caller;\r\n }\r\n list = list.map(function(fn) {\r\n return '' + fn;\r\n });\r\n res.die(list.join('\\r\\n\\r\\n'));\r\n}", "getPreviousEnvironment() {\n\n }", "toString() {\n return `${this.constructor.name}( ${this._stack\n .map((rc) => rc.toString())\n .join(', ')} )`;\n }", "function show(exn) /* (exn : exception) -> string */ {\n return stack_trace(exn);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try to get a parse tree that spans at least up to `upto`. The method will do at most `timeout` milliseconds of work to parse up to that point if the tree isn't already available.
function ensureSyntaxTree(state, upto, timeout = 50) { var _a let parse = (_a = state.field(Language.state, false)) === null || _a === void 0 ? void 0 : _a.context if (!parse) return null let oldVieport = parse.viewport parse.updateViewport({ from: 0, to: upto }) let result = parse.isDone(upto) || parse.work(timeout, upto) ? parse.tree : null parse.updateViewport(oldVieport) return result }
[ "function forceParsing(view, upto = view.viewport.to, timeout = 100) {\n let success = ensureSyntaxTree(view.state, upto, timeout)\n if (success != dist_syntaxTree(view.state)) view.dispatch({})\n return !!success\n }", "static getSkippingParser(until) {\n return new (class extends dist_Parser {\n createParse(input, fragments, ranges) {\n let from = ranges[0].from,\n to = ranges[ranges.length - 1].to\n let parser = {\n parsedPos: from,\n advance() {\n let cx = currentContext\n if (cx) {\n for (let r of ranges) cx.tempSkipped.push(r)\n if (until)\n cx.scheduleOn = cx.scheduleOn\n ? Promise.all([cx.scheduleOn, until])\n : until\n }\n this.parsedPos = to\n return new dist_Tree(dist_NodeType.none, [], [], to - from)\n },\n stoppedAt: null,\n stopAt() {}\n }\n return parser\n }\n })()\n }", "function unrollNodeUptoLimit(node, limit) {\n\tif (limit < 0) {\n\t\treturn limit;\n\t}\n\t\n\t// Current node is not a repeated node, unroll its children\n\tif (!node.repeat || !node.repeat.count) {\n\t\treturn unrollChildrenUptoLimit(node, limit);\n\t}\n\n\t// Curent node is a repeated node. \n\t// Make clones of it, unroll its children and append the clones to the parent.\n\t// If Current node is a group, then append its children to the parent instead\n\tfor (let i = 0; i < node.repeat.count; i++) {\n\t\tif (limit <= 0) {\n\t\t\tbreak;\n\t\t}\n\n\t\tconst clone = node.clone(true);\n\t\tclone.repeat.value = i+1;\n\t\tlimit = unrollChildrenUptoLimit(clone, limit);\n\t\t\n\t\tif (clone.isGroup) {\n\t\t\twhile (clone.children.length > 0) {\n\t\t\t\tclone.firstChild.repeat = clone.repeat;\n\t\t\t\tnode.parent.insertBefore(clone.firstChild, node);\n\t\t\t}\n\t\t} else {\n\t\t\tnode.parent.insertBefore(clone, node);\n\t\t}\n\t}\n\t\n\tnode.parent.removeChild(node);\n\treturn limit;\n}", "function tryInfiniteScroll(n) {\n var p = new Promise();\n\n whenAll(\n whenXhrFinished(),\n scroll(window, 'left', 'bottom')\n ).then(function (values) {\n var intercepted = values[0]; // The return value from whenXhrFinished()\n\n if (intercepted && n > 1) {\n p.resolve(tryInfiniteScroll(n-1));\n } else {\n p.resolve();\n }\n });\n\n return p;\n }", "buildLimit(t, value) {\n value = parseInt(value)\n if (value === 0)\n return t\n return t.limit(value)\n }", "newNode (options) {\n return process.env._TEST_ARBORIST_SLOW_LINK_TARGET_ === '1'\n ? new Promise(res => setTimeout(() => res(new Node(options)), 10))\n : new Node(options)\n }", "function unrollChildrenUptoLimit(node, limit) {\n\tif (!node.isGroup) {\n\t\tlimit--;\n\t}\n\tif (node.children) {\n\t\t// Make a copy of the children before unrolling as more might get added during unrolling\n\t\tvar nodeChildren = node.children.slice();\n\t\tfor (var i = 0; i < nodeChildren.length; i++) {\n\t\t\tif (limit > 0) {\n\t\t\t\tlimit = unrollNodeUptoLimit(nodeChildren[i], limit);\n\t\t\t} else {\n\t\t\t\tnode.removeChild(nodeChildren[i]);\n\t\t\t}\n\t\t}\n\t}\n\treturn limit;\n}", "next() {\n let tmp = this.currentNode.next();\n\n if (!tmp.done) {\n this.currentNode = tmp.value;\n this.ptree();\n }\n\n return tmp;\n }", "function findAndAdd(n, matches) {\n\tif (! n || ! n.parentNode) return;\n\tif (! matches) matches = function(n) { return true; };\n\tvar df = document.createDocumentFragment();\n\tcollectNodes(n, matches, df);\n\t// for (var i=0; i<df.childNodes.length; i++) {\n\t//\tconsole.log(df.childNodes[i]);\n\t// }\n\tn.parentNode.appendChild(df);\n}", "function findReachablePositions(player, position) { // PARAMETERS : player, position\n\n reachs = []; // vider le tableau des cases atteignables\n\n var surrounds = findSurroundingPositions(position); // create a variable to define surrounding positions\n var range = 0; // set distance tested to zero\n\n // Define reachable positions : top\n\n while ( // WHILE...\n (surrounds[1] !== null) && // ...the position above exist (not outside of the board)\n (squares[surrounds[1]].player === 0) && // ... AND the position above is not occupied by a player\n (squares[surrounds[1]].obstacle === 0) && // ... AND the position above is not occupied by an obstacle\n (range < 3) // ... AND the tested position distance from player position is below 3\n ) { // THEN\n var reach = Object.create(Reach); // create an object reach\n reachFight = isLeadingToFight(player, surrounds[1]); // define is the reachable position is a fighting position\n reach.initReach(player, surrounds[1], -10, (range + 1), reachFight); // set properties\n reachs.push(reach); // push object in array\n range++; // increase range of position tested\n surrounds = findSurroundingPositions(position - (10 * range)); // move forward the test\n }\n\n // Define reachable positions : right\n\n range = 0; // reset range for next test\n surrounds = findSurroundingPositions(position); // reset surrounds for next test\n\n while (\n (surrounds[4] !== null) &&\n (squares[surrounds[4]].player === 0) &&\n (squares[surrounds[4]].obstacle === 0) &&\n (range < 3)\n ) {\n var reach = Object.create(Reach);\n reachFight = isLeadingToFight(player, surrounds[4]);\n reach.initReach(player, surrounds[4], +1, (range + 1), reachFight);\n reachs.push(reach);\n range++;\n surrounds = findSurroundingPositions(position + (1 * range));\n }\n\n // Define reachable positions : bottom\n\n range = 0;\n surrounds = findSurroundingPositions(position);\n\n while (\n (surrounds[6] !== null) &&\n (squares[surrounds[6]].player === 0) &&\n (squares[surrounds[6]].obstacle === 0) &&\n (range < 3)\n ) {\n var reach = Object.create(Reach);\n reachFight = isLeadingToFight(player, surrounds[6]);\n reach.initReach(player, surrounds[6], +10, (range + 1), reachFight);\n reachs.push(reach);\n range++;\n surrounds = findSurroundingPositions(position + (10 * range));\n }\n\n // Define reachable positions : left\n\n range = 0;\n surrounds = findSurroundingPositions(position);\n\n while (\n (surrounds[3] !== null) &&\n (squares[surrounds[3]].player === 0) &&\n (squares[surrounds[3]].obstacle === 0) &&\n (range < 3)\n ) {\n var reach = Object.create(Reach);\n reachFight = isLeadingToFight(player, surrounds[3]);\n reach.initReach(player, surrounds[3], -1, (range + 1), reachFight);\n reachs.push(reach);\n range++;\n surrounds = findSurroundingPositions(position - (1 * range));\n }\n\n return reachs; // return array\n\n}", "function findPanorama(point, index, paLength, panoArray){\n webService.getPanoramaByLocation(point, RADIUS, function(result, status){\n console.log('index', index);\n currentIteration++;\n panoArray[index] = result;\n\n //Conditional to check if we move on can only be done in here\n //by incrementing currentIteration until it matches\n //the limit, or the length of routes[0].overview_path\n //If we're on the last iteration, parse the entire array\n if (currentIteration == (paLength > LIMIT ? LIMIT : paLength)){\n parsePanoramaArray(panoArray);\n }\n });\n }", "function parseTree(text, errors, options) {\n if (errors === void 0) { errors = []; }\n var currentParent = { type: 'array', offset: -1, length: -1, children: [] }; // artificial root\n function ensurePropertyComplete(endOffset) {\n if (currentParent.type === 'property') {\n currentParent.length = endOffset - currentParent.offset;\n currentParent = currentParent.parent;\n }\n }\n function onValue(valueNode) {\n currentParent.children.push(valueNode);\n return valueNode;\n }\n var visitor = {\n onObjectBegin: function (offset) {\n currentParent = onValue({ type: 'object', offset: offset, length: -1, parent: currentParent, children: [] });\n },\n onObjectProperty: function (name, offset, length) {\n currentParent = onValue({ type: 'property', offset: offset, length: -1, parent: currentParent, children: [] });\n currentParent.children.push({ type: 'string', value: name, offset: offset, length: length, parent: currentParent });\n },\n onObjectEnd: function (offset, length) {\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onArrayBegin: function (offset, length) {\n currentParent = onValue({ type: 'array', offset: offset, length: -1, parent: currentParent, children: [] });\n },\n onArrayEnd: function (offset, length) {\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onLiteralValue: function (value, offset, length) {\n onValue({ type: getLiteralNodeType(value), offset: offset, length: length, parent: currentParent, value: value });\n ensurePropertyComplete(offset + length);\n },\n onSeparator: function (sep, offset, length) {\n if (currentParent.type === 'property') {\n if (sep === ':') {\n currentParent.columnOffset = offset;\n }\n else if (sep === ',') {\n ensurePropertyComplete(offset);\n }\n }\n },\n onError: function (error) {\n errors.push({ error: error });\n }\n };\n visit(text, visitor, options);\n var result = currentParent.children[0];\n if (result) {\n delete result.parent;\n }\n return result;\n}", "goLeft(n, tree) {\n\t\tfor (let i = 0; i < n; i++){\n\t\t\tif (!tree.root.left)\n\t\t\t\tthrow new Error(`Cannot go further left than ${i + 1} moves.`)\n\t\t\ttree.root = tree.root.left;\n\t\t}\n\t\treturn tree;\n\t}", "scanUntil(regexp) {\n const index = this._tail.search(regexp);\n let match;\n switch (index) {\n case -1:\n match = this._tail;\n this._tail = '';\n break;\n case 0:\n match = '';\n break;\n default:\n match = this._tail.substring(0, index);\n this._tail = this._tail.substring(index);\n }\n this._pos += match.length;\n return match;\n }", "function parse(html, shouldSort) {\n var $ = cheerio.load(html);\n\n return $('page').map((idx, pageElem) => {\n var $page = $(pageElem);\n\n return new Page(\n $page.attr('width'), $page.attr('height'),\n $page.children('word').map((idx, wordElem) => {\n var $word = $(wordElem);\n\n return new Text(\n $word.attr('xmin'), $word.attr('xmax'),\n $word.attr('ymin'), $word.attr('ymax'), $word.text().trim()\n );\n }).get()\n );\n }).get();\n}", "function fillupTripCountTreeNode(tripCountNode) {\n if (Object.entries(tripCountNode['children']) == 0)\n return;\n let tripCount = tripCountNode.trip_count;\n for (let childID in tripCountNode['children']) {\n // For every subloop, make sure there are enough trip count nodes\n if (parseInt(tripCountNode['children'][childID].length) < tripCount) {\n let savedLength = tripCountNode['children'][childID].length;\n let lastTCNode = tripCountNode['children'][childID][savedLength - 1];\n for (let i = savedLength; i < tripCount; i++) {\n tripCountNode['children'][childID].push(lastTCNode); // A bunch of references should be fine...?\n }\n }\n else if (parseInt(tripCountNode['children'][childID].length) > tripCount) {\n let savedLength = tripCountNode['children'][childID].length;\n for (let i = tripCount; i < savedLength; i++) {\n tripCountNode['children'][childID].pop(); // Remove last element\n }\n } // Do nothing if they're equal \n }\n for (let childID in tripCountNode['children']) {\n for (let i = 0; i < tripCount; i++) {\n fillupTripCountTreeNode(tripCountNode['children'][childID][i]);\n }\n }\n}", "tokenBefore(types) {\n let token = this.state.tree.resolve(this.pos, -1);\n while (token && types.indexOf(token.name) < 0)\n token = token.parent;\n return token ? { from: token.from, to: this.pos,\n text: this.state.sliceDoc(token.from, this.pos),\n type: token.type } : null;\n }", "__groupNodesByPosition(rawNodes) {\n const nodes = [];\n let tmpStack = [];\n _.each(rawNodes, (rawNode, index) => {\n // Check current and next node position\n const $rawNode = $(rawNode);\n const currentNodePosition = this.__getBottomPosition($rawNode);\n let nextNodePosition = -9999;\n if (rawNodes[index + 1]) {\n nextNodePosition = this.__getBottomPosition(rawNodes[index + 1]);\n }\n\n const isListItem = this.__isListItem($rawNode);\n let gapThreshold = 20;\n if (isListItem) {\n gapThreshold = 15;\n }\n\n // Too far appart, we need to add them\n if (currentNodePosition - nextNodePosition > gapThreshold) {\n let content = $rawNode.html();\n\n // We have something in the stack, we need to add it\n if (tmpStack.length > 0) {\n tmpStack.push($rawNode);\n content = _.map(tmpStack, tmpNode => tmpNode.html()).join('\\n');\n tmpStack = [];\n }\n\n nodes.push({ type: this.getNodeType($rawNode), content });\n return;\n }\n\n // Too close, we keep in the stack\n tmpStack.push($rawNode);\n });\n return nodes;\n }", "parseUnknown(tokenizer) {\n const start = tokenizer.advance();\n let end;\n if (start === null) {\n return null;\n }\n while (tokenizer.currentToken &&\n tokenizer.currentToken.is(token_1.Token.type.boundary)) {\n end = tokenizer.advance();\n }\n return this.nodeFactory.discarded(tokenizer.slice(start, end), tokenizer.getRange(start, end));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
==================== Ende Abschnitt fuer Klasse Classification ==================== ==================== Abschnitt fuer Klasse TeamClassification ==================== Klasse fuer die Klassifikation der Optionen nach Team (Erst und Zweitteam oder Fremdteam)
function TeamClassification() { this.team = new Team(); this.teamParams = { }; this.renameParamFun = function() { const __MYTEAM = this.team; getMyTeam(this.optSet, this.teamParams, __MYTEAM); if (__MYTEAM.LdNr !== undefined) { // Prefix fuer die Optionen mit gesonderten Behandlung... return __MYTEAM.LdNr.toString() + __MYTEAM.LgNr.toString(); } else { return undefined; } }; }
[ "function Team() {\n this.Team = undefined;\n this.Liga = undefined;\n this.Land = undefined;\n this.LdNr = 0;\n this.LgNr = 0;\n}", "function Off_Teams(a_team){\n\tthis.against = a_team; // This is the team that the offense is built against\n\tthis.num = 0;\n\t\n\tthis.addTeam = function(team, score, version, comment = \"\"){\n\t\tif(comment === null) comment = \"\";\n\t\tthis[this.num] = {team: team, score: score, version: version, comment: comment};\n\t\tthis.num++;\n\t}\n\t\n\tthis.getDefStr = function(){\n\t\treturn this.against.unitsStr();\n\t}\n\t\n\tthis.getTeam = function(num){\n\t\treturn this[num].team.unitsStr();\n\t}\n\t\n\tthis.getScore = function(num){\n\t\treturn this[num].score;\n\t}\n\t\n\tthis.getVersion = function(num){\n\t\treturn this[num].version;\n\t}\n\t\n\tthis.getComment = function(num){\n\t\treturn this[num].comment;\n\t}\n\t\n\t// example properties\n\t// this[0] = Jun_Miyako_Kuka_Ilya_Hiyori\n\t// this[\"Jun_Miyako_Kuka_Ilya_Hiyori\"] = 512\n\t\n\tthis.teamStr = function(num){\n\t\tlet data = this[num];\n\t\tlet team = data.team.split(\"_\");\n\t\tlet main = \":\" + team.join(\": :\") + \": \" + \"Score:\" + data.score + \" V\" + data.version;\n\t\tlet comm = data.comment;\n\t\tif(comm !== \"\"){\n\t\t\tmain = main + \"\\n\" + comm;\n\t\t}\n\t\treturn main;\n\t}\n\t\n\tthis.filtStr = function(){\n\t\tif(this.num == 1){\n\t\t\treturn [this.teamStr(0)];\n\t\t}else{\n\t\t\tlet arr = [];\n\t \t\tfor(let i = 0; i < this.num; i++){\n\t \t\t\tarr[i] = this.teamStr(i);\n\t \t\t}\n\t \t\treturn arr;\n\t \t}\n\t}\n}", "function determineBestTeam(guild) {\n $.each($('body').find('.js-'+ guild +'-hero'), function () {\n var $t = $(this);\n var id = $t.attr('data-id');\n var heroPower = parseInt( $t.attr('data-power') );\n var $titanTeam = $('.js-'+ guild +'-titan[data-id=\"'+ id +'\"]');\n var titanPower = parseInt( $titanTeam.attr('data-power') );\n var className = 'best-team';\n\n if (heroPower > titanPower) {\n $t.addClass(className);\n $titanTeam.removeClass(className);\n } else {\n $titanTeam.addClass(className);\n $t.removeClass(className);\n }\n });\n}", "function selectTeam(data, config) {\n const constraints = config.constraints;\n const t = config.team_type.team;\n let max_players_from_fav_team = constraints.max;\n if (config.team_type.type === 'balanced')\n max_players_from_fav_team = 6;\n \n let players = [];\n let creditLeft = config.max_credit;\n const team1 = t === 1 ? data.team1 : data.team2;\n const team2 = t !== 1 ? data.team1 : data.team2;\n const fav_team_sorted = t === 1 ? _.cloneDeep(data.t1_sorted) : _.cloneDeep(data.t2_sorted);\n const other_team_sorted = t !== 1 ? _.cloneDeep(data.t1_sorted) : _.cloneDeep(data.t2_sorted);\n let fav_team_count = 0;\n let other_team_count = 0;\n\n let counts = {\n wk: 0,\n ar: 0,\n bt: 0,\n bl : 0,\n }\n let totalPlayersToSelect = constraints.wk[0] + constraints.bt[0] + constraints.ar[0] + constraints.bl[0];\n for (let i = 0; i < fav_team_sorted.length; i++) {\n const p = fav_team_sorted[i];\n if (canSelectPlayer(p, counts, constraints, creditLeft)) {\n players.push(p);\n creditLeft -= p.credit;\n counts[p.role]++;\n fav_team_count++;\n totalPlayersToSelect--;\n }\n if (totalPlayersToSelect === 0 || fav_team_count === max_players_from_fav_team)\n break;\n }\n\n // find what are remaining min players and add from other team\n if (totalPlayersToSelect > 0)\n Object.keys(counts).forEach((k) => {\n if (counts[k] < constraints[k][0]) {\n let ot = addPlayer(k, other_team_sorted, constraints[k][0] - counts[k], creditLeft, players);\n creditLeft = ot.rem_credit;\n other_team_count += ot.added_players || 0;\n if (ot.rem_players === 0) // constraints met update counts\n counts[k] = constraints[k][0]\n }\n })\n \n // need to select remaining players from other team with remaining credits left\n totalPlayersToSelect = 11 - players.length; \n const remPlayers = getMaxPointPlayersUnderCredit(other_team_sorted, creditLeft)\n if (remPlayers && remPlayers.players) {\n other_team_count += remPlayers.players.length;\n if (remPlayers.players.length < totalPlayersToSelect) {\n console.error('[getMaxPointPlayersUnderCredit] could not find remaining players within credit limit')\n }\n }\n // console.log('all players')\n const playing11 = [...players, ...remPlayers.players];\n // console.log(playing11)\n const sortedPlaying11 = _.orderBy(playing11, ['points'], ['desc']);\n // console.log('all players - sorted')\n // console.log(sortedPlaying11)\n const cvc_candidates = _.slice(sortedPlaying11, 0, 2);\n // console.log(cvc_candidates)\n return {\n rem_credit: remPlayers.rem_credit,\n players: playing11,\n cvc_candidates: cvc_candidates,\n counts: counts,\n t1: {\n name: team1.name,\n code: team1.code,\n color: team1.color,\n playingCount: fav_team_count\n },\n t2: {\n name: team2.name,\n code: team2.code,\n color: team2.color,\n playingCount: other_team_count\n },\n }\n}", "function selectTeam(team) {\n selectedTeam = team;\n team.classList.add(\"select\");\n\n const opponent = team == teamA ? teamB : teamA;\n if (opponent.classList.contains(\"select\")) {\n opponent.classList.remove(\"select\");\n }\n}", "function Team(teamName, teamColour, numberOfDice, numberOfBacklog, backlogFilled, maximumTaskSize) {\n this.teamName = teamName;\n this.teamColour = teamColour;\n\n this.numberOfDice = ((numberOfDice != null) ? numberOfDice : defaultNumberOfDice);\n this.numberOfBacklog = ((numberOfBacklog != null) ? numberOfBacklog : defaultNumberOfBacklog);\n this.backlogFilled = ((backlogFilled != null) ? backlogFilled : defaultBacklogFilled);\n this.maximumTaskSize = ((maximumTaskSize != null) ? maximumTaskSize : defaultMaximumTaskSize);\n\n /*\n Counter to measure how many tasks are completed\n in current sprint\n */\n this.unitOfWorkCompleted = 0;\n\n /* array of completed tasks per sprint\n */\n this.unitOfWorkCompletedArray = new Array();\n\n /*\n Counter to measure wasted one dice\n in current sprint\n */\n this.wastedOneDice = 0;\n\n /* array of wasted one dice per sprint\n */\n this.wastedOneDiceArray = new Array();\n\n this.teamID = \"team_\" + teamCounter++;\n this.tasksArray = new Array();\n this.backlogTasksArray = new Array();\n this.workInProgressTasksArray = new Array();\n this.doneTasksArray = new Array();\n}", "setPlayerTeam(player, zone, team = undefined) {\n const location = DeathMatchLocation.getById(zone);\n if (!location.hasTeams)\n return;\n\n if (!this.teamScore_.has(zone))\n this.teamScore_.set(zone, new DeathMatchTeamScore());\n\n if (!this.zoneTextDraws_.has(zone)) {\n this.zoneTextDraws_.set(zone, -1);\n const textDraw = new TextDraw({\n position: [482, 311],\n text: '_',\n\n color: Color.fromNumberRGBA(-1),\n shadowColor: Color.fromRGBA(0, 0, 0, 255),\n font: 2,\n letterSize: [0.33, 1.5],\n outlineSize: 1,\n proportional: true,\n });\n\n\n this.zoneTextDraws_.set(zone, textDraw);\n textDraw.displayForPlayer(player);\n } else {\n const textDraw = this.zoneTextDraws_.get(zone);\n textDraw.displayForPlayer(player);\n }\n\n this.updateTextDraw(zone);\n\n if (!isNaN(team) && team < 2) {\n this.playerTeam_.set(player, { zone: zone, team: team });\n return;\n }\n\n const teams = [...this.playerTeam_]\n .filter(item => item[1].zone === zone)\n .map(item => item[1].team);\n\n const amountOfRedTeam = teams.filter(item => item === RED_TEAM).length;\n const amountOfBlueTeam = teams.filter(item => item === BLUE_TEAM).length;\n\n const newTeam = amountOfRedTeam <= amountOfBlueTeam ? RED_TEAM : BLUE_TEAM;\n\n this.playerTeam_.set(player, { zone: zone, team: newTeam });\n }", "init_teams(teams)\n {\n console.log(teams);\n this.teams = {};\n // insert each team object in the teams array\n Object.keys(teams).forEach((t, idx) =>\n {\n // this.teams.push(new this.team_class(this, team_name, teams[team_name], idx));\n this.teams[teams[t][\"name\"]] = new this.team_class(this, teams[t][\"name\"], teams[t][\"score\"], idx, teams[t][\"color\"]);\n });\n }", "function solveClasses() {\n class Developer {\n constructor ( firstName, lastName ) {\n this.firstName = firstName; \n this.lastName = lastName; \n this.baseSalary = 1000; \n this.tasks = []; \n this.experience = 0; \n }\n addTask ( id, name, priority ) {\n let obj = {id, name, priority};\n if(priority == 'high') this.tasks.unshift(obj);\n else this.tasks.push(obj);\n return Task id ${id}, with ${priority}", "function addNATeams(teamDropdown) {\n\t$(teamDropdown).append(createTeamOption('Team Solo Mid',TSMimg));\n\t$(teamDropdown).append(createTeamOption('Counter Logic Gaming',CLGimg));\n\t$(teamDropdown).append(createTeamOption('Cloud9 HyperX',C9img));\n\t$(teamDropdown).append(createTeamOption('XDG',XDGimg));\n\t$(teamDropdown).append(createTeamOption('Evil Geniuses',EGimg));\n\t$(teamDropdown).append(createTeamOption('Dignitas',DIGimg));\n\t$(teamDropdown).append(createTeamOption('Team Coast',CSTimg));\n\t$(teamDropdown).append(createTeamOption('Curse Gaming',CRSimg));\n\t$(teamDropdown).append(createTeamOption('LMQ',LMQimg));\n\t$(teamDropdown).append(createTeamOption('compLexity Gaming',COLimg));\n\t/* ADD OTHER TEAMS HERE */\n}", "function teamValidation() {\r\n //Setup team\r\n var team = $(\".team\");\r\n\r\n //Validate the team when we select\r\n team.change(function() {\r\n var teamSelect = $(this).val();\r\n\r\n //Make sure that it is in the teams array\r\n if($.inArray(teamSelect, teams) !== -1) {\r\n $(this).css({\"borderColor\": \"lime\"});\r\n if($(this).parent().is(\"div\")) {\r\n $(this).unwrap();\r\n $(this).siblings().remove();\r\n Global.enableButton($(\"#saveAll\"));\r\n }\r\n } else {\r\n //It isn't valid, create the tooltip, set the border color to red for failure and disable the save all button\r\n $(this).wrap(\"<div class='tooltip'>\");\r\n $(this).after(\"<span class='tooltipMessage'>Please select a valid team.</span>\");\r\n $(this).css({\"borderColor\": \"red\"});\r\n Global.disableButton($(\"#saveAll\"));\r\n }\r\n });\r\n }", "function teamNumber(teamtext) {\n if(teamtext == 'CT') {\n if(structure.rounds.length > 15) {\n return 2;\n } else {\n return 1;\n }\n } else if(teamtext == 'TERRORIST') {\n if(structure.rounds.length > 15) {\n return 1;\n } else {\n return 2;\n }\n }\n}", "static loadTeam(_id) {\n if (!loadedTeams[_id]) {\n Account.find({_id})\n .then((res, err) => {\n if (res[0].accountType === \"player\") {\n if (err) {\n logger.error(\"Error loading team data from db... \", err);\n } else {\n const {\n _id,\n name,\n locationId,\n score,\n puzzles,\n lastUpdated\n } = res[0];\n\n new this(_id, name, locationId, score, puzzles, lastUpdated);\n }\n }\n });\n }\n loadedTeams[_id] = true;\n }", "function calculate_class_score_commonality(sentence, className){\r\n\tvar score = 0;\r\n\tvar mySentence = sw.removeStopwords(token.tokenize(sentence));\r\n\tvar word;\r\n\tfor (word in mySentence){\r\n\t\tvar stemmed_word = stemmer(mySentence[word])\r\n\t\tif (class_words[className].contains(stemmed_word)){\r\n\t\t\t score += (1 / corpus_words[stemmed_word])\r\n\t\t}\r\n\t}\r\n\treturn score;\r\n}", "function makeTeams() {\n for (var i = 0; i < data.players.length; i++) {\n if (data.players[i].team_name === team1Name) {\n team1 = team1.concat(data.players[i]);\n } else {\n team2 = team2.concat(data.players[i]);\n }\n }\n}", "function optimalClasses(classes) {\n if (classes.length <= 4) {\n return escapeClasses(classes)\n }\n let optima\n if (classes.slice) {\n optima = classes.slice()\n } else {\n optima = []\n for (let i = 0; i < classes.length; i++) {\n optima.push(classes[i])\n }\n }\n const uniq = new Set()\n for (let i = 0; i < optima.length;) {\n if (uniq.has(optima[i])) {\n optima.splice(i, 1)\n } else {\n uniq.add(optima[i])\n i += 1\n }\n }\n optima = escapeClasses(optima)\n if (optima.length <= 4) {\n return optima\n }\n optima.sort(function (a, b) {\n let cmp = hits(a).length - hits(b).length\n if (!cmp) {\n cmp = a.length - b.length\n }\n if (!cmp) {\n cmp = a < b ? -1 : 1\n }\n return cmp\n })\n return optima.slice(0, 4)\n}", "function CheckInSubEntityTeamCoach(parameters) {\n var first_name = parameters.first_name, full_name = parameters.full_name, id = parameters.id, last_name = parameters.last_name, member_number = parameters.member_number, compliance_summary = parameters.compliance_summary, can_be_added_to_roster = parameters.can_be_added_to_roster, cannot_be_added_to_roster_reason = parameters.cannot_be_added_to_roster_reason, email_address = parameters.email_address, phone_number = parameters.phone_number;\n this.first_name = first_name;\n this.full_name = full_name;\n this.id = id;\n this.last_name = last_name;\n this.member_number = member_number;\n this.compliance_summary = compliance_summary;\n this.can_be_added_to_roster = can_be_added_to_roster;\n this.cannot_be_added_to_roster_reason = cannot_be_added_to_roster_reason;\n this.email_address = email_address;\n this.phone_number = phone_number;\n }", "function addEUTeams(teamDropdown) {\n\t$(teamDropdown).append(createTeamOption('Supa Hot Crew',SHCimg));\n\t$(teamDropdown).append(createTeamOption('SK Gaming',SKimg));\n\t$(teamDropdown).append(createTeamOption('Copenhagen Wolves',CWimg));\n\t$(teamDropdown).append(createTeamOption('Alliance',ALLimg));\n\t$(teamDropdown).append(createTeamOption('Gambit Gaming',GMBimg));\n\t$(teamDropdown).append(createTeamOption('Fnatic',FNCimg));\n\t$(teamDropdown).append(createTeamOption('Millenium',MILimg));\n\t$(teamDropdown).append(createTeamOption('Team ROCCAT',ROCimg));\n\t/* ADD OTHER TEAMS HERE */\n}", "servingTeam() {\n if (this.serving == this.players[0]) {\n return(nameWest);\n } else if (this.serving == this.players[1]) {\n return(nameWest);\n } else if (this.serving == this.players[2]) {\n return(nameEast);\n } else if (this.serving == this.players[3]) {\n return(nameEast);\n } else {\n alert(txt_Invalid1 + this.serving\n + txt_Invalid2 + name_e\n + txt_SQComma + name_o\n + txt_SQComma + name_E\n + txt_SQCommaOr + name_O\n + txt_SQParen);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Render the minimap gravity grid . ctx: The canvas rendering context instance. cameraPos: Camera position as an x, y object. w: Width of the minimap as a number. h: Height of the minimap as a number. scale: Zoom out factor of the minimap as a number. planets: An array of Planet instances in the game world.
function renderMinimapGravityGrid(ctx, cameraPos, w, h, scale, planets) { ctx.save(); let start = { x: -(MINIMAP_POINT_SPREAD * MINIMAP_GRID_BUFFER + cameraPos.x) % MINIMAP_POINT_SPREAD, y: -(MINIMAP_POINT_SPREAD * MINIMAP_GRID_BUFFER + cameraPos.y) % MINIMAP_POINT_SPREAD }; ctx.fillStyle = '#ffffff'; ctx.strokeStyle = '#0C3613'; ctx.lineWidth = scale; // To make the lines about 1 pixel in width. let colsAmount = ((w * scale) / MINIMAP_POINT_SPREAD) + MINIMAP_GRID_BUFFER; let rowsAmount = ((h * scale) / MINIMAP_POINT_SPREAD) + MINIMAP_GRID_BUFFER; let columns = []; for (let i = 0; i < colsAmount; i++) { if (!columns[i]) { columns.push([]); } for (let j = 0; j < rowsAmount; j++) { let pointVisual = { x: start.x + i * MINIMAP_POINT_SPREAD, y: start.y + j * MINIMAP_POINT_SPREAD }; let pointWorld = makeWorldPoint(pointVisual, w, h, scale, cameraPos); let finalWorldPoint = applyMinimapGravity(pointWorld, pointVisual, planets, w, h, scale, cameraPos); let finalVisual = makeVisualPoint(finalWorldPoint, w, h, scale, cameraPos); columns[i].push(finalVisual); // look for the point next to this point if (columns[i - 1] && columns[i - 1][j]) { renderLine(ctx, columns[i - 1][j], finalVisual); } // look for the point above this point if (columns[i] && columns[i][j - 1]) { renderLine(ctx, columns[i][j - 1], finalVisual); } } } ctx.restore(); }
[ "function applyMinimapGravity(pointWorld, pointVisual, planets, w, h, scale, cameraPos) {\n let visual = { x: pointVisual.x, y: pointVisual.y };\n\n let gravityDominator = planets[0];\n let gravity = null;\n\n for (let k = planets.length - 1; k >= 0; k--) {\n let g = applyGravity(planets[k], pointWorld);\n let gMag = V.magnitude(g);\n if (gravity === null || gravity < gMag) {\n gravityDominator = planets[k];\n gravity = gMag;\n }\n visual.x += g.x * MINIMAP_G_FACTOR;\n visual.y += g.y * MINIMAP_G_FACTOR;\n }\n\n let visualWorldPoint = makeWorldPoint(visual, w, h, scale, cameraPos);\n return limitGravityLine(pointWorld, visualWorldPoint, gravityDominator);\n}", "function renderGrid(ctx) {\n drawGridLines(ctx);\n drawGridCells(ctx, minesweeper.cells );\n}", "function render() {\n\n // This array holds the relative URL to the image used\n // for that particular row of the game level.\n var rowImages = [\n 'images/water-block.png', // Top row is water\n 'images/stone-block.png', // Row 1 of 3 of stone\n 'images/stone-block.png', // Row 2 of 3 of stone\n 'images/stone-block.png', // Row 3 of 3 of stone\n 'images/grass-block.png', // Row 1 of 2 of grass\n 'images/grass-block.png' // Row 2 of 2 of grass\n ],\n numRows = 6,\n numCols = 5,\n row, col;\n\n // Loop through the number of rows and columns we've defined above\n // and, using the rowImages array, draw the correct image for that\n // portion of the \"grid\"\n for (row = 0; row < numRows; row++) {\n for (col = 0; col < numCols; col++) {\n /* The drawImage function of the canvas' context element\n * requires 3 parameters: the image to draw, the x coordinate\n * to start drawing and the y coordinate to start drawing.\n * We're using our Resources helpers to refer to our images\n * so that we get the benefits of caching these images, since\n * we're using them over and over.\n */\n ctx.drawImage(Resources.get(rowImages[row]), col * 101, row * 83);\n }\n }\n\n renderEntities();\n\n scoreBoard();\n }", "function renderContinuous() {\n\n mctx.clearRect(0, 0, mcanvas.width, mcanvas.height );\n\n for (var el in map) {\n mctx.drawImage( map[el].buffer, \n map[el].ref.x - map[el].ref.width/2, \n map[el].ref.y - map[el].ref.height/2 );\n };\n }", "function setSizes() {\n if (!currentMap) return;\n\n const viewMaxWidth = canvasElement.width - dpi(40);\n const viewMaxHeight = canvasElement.height - dpi(40);\n const tileWidth = Math.floor(viewMaxWidth / currentMap.cols);\n const tileHeight = Math.floor(viewMaxHeight / currentMap.rows);\n\n tileSize = Math.min(tileWidth, tileHeight);\n viewWidth = tileSize * currentMap.cols;\n viewHeight = tileSize * currentMap.rows;\n viewX = (canvasElement.width - viewWidth) / 2;\n viewY = (canvasElement.height - viewHeight) / 2;\n}", "function render_gamer() {\n render_aim_helper_line();\n\n if(!processing) {\n gamer.planet.x = gamer.x;\n gamer.planet.y = gamer.y;\n }\n\n if(!remove_animation) {\n var crop = get_planet_crop(gamer.planet.type);\n context.drawImage(planets_image.source, crop, 0, map.planet_w, map.planet_h, gamer.planet.x, gamer.planet.y, map.planet_w, map.planet_h);\n }\n }", "calculateGravity(){\n this.gravity = new Vector(0, 0);\n var range = 1;\n for(var tileX = -range; tileX <= range; tileX++){\n for(var tileY = -range; tileY <= range; tileY++){\n var currTileX = Math.floor(this.position.x) + tileX;\n var currTileY = Math.floor(this.position.y) + tileY;\n\n // check if planet exists at this planet tile. If so, add it to the gravity vector.\n var planet = new Planet(currTileX, currTileY, screen.zoomFactor / 2);\n if (planet.planetExists){\n var distFromPlanet = Math.hypot(currTileX - this.position.x, currTileY - this.position.y);\n var gravityStrength = ((range*3 - distFromPlanet) * planet.gravity) * 0.00001;\n var tempGravVec = new Vector();\n tempGravVec.setMagnitude(gravityStrength);\n tempGravVec.setDirection(Math.atan2(currTileY - this.position.y, currTileX - this.position.x));\n\n this.gravity.addTo(tempGravVec);\n }\n }\n }\n }", "function drawLandscapeTile(v, x, y){\n var top, sides, nearWater = false;\n\tvar v2 = noiseTracker2[y][x];\n if (v < 0.2) {\n top = color(184, 100, 98);\n sides = color(215, 56, 60);\n translate(0, 10);\n }\n else if (v < 0.75) {\n top = color(255, 74, 43);\n\t\tsides = color(215, 56, 60);\n }\n else {\n top = color(120, 100, 70);\n\t\tsides = color(276, 66, 62);\n translate(0, -40);\n }\n\n\n //regular cube\n if (v < 0.75) {\n fill(top);\n //top\n quad(0, 20, 40, 40, 0, 60, -40, 40);\n fill(sides);\n //left side\n quad(-40, 40, 0, 60, 0, 100, -40, 80);\n //right side\n quad(40, 40, 0, 60, 0, 100, 40, 80);\n\t\t\n\t\tnearWater = isThereWaterNearby(x, y);\n\t\tif(v > 0.19){\t\n\t\t\tif(nearWater && v2 > 0.5){\n\t\t\t\timage(city, 0, 30, 50, 50);\n\t\t\t}\n\t\t\telse if(v2 > 0.7){\n\t\t\t\t//calculations to give the trees varying sizes and allow to grow each day\n\t\t\t\tvar treeSize = ((v2 * 100) - 50) + (dayNumber * 5);\n\t\t\t\tif(treeSize > 50){\n\t\t\t\t\ttreeSize = 50;\n\t\t\t\t}\n\t\t\t\timage(trees, 0, 30, treeSize, treeSize);\n\t\t\t}\n\t\t}\n\t\t\n }\n //mountain\n else {\n fill(317, 97, 80);\n\t\t//left side\n quad(0, 20, 0, 60, 0, 100, -40, 80);\n\t\tfill(sides);\n //right side\n quad(0, 20, 0, 60, 0, 100, 40, 80);\n fill(top);\n }\n\n\n\n //reset any translations\n if (v < 0.2) {\n translate(0, -10);\n }\n else if (v < 0.75) {\n //do nothing\n }\n else {\n translate(0, 40);\n }\n}", "function renderGame()\n{\n // CLEAR THE CANVAS\n canvas2D.clearRect(0, 0, canvasWidth, canvasHeight);\n \n // RENDER THE GRID LINES, IF NEEDED\n if (cellLength >= GRID_LINE_LENGTH_RENDERING_THRESHOLD)\n renderGridLines();\n \n // RENDER THE GAME CELLS\n drawBorders();\n renderCells();\n \n // AND RENDER THE TEXT\n renderText();\n \n // THE GRID WE RENDER THIS FRAME WILL BE USED AS THE BASIS\n // FOR THE UPDATE GRID NEXT FRAME\n swapGrids();\n}", "function render() {\n\t//clear all canvases for a fresh render\n\tclearScreen();\n\t\n\t//draw objects centered in order\n\tfor (let i = 0; i < objects.length; ++i) {\n\t\tdrawCentered(objects[i].imgName,ctx, objects[i].x, objects[i].y,objects[i].dir);\n\t}\n\t\n\t//finally draw the HUD\n\tdrawHUD();\n}", "function Engine(viewport, tileFunc, w, h) {\n this.viewport = viewport;\n this.tileFunc = tileFunc;\n this.w = w;\n this.h = h;\n this.refreshCache = true;\n this.cacheEnabled = false;\n this.transitionDuration = 0;\n this.cachex = 0;\n this.cachey = 0;\n this.tileCache = new Array(viewport.h);\n this.tileCache2 = new Array(viewport.h);\n for (var j = 0; j < viewport.h; ++j) {\n this.tileCache[j] = new Array(viewport.w);\n this.tileCache2[j] = new Array(viewport.w);\n }\n }", "function gravity_spawn()\n{\n\tstop_gravity();\n\tspawn_piece();\n\trender_board(board);\n\tqueue_gravity();\n}", "function renderplat(){\n for(var i=0; i<platforms.length;i++){\n ctx.fillStyle = platforms[i].color;\n ctx.fillRect(platforms[i].x, platforms[i].y, platforms[i].width, platforms[i].height);\n }\n}", "function renderplat(){\n ctx.fillStyle = \"#8C158E\";\n platforms.forEach((platform) => {\n ctx.fillRect(platform.x, platform.y, platform.width, platform.height);\n })\n}", "function renderLevel(args,cb){\n var bbox = args.bbox;\n var xyz = mercator.xyz(bbox, args.z);\n\n var alltiles = [];\n \n var i = 1;\n var total = (xyz.maxX - xyz.minX + 1) * (xyz.maxY - xyz.minY+ 1);\n for (var x = xyz.minX; x <= xyz.maxX; x++) {\n for (var y = xyz.minY; y <= xyz.maxY; y++) {\n alltiles.push({\n progress: args.progress,\n city: args.city,\n index: i++,\n total: total,\n pool: args.pool,\n z: args.z,\n x: x,\n y: y\n });\n }\n }\n \n \n async.map(alltiles, renderTile, function(err, results){\n if (err) return cb(err);\n cb(results);\n });\n}", "function drawMaze(){\n\t//xy offsets so that the map is centered in the canvas\n\toffsetx = (canvas.width/2)-(width*imgSize)/2;\n\toffsety = (canvas.height/2)-(height*imgSize)/2;\n\t\n\t//Drawing coloured background, and then setting draw colour back to black.\n\tcontext.fillStyle=\"#D1FFF0\";\n\tcontext.fillRect( 0 , 0 , canvas.width, canvas.height );/*Clearing canvas*/\t\n\tcontext.fillStyle=\"#000000\";\n\t\n\t\n\tfor(var i=0; i<height; i++){\n\t\tfor(var j=0; j<width; j++){\n\t\t\t\n\t\t\t//If they can see the whole map, or the position is located directly next to the player.\n\t\t\tif(!limitedSight||\n\t\t\t((j>=playerPositionx-1&&j<=playerPositionx+1\n\t\t\t&&i>=playerPositiony-1&&i<=playerPositiony+1)&&!isPaused)){\n\t\t\t\t\n\t\t\t\tif(map[j][i]=='.'){/*Wall*/\n\t\t\t\t\tcontext.drawImage(wall, offsetx+j*imgSize, offsety+i*imgSize, imgSize, imgSize);\n\t\t\t\t} else if(map[j][i]=='P'&&solutionVisible){/*Path*/\n\t\t\t\t\tcontext.drawImage(path, offsetx+j*imgSize, offsety+i*imgSize, imgSize, imgSize);\n\t\t\t\t}else {/*Ground*/\n\t\t\t\t\tcontext.drawImage(floor, offsetx+j*imgSize, offsety+i*imgSize, imgSize, imgSize);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(j==playerPositionx&&i==playerPositiony)/*player*/\n\t\t\t\t\tcontext.drawImage(character, offsetx+j*imgSize, offsety+i*imgSize, imgSize, imgSize);\n\t\t\t\t\t\n\t\t\t\tif(j==targetx&&i==targety)/*toilet (maze end)*/\n\t\t\t\t\tcontext.drawImage(toiletGraphic, offsetx+j*imgSize, offsety+i*imgSize, imgSize, imgSize);\n\t\t\t\t\n\t\t\t\tif(showDistances)/*showing movement distance from the player to this tile*/\n\t\t\t\t\tcontext.fillText(distanceMap[j][i], offsetx+j*imgSize, offsety+(i+1)*imgSize);\n\t\t\t\t\t\n\t\t\t}else{\n\t\t\t\t//if it isnt a tile the player can see, draw a black square.\n\t\t\t\tcontext.drawImage(darkSquareGraphic, offsetx+j*imgSize, offsety+i*imgSize, imgSize, imgSize);\n\t\t\t}\n\t\t\t\n\t\t\tif(isPaused)context.drawImage(pausedTextGraphic, canvas.width/2-pausedTextGraphic.width/2, canvas.height/2-pausedTextGraphic.height/2);\n\t\t\t\n\t\t\t//Drawing lower background panel\n\t\t\tcontext.drawImage(lowerBackgroundGraphic, 0, canvas.height-40, canvas.width, 40);\n\t\t\t//Drawing hint button\n\t\t\tcontext.drawImage(hintButtonGraphic, hintButtonX, hintButtonY, 50, 20);\n\t\t\t//Drawing mute button\n\t\t\tif(isMuted){\n\t\t\t\tcontext.drawImage(mutedGraphic, muteButtonX, muteButtonY);\n\t\t\t}else{\n\t\t\t\tcontext.drawImage(speakerGraphic, muteButtonX, muteButtonY);\n\t\t\t}\n\t\t\t\n\t\t\t//Drawing upper buttons\n\t\t\tcontext.drawImage(trophyGraphic, muteButtonX-20, muteButtonY);\n\t\t\tcontext.drawImage(pauseGraphic, muteButtonX-40, muteButtonY);\n\t\t\t\n\t\t\t//Drawing guide graphics for first level\n\t\t\tif(gameLevel==1){\n\t\t\t\tcontext.drawImage(leftArrowGraphic, 10, (canvas.height/2)-(leftArrowGraphic.height/2));\n\t\t\t\tcontext.drawImage(rightArrowGraphic, canvas.width-10-rightArrowGraphic.width, (canvas.height/2)-(rightArrowGraphic.height/2));\t\t\t\n\t\t\t\tcontext.drawImage(upArrowGraphic, (canvas.width/2)-(upArrowGraphic.width/2), 10);\n\t\t\t\tcontext.drawImage(downArrowGraphic, (canvas.width/2)-(downArrowGraphic.width/2), canvas.height-40-downArrowGraphic.height);\n\t\t\t}\t\t\n\t\t\t//Text portion of guide graphics\n\t\t\tif(controlVisualVisible){\n\t\t\t\tcontext.font = \"17px Arial\";\n\t\t\t\tcontext.fillText(\"Memorize this path to the toilet\", offsetx-32, offsety-12);\n\t\t\t\tcontext.fillText(\"Then retrace it as fast as you can!\", offsetx-50, offsety+width*imgSize+16);\n\t\t\t\t\n\t\t\t\tif(fingerGraphicDown){/*Checking if the finger graphic is up or down*/\n\t\t\t\t\tcontext.drawImage(fingerGraphic, canvas.width-10-rightArrowGraphic.width, (canvas.height/2)-(rightArrowGraphic.height/2));\n\t\t\t\t}else{\n\t\t\t\t\tcontext.drawImage(fingerGraphic, canvas.width-10-rightArrowGraphic.width, (canvas.height/2)-(rightArrowGraphic.height/2)-20);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t//Drawing graphic for achievement menu window\n\t\t\tif(isAchievementMenu){\n\t\t\t\tcontext.drawImage(achievementsWindowGraphic, canvas.width/2-achievementsWindowGraphic.width/2, canvas.height/2-achievementsWindowGraphic.height/2);\t\t\t\t\n\t\t\t\tif(firstPlayAchievement)context.drawImage(checkMarkGraphic, canvas.width/2-achievementsWindowGraphic.width/2+20, canvas.height/2-achievementsWindowGraphic.height/2+44);\n\t\t\t\tif(firstLevelAchievement)context.drawImage(checkMarkGraphic, canvas.width/2-achievementsWindowGraphic.width/2+20, canvas.height/2-achievementsWindowGraphic.height/2+74);\n\t\t\t\tif(firstHintAchievement)context.drawImage(checkMarkGraphic, canvas.width/2-achievementsWindowGraphic.width/2+20, canvas.height/2-achievementsWindowGraphic.height/2+104);\n\t\t\t\tif(fifthLevelAchievement)context.drawImage(checkMarkGraphic, canvas.width/2-achievementsWindowGraphic.width/2+20, canvas.height/2-achievementsWindowGraphic.height/2+136);\n\t\t\t}\n\t\t\t\n\t\t\t//draw achievement window if its currently being displayed\n\t\t\tif(isShowingMessage)displayAchievement();\n\t\t}\n\t}\n\t//prints score and time at the bottom of the screen\n\ttestingOutput();\n}", "function displayFloor(){\n var countTilesX;\n var countTilesY;\n\n // initialize variables\n countTilesX = 0;\n countTilesY = 0;\n numberOfTilesX = floor_length / tile_length; // stores number of tiles in a row\n numberOfTilesY = floor_width / tile_width; // stores number of tiles in a column\n\n strokeWeight(2);\n rect(0, 0, floor_length, floor_width); // output the background\n\n // generate tiles\n while (countTilesY < numberOfTilesY){ // prevents drawing over in a column\n if (countTilesX < numberOfTilesX){ // prevents drawing over in a row\n rect((0 + countTilesX) * tile_width, (0 + countTilesY) * tile_length, tile_width, tile_length);\n countTilesX = countTilesX + 1;\n } else {\n countTilesY = countTilesY + 1;\n countTilesX = 0;\n }\n }\n}", "render() {\n // Render as usual\n super.render();\n\n // render depth map as texture to quad for testing\n // this.renderDepthMapQuad();\n }", "function patchInCollisionMaps(engine, widthAccessor, heightAccessor) {\n var collisionCanvas = document.createElement(\"canvas\");\n collisionCanvas.id = \"collisionCanvas\";\n collisionCanvas.width = widthAccessor();\n collisionCanvas.height = heightAccessor();\n var collisionCtx = collisionCanvas.getContext('2d');\n // DEBUG\n // document.body.appendChild(collisionCanvas);\n var oldUpdate = ex.Engine.prototype[\"update\"];\n ex.Engine.prototype[\"update\"] = function (delta) {\n var width = widthAccessor();\n var height = heightAccessor();\n if (collisionCanvas.width !== width || collisionCanvas.height !== height) {\n collisionCanvas.width = widthAccessor();\n collisionCanvas.height = heightAccessor();\n collisionCtx = collisionCanvas.getContext('2d');\n }\n oldUpdate.apply(this, [delta]);\n };\n var oldDraw = ex.Engine.prototype[\"draw\"];\n ex.Engine.prototype[\"draw\"] = function (delta) {\n var width = widthAccessor();\n var height = heightAccessor();\n collisionCtx.fillStyle = 'white';\n collisionCtx.fillRect(0, 0, width, height);\n oldDraw.apply(this, [delta]);\n };\n ex.Scene.prototype.draw = function (ctx, delta) {\n ctx.save();\n if (this.camera) {\n this.camera.update(ctx, delta);\n }\n var i, len;\n for (i = 0, len = this.children.length; i < len; i++) {\n // only draw actors that are visible\n if (this.children[i].visible) {\n this.children[i].draw(ctx, delta);\n }\n if (this.children[i] instanceof CollisionActor) {\n this.children[i].drawCollisionMap(collisionCtx, delta);\n }\n }\n ctx.restore();\n };\n engine.collisionCtx = collisionCtx;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove column card count constraints.
removeColumnConstraints() { $('.ghx-busted-max, .ghx-busted-min').removeClass('ghx-busted-min ghx-busted-max'); // Red/yellow background remove $('.ghx-constraint').remove(); // Column header remove }
[ "removeConstraint(constraint) {\n var index = constraintList.indexOf(constraint);\n if (index !== -1) {\n constraintList.splice(index, 1);\n }\n }", "function removeShrink(){\n\t\tvar rows = $b42s_header.find( '.fl-row-content-wrap' ),\n\t\t\tmodules = $b42s_header.find( '.fl-module-content' );\n\n\t\trows.removeClass( 'fl-theme-builder-header-shrink-row-bottom' );\n\t\trows.removeClass( 'fl-theme-builder-header-shrink-row-top' );\n\t\tmodules.removeClass( 'fl-theme-builder-header-shrink-module-bottom' );\n\t\tmodules.removeClass( 'fl-theme-builder-header-shrink-module-top' );\n\t\t$b42s_header.removeClass( 'fl-theme-builder-header-shrink' );\n\t}", "function hide_empty_columns(table) {\r\n\t\tvar column_count = 0;\r\n\t table.each(function(a, tbl) {\r\n\t $(tbl).find('th').each(function(i) {\r\n\t \tcolumn_count++;\r\n\t var remove = true;\r\n\t var currentTable = $(this).parents('table');\r\n\t var tds = currentTable.find('tr td:nth-child(' + (i + 1) + ')');\r\n\t tds.each(function(j) { if (this.innerHTML != '') remove = false; });\r\n\t if (remove) {\r\n\t \tcolumn_count--;\r\n\t $(this).hide();\r\n\t tds.hide();\r\n\t }\r\n\t });\r\n\t });\r\n\r\n\t return column_count;\r\n\t}", "function resetColumns() {\r\n d3.selectAll(\"span\").each(function() {\r\n d3.select(this).style(\"position\", \"static\").style(\"left\", \"0%\");\r\n })\r\n\r\n d3.select(\"#text_container\").style(\"font-size\", \"1.6vw\");\r\n d3.select(\"#column_controls\").style(\"display\", \"none\");\r\n\r\n d3.select(\"#column-controls\").style(\"display\", \"none\");\r\n}", "function removeDim() {\r\n\r\n var gO = NewGridObj; // currently configured grid\r\n\r\n gO.numDims--;\r\n if (gO.numDims == 1) gO.multiCol = 0; //MPI: bug fix\r\n gO.dimTitles.pop();\r\n gO.dimComments.pop();\r\n gO.dimIsExtended.pop(); //MPI:\r\n\r\n // Note. Not updating other variables because they are not visible\r\n //\r\n reDrawConfig(); // redraw with updates\r\n}", "checkCols(){\n\t\tthis.canJump = false;\n\t\tthis.onCeil = false;\n\t\tthis.checkBounds();\n\t\tthis.checkBlocks();\n\t}", "removeAllSlots() {\n var size = this.closet_slots_faces_ids.length;\n for (let i = 0; i < size; i++) {\n this.removeSlot();\n }\n }", "deleteColumn() {\n let tableBand = this.getParent();\n let table = this.getTable();\n if (tableBand !== null && table !== null) {\n let colIndex = tableBand.getColumnIndex(this);\n if (colIndex !== -1) {\n let cmdGroup = new __WEBPACK_IMPORTED_MODULE_3__commands_CommandGroupCmd__[\"a\" /* default */]('Delete column');\n // delete table with current settings and restore below with new columns, necessary for undo/redo\n let cmd = new __WEBPACK_IMPORTED_MODULE_2__commands_AddDeleteDocElementCmd__[\"a\" /* default */](false, table.getPanelItem().getPanelName(),\n table.toJS(), table.getId(), table.getContainerId(), -1, this.rb);\n cmdGroup.addCommand(cmd);\n\n // decrease column count of table\n let columns = __WEBPACK_IMPORTED_MODULE_6__utils__[\"a\" /* convertInputToNumber */](table.getValue('columns')) - 1;\n table.setValue('columns', columns, 'rbro_table_element_columns', false);\n\n // remove column from each table band\n table.getValue('headerData').deleteColumn(colIndex);\n for (let i = 0; i < table.getValue('contentDataRows').length; i++) {\n table.getValue('contentDataRows')[i].deleteColumn(colIndex);\n }\n table.getValue('footerData').deleteColumn(colIndex);\n\n // restore table with new column count and updated settings\n cmd = new __WEBPACK_IMPORTED_MODULE_2__commands_AddDeleteDocElementCmd__[\"a\" /* default */](true, table.getPanelItem().getPanelName(),\n table.toJS(), table.getId(), table.getContainerId(), -1, this.rb);\n cmdGroup.addCommand(cmd);\n\n this.rb.executeCommand(cmdGroup);\n }\n }\n }", "function getNumCols () {\n if (typeof settings.cols === 'function') {\n return settings.cols($win.width());\n }\n else if (typeof settings.cols === 'number') {\n return settings.cols;\n }\n else {\n return base.length;\n }\n }", "function unhideColumns (){\n /* hide the \"unhide\" button, reveal the \"hide\" button */\n hideButtonName=\"hide\"+modelKind;\n unhideButtonName=\"unhide\"+modelKind;\n document.getElementById(unhideButtonName).style.visibility=\"hidden\"; \n document.getElementById(hideButtonName).style.visibility=\"visible\";\n/* make the column with that column name re-appear */\n for (var scanHeader=1;scanHeader<colCount;scanHeader++){\n cetteCol=oneRow[0].getElementsByTagName(\"th\")[scanHeader];\n var colHeader=cetteCol.innerText.replace( /^\\s+|\\s+$/g,\"\");\n if (colHeader==modelKind){\n for (var chaqueRow=0;chaqueRow<rowCount;chaqueRow++){\n var chaqueCell=oneRow[chaqueRow].children[scanHeader];\n chaqueCell.style.display=\"table-cell\";\n chaqueCell.style.width=colWidthUsage;\n }\n }\n }\n}", "function remuevecolumnaEliminar(){\r\n\t\tvar tablaLength = obtenTablaLength(\"invitado_table\");\r\n\t\tfor(var i = 1; i <= tablaLength; i++){\r\n\t\t\t$(\"#tr_\"+i+\" td\", $(\"#invitado_table\")).eq(5).hide();\r\n\t\t}\r\n\t}", "checkCols(){\n\t\tthis.checkBounds();\n\t\tthis.checkBlocks();\n\t}", "normalizeWidths(contentWidth) {\n if (this.size == 0) {\n return;\n }\n const c = this.columns_[0];\n c.width = Math.max(10, c.width - this.totalWidth + contentWidth);\n }", "emptyColumnsCountNew() {\n\t\tvar cnt = 0;\n for (var i = 0; i < this.width; ++i) {\n if (this.isColumnEmptyNew(i)) {\n cnt = cnt + 1;\n }\n }\n return cnt;\n\t}", "function _cleanAllowedCards(allowedCards){\n\t\tvar allKeys = Object.keys(cardPrefixesAndLengths);\n\t\tvar remove = [];\n\t\tfor(var i in allowedCards){\n\t\t\tif (allKeys.indexOf(allowedCards[i]) === -1 ){\n\t\t\t\tremove.push(i);\n\t\t\t}\n\t\t}\n\t\tremove.reverse();\n\t\tfor(var i in remove){\n\t\t\tallowedCards.splice(remove[i], 1);\n\t\t}\n\t\treturn allowedCards;\n\t}", "recalculateColumnWidths() {\n if (!this._columnTree) {\n return; // No columns\n }\n if (this._cache.isLoading()) {\n this._recalculateColumnWidthOnceLoadingFinished = true;\n } else {\n const cols = this._getColumns().filter((col) => !col.hidden && col.autoWidth);\n this._recalculateColumnWidths(cols);\n }\n }", "function CtrlDeleteAllFieldsInOneCoupon(){\n addNewCouponFlag = 0; // we are not allowed to add new coupon\n UICtrl.deleteAllFieldsInOneCoupon();\n UICtrl.fieldsClickable();\n UICtrl.hideNextCouponButton();\n // jackpotCtrl.removeCoupon((UICtrl.getExpandedCoupon()).id); //we shoulnd call it here. ! instead , it should be called when click goBack button. in that way we are 100% sure the user wanted to delete\n checkedFields = 0;\n }", "visitDrop_constraint(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function clearEligables() {\r\n $eligableList.empty();\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current set of Stack outputs from the last Stack.up().
outputs() { return __awaiter(this, void 0, void 0, function* () { return this.workspace.stackOutputs(this.name); }); }
[ "outputs() {\n return this.stack.outputs();\n }", "function last() {\n return _navigationStack[_navigationStack.length - 1];\n }", "static async getStackOutput(stackName) {\n var stack = await this.getStackInfo(stackName);\n var outputs = {};\n stack['Outputs'].forEach(output => {\n outputs[output.OutputKey] = output.OutputValue;\n })\n return outputs;\n }", "function getStack() {\n return settings.getStack();\n}", "exportStack() {\n return this.stack.exportStack();\n }", "get back() {\n return this.get(this.length - 1);\n }", "pop() {\n if(this.stack.length == 0) {return null\n }\n\n return this.stack[this.top--];\n }", "function tasks_stack() {\r\n let stackdata = new Stack(1);\r\n stackdata.push(4);\r\n stackdata.push(8);\r\n stackdata.push(9);\r\n stackdata.push(10);\r\n stackdata.push(11);\r\n\r\n stackdata.parse_llist();\r\n let out = stackdata.pop();\r\n let out1 = stackdata.pop();\r\n let out2 = stackdata.pop();\r\n let out3 = stackdata.pop();\r\n // let out4 = stackdata.pop();\r\n // let out5 = stackdata.pop();\r\n // let out6 = stackdata.pop();\r\n // let out7 = stackdata.pop();\r\n console.log(\r\n \" gotten out \",\r\n out.value,\r\n out1.value,\r\n out2.value,\r\n out3.value\r\n // out4.value,\r\n // out5.value,\r\n // out6.value,\r\n // out7.value\r\n );\r\n stackdata.push(100);\r\n stackdata.pop();\r\n // stackdata.pop();\r\n // stackdata.pop();\r\n // stackdata.pop();\r\n // stackdata.pop();\r\n // stackdata.pop();\r\n\r\n console.log(\r\n \"peeking out \",\r\n // stackdata.peek(),\r\n stackdata.is_empty(),\r\n stackdata\r\n );\r\n stackdata.parse_llist();\r\n }", "get stack() {\n \t\treturn extractStacktrace(this.errorForStack, 2);\n \t}", "function parserPrintStack() {\n var i;\n\n console.log(\"States: [\");\n for(i=stackTop; i>=0; i--) {\n var ln = \" \" + stateStack[i];\n if (i == stackTop) {\n ln = ln + \"<--Top Of Stack (\" + stackTop + \")\";\n }\n console.log(ln);\n }\n console.log(\"]\");\n console.log(\"Values: [\");\n for (i=stackTop; i >=0; i--) {\n var ln = \" \" + (stack[i] != null ? stack[i] : \"(null)\");\n if (i == stackTop) {\n ln = ln + \"<--Top Of Stack (\" + stackTop + \")\";\n }\n console.log(ln);\n }\n console.log(\"]\");\n }", "save_stack(s){\n var v = [];\n for(var i=0; i<s; i++){\n v[i] = this.stack[i];\n }\n return { stack: v, last_refer: this.last_refer, call_stack: [...this.call_stack], tco_counter: [...this.tco_counter] };\n }", "future() {\n if (this.stack.length === 0) {\n this.pushToken(this.lexer.lex());\n }\n\n return this.stack[this.stack.length - 1];\n }", "function running_command() {\n\treturn command_stack[command_stack.length - 1];\n}", "restore_stack(stuff){\n const v = stuff.stack;\n const s = v.length;\n for(var i=0; i<s; i++){\n this.stack[i] = v[i];\n }\n this.last_refer = stuff.last_refer;\n this.call_stack = [...stuff.call_stack];\n this.tco_counter = [...stuff.tco_counter];\n return s;\n }", "popBack() {\n const last = this.length - 1;\n const value = this.get(last);\n this._vec.remove(last);\n this._changed.emit({\n type: 'remove',\n oldIndex: this.length,\n newIndex: -1,\n oldValues: [value],\n newValues: []\n });\n return value;\n }", "function display(stack) {\n let items = [];\n \n if (stack.top === null) {\n return 'Stack is empty'\n } \n \n currNode = stack.top\n while (currNode !== null) {\n items.push(currNode)\n currNode = currNode.next;\n }\n \n return items[items.length - 1]\n }", "pop() {\r\n return this._msgStack.pop()\r\n }", "function getLast() {\n return lastRemoved;\n}", "print() { \n let str = \"\"; \n for (var i = 0; i < this.size(); i++) \n str += this.stack[i] + \" \"; \n console.log(str); \n }", "popValue() {\n let size = this.stack.pop().size;\n this.write(\"[-]<\".repeat(size));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
adds the provided callback function to the callbacks object under the desired type
function registerCallback(type, func) { if( callbacks.hasOwnProperty(type) == false ) { callbacks[type] = []; } callbacks[type].push(func); }
[ "register (name: string, callback: Callback, type: CallbackKind = 'didSave') {\n if (typeof callback !== 'function') {\n throw new Error('callback must be a function')\n }\n if (type !== 'didSave' && type !== 'willSave') {\n throw new Error('type must be a willSave or didSave')\n }\n if (type === 'willSave') {\n const cb: WillSaveCallback = ((callback: any): WillSaveCallback)\n this.willSaveCallbacks.add(cb)\n return new Disposable(() => {\n if (this.willSaveCallbacks) {\n this.willSaveCallbacks.delete(cb)\n }\n })\n }\n\n const cb: DidSaveCallback = ((callback: any): DidSaveCallback)\n this.didSaveCallbacks.set(name, cb)\n return new Disposable(() => {\n if (this.didSaveCallbacks) {\n this.didSaveCallbacks.delete(name)\n }\n })\n }", "function dh_callback (type) {\r\n type = type.toLowerCase();\r\n for (var c=0;c<CallbackList[type].length;c++) {\r\n CallbackList[type][c][0].call(null, CallbackList[type][c][1], type);\r\n }\r\n CallbackList[type] = null;\r\n}", "function addType(newType, configFunction) {\n OPTION_CONFIGURERS[newType] = configFunction;\n }", "function add (callback) {\n multicast.push(callback);\n return callback;\n }", "set onInputCreated(callback) {\n if (typeof(callback) == 'function') {\n this.callback_on_input_created = callback;\n } else {\n console.error(`${this.logprefix} Error setting onInputCreated callback => the argument is not a function`);\n }\n }", "function callback(callback){\n callback()\n}", "function addForgettableCallback(event, callback, listenerId) {\n \n // listnerId is optional and if not given, the original\n // callback will be used\n listenerId = listenerId || callback;\n \n var safeCallback = protectedCallback(callback);\n \n event.on( function() {\n \n var discard = false;\n \n oboeApi.forget = function(){\n discard = true;\n }; \n \n apply( arguments, safeCallback ); \n \n delete oboeApi.forget;\n \n if( discard ) {\n event.un(listenerId);\n }\n }, listenerId);\n \n return oboeApi; // chaining \n }", "function isCallback(node) {\n return node && node.type === typescript_estree_1.AST_NODE_TYPES.TSFunctionType;\n }", "function onetimeEventListener(node, type, callback) {\n\n\t// create event\n\tnode.addEventListener(type, function(event) {\n\t\t// remove event\n\t\tevent.target.removeEventListener(event.type, arguments.callee);\n\t\t// call handler\n\t\treturn callback();\n\t});\n\n}", "setDefaultCallback(callback) {\n this._defaultCallback = callback;\n }", "function addMapListener(element, eventType, callBackFunction) {\n\tgoogle.maps.event.addListener(element, eventType, callBackFunction);\n}", "function foo(callback){\n callback();\n}", "function YInputChain_registerEventCallback(callback)\n {\n if (callback != null) {\n this.registerValueCallback(yInternalEventCallback);\n } else {\n this.registerValueCallback(null);\n }\n // register user callback AFTER the internal pseudo-event,\n // to make sure we start with future events only\n this._eventCallback = callback;\n return 0;\n }", "addFeatureListener(callback) {\n this.featureListeners.push(callback);\n }", "function registerFiltersHaveChangedCallback(listKey, callback) {\n filtersHaveChangedCallbacks[listKey] = callback;\n }", "hasCallback() {}", "function typeFilter(type, callback) {\n return function(event) {\n var obj = event.newValue || event.oldValue;\n\n console.log(\"Filtering event\", event, \"for type\", type, \"obj\", obj, obj['@type']);\n \n if(obj && obj['@type']) {\n var parts = obj['@type'].split('/');\n if(parts[parts.length - 1] == type) {\n callback(event);\n }\n }\n }\n }", "static conduct(a, b, callback, on) {\r\n callback(a, b)\r\n\r\n }", "function attachCallback(req, callback) {\n req.onreadystatechange = function () {\n if (req.readyState == 4) {\n callback(req.status, req.statusText, req.responseText);\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
define a function that fetches a given metric for a given queue
function metric_fetch_gen(cw, queue_name, metric_name) { var f = function(callback) { //console.log("fetching " + metric_name + " for queue " + queue_name) var end = new Date(); // fetch the last 30 minutes of data, but return the most recent data point var start = new Date(end.getTime() - 60 * 30 * 1000); var params = { EndTime: end, MetricName: metric_name, /* required */ Namespace: 'AWS/SQS', /* required */ Period: 60, /* required */ StartTime: start, Dimensions: [{ Name: 'QueueName', /* required */ Value: queue_name /* required */ }], Statistics: [ "Sum" ], }; cw.getMetricStatistics(params, function(err, data) { if (err) { console.log(err, err.stack); // an error occurred callback(err, null); return; } var metric_data = 0; if (data['Datapoints'].length != 0) { var newest = null; for (var i in data['Datapoints']) { if (newest == null) newest = data['Datapoints'][i]; else if (data['Datapoints'][i]['Timestamp'] > newest['Timestamp']) newest = data['Datapoints'][i]; } metric_data = newest['Sum']; } result = { 'queue_name': queue_name, 'metric_name' : metric_name, 'data' : metric_data }; callback(err, result); }); } return f; }
[ "getV3SidekiqQueueMetrics(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.SidekiqApi();\napiInstance.getV3SidekiqQueueMetrics((error, data, response) => {\n if (error) {\n console.error(error);\n } else {\n console.log('API called successfully.');\n }\n});\n }", "function metric(metricName, change = {}) {\n const dimensions = {};\n if (change.queue !== undefined) {\n dimensions.QueueName = change.queue.name;\n }\n return new cloudwatch.Metric(Object.assign({ namespace: \"AWS/SQS\", name: metricName }, change)).withDimensions(dimensions);\n }", "async function runQueryGET(q, token) {\n\n let LAMBDA_ENDPOINT = \"https://simple-test.netlify.com/.netlify/functions/gql?\"\n var url = LAMBDA_ENDPOINT + \"token=\" + token + \"&query=\" + encodeURI(q);\n doNotifications(q,url);\n\n return fetch(url).then(function(response) {\n return response.text();\n });\n}", "getV3SidekiqCompoundMetrics(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.SidekiqApi();\napiInstance.getV3SidekiqCompoundMetrics((error, data, response) => {\n if (error) {\n console.error(error);\n } else {\n console.log('API called successfully.');\n }\n});\n }", "standardizeJob (name,payload) {\n\n let jobQueue = {\n name,\n attempts : 0,\n payload\n };\n\n return jobQueue;\n\n }", "getV3SidekiqJobStats(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.SidekiqApi();\napiInstance.getV3SidekiqJobStats((error, data, response) => {\n if (error) {\n console.error(error);\n } else {\n console.log('API called successfully.');\n }\n});\n }", "getV3SidekiqProcessMetrics(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.SidekiqApi();\napiInstance.getV3SidekiqProcessMetrics((error, data, response) => {\n if (error) {\n console.error(error);\n } else {\n console.log('API called successfully.');\n }\n});\n }", "function getQueue(lobby, role) {\n if(getPlayer(lobby, role) != undefined)\n return getPlayer(lobby, role).queue;\n}", "function put(value, op, cb) {\n\n if (typeof value !== 'number') {\n // TODO throw error\n }\n\n var ts\n op = op || {}\n\n if (typeof op === 'function') {\n cb = op\n op = {}\n ts = ISODateString(new Date())\n } else if (typeof op === 'string') {\n // I assume you have given me an ISO 8601 timestamp\n ts = op\n op = {}\n } else if (isDate(op)) {\n ts = ISODateString(ts)\n } else {\n ts = ISODateString(new Date())\n }\n\n var metric = {\n namespace : namespace\n , name : name\n , value : value\n , unit : op.unit || _metric.unit\n , dimensions : op.dimensions || _metric.dimensions}\n\n // TODO return request stream? vs metric obj?\n if (typeof cb === 'function') {\n transport(host\n , protocol\n , putMetricData(awskey\n , secret\n , host\n , namespace\n , ts\n , metric)\n , cb)\n }\n\n return metric\n }", "function queueAPIRequest(path, params){\n return gw2_API_queue.add(() => gw2API.get(path, {params})\n\n //then parse response depending on path\n .then((response) => {\n\n switch (path) {\n\n case '/items':\n //put each of the 200 items from API into DB\n itemsResponseHandler(response)\n break;\n\n case '/currencies':\n //for when I do currencies\n currenciesResponseHandler(response)\n break;\n\n default:\n break;\n }\n })\n\n //catch here for http error\n .catch((error) => {\n httpErrorHandler(error)\n\n })\n )\n}", "function sumNextQueue(nextQueue){}", "getGrandMasterLeagueByQueue(queue, region) {\n return __awaiter(this, void 0, void 0, function* () {\n const params = {\n queue\n };\n return this.request(region, endpoints_1.endpointsV4.GrandMasterLeaguesByQueue, params);\n });\n }", "async editQueue(queue) {\n await fetchData.editQueue(queue)\n }", "getFailSize(onGet){\r\n assert.equal(typeof onGet,'function','onGet must be a function');\r\n this.queueMgr.countQueue(FATUS_QUEUE_FAIL_NAME,onGet);\r\n }", "get queue() {\n return this.device.queue;\n }", "function getQueueFromLocalStorage() {\n localforage.getItem(QUEUE_STORAGE_KEY)\n .then((storageItem) => {\n if (storageItem !== null && Array.isArray(storageItem)) {\n analyticsQueue = [...storageItem, ...analyticsQueue].slice(-100);\n }\n })\n .catch(err => log.warn(`Error fetching from localstorage: ${err.message}`));\n}", "async request(command, ...args) {\n // Ask for connection, we get a promise that resolves into a client.\n // We return a new promise that resolves to the output of the request.\n const client = await this.connect();\n return await new Promise((resolve, reject)=> {\n // Processing (continuously or not) know to ignore the TIMED_OUT\n // and CLOSED errors.\n\n // When Fivebeans client executes a command, it doesn't monitor for\n // connection close/error, so we need to catch these events ourselves\n // and reject the promise.\n const onConnectionEnded = (error)=> {\n reject(new QueueError(error || 'CLOSED'));\n this._notify.debug('%s: %s => %s', this.id, command, error || 'CLOSED');\n }\n\n client.once('close', onConnectionEnded);\n client.once('error', onConnectionEnded);\n\n this._notify.debug('%s: $ %s', this.id, command, ...args);\n client[command](...args, (error, ...results)=> {\n // This may never get called\n client.removeListener('close', onConnectionEnded);\n client.removeListener('error', onConnectionEnded);\n\n if (error) {\n this._notify.debug('%s: %s => !%s', this.id, command, args, error);\n reject(new QueueError(error));\n } else if (results.length > 1) {\n this._notify.debug('%s: %s => %s', this.id, command, results);\n resolve(results);\n } else {\n this._notify.debug('%s: %s => %s', this.id, command, results[0]);\n resolve(results[0]);\n }\n });\n\n });\n }", "function tasks_queue() {\r\n let q_data = new Queue(1);\r\n q_data.push(4);\r\n q_data.push(8);\r\n q_data.push(9);\r\n q_data.push(19);\r\n\r\n q_data.parse_llist();\r\n let out = q_data.pop();\r\n let out1 = q_data.pop();\r\n let out2 = q_data.pop();\r\n let out3 = q_data.pop();\r\n console.log(\r\n \" queue gotten out \",\r\n out.value,\r\n out1.value,\r\n out2.value,\r\n out3.value\r\n );\r\n q_data.push(100);\r\n // q_data.pop();\r\n\r\n console.log(\"queueu peeking out \", q_data.peek(), q_data.is_empty());\r\n q_data.parse_llist();\r\n }", "calculateSqsPrice(fullTrace, fifoQueueChunkAmount = 0, isTraceFromCache = false) {\n // Pricing per 1 million Requests after Free tier(Monthly)\n // Standard Queue $0.40 ($0.0000004 per request)\n // FIFO Queue $0.50 ($0.0000005 per request)\n\n // FIFO Requests\n // API actions for sending, receiving, deleting, and changing visibility of messages from FIFO\n // queues are charged at FIFO rates. All other API requests are charged at standard rates.\n\n // Size of Payloads\n // Each 64 KB chunk of a payload is billed as 1 request\n // (for example, an API action with a 256 KB payload is billed as 4 requests).\n\n let messageAmountsPerType\n if (isTraceFromCache) {\n messageAmountsPerType = {\n standard: Number(fullTrace),\n fifo: Number(fifoQueueChunkAmount),\n }\n } else {\n const sqsRequestsMapPerQueue = calculateSqsRequestAmountsPerQueue(fullTrace)\n const queueUrls = Object.keys(sqsRequestsMapPerQueue)\n messageAmountsPerType = queueUrls.reduce((acc, url) => {\n const queueType = sqsRequestsMapPerQueue[url].QueueType\n const SendMessageRequestAmount = sqsRequestsMapPerQueue[url].SendMessage\n\n return {\n ...acc,\n [queueType]: acc[queueType] + SendMessageRequestAmount,\n }\n }, {\n standard: 0,\n fifo: 0,\n })\n }\n\n const { fifo, standard } = this.sqsPricing\n // in Nano USD\n const sqsStandardPrice = Number(`${standard}e9`) * messageAmountsPerType.standard\n const sqsFIFOPrice = Number(`${fifo}e9`) * messageAmountsPerType.fifo\n\n const sqsTotalPrice = sqsStandardPrice + sqsFIFOPrice\n return sqsTotalPrice\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
preload() The frog image will load on startup
function preload() { frogImage = loadImage("assets/images/Frog.png"); }
[ "function preload(){\n\thelicopterIMG=loadImage(\"helicopter.png\")\n\tpackageIMG=loadImage(\"package.png\")\n}", "function preload() {\n img = loadImage('./img/body.png');\n}", "function preload() {\n game.load.image('chair', 'https://media1.popsugar-assets.com/static/imgs/interview/chair.png');\n}", "function preload()\n{\n\tpaperImage = loadImage(\"paperImage.png\")\n\tdustbinImage = loadImage(\"dustbinWHJ.png\")\n\n}", "function preload() {\n\tkernelImg = loadImage(\"assets/kernel.png\");\n\tpopcornImg = loadImage(\"assets/popcorn.png\");\n\tburntImg = loadImage(\"assets/burnt.png\");\n}", "function preload() {\n lemonMilk = loadFont(\"assets/text/LemonMilk.otf\");\n catN = loadImage(\"assets/images/cat.png\");\n lionN = loadImage(\"assets/images/lion.png\");\n jungleN = loadImage(\"assets/images/jungle.jpg\");\n catRetro = loadImage(\"assets/images/catRetro.png\");\n lionRetro = loadImage(\"assets/images/lionRetro.png\");\n jungleRetro = loadImage(\"assets/images/jungleRetro.jpg\");\n}", "function preload()\r\n{\r\n // Spiderman Mask Filter asset\r\n imgSpidermanMask = loadImage(\"https://i.ibb.co/9HB2sSv/spiderman-mask-1.png\");\r\n\r\n // Dog Face Filter assets\r\n imgDogEarRight = loadImage(\"https://i.ibb.co/bFJf33z/dog-ear-right.png\");\r\n imgDogEarLeft = loadImage(\"https://i.ibb.co/dggwZ1q/dog-ear-left.png\");\r\n imgDogNose = loadImage(\"https://i.ibb.co/PWYGkw1/dog-nose.png\");\r\n}", "preload() {\n this.load.sprite('gun', 'assets/sprites/gun.png');\n }", "function preload() {\r\n\tgame.images.IPiece = loadImage('assets/tetrisI.png');\r\n\tgame.images.JPiece = loadImage('assets/tetrisJ.png');\r\n\tgame.images.LPiece = loadImage('assets/tetrisL.png');\r\n\tgame.images.OPiece = loadImage('assets/tetrisO.png');\r\n\tgame.images.SPiece = loadImage('assets/tetrisS.png');\r\n\tgame.images.TPiece = loadImage('assets/tetrisT.png');\r\n\tgame.images.ZPiece = loadImage('assets/tetrisZ.png');\r\n}", "_preload () {\n const preloader = new Preloader();\n\n preloader.run().then(() => { this._start() });\n }", "function Preload() {\n assets = new createjs.LoadQueue(); // asset container\n util.GameConfig.ASSETS = assets; // make a reference to the assets in the global config\n assets.installPlugin(createjs.Sound); // supports sound preloading\n assets.loadManifest(assetManifest); // load assetManifest\n assets.on(\"complete\", Start); // once completed, call start function\n }", "function PreloadImage()\n{\n var appVer=parseInt(navigator.appVersion);\n var isNC=(document.layers && (appVer >= 4));\n var isIE=(document.all && (appVer >= 4));\n if (isNC || isIE)\n {\n if (document.images)\n {\n var imgName = PreloadImage.arguments[0];\n var cnt;\n swImg[imgName] = new Array;\n for (cnt = 1; cnt < PreloadImage.arguments.length; cnt++)\n {\n swImg[imgName][PreloadImage.arguments[cnt]] = new Image();\n swImg[imgName][PreloadImage.arguments[cnt]].src = HpbImgPreload.arguments[cnt];\n }\n }\n }\n}", "function preload(){\n var manifest = [\n {src: \"assets/text.txt\", id: \"txt\"},\n ];\n\n q = new createjs.LoadQueue(true);\n q.on(\"complete\", loadComplete);\n q.loadManifest(manifest);\n}", "function preloadImages(code) {\n var re = /SimpleImage\\(\\s*(\"|')(.*?)(\"|')\\s*\\)/g;\n while (ar = re.exec(code)) {\n // Used to screen out data: urls here, but that messed up the .loaded attr, strangely\n var url = ar[2];\n loadImage(url);\n }\n}", "function preloadOptions(game) {\n game.load.image('game-bg', 'assets/bg/blue-bg.png');\n game.load.image(\"screentint\", \"assets/ui/screentint-alpha-50.png\");\n game.load.image(\"screentint75\", \"assets/ui/screentint-alpha-75.png\");\n game.load.image('black', 'assets/ui/black.png');\n\n game.load.image(\"button-back\", \"assets/ui/button-back.png\");\n game.load.image(\"dialogue-option\", \"assets/ui/dialogue-option.png\");\n\n preloadUI(game);\n\n game.load.audio(\"menu-select\", [\"assets/sounds/select01.mp3\"]);\n game.load.audio('menu-accept', ['assets/sounds/accept01.mp3']);\n game.load.audio(\"accept02\", [\"assets/sounds/accept02.mp3\"]);\n}", "preloadMap() {\n\n // Read the previously parsed Tiled map JSON\n this.tilemapJson = this.game.cache.getJSON(this.mapName);\n\n // Load the Tiled map JSON as an actual Tilemap\n this.game.load.tilemap(this.mapName, null, this.tilemapJson, Phaser.Tilemap.TILED_JSON);\n\n // Load the tileset images\n this.loadTilesetImages();\n }", "load()\r\n {\r\n this.image = loadImage(this.imagePath);\r\n }", "async preloadData() {\n Util.log(`### ${this.workType} preload data ###`);\n await this.workObj.preloadData();\n }", "function loadAssets() {\n\t\tbackground.src = \"assets/Wall720.png\";\n\t\tTERRAIN_TYPES.BASE.img.src = \"assets/TileSandstone100.png\";\n\t\tTERRAIN_TYPES.LAVA.img.src = \"assets/lava.png\";\n\t\t\n\t\tPLAYER_CLASSES.PALADIN.img.src = \"assets/paladinRun.png\";\n\t\tPLAYER_CLASSES.RANGER.img.src = \"assets/rangerRun.png\";\n\t\tPLAYER_CLASSES.MAGI.img.src = \"assets/magiRun.png\";\n\t\t\n\t\tENEMY_TYPES.RAT.img.src = \"assets/ratRun.png\";\n\t\tENEMY_TYPES.BAT.img.src = \"assets/batRun.png\";\n\t\tENEMY_TYPES.GATOR.img.src = \"assets/gatorRun.png\";\n\t\t\n\t\tPROJECTILE_TYPES.ARROW.img.src = \"assets/arrow.png\";\n\t\tPROJECTILE_TYPES.FIREBALL.img.src = PROJECTILE_TYPES.MAGIFIREBALL.img.src = \"assets/fireball.png\";\n\t\t\n\t\tPARTICLE_TYPES.FLAME.img.src = \"assets/flameParticle.png\";\n\t\tPARTICLE_TYPES.ICE.img.src = PARTICLE_TYPES.FROST.img.src = \"assets/iceParticle.png\";\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If window is not the top level window, return parent for creating new child window, otherwise returns false.
function parentFrom(window) { if (window.parent !== window) return window.parent; }
[ "isWindowActive() {\n if (this.windowHandle === null) {\n this.windowHandle = Winhook.FindWindow(this.windowTitle);\n if (!this.windowHandle) {\n return false;\n }\n }\n return Winhook.GetForegroundWindow() === this.windowHandle;\n }", "function openChildWindow(){\n setErrorFlag();\n var lstrWidth = '750px';//set default width\n var lstrHeight = '450px';//set default height\n var lstrURL;\n var lstrArgument;\n\n lstrURL = openChildWindow.arguments[0];\n if( lstrURL.indexOf(\"?\") == -1 ) {\n lstrURL = lstrURL + \"?childFw=Y\" ;\n } else {\n lstrURL = lstrURL + \"&childFw=Y\" ;\n }\n lstrURL = encodeURI(lstrURL);\n lstrArgument = openChildWindow.arguments[1];\n\n //set the width\n if(openChildWindow.arguments[2] != null && openChildWindow.arguments[2].length > 0 ){\n lstrWidth= openChildWindow.arguments[2];\n }\n\n //set the height\n if(openChildWindow.arguments[3] != null && openChildWindow.arguments[3].length > 0 ){\n lstrHeight= openChildWindow.arguments[3];\n }\n\n // for appending the readonly flag of Parent Screen\n if(document.getElementById('readOnlyFlg') != null && document.getElementById('readOnlyFlg')!= undefined){\n if(lstrURL.indexOf('?') != -1 ){\n lstrURL = lstrURL+ '&childScreen=true&readOnlyFlg='+document.getElementById('readOnlyFlg').value;\n }else{\n lstrURL = lstrURL+ '?childScreen=true&readOnlyFlg='+document.getElementById('readOnlyFlg').value;\n }\n }\n\n //open model dialog\n window.showModalDialog(lstrURL,lstrArgument, 'dialogHeight:' + lstrHeight + ';dialogWidth:' + lstrWidth + ';center:yes;status:no');\n // Set Error Flag to true so that Buttons are not disabled of parent\n isErrFlg = true;\n}", "function getTestWindow () {\n\n var iframe,\n w = getWindow(),\n testWindow = null;\n \n if (w) {\n iframe = w.document.getElementById('test-iframe');\n if (iframe) {\n testWindow = iframe.contentWindow;\n testWindow.isTestWindow = true;\n }\n }\n\n return testWindow;\n }", "function aePopupModalWindow(aParentWindow, aUri, aWinName, aWidth, aHeight, aResizable, aParams)\r\n{\r\n\treturn aePopupWindow(aParentWindow, aUri, aWinName, aWidth, aHeight, aResizable, true, aParams);\r\n}", "function createWindow(initialParent, defaultContent, setupData) {\n\n defaultContent =\n defaultContent || \"\";\n\n setupData = \n setupData || null;\n\n\t\t\t// if no parent container has been provided, reject request\n\t\t\tif (initialParent == null)\n\t\t\t\treturn 0;\n\t\t\t\n var newWindow = \n new WTWindow(\n this, \n initialParent, \n defaultContent, \n setupData);\n\t\t\t\n windows\n .push(\n newWindow);\n\n\t\t\treturn newWindow.id;\n }", "function in_iframe () {\r\n try {\r\n return window.self !== window.top;\r\n } catch (e) {\r\n return true;\r\n }\r\n }", "parentEditable() {\n var parent = this.parent();\n var editable = false;\n\n while (parent) {\n if (parent.getAttribute('contenteditable') == 'true' &&\n parent.getAttribute(this.config.attribute.plugin) == this.config.attribute.plugin) {\n editable = parent;\n break;\n }\n\n parent = parent.parentElement;\n }\n\n return editable;\n }", "function getApiWindow()\n{\n // popup launch:\n // SCORM API related to current window(player.html)\n if( window.opener && window.opener.API )\n return window.opener;\n // SCORM API related to lesson frame\n else if( parent.opener && parent.opener.API )\n return parent.opener;\n \n // iPlayer launch:\n // SCORM API related to lesson frame\n else if( parent.parent && parent.parent.API )\n return parent.parent;\n // SCORM API related to iPlayer frame\n else\n return parent;\n}", "function windowExists(name) {\n\n for (var i = 0; i < windows.length; i++) {\n\n // IE needs a try/catch here for to avoid an access violation on windows[i].name\n // in some cases.\n try {\n if (windows[i].name == name) {\n return true;\n }\n }\n catch (exception) {\n }\n }\n\n return false;\n}", "function atTopLevel() {\n return Object.is(topBlock,currentBlock);\n }", "function IsWindowFocused(flags = 0) {\r\n return bind.IsWindowFocused(flags);\r\n }", "function WindowsManager () {\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Flag to raise while the main window is open.\r\n\t\t\t * @field\r\n\t\t\t * @private\r\n\t\t\t */\r\n\t\t\tvar isMainWindowOpen = false;\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Returns the default display options for a newly created window.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @return { NativeWindowInitOptions }\r\n\t\t\t * \t\tAn object specifying display options for a new window. \r\n\t\t\t */\r\n\t\t\tfunction getDefWindowOptions () {\r\n\t\t\t\tvar options = new NativeWindowInitOptions();\r\n\t\t\t\toptions.type = NativeWindowType.UTILITY;\r\n\t\t\t\treturn options;\r\n\t\t\t}\r\n\r\n\t\t\t/**\r\n\t\t\t * Returns the default display boundaries for a newly created \r\n\t\t\t * window.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @return { Rectangle }\r\n\t\t\t * \t\tA rectangle defining the boundaries of this new window.\r\n\t\t\t */\t\t\t\r\n\t\t\tfunction getDefBoundaries () {\r\n\t\t\t\tvar bounds = new Rectangle();\r\n\t\t\t\tbounds.x = Math.max(0, (screen.width-800)/2);\r\n\t\t\t\tbounds.y = Math.max(0, (screen.height-600)/2);\r\n\t\t\t\tbounds.width = 800;\r\n\t\t\t\tbounds.height = 600;\r\n\t\t\t\treturn bounds;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Creates the main window of the application.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t */\r\n\t\t\tthis.makeMainWindow = function () {\r\n\t\t\t\tvar htmlLoader = HTMLLoader.createRootWindow (\r\n\t\t\t\t\ttrue,\r\n\t\t\t\t\tgetDefWindowOptions(), \r\n\t\t\t\t\tfalse,\r\n\t\t\t\t\tgetDefBoundaries()\r\n\t\t\t\t);\r\n\t\t\t\thtmlLoader.addEventListener('htmlDOMInitialize', function() {\r\n\t\t\t\t\tisMainWindowOpen = true;\r\n\t\t\t\t\tmakeWindowModal (htmlLoader.window, self);\r\n\t\t\t\t\thtmlLoader.window.nativeWindow.addEventListener (\r\n\t\t\t\t\t\t'close',\r\n\t\t\t\t\t\t function() {isMainWindowOpen = false}\r\n\t\t\t\t\t);\r\n\t\t\t\t\tvar event = eventManager.createEvent(\r\n\t\t\t\t\t\tWINDOW_CREATED_EVENT,\r\n\t\t\t\t\t\t{'window': htmlLoader.window}\r\n\t\t\t\t\t);\r\n\t\t\t\t\teventManager.fireEvent(event);\r\n\t\t\t\t});\r\n\t\t\t\thtmlLoader.loadString('&nbsp;');\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Makes a window modal to a certain parent window.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @param oWindow { Object Window }\r\n\t\t\t * \t\tThe window to be made modal.\r\n\t\t\t * @param oParentWindow { Object Window }\r\n\t\t\t * \t\tThe parent of the modal window. Any attempt to access the \r\n\t\t\t * \t\tparent while the modal window is open will fail.\r\n\t\t\t */\r\n\t\t\tfunction makeWindowModal (oWindow, oParentWindow) {\r\n\t\t\t\t\r\n\t\t\t\toParentWindow.nativeWindow.addEventListener (\r\n\t\t\t\t\t'closing',\r\n\t\t\t\t\tfunction (event) {\r\n\t\t\t\t\t\t//if (isMainWindowOpen) { event.preventDefault() };\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t\toParentWindow.nativeWindow.addEventListener (\r\n\t\t\t\t\t'displayStateChanging', \r\n\t\t\t\t\tfunction (event) {\r\n\t\t\t\t\t\t//if (isMainWindowOpen) { event.preventDefault() };\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t\toParentWindow.nativeWindow.addEventListener (\r\n\t\t\t\t\t'moving',\r\n\t\t\t\t\tfunction (event) {\r\n\t\t\t\t\t\t//if (isMainWindowOpen) { event.preventDefault() };\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t\toParentWindow.nativeWindow.addEventListener (\r\n\t\t\t\t\t'resizing', \r\n\t\t\t\t\tfunction(event) {\r\n\t\t\t\t\t\t//if(isMainWindowOpen) { event.preventDefault() };\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t\toWindow.nativeWindow.addEventListener(\r\n\t\t\t\t\t'deactivate',\r\n\t\t\t\t\tfunction() {\r\n\t\t\t\t\t\t//oWindow.nativeWindow.activate();\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t\toWindow.nativeWindow.addEventListener(\r\n\t\t\t\t\t'closing',\r\n\t\t\t\t\tfunction(){\r\n\t\t\t\t\t\tvar ev = eventManager.createEvent(BROWSER_UNLOAD_EVENT);\r\n\t\t\t\t\t\teventManager.fireEvent(ev);\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t\t \r\n\t\t\t}\r\n\t\t}", "launchNewWindow(p) {\n let appInfo = this.app.get_app_info();\n let actions = appInfo.list_actions();\n if (this.app.can_open_new_window()) {\n this.animateLaunch();\n // This is used as a workaround for a bug resulting in no new windows being opened\n // for certain running applications when calling open_new_window().\n //\n // https://bugzilla.gnome.org/show_bug.cgi?id=756844\n //\n // Similar to what done when generating the popupMenu entries, if the application provides\n // a \"New Window\" action, use it instead of directly requesting a new window with\n // open_new_window(), which fails for certain application, notably Nautilus.\n if (actions.indexOf('new-window') == -1) {\n this.app.open_new_window(-1);\n }\n else {\n let i = actions.indexOf('new-window');\n if (i !== -1)\n this.app.launch_action(actions[i], global.get_current_time(), -1);\n }\n }\n else {\n // Try to manually activate the first window. Otherwise, when the app is activated by\n // switching to a different workspace, a launch spinning icon is shown and disappers only\n // after a timeout.\n let windows = this.getWindows();\n if (windows.length > 0)\n Main.activateWindow(windows[0])\n else\n this.app.activate();\n }\n }", "function checkIfFramed()\n{\n var anchors, i;\n\n if (window.parent != window) { // Only if we're not the top document\n anchors = document.getElementsByTagName('a');\n for (i = 0; i < anchors.length; i++)\n if (!anchors[i].hasAttribute('target'))\n\tanchors[i].setAttribute('target', '_parent');\n document.body.classList.add('framed'); // Allow the style to do things\n }\n}", "function newRobotWindow() {\n\tvar robotWindow = window.open(\"Images/robot.png\", \"robotWindow\", \"resizable=no,width=400,height=300\");\n\treturn false;\n}", "isItemParent(item) {\n return this.composer.isItemParent(item);\n }", "function get_window(node) {\n return get_document(node).defaultView;\n}", "detectDestroy() {\n if(this.parent === null) {\n this.destroy();\n return true;\n }\n return false;\n }", "function isPortalContainer(window) {\n return window.jQuery('#' + kradVariables.PORTAL_IFRAME_ID).length;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stripe component : Stamplay.Stripe This class rappresent the Stripe Object component on Stamplay platform It very easy to use: Stamplay.Stripe() constructor
function Stripe() { this.url = '/api/stripe/' + Stamplay.VERSION + '/'; this.createCustomer = function (userId) { if (Stamplay.Support.checkMongoId(userId)) return Stamplay.makeAPromise({ method: 'POST', data: { 'userId': userId }, url: this.url + 'customers' }) else return Stamplay.Support.errorSender(403, "Invalid userId isn't mongoid") } this.createCreditCard = function (userId, token) { if (arguments.length == 2) { if (Stamplay.Support.checkMongoId(userId)) return Stamplay.makeAPromise({ method: 'POST', data: { 'token': token }, url: this.url + 'customers/' + userId + '/cards' }) else return Stamplay.Support.errorSender(403, "Invalid userId isn't mongoid") } else { return Stamplay.Support.errorSender(403, "Missing parameters in createCreditCard methods") } } this.charge = function (userId, token, amount, currency) { if (arguments.length == 4) { if (Stamplay.Support.checkMongoId(userId)) return Stamplay.makeAPromise({ method: 'POST', data: { 'userId': userId, 'token': token, 'amount': amount, 'currency': currency }, url: this.url + 'charges' }) else return Stamplay.Support.errorSender(403, "Invalid userId isn't mongoid") } else { return Stamplay.Support.errorSender(403, "Missing parameters in charge methods") } } this.createSubscription = function (userId, planId) { if (arguments.length == 2) { if (Stamplay.Support.checkMongoId(userId)) { return Stamplay.makeAPromise({ method: 'POST', data: { 'planId': planId }, url: this.url + 'customers/' + userId + '/subscriptions' }) } else { return Stamplay.Support.errorSender(403, "Invalid userId isn't mongoid") } } else { return Stamplay.Support.errorSender(403, "Missing parameters in createSubscription methods") } } this.getSubscriptions = function (userId, options) { if (arguments.length >= 1) { if (Stamplay.Support.checkMongoId(userId)) { return Stamplay.makeAPromise({ method: 'GET', url: this.url + 'customers/' + userId + '/subscriptions', thisParams: options }); } else { return Stamplay.Support.errorSender(403, "Invalid userId isn't mongoid") } } else { return Stamplay.Support.errorSender(403, "Missing parameters in getSubscriptions methods") } } this.getSubscription = function (userId, subscriptionId) { if (arguments.length <= 2) { if (Stamplay.Support.checkMongoId(userId)) { return Stamplay.makeAPromise({ method: 'GET', url: this.url + 'customers/' + userId + '/subscriptions/' + subscriptionId, }); } else { return Stamplay.Support.errorSender(403, "Invalid userId isn't mongoid") } } else { return Stamplay.Support.errorSender(403, "Missing parameters in getSubscription methods") } } this.deleteSubscription = function (userId, subscriptionId, options) { if (arguments.length == 2) { if (Stamplay.Support.checkMongoId(userId)) { return Stamplay.makeAPromise({ method: 'DELETE', url: this.url + 'customers/' + userId + '/subscriptions/' + subscriptionId, data: options || {} }); } else { return Stamplay.Support.errorSender(403, "Invalid userId isn't mongoid") } } else { return Stamplay.Support.errorSender(403, "Missing parameters in deleteSubscription methods") } } this.updateSubscription = function (userId, subscriptionId, options) { if (arguments.length >= 2) { if (Stamplay.Support.checkMongoId(userId)) { options = options || {}; return Stamplay.makeAPromise({ method: 'PUT', url: this.url + 'customers/' + userId + '/subscriptions/' + subscriptionId, data: { options: options } }); } else { return Stamplay.Support.errorSender(403, "Invalid userId isn't mongoid") } } else { return Stamplay.Support.errorSender(403, "Missing parameters in updateSubscription methods") } } }
[ "function paymentFactory() {\n\tvar payment = {\n\t\tcNumber: \"\",\n\t\tcType: \"\",\n\t\tCName: \"\",\n\t\tcExp: \"\",\n\t\tcCvv: \"\"\n\t}\n\treturn payment;\n}", "constructor() { \n \n StakingLedger.initialize(this);\n }", "static fromObject(obj) {\n if (Card.isValid(obj)) {\n const caption = obj.caption && typeof obj.caption === 'string' ? obj.caption : '';\n const frontUrl = obj.frontUrl && typeof obj.frontUrl === 'string' ? obj.frontUrl : '';\n const backUrl = obj.backUrl && typeof obj.backUrl === 'string' ? obj.backUrl : '';\n return new Card(obj.name, obj.value, obj.color, caption, frontUrl, backUrl);\n }\n else{\n throw new Error('Invalid card object', obj);\n }\n }", "function createStripeSubscription(req, res, next) {\n stripe.customers.create(\n {\n card: req.body.stripeToken,\n email: req.user.email,\n plan: config.stripe.plan,\n quantity: req.user.blogs.length,\n description: \"Blot subscription\",\n },\n function (err, customer) {\n if (err) return next(err);\n\n User.set(req.user.uid, { subscription: customer.subscription }, next);\n }\n );\n}", "constructor() {\n //name of the Smart Contract => registration\n super(\"org.pharma-network.drugRegistration\");\n }", "openStripeModal() {\n this.setState({\n open: true,\n });\n }", "charge(payee, amt){\n if (this.balance()< amt){\n return;\n// This is overdraft protection. It basically says that if the charge issued\n// to the account is greater than the account balance then do not allow the \n// charge to process. \n }\n let charge = new Transaction (-amt, payee)\n// charge is using the same structure of deposit however its taking on the negative\n// of the amount value and a payee.\n\n this.transactions.push(charge)\n// In the same manner as the deposit. We are taking in the charge method, and pushing\n// our inputs to the end of the transactions array\n}", "function handle_cm_add_payment_card(req, startTime, apiName) {\n this.req = req; this.startTime = startTime; this.apiName = apiName;\n}", "constructor() { \n \n PatchedBankAccountCreateUpdate.initialize(this);\n }", "constructor(amount, payee){\n this.date = new Date();\n this.amount = amount;\n this.payee = payee;\n}", "migrateCreditCards() {}", "function BasicFlashcard(front, back) {\n // making it scope safe \n // evaluate if the this object is a BasicFlashcard if so proceed as normal\n if (this instanceof BasicFlashcard) {\n this.front = front;\n this.back = back;\n this.create = function() {\n // flashcard object is created\n var data = {\n front: this.front,\n back: this.back,\n type: \"basic\",\n };\n // basic flash card object is added to log.txt\n fs.appendFile(\"log.txt\", JSON.stringify(data) + ';', \"utf8\", function(error) {\n // if there is an error, log the error\n if (error) {\n console.log(error);\n }\n });\n };\n } else {\n /* If the this object is not a BasicFlashcard (ie, it's a window object), \n call the constructor again, this time with the new operator.\n Now the constructor works properly with or without the new operator */\n return new BasicFlashcard(front, back);\n }\n}", "function BardObject__init()\n{\n return this;\n}", "constructor(contractAddress = \"\", provider, signer, nominatedValue) {\n const address = new Address(contractAddress);\n this.contract = new SmartContract({ address });\n this.proxyProvider = provider;\n this.signerProvider = signer;\n this.nominatedValue = nominatedValue;\n }", "function processPayment(amount, { number, expMonth, expYear, cvc }, callback){\n\n // Configure the request details\n const options = {\n protocol: \"https:\",\n hostname: \"api.stripe.com\",\n method: \"POST\",\n auth: `${config.stripe.secretKey}:`,\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" }\n };\n\n // Configure the token request payload\n const tokenStringPayload = querystring.stringify({\n 'card[number]': number,\n 'card[exp_month]': expMonth,\n 'card[exp_year]': expYear,\n 'card[cvc]': cvc,\n });\n\n options.path = \"/v1/tokens\";\n options.headers[\"Content-Length\"] = Buffer.byteLength(tokenStringPayload);\n\n // Instantiate the token request\n const tokenReq = https.request(options, function(res){\n\n // Grab status from response\n const tokenResStatus = res.statusCode\n\n // Callback successfully if the request went through\n if(successStatus(tokenResStatus)){\n\n // Parse and read response\n res.setEncoding('utf8');\n res.on('data', chunk => {\n // Parse string response\n const tokenId = parseJsonToObject(chunk).id;\n\n // Configure the token request payload\n const chargeStringPayload = querystring.stringify({\n amount,\n currency: 'eur',\n // Extract token id from token response\n source: tokenId,\n });\n\n options.path = \"/v1/charges\";\n options.headers[\"Content-Length\"] = Buffer.byteLength(chargeStringPayload);\n\n // Create charge using order information using stripe service\n const chargeReq = https.request(options, function(res){\n\n // Grab status from response\n const chargeResStatus = res.statusCode\n\n // Callback successfully if the request went through\n if(successStatus(chargeResStatus)){\n\n // Parse and read response\n res.setEncoding('utf8');\n res.on('data', chunk => {\n // Parse string response\n const chargeStatus = parseJsonToObject(chunk).status;\n\n // Callback successfully if charge succeeded\n if(chargeStatus === 'succeeded'){\n callback(false);\n } else {\n callback(`Failed to charge payment successfully. Charge status returned was ${chargeStatus}`);\n };\n });\n\n } else {\n callback(`Failed charge request. Status code returned was ${chargeResStatus}`);\n };\n });\n\n // Bind to the error event so it doesn't get thrown\n chargeReq.on(\"error\", e => callback(e));\n\n // Add the payload\n chargeReq.write(chargeStringPayload);\n\n // End the request\n chargeReq.end();\n });\n\n } else {\n callback(`Failed token request. Status code returned was ${tokenResStatus}`);\n };\n });\n\n // Bind to the error event so it doesn't get thrown\n tokenReq.on(\"error\", e => callback(e));\n\n // Add the payload\n tokenReq.write(tokenStringPayload);\n\n // End the request\n tokenReq.end();\n}", "constructor() { \n \n PullRequest.initialize(this);\n }", "function BasicFlashCards(front, back){\r\n this.front = front;\r\n this.back = back;\r\n}", "function CreditCardTrackData(track_data) {\n this.fields = ['format_code', 'number', 'expiration', 'last_name', 'first_name', 'service_code']\n this.track_data = track_data\n this.parse()\n this.CENTURY = \"20\"\n}", "function Register(cash) {\n this.cash = cash;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Appends a media entry to the end of the mix timeline, this will save the mix timeline as a new version.
static appendMediaEntry(mixEntryId, mediaEntryId){ let kparams = {}; kparams.mixEntryId = mixEntryId; kparams.mediaEntryId = mediaEntryId; return new kaltura.RequestBuilder('mixing', 'appendMediaEntry', kparams); }
[ "function addMediaAfterSubmit (post) {\n var set = {};\n if(post.url){\n var data = getEmbedlyData(post.url);\n if (!!data) {\n // only add a thumbnailUrl if there isn't one already\n if (!post.thumbnailUrl && !!data.thumbnailUrl) {\n set.thumbnailUrl = data.thumbnailUrl;\n }\n // add media if necessary\n if (!!data.media.html) {\n set.media = data.media;\n }\n // add source name & url if they exist\n if (!!data.sourceName && !!data.sourceUrl) {\n set.sourceName = data.sourceName;\n set.sourceUrl = data.sourceUrl;\n }\n }\n // make sure set object is not empty (Embedly call could have failed)\n if(!_.isEmpty(set)) {\n Posts.update(post._id, {$set: set});\n }\n }\n}", "addMedia(mediaType, uid, url, options) {\n console.log(`add media ${mediaType} ${uid} ${url}`);\n let media = this.data.media || [];\n\n if (mediaType === 0) {\n //pusher\n media.splice(0, 0, {\n key: options.key,\n type: mediaType,\n uid: `${uid}`,\n holding: false,\n url: url,\n left: 0,\n top: 0,\n width: 0,\n height: 0\n });\n } else {\n //player\n media.push({\n key: options.key,\n rotation: options.rotation,\n type: mediaType,\n uid: `${uid}`,\n holding: false,\n url: url,\n left: 0,\n top: 0,\n width: 0,\n height: 0\n });\n }\n\n media = this.syncLayout(media);\n return this.refreshMedia(media);\n }", "addMedia() {\n\n this.mediaFrame.open();\n }", "function addMediaFilePoster() {\n if (!vm.modelContentNew || !vm.modelContentNew.mediaFile) {\n return;\n }\n\n // create a canvas (HTML5) element\n var elCanvas = document.createElement('canvas');\n\n // get the media file element (tag)\n var elMediaFile = document.getElementById('media-file-new');\n\n // define size depending on the media file\n var numWidth = elMediaFile.clientWidth;\n var numHeight = elMediaFile.clientHeight;\n\n // set the canvas element's size\n elCanvas.width = numWidth;\n elCanvas.height = numHeight;\n\n // get the 2D context of the canvas to manipulate it\n var context = elCanvas.getContext('2d');\n\n // draw the screenshot of the media file into the context\n context.drawImage(elMediaFile, 0, 0, numWidth, numHeight);\n\n // display the image in the view\n var objUrl = elCanvas.toDataURL('image/jpeg');\n vm.modelContentNew.mediaFilePoster = objUrl;\n vm.modelContentNew.mediaFilePosterTmp = $sce.trustAsResourceUrl(objUrl);\n }", "function addMovieToEnd(movie){\n movieQueue.push(movie);\n return movie;\n }", "function handleMediaShare(entry) {\n\t\t\t// need to click the entry before entry_method.media is defined\n\t\t\tentry.enterLinkClick(entry.entry_method);\n\t\t\tmarkEntryLoading(entry);\n\n\t\t\t// and then wait\n\t\t\tvar temp_interval = setInterval(function() {\n\t\t\t\tif(entry.entry_method.media) {\n\t\t\t\t\tvar choices = entry.entry_method.media,\n\t\t\t\t\t\trand_choice = choices[Math.floor(Math.random() * choices.length)];\n\n\t\t\t\t\tclearInterval(temp_interval);\n\t\t\t\t\tentry.entry_method.selected = rand_choice;\n\t\t\t\t\tentry.mediaChoiceContinue(entry.entry_method);\n\t\t\t\t\tmarkEntryCompleted(entry);\n\t\t\t\t}\n\t\t\t}, 500);\n\t\t}", "static add(entry){\n\t\tlet kparams = {};\n\t\tkparams.entry = entry;\n\t\treturn new kaltura.RequestBuilder('externalmedia_externalmedia', 'add', kparams);\n\t}", "static addFromUrl(mediaEntry, url){\n\t\tlet kparams = {};\n\t\tkparams.mediaEntry = mediaEntry;\n\t\tkparams.url = url;\n\t\treturn new kaltura.RequestBuilder('media', 'addFromUrl', kparams);\n\t}", "onMediaAttached(data) {\n this.media = data.media;\n if (!this.media) {\n return;\n }\n\n this.id3Track = this.media.addTextTrack('metadata', 'id3');\n this.id3Track.mode = 'hidden';\n }", "static addMediaEntry(mediaEntry, uploadTokenId, emailProfId, fromAddress, emailMsgId){\n\t\tlet kparams = {};\n\t\tkparams.mediaEntry = mediaEntry;\n\t\tkparams.uploadTokenId = uploadTokenId;\n\t\tkparams.emailProfId = emailProfId;\n\t\tkparams.fromAddress = fromAddress;\n\t\tkparams.emailMsgId = emailMsgId;\n\t\treturn new kaltura.RequestBuilder('emailingestionprofile', 'addMediaEntry', kparams);\n\t}", "function syncMedia() {\n\n var HypervideoController = FrameTrail.module('HypervideoController'),\n isPlaying = HypervideoController.isPlaying,\n currentTime = HypervideoController.currentTime,\n overlay;\n\n for (var idx in syncedMedia) {\n\n overlay = syncedMedia[idx];\n\n // Note: Currently, the only synced media type is 'video', so we shortcut it\n\n overlay.mediaElement.currentTime = currentTime - overlay.data.start + overlay.data.startOffset;\n\n\n if (overlay.mediaElement.currentTime > overlay.mediaElement.duration - overlay.data.endOffset) {\n\n overlay.mediaElement.pause();\n overlay.mediaElement.currentTime = overlay.mediaElement.duration - overlay.data.endOffset;\n\n }\n\n if (isPlaying) {\n\n if (overlay.mediaElement.paused) {\n var promise = overlay.mediaElement.play();\n if (promise) {\n promise.catch(function(){});\n }\n }\n } else {\n overlay.mediaElement.pause();\n }\n\n\n }\n\n }", "function addAlbumsToTimelineByUser(guid, beingFollowedGuid) {\n \n // sql: \"INSERT INTO album_timeline (guid, fguid, album_id) SELECT ?, ?, id FROM user_album AS ua WHERE ua.guid = ? AND is_private = 0 AND (ua.expire_date IS NULL OR ua.expire_date > NOW())\",\n\n /**\n * \n INSERT INTO album_timeline (guid, fguid, album_id) \n SELECT ?, ?, id \n FROM user_album AS ua \n LEFT JOIN album_permissions AS ap \n ON ap.guid = ? AND ap.fguid = ua.guid AND ap.album_id = ua.id \n WHERE ua.guid = ? AND (is_private = 0 OR ap.fguid IS NOT NULL) AND (ua.expire_date IS NULL OR ua.expire_date > NOW())\",\n\n */\n\n connection.query({\n sql: \"INSERT INTO album_timeline (guid, fguid, album_id, date) SELECT ?, ?, id, newest_media_timestamp FROM user_album AS ua LEFT JOIN album_permissions AS ap ON ap.guid = ? AND ap.fguid = ua.guid AND ap.album_id = ua.id WHERE ua.guid = ? AND ua.count > 0 AND (is_private = 0 OR ap.fguid IS NOT NULL) AND (ua.expire_date IS NULL OR ua.expire_date > NOW())\",\n values: [guid, beingFollowedGuid, guid, beingFollowedGuid ] \n }, function(err, result) {\n if (err) {\n printError(err); \n rollbackErrorResponse();\n } else {\n commitFollowRequest();\n } \n });\n }", "setMediaFile() {\n if (!this.creative()) {\n return this;\n }\n\n this.$media = bestMedia(this.creative().mediaFiles().all());\n\n if (!this.media()) {\n console.warn('No media.');\n\n return this;\n }\n\n const virtual = document.createElement('textarea');\n virtual.innerHTML = this.$media.source();\n this.$media.$source = virtual.value.trim();\n\n\n this.$hasAds = true;\n\n return this;\n }", "static addContent(entryId, resource = null){\n\t\tlet kparams = {};\n\t\tkparams.entryId = entryId;\n\t\tkparams.resource = resource;\n\t\treturn new kaltura.RequestBuilder('media', 'addContent', kparams);\n\t}", "function push_version() {\n if (versions.length == 30) { // 30 = Max undo\n versions.pop(); // Removes last element in Versions\n }\n var v_artwork = artwork.cloneNode(true);\n versions.unshift(v_artwork); // Adds current artwork to beginning of Versions\n}", "static update(entryId, mediaEntry){\n\t\tlet kparams = {};\n\t\tkparams.entryId = entryId;\n\t\tkparams.mediaEntry = mediaEntry;\n\t\treturn new kaltura.RequestBuilder('media', 'update', kparams);\n\t}", "static update(id, entry){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.entry = entry;\n\t\treturn new kaltura.RequestBuilder('externalmedia_externalmedia', 'update', kparams);\n\t}", "function addHashesToMedia(bundles, cb) {\n async.map(bundles, function (bundle, cbMapBundles) {\n async.map(bundle.media, function (media, cbMapMedia) {\n fs.readFile(media.path, function (err, imageData) {\n if (!err) {\n media.md5 = md5(imageData);\n }\n\n cbMapMedia(null, media);\n });\n }, function (ignoredError, media) {\n bundle.media = media;\n\n cbMapBundles(null, bundle);\n });\n }, cb);\n}", "set media(aValue) {\n this._logService.debug(\"gsDiggEvent.media[set]\");\n this._media = aValue;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
save user and the password hash into the DB, returns a promise
function saveToDB(user, pass) { return bcrypt.hash(pass, salt) .then(hash=>{ return User.create(user, hash) }) }
[ "function saveUser(username, password) {\n\n //This newUserRef allows for a NEW user to be submitted rather than replaced\n var newUserRef = usersRef.push();\n\n //Sets the data into the database under a randomly generated key \n newUserRef.set({\n username: username,\n password: password\n });\n }", "updatePassword(userId, password) {\n return new Promise((resolve, reject) => {\n const url = `${this.apiBase}/auth/passwordRecoveryPerform`;\n const payload = {userId, password };\n\n const requestOpts = this._makeFetchOpts('POST', payload);\n fetch(url, requestOpts).then(response => {\n if (response.ok) {\n response.json().then(user => {\n console.log('user', user);\n this.currentUser = user;\n this._saveUser(user);\n resolve(user);\n });\n } else {\n response.json().then(res => {\n reject(res.message);\n }\n )}\n });\n })\n }", "async savePassword(values) {\n\t\tconst data = {\n\t\t\tuserId: this.userId,\n\t\t\tcurrentPassword: values.currentPassword,\n\t\t\tpassword: values.password,\n\t\t\tpasswordConfirm: values.passwordConfirm\n\t\t};\n\t\tawait axios.patch('/user/update-password', data, config);\n\t}", "function createUserMongo(pass) {\n User\n .create({ email: email })\n .then(response => {\n // get id from mongo\n let id = response.id;\n corbato(pass)\n .then(hashPass => {\n createUserSQL(hashPass, id);\n })\n .catch(err => {\n return res.status(500).send(err);\n });\n })\n .catch(err => {\n res.status(422).json(err);\n });\n }", "static async register(data) {\n const duplicateCheck = await db.query(\n `SELECT username \n FROM users \n WHERE username = $1`,\n [data.username]\n );\n\n if (duplicateCheck.rows[0]) {\n throw new ExpressError(\n `There already exists a user with username '${data.username}`,\n 400\n );\n }\n\n const hashedPassword = await bcrypt.hash(data.password, BCRYPT_WORK_FACTOR);\n\n // create shrimpy user\n const shrimpy_user_id = await client.createUser(data.username);\n\n if (!shrimpy_user_id)\n throw new ExpressError(\"Could not create user in Shrimpy\");\n\n // create API keys in shrimpy for user management\n await client.createApiKeys(shrimpy_user_id);\n\n const result = await db.query(\n `INSERT INTO users \n (username, password, email, shrimpy_user_id) \n VALUES ($1, $2, $3, $4) \n RETURNING username, password, email, shrimpy_user_id`,\n [data.username, hashedPassword, data.email, shrimpy_user_id]\n );\n\n return result.rows[0];\n }", "function createWithHash(context) {\n if (context.data.hash) {\n // user provided password hash\n context.data.password = context.data.hash;\n delete context.data.hash;\n return Promise.resolve(context);\n }\n else {\n // hash the provided password\n return Local.hooks.hashPassword()(context);\n }\n }", "function insertData(e) {\n e.preventDefault();\n const fullName = document.getElementById('signup-name').value + \" \" + document.getElementById('signup-surname').value;\n const email = document.querySelector('#signup-email').value;\n const password = document.querySelector('#signup-password').value;\n idUser++;\n set(ref(database, \"Users/\" + idUser), {\n id: idUser,\n userName: fullName,\n userEmail: email\n })\n .then(() => {\n createUserWithEmailAndPassword(auth, email, password)\n .then((userCredential) => {\n signupForm.reset();\n $('#signupModal').modal('hide');\n })\n .catch((error) => {\n const errorCode = error.code;\n const errorMessage = error.message;\n });\n alert(\"Datos guardados correctamente\");\n })\n .catch((error) => {\n alert(\"Ha ocurrido un error\" + error);\n })\n}", "async function newPassword(req, res) {\n try {\n const { token } = req.query;\n const database = res.database;\n const user = await findUserBy(\"tokenPassword\", token, database);\n if (user) {\n const { email } = user;\n const newPassword = createHash();\n await updatetUser(\n user._id,\n {\n email,\n tokenPassword: null,\n tokenValidation: null,\n password: md5(newPassword)\n },\n database\n );\n await sendEmail(\n mailNewPassword({ email, password: newPassword }),\n res.mail\n );\n return res.status(200).send({\n message: \"Password reset. A new password was send to your mail.\"\n });\n } else {\n return res.status(403).send({\n message: \"No account found\"\n });\n }\n\n } catch (err) {\n console.log(\"INTER ERROR\", err.message);\n return res.status(500).send({ error: \"internal server error\" });\n }\n}", "validateLogin (username, password) {\n const database = this.database;\n const sha512 = this.sha512;\n return new Promise (function(resolve, reject) {\n database.query(\"SELECT * FROM login WHERE username = ?\", [username])\n .then((data) => {\n if(data.length === 0) {\n resolve(false);\n }\n if (sha512(password, data[0].salt) === data[0].pass) {\n resolve(true);\n } else {\n resolve(false);\n }\n })\n .catch(error => {\n reject(error);\n });\n });\n\n }", "function saveUser() {\n UserService.Update(vm.user)\n .then(function () {\n FlashService.Success('Usuario modificado correctamente');\n })\n .catch(function (error) {\n FlashService.Error(error);\n });\n }", "async create(attrs) {\r\n // {email: '', password:''} this is what we assume attrs is\r\n attrs.id = this.randomId();\r\n const salt = crypto.randomBytes(8).toString('hex');\r\n const buf = await scrypt(attrs.password, salt, 64);\r\n //salt + attrs.password\r\n const records = await this.getAll() //gets existing users\r\n const record = {\r\n ...attrs,\r\n password: `${buf.toString('hex')}.${salt}`\r\n } // the fullstop splits the hashed pw from the salt\r\n records.push(record); // pushes new user into our records\r\n await this.writeAll(records);\r\n\r\n return record; // returns object with user ID, plus hash and salted pw\r\n }", "signup(email, password, data) {\n return new Promise((resolve, reject) => {\n const url = `${this.apiBase}/auth/signup`;\n const payload = { email, password, data };\n\n const requestOpts = this._makeFetchOpts('POST', payload);\n fetch(url, requestOpts).then(response => {\n resolve();\n });\n })\n }", "function passwordManagerSave(aUsername, aPassword) {\n cal.auth.passwordManagerSave(aUsername, aPassword, aUsername, \"Google Calendar\");\n}", "function postUpdatePassword(req, res) {\r\n\tif (req.session.uid) {\r\n\t\tvar query = \"UPDATE Users SET password=? WHERE uid=?\";\r\n\t\tdatabase.query(req, res, query, [req.body.password, req.session.uid], ajaxSimplePostCbFcn);\r\n\t}\r\n}", "async beforeCreate(newUserData) {\n newUserData.password = await bcrypt.hash(newUserData.password, 10);\n return newUserData;\n }", "function loginUser(email, password) {\n\n return new Promise((resolve, reject) => {\n\n setTimeout(() => {\n\n if (validate(email, password)) {\n resolve(mockUser)\n }\n\n reject(Error('Login Failed'))\n }, 100)\n })\n}", "async registerNewUser(email, password, displayName) {\n console.log(\"registering new user\");\n try {\n let user = await app\n .auth()\n .createUserWithEmailAndPassword(email, password);\n let userObj = {\n id: user.user.uid,\n displayName,\n favorites: [],\n store: defaultSpices,\n };\n localStorage.setItem(\"sprackId\", user.user.uid);\n await db.collection(\"users\").doc(userObj.id).set(userObj);\n return await this.fetchUserData(user.user.uid);\n } catch (error) {\n console.log(error);\n return error;\n }\n }", "async signInUser(email, password) {\n return await app\n .auth()\n .signInWithEmailAndPassword(email, password)\n .then((user) => {\n localStorage.setItem(\"sprackId\", user.user.uid);\n return user.user.uid;\n })\n .catch((error) => {\n const err = {\n code: error.code,\n message: error.message,\n };\n return err;\n });\n }", "function setupUser (results, pass, callback) {\n const imprint = results[0].toString()\n const stampLocked = results[1].toString()\n const lock = results[2].toString()\n const keyLocked = results[3].toString()\n const cert = results[4].toString()\n const salt = results[5].toString()\n const stampedUsers = JSON.parse(results[6].toString())\n crypto.hashPass(pass, salt, function (err, pwhash) {\n if (err) return callback(err)\n var stamp, key\n try {\n stamp = crypto.decrypt(pwhash.secret, stampLocked)\n key = crypto.decrypt(pwhash.secret, keyLocked)\n } catch (err) {\n if (err) return callback(err)\n }\n const user = {\n imprint: imprint,\n stamp: stamp,\n stamp_locked: stampLocked,\n lock: lock,\n key: key,\n key_locked: keyLocked,\n cert: cert,\n _salt: salt,\n stamped_users: stampedUsers\n }\n callback(null, user)\n })\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse an ip and port from a 'tcp://:' string
function _parse(info) { if (typeof info !== 'string') { throw new TypeError('expecting string transport uri'); } var uri = url.parse(info); if (!(uri.port > 0)) { throw new Error('expected valid transport uri'); } return { host: uri.hostname, port: uri.port }; }
[ "function parseOnePortRule(rule){\n if (validRule(rule)==false ) {\n return \"err\";\n }\n\n rule = rule.split(\"\\x02\");\n\n //------------SOURCE PORT-----------------------\n rule[_src] = rule[_src].split(\"+\"); //tcp+udp\n if(isArray(rule[_src])){\n if(rule[_src].length == 2){\n rule[_src][_TCP] = rule[_src][_TCP].split(\",\"); //TCP\n rule[_src][_UDP] = rule[_src][_UDP].split(\",\"); //UDP\n }else{\n alert(\"1 \"+\"rule\"+\"#\"+n+\"srcport format error: should consists of TCP and UDP: using '+'\");\n }\n }else{\n alert(\"2 \"+\"rule\"+\"#\"+n+\"srcport format error: should consists of TCP and UDP: using '+'; is not an array??\");return \"err\";\n }\n //------------DESTINATION PORT-----------------------\n rule[_dst] = rule[_dst].split(\"+\"); //tcp+udp\n if(isArray(rule[_dst])){\n if(rule[_dst].length == 2){\n rule[_dst][_TCP] = rule[_dst][_TCP].split(\",\"); //TCP\n rule[_dst][_UDP] = rule[_dst][_UDP].split(\",\"); //UDP\n }else{\n alert(\"1 \"+\"rule\"+\"#\"+n+\"srcport format error: should consists of TCP and UDP: using '+'\");return \"err\";\n }\n }else{\n alert(\"2 \"+\"rule\"+\"#\"+n+\"srcport format error: should consists of TCP and UDP: using '+'; is not an array??\");return \"err\";\n }\n return rule;\n}", "function getPort(browser) {\n return parseInt(/(?<=:)\\d{1,5}(?=\\/)/.exec(browser.wsEndpoint())[0]);\n}", "function _unpackIPv4(ipStr) {\n if (ipStr.toLowerCase().indexOf('0000:0000:0000:0000:0000:ffff:') != 0) {\n return null\n }\n\n var hextets = ipStr.split(':')\n return hextets.pop()\n}", "vaidateProtocol(host){\n let protocols = ['https://', 'http://'];\n if (protocols.map(protocol => host.includes(protocol)).includes(true)) return host\n throw new Error('Host String must include http:// or https://')\n }", "function _format(host, port) {\n return url.format({\n slashes: true,\n protocol: 'tcp',\n hostname: host,\n port: port\n });\n}", "function extractHostname(t) {\n return (t.indexOf(\"//\") > -1 ? t.split(\"/\")[2] : t.split(\"/\")[0]).split(\":\")[0].split(\"?\")[0]\n}", "function displayConnections() {\n console.log(\"\\nid:\\tIP Address\\t\\tPort No.\");\n for (i = 0; i < clientSockets.length; i++) {\n var ip = clientSockets[i].request.connection._peername.address;\n\n if (ip == '127.0.0.1') {\n ip = clientIP;\n }\n var port = clientSockets[i].request.connection._peername.port;\n console.log((i + 1) + \"\\t\" + ip + \"\\t\\t\" + port);\n }\n console.log(\"\\n\");\n} // End displayConnections()", "function getIpProtoByServCatPubUrl (pubUrl)\n{\n var ipAddr = null;\n var port = null;\n var reqProto = global.PROTOCOL_HTTP;\n var ipAddrStr = pubUrl, portStr = null;\n var ipIdx = -1, portIdx = -1;\n\n ipIdx = pubUrl.indexOf(global.HTTPS_URL);\n if (ipIdx >= 0) {\n reqProto = global.PROTOCOL_HTTPS;\n ipAddrStr = pubUrl.slice(ipIdx + (global.HTTPS_URL).length);\n }\n ipIdx = pubUrl.indexOf(global.HTTP_URL);\n if (ipIdx >= 0) {\n ipAddrStr = pubUrl.slice(ipIdx + (global.HTTP_URL).length);\n }\n\n /* Format is http://<ip/host>:<port>/XXXX */\n portIdx = ipAddrStr.indexOf(':');\n if (-1 != portIdx) {\n ipAddr = ipAddrStr.substr(0, portIdx);\n portStr = ipAddrStr.slice(portIdx + 1);\n portIdx = portStr.indexOf('/');\n if (-1 != portIdx) {\n port = portStr.substr(0, portIdx);\n } else {\n port = portStr;\n }\n }\n return {'ipAddr': ipAddr, 'port': port, 'protocol': reqProto};\n}", "function processUrl (inputUrl, port) {\n const parsedUrl = url.parse(inputUrl)\n\n if (parsedUrl.host === TEST_HOSTNAME &&\n parsedUrl.port === TEST_PORT) {\n const path = url.format({\n protocol: 'http',\n hostname: 'localhost',\n port,\n pathname: parsedUrl.pathname,\n search: parsedUrl.search\n })\n return path\n }\n\n return inputUrl\n}", "function getPort () {\n if (process.env.PORT) {\n return process.env.PORT\n }\n const u = new url.URL(process.env.SVC_BASE_URI)\n if (u.port) {\n return u.port\n }\n if (u.protocol === 'https:') {\n return '443'\n } else if (u.protocol === 'http:') {\n return '80'\n }\n throw new Error('protocol must be http: or https:')\n}", "function parseIPv6Section(addressSection) {\n const numberValue = Number.parseInt(addressSection, 16);\n return [(numberValue / 256) | 0, numberValue % 256];\n}", "function parseCIDR(cidr) {\n // let parts = parseCIDR(\"123.255.78.90/12\");\n // yields:\n // parts.ipAddress = 123.255.78.90\n // parts.prefixLength = 12\n\n //OLD: let patt = /^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\/(\\d{1,2})$/;\n let patt = /^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\/(\\d{1,2})$/;\n let matches = patt.exec(cidr);\n\n if (matches == null) {\n throw \"Invalid CIDR format provided.\";\n }\n\n console.log(\"matches: \" + matches.length + \" from matches[0]: \" + matches[0]);\n\n // OLD: let ipAddress = matches[1]; // BEFORE: whole IP, AFTER: 123 => 123.45.67.8\n let ipAddress = `${matches[1]}.${matches[2]}.${matches[3]}.${matches[4]}`;\n let prefixLength = matches[5];\n\n // If ipAddress has any unneccessary leading zeros\n // throw \"Unexpected leading zero in IP address.\";\n for (let i = 1; i <= 4; i++) {\n if (matches[i].length > 1) {\n if (matches[i].charAt(0) == \"0\") {\n throw \"Unexpected leading zero in IP address.\";\n }\n }\n }\n\n // If prefixLength has an unneccessary leading zero\n // throw \"Unexpected leading zero in prefix.\";\n if (matches[5].length > 1) {\n if (matches[5].charAt(0) == \"0\") {\n throw \"Unexpected leading zero in prefix\";\n }\n }\n\n // If ipAddress has any segments >255\n // throw \"IP address values should be only 0..255.\";\n for (let y = 1; y <= 4; y++) {\n // if ((matches[y] > 255) && (matches[y] < 0))\n // if ((matches[y] > 255) || (matches[y] < 0))\n if (matches[y] > 255 || matches[y] < 0) {\n throw \"Invalid IP Address.\";\n }\n }\n\n // If prefixLength is >32 (or <0)\n // throw \"Prefix value should be only 0..32\";\n if (matches[5] > 32 || matches[5] < 0) {\n throw \"invalid CIDR bit length - /N value should be only 0..32\";\n }\n\n return {\n ipAddress,\n prefixLength,\n };\n}", "function printAddresses() {\n var httpAddress = \"http://0.0.0.0\";\n if (ports[0] != 80) httpAddress += \":\" + ports[0];\n httpAddress += \"/\";\n var httpsAddress = \"https://0.0.0.0\";\n if (ports[1] != 443) httpsAddress += \":\" + ports[1];\n httpsAddress += \"/\";\n console.log('Server running at', httpAddress, 'and', httpsAddress);\n}", "function marvin_client(ip, port) {\n this.ip = ip;\n this.port = port;\n}", "function convertIPv4toUInt32(ip) {\n if (ip === 'localhost')\n ip = '127.0.0.1';\n let bytes = ip.split('.');\n // console.assert(bytes.length === 4);\n let uint = 0;\n bytes.forEach(function iterator(byte) {\n uint = uint * 256 + (+byte);\n });\n return uint >>> 0;\n }", "_socket (host, port) {\n const pool = this._getPool(host, port)\n return pool.acquire()\n }", "function parseServoPosition(buf) {\n\n return parseInt((new Number(buf[2])).toString(16) + (new Number(buf[1])).toString(16), 16);\n}", "function getHostByArg() {\n\t//Recojemos los parametros con slice a partir del segundo elemento de la peticion\n\tvar args = process.argv.slice(2);\n\n\t//Valor por defecto para el host\n\tvar host = '127.0.0.1';\n\n\t//console.log(\"Host \" + host);\n\n\tif (args.length > 0) {\n\t\t//Procesamos el array de parametros para conocer el par host:puerto\n\t\tvar aux = args[0]\n\t\tvar args_split = aux.split(\":\");\n\n\t\t//Asignamos a host el valor anterior a la aparicion del separador :\n\t\thost = args_split[0];\n\n\t\t//console.log(\"Host \" + host);\n\t}\n\n\treturn host;\n}", "function TcpPolyfillPlugin(contextPattern) {\n this.contextPattern = contextPattern;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
What is the ID of the model. In 100% of the cases this method should be overriden to provide a scalar value or object representing ID. That in mind, implementation of this method is completly optional if the application does not want to store models.
id() { // implementation should be inside the child class, but below implementation // if for simplicity in many occasions if (typeof this.data.id != 'undefined') return this.data.id; // no ID return null; }
[ "get id() {\n this._id = getValue(`cmi.objectives.${this.index}.id`);\n return this._id;\n }", "preSaveSetId() {\n if (isNone(this.get('id'))) {\n this.set('id', generateUniqueId());\n }\n }", "static async findById(id) {\n // Ensure model is registered before finding by ID\n assert.instanceOf(this.__db, DbApi, 'Model must be registered.');\n\n // Return model found by ID\n return await this.__db.findById(this, id);\n }", "function getId(dbEntity){\n return dbEntity.entity.key.path[0].id ||\n dbEntity.entity.key.path[0].name;\n}", "indexOfId(id) {\n var Model = this.constructor.classes().model;\n var index = 0;\n var result = -1;\n id = String(id);\n\n while (index < this._data.length) {\n var entity = this._data[index];\n if (!(entity instanceof Model)) {\n throw new Error('Error, `indexOfId()` is only available on models.');\n }\n if (String(entity.id()) === id) {\n result = index;\n break;\n }\n index++;\n }\n return result;\n }", "function data(model, id) {\n if (!metaData || !metaData[model] || !metaData[model][id]) {\n return false;\n }\n\n return metaData[model][id];\n }", "getID() {\r\n return this.id.toString().padStart(3, '0');\r\n }", "getById(id) {\n return ContentType(this).concat(`('${id}')`);\n }", "@api get assetId(){\n return this.recordId;\n }", "function setId(entity){\n entity['id'] = entity[datastore.KEY].id;\n return entity;\n}", "static createModel(inobj) {\n\t\tconst model = super.createModel(inobj);\n\t\tmodel.creationDate = new Date();\n\t\tmodel.pid = process.pid;\n\t\treturn model;\n\t}", "getById(id) {\n return FieldLink(this).concat(`(guid'${id}')`);\n }", "function idComponent(v) {\n return id[v];\n }", "pathId(){\n return this.id\n }", "set id(newId) {\n this._id = newId;\n setValue(`cmi.objectives.${this.index}.id`, newId);\n }", "getById(id) {\n return tag.configure(FieldLink(this).concat(`(guid'${id}')`), \"fls.getById\");\n }", "get id() {\n let cityID = this.city\n\n if (cityID === 'Berlin') {\n cityID = 'Frankfurt'\n } else if (cityID.includes('_')) {\n cityID = cityID.replace('_', '-')\n }\n\n return cityID.toLowerCase()\n }", "function rootFieldByID(idName, gotType) {\n const getter = id => getObjectFromTypeAndId(gotType, id);\n const argDefs = {};\n argDefs.id = { type: GraphQLID };\n argDefs[idName] = { type: GraphQLID };\n return {\n type: gotTypeToGraphQLType(gotType),\n args: argDefs,\n resolve: (_, args) => {\n if (args[idName] !== undefined && args[idName] !== null) {\n return getter(args[idName]);\n }\n\n if (args.id !== undefined && args.id !== null) {\n const globalId = fromGlobalId(args.id);\n if (\n globalId.id === null ||\n globalId.id === undefined ||\n globalId.id === ''\n ) {\n throw new Error(`No valid ID extracted from ${args.id}`);\n }\n return getter(globalId.id);\n }\n throw new Error(`must provide id or ${idName}`);\n },\n };\n}", "idOrCriteria(idOrCriteria) {\n if (typeof idOrCriteria === 'object') {\n return idOrCriteria;\n } else {\n return { _id: idOrCriteria };\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Getter for evidence This will return an array of displayText strings from Evidence array
get evidence() { if (!this._evidence) return []; return this._evidence.map((e) => { return e.value; }); }
[ "listEvidence(propRefs) {\n let output = [];\n for (let prop = 0; prop < propRefs.length; prop++) {\n output.push(<h4 key={eval('this.props.topic.' + propRefs[prop] + '.key1')}>{propRefs[prop] + \". Evidence\"}</h4>);\n output.push(<ul key={eval('this.props.topic.' + propRefs[prop] + '.key2')}>{this.cascadeData('evidence', propRefs[prop], 'no', 'no')}</ul>);\n };\n return output;\n }", "set evidence(evidence) {\n // filter evidence to ignore case and to make sure there are no duplicates\n const filteredEvidence = evidence.map(e => e.toLowerCase()).filter((e, index, arr) => {\n return arr.indexOf(e) === index;\n });\n\n this._evidence = filteredEvidence.map((e) => {\n let ev = new FluxEvidence();\n ev.value = lookup.getEvidenceCodeableConcept(e);\n return ev;\n });\n }", "function getTypographyDetailsArray() {\n var currentSlideId = getCurrentSlideId()\n switch (currentSlideId) {\n case 'typography-details-good':\n var array = TYPOGRAPHY_DETAILS_GOOD\n break\n case 'typography-details-typewriter':\n var array = TYPOGRAPHY_DETAILS_TYPEWRITER\n break\n }\n\n return array\n}", "get titles() {\n return issues.map(obj => obj.title);\n }", "get details() {\n if (this._study.details) {\n return this._study.details.value;\n } else {\n return \"\";\n }\n }", "function zooInventory(array) {\n\t// create a variable, sentences and assign to an empty array\n\tconst sentences = [];\n\t// iterate through the array\n\tfor (let i = 0; i < array.length; i++) {\n\t\t// grab the elements assign to a variable animal\n\t\tlet animal = array[i];\n\t\t// create a name assign to the first element\n\t\tlet name = animal[0];\n\t\t// create a variable species assign to the first element at index 0\n\t\tlet species = animal[1][0];\n\t\t// create an age variable and assign to the first element at index 1\n\t\tlet age = animal[1][1];\n\t\t// create a variable called sentence assign to - name the species is age\n\t\tlet sentence = `${name} the ${species} is ${age}.`;\n\t\t// push sentence into sentences array\n\t\tsentences.push(sentence);\n\t}\n}", "function visibleAttendees(state) {\n let attendees = state.attendees\n let skillsFilters = state.skillsFilters\n let searchName = state.searchName\n\n if (skillsFilters.length !== 0) {\n attendees = attendees.filter(filterBySkills.bind(this, skillsFilters))\n }\n\n if (searchName !== '') {\n attendees = attendees.filter(searchFirstAndLastName.bind(this, searchName))\n }\n\n return attendees\n}", "function textList(array) {\n return array.join();\n}", "function extractSentences(raw) {\n return $.map(raw[0], (function(v) { return v[0]; })).join('');\n}", "get fieldValuesAsText() {\n return SPInstance(this, \"FieldValuesAsText\");\n }", "get getGrades() {\r\n var text = \"\";\r\n if (this.grades.length === 0) {\r\n return \"Nie ma żadnych ocen\";\r\n } else {\r\n for (var i = 0; i < this.grades.length; i++) {\r\n text += this.grades[i] + \", \";\r\n }\r\n }\r\n return text;\r\n }", "function gatherFeedback(arr) {\n\t\tlet newArray = [];\n\t\tfor (let i = 0; i < arr.length; i++) {\n\t\t\tif (arr[i].length > 0) {\n\t\t\t\tfor (let k = 0; k < arr[i].length; k++) {\n\t\t\t\t\tif (arr[i][k].viewed === false) {\n\t\t\t\t\t\tnewArray.push(arr[i][k]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn newArray;\n\t}", "getVoices() {\n\t\tlet voiceList = [];\n\n\t\tthis.textToSpeech.listVoices(null,\n\t\t\tfunction(err, voicesObj) {\n\t\t\t\t\tif (err) {\n\t\t\t\t\t\t//throw err;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tvoicesObj.voices.forEach(function(voice) {\n\t\t\t\t\t\t\tvoiceList.push(voice.name);\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t}\n\t\t);\n\t\treturn voiceList;\n\t}", "function passengersInfoText() {\n passengerInfoText = [];\n $(\".popover-content input\").each(function(i) {\n if(this.value > 0){\n //passengerInfoText.push(typeText[this.id][this.value>1?'plural':'singular'] + ': ' + this.value);\n passengerInfoText.push(this.value +' '+ typeText[this.id][this.value>1?'plural':'singular']);\n }\n });\n $('#passenger-info').val(passengerInfoText.join(', '))\n }", "function getSummaryInfo(){\r\n var summaryArray=[];\r\n var summaryStr=obj['subfield'][0]['_'];\r\n summaryStr = summaryStr.trim();\r\n if (debug) console.log(summaryStr);\r\n book['summary']=summaryStr;\r\n}", "getVerbsList() {\n // return Object.keys(VerbDictionary).map((key) => VerbDictionary[key].display[defaultLanguage]);\n return this.getDictionaryWordsList(ADLVerb);\n }", "get generalNames() {\n return this.extnValueObj.subs[0].subs;\n }", "function getBenefits() {\n return payGrades[getCadre()].benefits.join(', ');\n}", "function getTitles(courseIds) {\n var titles = [];\n for (var i = 0; i < courseIds.length; i++) {\n var id = courseIds[i];\n var courseNumber = id.split('.')[1];\n var courses = coursesByDepartments[id.split('.')[0]];\n var title = '';\n for (var j = 0; j < courses.length; j++) {\n if (courses[j].cnum === courseNumber) {\n title = courses[j].title;\n break;\n }\n }\n titles.push(title);\n }\n return titles;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns whether the token will expire within eagerRefreshThresholdMillis
isTokenExpiring() { var _a; const now = new Date().getTime(); const eagerRefreshThresholdMillis = (_a = this.eagerRefreshThresholdMillis) !== null && _a !== void 0 ? _a : 0; if (this.rawToken && this.expiresAt) { return this.expiresAt <= now + eagerRefreshThresholdMillis; } else { return true; } }
[ "function expired() {\n return (this.token && this.token.expires_at && new Date(this.token.expires_at) < new Date());\n }", "checkIdToken() {\r\n console.log('check Id token expiration')\r\n let user = this.user();\r\n if (user) {\r\n const expirationDateSecs = user.idTokenClaims.exp\r\n const expDate = new Date(expirationDateSecs * 1000)\r\n console.log('expDateSecs: '+expDate);\r\n\r\n if ((new Date()).getTime() >= expirationDateSecs * 1000) {\r\n console.log('IdToken expired. Clearing internal cache')\r\n this.clearLocal()\r\n return false \r\n } else {\r\n console.log('ID token is still valid')\r\n return true\r\n } \r\n } else {\r\n return false\r\n }\r\n }", "isTokenExpired(token){\n try {\n const decoded = decode(token);\n return (decoded.exp < Date.now() / 1000);\n } catch (err) {\n console.log(\"expired check failed!\");\n return true;\n }\n }", "function getTokenRefreshTimeout(token) {\n if (token) {\n var decoded = jwt.decode(token);\n\n // expiry date in future?\n if (decoded.exp && 1000 * decoded.exp > Date.now()) {\n // refresh once a day or halfway to expiry\n var timeout = Math.min(24 * 3.6e6, Math.ceil((1000 * decoded.exp - Date.now()) / 2));\n return timeout;\n }\n }\n\n // retry in 1s\n return 1000;\n }", "checkToken() {\n if(localStorage.getItem(\"token_time\") != null) {\n if(new Date().getTime() - new Date(localStorage.getItem(\"token_time\")).getTime() > 60000) {\n localStorage.setItem(\"token_time\", (new Date()).toString());\n console.log(\"update token\");\n this.updateToken();\n }\n } else {\n localStorage.setItem(\"token_time\", (new Date()).toString());\n this.updateToken();\n }\n }", "has_life_expired() {\n if ((this.lifetime !== null) && (this.age >= this.lifetime)) {\n return true;\n } else {\n return false;\n }\n }", "function isExpired(date) {\n var then = new Date(date);\n var now = new Date();\n return (Math.abs(now - then) > 3600000);\n }", "function is_data_stale() {\n\treturn last + max_age < Date.now();\n}", "isRefreshNeeded() {\n if (this.refreshNeeded) {\n return true;\n }\n if (null != this.exception) {\n // If we encountered an exception on the last attempt\n // we do not want to keep retrying without a pause between\n // the refresh attempts.\n //\n // If we have exceeded our backoff time we will refresh\n // the secret now.\n if ((+new Date()) >= this.nextRetryTime) {\n return true;\n }\n // Don't keep trying to refresh a secret that previously threw\n // an exception.\n return false;\n }\n return false;\n }", "checkGrant_type()\n {\n if(this.grant_type == 'refresh_token')\n {\n return true;\n }\n }", "hasUntouchableTokens(){ return false; }", "if (_cacheRepoAssure.lastAssured + 5 * 1000 * 60 >= Date.now()) {\n return _cacheRepoAssure.pendingAssure;\n }", "function hasStoredToken() {\n //const vault = await this.getVault();\n return authVault.hasStoredToken();\n }", "setupTokenReconnectTimer(){\n log.debug('[PageSharedDB] setting up timer for token refresh')\n let reconnectInMilliseconds = (this.expires_at * 1000) - Date.now() - 5000\n clearTimeout(this.tokenReconnectTimer)\n\n this.tokenReconnectTimer = setTimeout(() => {\n this.tokenReconnect()\n }, reconnectInMilliseconds)\n }", "function timeUntilActivationTimeout() {\n // use same timeout logic as `@adobe/node-openwhisk-newrelic`: https://github.com/adobe/node-openwhisk-newrelic/blob/master/lib/metrics.js#L38-L44\n return (process.env.__OW_DEADLINE - Date.now()) || DEFAULT_METRIC_TIMEOUT_MS;\n}", "function userPurchasedWithinLast30Minutes() {\n for (var i = 0; i < splitCookieArray.length; i++) {\n if (splitCookieArray[i].indexOf('userLastPurchased') >= 0) {\n var userLastPurchasedTimestamp = parseInt(splitCookieArray[i].split('=')[1]);\n console.log('The user last purchased at timestamp ' + userLastPurchasedTimestamp);\n if ( (Math.round(new Date().getTime()/1000) - userLastPurchasedTimestamp) <= 1800) { // If the time difference between now and the last time the user purchased is less than 30 minutes\n console.error('The user has purchased within the last 30 minutes. We will not fire a tracking pixel.');\n return true;\n break;\n }\n else {\n console.log('The time difference between now and the time the user last purchased is greater than 30 minutes.');\n return false; // Return false if the time difference is greater than 30 minutes\n }\n }\n }\n console.log('The userLastPurchased cookie does not exist.');\n return false; // Return false if the cookie doesn't exist.\n }", "async getRefreshToken () {\n return this.client.auth.refresh_token\n }", "function isActiveToken () {\n const url = `${baseURl}/api/user/verifyToken`\n return localforage.getItem('token').then((jwt) => {\n return axios.post(url, { params: jwt })\n })\n}", "function setAutoRefreshTimeout() {\n clearTimeout(autoRefreshTimeoutId);\n if (auth.autoRefresh && typeof auth.expires !== 'undefined') {\n autoRefreshTimeoutId = setTimeout(auth.refresh, auth.expires + 1000);\n }\n }", "function checkRateLimitResetTime () {\n const now = +(new Date().getTime() / 1000).toFixed(0)\n if (now > state.rateLimiting.resetTime) {\n state.rateLimiting.active = false\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if a value implements the `Point` interface.
isPoint(value) { return isPlainObject(value) && typeof value.offset === 'number' && Path.isPath(value.path); }
[ "function isAPosPointDescription(desc)\n{\n var type = PosPoint.prototype.determineType(desc);\n return (type !== undefined);\n}", "function check_point(p) {\n if (p.x < 0 || p.x > 9) {\n return false;\n } else if (p.y < 0 || p.y > 9) {\n return false;\n } else if (spielfeld[p.y][p.x]) {\n //console.log(\"point already in use:\", p);\n return false;\n } else {\n //console.log(\"point ok:\", p);\n return true;\n }\n}", "isLocation(value) {\n return Path.isPath(value) || Point.isPoint(value) || Range.isRange(value);\n }", "function isInBounds(point) {\n\t\tif (point >= bounds.sw && point <= bounds.nw) {\n\t\t\tconsole.log(\"point in bounds\");\n\t\t}\n\t}", "function hasValidPoint(data) {\n return (typeof data.latitude != \"undefined\" && data.longitude != \"undefined\" && data.latitude != null && data.longitude != null && !isNaN(data.latitude) && !isNaN(data.longitude));\n }", "function isPointBetween(point, min, max) {\n if(point > min && point < max)\n return true;\n\n return false;\n}", "function isPointOnBezierExtension(ps, p) {\n if (ps.length === 4) {\n return isPointOnBezierExtension3(ps, p);\n }\n if (ps.length === 3) {\n return isPointOnBezierExtension2(ps, p);\n }\n return isPointOnBezierExtension1(ps, p);\n}", "function pointIsInCanvas(x, y, w, h) {\n return x >= 0 && x <= w && y >= 0 && y <= h;\n}", "contains(x, y) {\r\n if (!this.isEnabled()) return false;\r\n if (x < this.at().x || x > (this.at().x + this.width())) return false;\r\n if (y < this.at().y || y > (this.at().y + this.height())) return false;\r\n return true;\r\n }", "function checkInsideBoundingBox(bound, pt)\n{\n\tif (pt.x < bound.lower_bound.x || pt.x > bound.higher_bound.x) {\n\t\treturn false;\n\t}\n\tif (pt.y < bound.lower_bound.y || pt.y > bound.higher_bound.y) {\n\t\treturn false;\n\t}\n\tif (pt.z < bound.lower_bound.z || pt.z > bound.higher_bound.z) {\n\t\treturn false;\n\t} \n\treturn true;\n}", "function is_pivot(piece, x, y)\n{\n\treturn piece.pivot_x == x && piece.pivot_y == y;\n}", "isInside(modelSpacePoint) {\n\t\t// jshint unused:vars\n\t\treturn false;\n\t}", "isStart(editor, point, at) {\n // PERF: If the offset isn't `0` we know it's not the start.\n if (point.offset !== 0) {\n return false;\n }\n\n var start = Editor.start(editor, at);\n return Point.equals(point, start);\n }", "isLocation() {\n return this.truthObject.constructor.name == 'Location'\n }", "intersectsPoint(a, b) {\n if (!b) {\n var x2 = a.x;\n var y2 = a.y;\n } else {\n var x2 = a;\n var y2 = b;\n }\n const x = this.x;\n const y = this.y;\n const w = this.width;\n const h = this.height;\n return x2 >= x && x2 <= x + w && y2 >= y && y2 <= y + h;\n }", "function isPointInRect(pt,rpt, rsz){\n\t//logic that checks a point is in a rectangle\n\t if(!(pt.x < rpt.x || pt.y < rpt.y\n\t\t|| pt.x > rpt.x + rsz.x || pt.y > rpt.y + rsz.y)){\n\t\t\t//alert();\n\t\t\treturn true;\t\t\n\t}else\n\t\treturn false;\n}", "hasBlockAt(position) {\n\t\tconst xVals = this.blocks.get(position.y);\n\t\treturn (xVals && xVals.has(position.x)) || false;\n\t}", "function IsMousePosValid(mouse_pos = null) {\r\n return bind.IsMousePosValid(mouse_pos);\r\n }", "function onLine(line, point) {\n\tif(point.x <= Math.max(line.p1.x, line.p2.x) && point.x <= Math.min(line.p1.x, line.p2.x) &&\n\t\t(point.y <= Math.max(line.p1.y, line.p2.y) && point.y <= Math.min(line.p1.y, line.p2.y)))\n\t\treturn true;\n\treturn false;\n}", "function isPointInView(p) {\n for (var i = 0; i < view_plane_normals.length; i++)\n if (dot([p.x-camera_location.x, \n\t\t\t\t\t p.y-camera_location.y, \n\t\t\t\t\t\t p.z-camera_location.z], \n\t\t\t\t\t\t view_plane_normals[i]) < -0.001)\n return false\n return true\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if JS media query matches the query string passed
function getMediaQuery(query) { var mediaQueryList = window.matchMedia == null ? void 0 : window.matchMedia(query); if (!mediaQueryList) { return undefined; } return !!mediaQueryList.media === mediaQueryList.matches; }
[ "registerQuery(mediaQuery) {\n const list = Array.isArray(mediaQuery) ? mediaQuery : [mediaQuery];\n const matches = [];\n buildQueryCss(list, this._document);\n list.forEach((query) => {\n const onMQLEvent = (e) => {\n this._zone.run(() => this.source.next(new MediaChange(e.matches, query)));\n };\n let mql = this.registry.get(query);\n if (!mql) {\n mql = this.buildMQL(query);\n mql.addListener(onMQLEvent);\n this.pendingRemoveListenerFns.push(() => mql.removeListener(onMQLEvent));\n this.registry.set(query, mql);\n }\n if (mql.matches) {\n matches.push(new MediaChange(true, query));\n }\n });\n return matches;\n }", "function isMediumSet() {\n if (allUrlParameters.hasOwnProperty('utm_medium')){\n return allUrlParameters.utm_medium;\n } else {\n return '(not set)';\n }\n}", "function fInitMediaQueries () {\n tMx.ticker.addEventListener (\"tick\", fTimer);\n function fTimer () {\n /**-----===( Load Media Queries )===-----**/\n fMediaQueries ();\n //fLoadNextPreviousButtons();\n ix++;\n if (ix >= 2) {\n fRemoveEvntListnr (fTimer);\n }\n }\n }", "function disableMatchMedia() {\n\twindow.matchMedia = undefined;\n}", "function isMediaDevicesSuported(){return hasNavigator()&&!!navigator.mediaDevices;}", "function isResponsiveMode(){\r\n return hasClass($body, RESPONSIVE);\r\n }", "function selectQuality(q) {\t\r\n\t\t\tvar p = 0;\r\n\t\t\tvar f = false;\r\n\t\t\tvar pref = YT_EMBED_QUALTIY.split(\",\");\r\n\t\t\tfor(px in pref) {\r\n\t\t\t\tif(pref[px] == \"1080p\")\r\n\t\t\t\t\tpref[px] = \"hd1080\";\r\n\t\t\t\telse if(pref[px] == \"720p\")\r\n\t\t\t\t\tpref[px] = \"hd720\"\r\n\t\t\t\telse if(pref[px] == \"480p\")\r\n\t\t\t\t\tpref[px] = \"large\"\r\n\t\t\t\telse if(pref[px] == \"360p\")\r\n\t\t\t\t\tpref[px] = \"medium\"\t\r\n\t\t\t}\r\n\t\t\tvar find = function() {\r\n\t\t\t\tfor(j in q) {\r\n\t\t\t\t\tif(q[j] == pref[p]) {\r\n\t\t\t\t\t\tf = true;\r\n\t\t\t\t\t\tp = j;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t};\r\n\t\t\tfor(c = 0; c < pref.length; c++) {\r\n\t\t\t\tfind();\r\n\t\t\t\tif(f == true) {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tp++;\r\n\t\t\t};\r\n\t\t\treturn q[p];\r\n\t\t}", "function checkURL()\n{\n if (/\\bfull\\b/.test(location.search)) toggleMode();\n if (/\\bstatic\\b/.test(location.search)) interactive = false;\n}", "function checkWindowWidthSm() {\n\t\tvar e = window, \n a = 'inner';\n if (!('innerWidth' in window )) {\n a = 'client';\n e = document.documentElement || document.body;\n }\n if ( e[ a+'Width' ] <= breakpoint ) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}", "function createMediaQueries(breakpoints) {\n /**\n * Get the non-number breakpoint keys from the provided breakpoints\n */\n var keys = Object.keys(breakpoints);\n /**\n * Use only the keys matching the official breakpoints names, and sort them in\n * largest to smallest order\n */\n\n var sorted = _utils.breakpoints.filter(bp => keys.includes(bp)).reverse();\n /**\n * create a min-max media query string\n */\n\n\n return sorted.map((breakpoint, index) => {\n var minWidth = breakpoints[breakpoint];\n var next = sorted[index - 1];\n var maxWidth = next ? breakpoints[next] : undefined;\n var query = \"\";\n\n if (parseInt(minWidth) >= 0) {\n query = \"(min-width: \" + toMediaString(minWidth) + \")\";\n }\n\n if (maxWidth) {\n if (query) {\n query += \" and \";\n }\n\n query += \"(max-width: \" + toMediaString(subtract(maxWidth)) + \")\";\n }\n\n var mediaQuery = {\n breakpoint,\n maxWidth,\n minWidth,\n query\n };\n return mediaQuery;\n });\n}", "mediaTypeCss(media, data) {\n const type = this.mediaType(media, data);\n return type ? type.id.replace(/^.*media\\.type/, '').toLowerCase() : '';\n }", "function isAudioParam(arg) {\n return (0, _standardizedAudioContext.isAnyAudioParam)(arg);\n}", "function useVideoJs() {\n return !(typeof videojs === \"undefined\");\n }", "function findMediaType( url ){\n var regexResult = __urlRegex.exec( url ),\n // if the regex didn't return anything we know it's an HTML5 source\n mediaType = \"object\",\n flashVersion;\n if ( regexResult ) {\n\n mediaType = regexResult[ 1 ];\n // our regex only handles youtu ( incase the url looks something like youtu.be )\n if ( mediaType === \"youtu\" ) {\n mediaType = \"youtube\";\n }\n\n if ( !_checkedFlashVersion ) {\n _checkedFlashVersion = true;\n flashVersion = PluginDetect.getVersion( \"Flash\" );\n if ( flashVersion && +flashVersion.split( \",\" )[ 0 ] < MIN_FLASH_VERSION ) {\n Warn.showWarning( Localized.get( \"flashWarning\" ) + \" \" + Localized.get( \"Click to remove warning\" ) );\n }\n }\n }\n return mediaType;\n }", "function video_property_exist(property_name)\n{\n test( function() {\n getmedia();\n assert_true(property_name in media, \"media.\" + property_name +\" exists\");\n }, name);\n}", "static getMediaElement(mediaElementId,type){const mediaElement=document.getElementById(mediaElementId);if(!mediaElement){throw new ArgumentException(`element with id '${mediaElementId}' not found`);}if(mediaElement.nodeName.toLowerCase()!==type.toLowerCase()){throw new ArgumentException(`element with id '${mediaElementId}' must be an ${type} element`);}return mediaElement;}", "function detectWMP()\r\n{\r\n\tvar wmpInfo = {\r\n\t\tinstalled: false,\r\n\t\tscriptable: false,\r\n\t\ttype: null,\r\n\t\tversionInfo: null\r\n\t};\r\n\tvar wmp64 = \"MediaPlayer.MediaPlayer.1\";\r\n\tvar wmp7 = \"WMPlayer.OCX.7\";\r\n\tif((window.ActiveXObject && navigator.userAgent.indexOf('Windows') != -1) || window.GeckoActiveXObject)\r\n\t{\r\n\t\twmpInfo.type = \"ActiveX\";\r\n\t\tvar player = createActiveXObject(wmp7);\r\n\t\tif(player)\r\n\t\t{\r\n\t\t\twmpInfo.installed = true;\r\n\t\t\twmpInfo.scriptable = true;\r\n\t\t\twmpInfo.versionInfo = player.versionInfo;\r\n\t\t\treturn wmpInfo;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tplayer = createActiveXObject(wmp64);\r\n\t\t\tif(player)\r\n\t\t\t{\r\n\t\t\t\twmpInfo.installed = true;\r\n\t\t\t\twmpInfo.scriptable = true;\r\n\t\t\t\twmpInfo.versionInfo = \"6.4\";\r\n\t\t\t\treturn wmpInfo;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\twmpInfo.versionInfo = \"none\";\r\n\t\t\t\treturn wmpInfo;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\telse if(navigator.mimeTypes)\r\n\t{\r\n\t\twmpInfo.type = \"NetscapePlugin\";\r\n\t\tnumPlugins = navigator.plugins.length;\r\n\t\tfor (i = 0; i < numPlugins; i++)\r\n\t\t{\r\n\t\tplugin = navigator.plugins[i];\r\n\t\t\tif (plugin.name.substring(0,10)==\"Windows Media Player\")\r\n\t\t\t{\r\n\t\t\t\twmpInfo.installed = true;\r\n\t\t\t\t//wmpInfo.scriptable = false;\r\n\t\t\t\twmpInfo.versionInfo = \"PluginVersion\";\r\n\t\t\t\treturn wmpInfo;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/*if(player)\r\n\t\t{\t\r\n\t\t\t\r\n\t\t\talert(\"if netscape and windows media\");\r\n\t\t\twmpInfo.installed = true;\r\n\t\t\twmpInfo.scriptable = false;\r\n\t\t\twmpInfo.versionInfo = \"PluginVersion\";\r\n\t\t\treturn wmpInfo;\r\n\t\t}*/\r\n\t\treturn wmpInfo;\r\n\t}\r\n\t\r\n\t\r\n}", "function onLoadMediaSearch()\n{\n\t// Check WinAmp API available.\n checkForWinAmpAPI();\n \n\t// Setup stylesheet.\n\tsetupStylesheet();\n\t\n\t// Set focus on input box.\n\t$('#SearchInput')[0].focus();\n}", "function chkMobile() {\r\n\treturn /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);\r\n}", "function potentialMatch(data, query) {\n let title = data.title;\n let number = data.number;\n return title.toLowerCase().indexOf(query) !== -1 || number.indexOf(query) !== -1;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Logic or a register with accumulator
orReg(register) { regA[0] |= register[0]; regF[0] = regA[0] ? 0 : F_ZERO; return 4; }
[ "visitXor_expr(ctx) {\r\n console.log(\"visitXor_expr\");\r\n let length = ctx.getChildCount();\r\n let value = this.visit(ctx.and_expr(0));\r\n for (var i = 1; i * 2 < length; i = i + 1) {\r\n if (ctx.getChild(i * 2 - 1).getText() === \"^\") {\r\n value = {\r\n type: \"BinaryExpression\",\r\n operator: \"^\",\r\n left: value,\r\n right: this.visit(ctx.and_expr(i)),\r\n };\r\n }\r\n }\r\n return value;\r\n }", "function Logical (type, ax, bx) {\n var result = {value: null, // the result of the Logical operation\n diff : 0, // number of bits that are different between ax and bx\n change : 0, // estimate of the number of bits that need to be changed to get to eaither ax or bx from .value\n length : null, // size in terms of the number of bits\n up : 0, // number of bits rounded up\n down : 0, // number of bits rounded down\n type : type}; // type of operation\n if(ax.length != bx.length) {\n var resized = resize(ax, bx);\n ax = resized.ax;\n bx = resized.bx;\n }\n if (ax.length > 1 || bx.length > 1) {\n var msb = Logical(type, [ax[0]], [bx[0]]);\n var rem = Logical(type, ax.slice(1, ax.length), bx.slice(1, bx.length));\n // concatinate the msb with all the remaining bits\n result.value = [].concat(msb.value, rem.value);\n result.diff = msb.diff + rem.diff;\n result.change = msb.change + rem.change;\n result.length = msb.length + rem.length;\n result.up = msb.up + rem.up;\n result.down = msb.down + rem.down;\n return result;\n } \n else {\n if(ax[0] != bx[0] && (ax[0] != null && bx[0] != null)) {\n result.diff = 1;\n }\n switch (type) {\n case \"xor\": // xor means that things are totally different\n if (ax[0] != bx[0]) { \n result.value = (ax[0] == null || bx[0] == null) ? null : (ax[0] == 1 || bx[0] == 1) ? 1 : ax[0] > bx[0] ? ax[0] : bx[0]; // or maybe have the value be whatever value is larger or non zero\n result.length = 1;\n if(ax[0] != null && bx[0] != null){\n result.change = .5; \n result.up = .5; \n }\n return result;\n } \n else { //(ax[0] == bx[0]) - with a corner case of null\n result.value = (ax[0] == null) ? null : 0; // TODO maybe both 0\n result.length = 1;\n if(ax[0] != 0 && ax[0] != null){\n result.down = 1; // TODO: maybe should be a % 3 and 3 for example\n result.change = 1; // both are 1 or both are the same value // maybe should be\n } \n }\n return result;\n break;\n case \"or\": // or means that things are similar or the same (similar to a round up only)\n result.value = (ax[0] == null || bx[0] == null) ? null : (ax[0] == 0 && bx[0] == 0) ? 0 : ax[0] > bx[0] ? ax[0] : bx[0];\n if(result.value != null && result.value != 0){\n result.up = .5; \n result.change = .5; // TODO: check for null case maybe also check for case for result.down where ax or bx > 1 or a non 1 number\n }\n result.length = 1;\n return result;\n break;\n case \"and\": // and means that things are identical (similar to a round down only)\n if (ax[0] == bx[0]) {\n result.value = ax[0];\n result.change = 0;\n result.length = 1;\n return result;\n } \n else {\n result.value = (ax[0] == null || bx[0] == null) ? null : 0; // TODO: add these into the same function\n if(ax[0] != 0 && bx[0] != 0 && ax[0] != null && bx[0] != null){\n result.change = 1; // maybe 2\n result.down = 1; // maybe do a %%\n } else { // one is 1 the other is 0\n if(ax[0] != null && bx[0] != null) {\n result.change = .5;\n result.up = .5; // TODO maybe add the ammount up...\n } \n }\n result.length = 1;\n return result;\n }\n return result; \n break;\n default: // nand\n if(ax[0] == bx[0] && ax[0] != 0) {\n result.value = (ax[0] == null) ? null : 0; \n result.change = (ax[0] == null) ? 0 : 1;\n result.length = 1;\n result.down = (ax[0] == null) ? 0 : 1;\n return result;\n }\n else {\n result.value = (ax[0] == null || bx[0] == null) ? null : (ax[0] == 0 && bx[0] == 0) ? 1 : ax[0] == 0 ? bx[0] : bx[0] == 0 ? ax[0] : ax[0] < bx[0] ? ax[0] : bx[0]; // TODO: sepcial case we do less (maybe change)\n if(ax[0] == 0 && bx[0] == 0) {\n result.change = 1;\n result.up = 1;\n } else {\n if(ax[0] != null && bx[0] != null){\n result.change = .5;\n result.up = .5; // TODO: Check this case maybe do Math.abs()\n }\n return result;\n }\n }\n return result;\n }\n }\n return result;\n}", "function orGate () {\n return {\n id: nextId(),\n type: 'or',\n inputs: [pin(), pin()],\n outputs: Object.seal([pin()])\n }\n}", "EOR() { this.A = this.eqFlags_(this.M ^ this.A); }", "function accumulator(xf) {\n function xformed(source, additional) {\n // Return a new accumulatable object who's accumulate method transforms the `next`\n // accumulating function.\n return accumulatable(function accumulateXform(next, initial) {\n // `next` is the accumulating function we are transforming. \n accumulate(source, function nextSource(accumulated, item) {\n // We are essentially wrapping next with `xf` provided the `item` is\n // not `end`.\n return item === end ? next(accumulated, item) :\n xf(additional, next, accumulated, item);\n }, initial);\n });\n }\n\n return xformed;\n}", "function evaluateOr(assignment){\n var myString = \"\";\n myString += evaluateAnd(assignment); //string\n while (globalMarker < assignment.length && assignment[globalMarker] == \"or\"){\n globalMarker += 1;\n myString += \"||\"\n myString += evaluateAnd(assignment);\n }\n return eval(myString);\n}", "function getSum(a, b) { \n return b == 0 ? a : getSum(a ^ b, (a & b) << 1)\n}", "function i31( x )\n {\n\n let a = x.v[ 0 ] ;\n let b = x.v[ 1 ] ;\n let c = x.v[ 2 ] ;\n\n let r = ( a + b + c )\n\n return( r ) ;\n\n }", "subcReg(register) {\n const sum = regA[0] - register[0] - ((regF[0] & F_CARRY) ? 1 : 0);\n regA[0] = sum;\n\n // TODO: test carry register\n regF[0] = F_OP | (regA[0] ? 0 : F_ZERO) | ((sum < 0) ? F_CARRY : 0);\n if ((regA[0] ^ register[0] ^ sum) & 0x10) regF[0] |= F_HCARRY;\n return 4;\n }", "loadNextInstruction() {\n switch (this.opCode) {\n case 0:\n this.instructionCounter = 0;\n break;\n case 40:\n this.instructionCounter = this.operand;\n break;\n case 41:\n if (this.accumulator < 0) {\n this.instructionCounter = this.operand;\n } else {\n this.instructionCounter++;\n }\n break;\n case 42:\n if (this.accumulator === 0) {\n this.instructionCounter = this.operand;\n } else {\n this.instructionCounter++;\n }\n break;\n default:\n this.instructionCounter++;\n break;\n }\n\n this.instructionRegister = this.memory[this.instructionCounter];\n this.opCode = Number.parseInt(('' + this.instructionRegister).substring(0, 2));\n this.operand = Number.parseInt(('' + this.instructionRegister).substring(2, 4));\n }", "visitUnary_logical_expression(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "addOrExpression() {\n const andExpression = OrExpression.new({\n leftExpression: this.assertionExpression,\n rightExpression: null,\n })\n\n this.assertionExpression = andExpression \n }", "function appendNumberOrOperator(value) {\n resultInput.value += value;\n}", "AND() { this.A = this.eqFlags_(this.M & this.A); }", "function acc(func, initial) {\n \n}", "term() {\n let node = this.factor();\n while (\n this.currentToken.type === tokens.mul ||\n this.currentToken.type === tokens.DIV ||\n this.currentToken.type === tokens.floatDiv\n ) {\n const token = this.currentToken;\n if (token.type === tokens.mul) {\n this.eat(tokens.mul);\n } else if (token.type === tokens.DIV) {\n this.eat(tokens.DIV);\n } else if (token.type === tokens.floatDiv) {\n this.eat(tokens.floatDiv);\n }\n\n node = new BinOp(node, token, this.factor());\n }\n\n return node;\n }", "function andGate () {\n return {\n id: nextId(),\n type: 'and',\n inputs: [pin(), pin()],\n outputs: Object.seal([pin()])\n }\n}", "function func(accumulator, currentValue, currentIndex, sourceArray) {\n return accumulator + currentValue;\n}", "performUserReduction() {\n if (!this._reducing) {\n if (!this.canReduce()) {\n mag.Stage.getAllNodes([this]).forEach((n) => {\n if (n instanceof Expression && n.isPlaceholder()) {\n n.animatePlaceholderStatus();\n }\n });\n return Promise.reject(\"Expression: expression cannot reduce\");\n }\n console.log('r', this.canReduce);\n\n this.animateReducingStatus();\n\n this._reducing = this.performReduction(true);\n this._reducing.then(() => {\n this._reducing = false;\n }, () => {\n this._reducing = false;\n });\n }\n return this._reducing;\n }", "function binaryL(subExpr, stream, a, ops) {\n var lhs = subExpr(stream, a);\n if (lhs == null) return null;\n var op;\n while (op = stream.trypop(ops)) {\n var rhs = subExpr(stream, a);\n if (rhs == null) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': Expected something after ' + op);\n lhs = a.node(op, lhs, rhs);\n }\n return lhs;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
allListings returns the IDs of all the listings currently on the market Once an item is sold, it will not be returned by allListings returns: a promise containing an array of listing IDs
function allListings() { return itemListings.once('value') .then(data => data.val()) .then(itemListings => { let items = Object.keys(itemListings) return items.filter( listingID => itemListings[listingID].forSale === true ) }) }
[ "function getAllBookings() {\n // the URL for the request\n const url = '/bookings';\n // Since this is a GET request, simply call fetch on the URL\n fetch(url)\n .then((res) => {\n if (res.status === 200) {\n // return a promise that resolves with the JSON body\n return res.json();\n } else {\n alert('Could not get bookings');\n }\n })\n .then((json) => { // the resolved promise with the JSON body\n bookingsList = document.querySelector('#allBookingsList');\n bookingsList.innerHTML = '';\n log(json);\n json.bookings.map((b) => {\n addToBookings(b);\n });\n }).catch((error) => {\n log(error);\n });\n}", "function allItemsBought(buyerID) {\n let arrayOfListings = [];\n\n var logElements = (value, key, map) => {\n if (value.buyer == buyerID) {\n arrayOfListings.push(key);\n }\n }\n listing.forEach(logElements);\n return arrayOfListings;\n}", "async function searchForListings(searchTerm) {\n let items = await itemListings.once('value')\n .then(data => data.val())\n // console.log(items)\n return allListings()\n .then(listingIDs => listingIDs.filter(\n listingID => items[listingID].blurb.toLowerCase().includes(searchTerm.toLowerCase())\n ))\n}", "getListing(id, callback) {\n $.ajax({\n type: 'GET',\n url: `/listings${id}`,\n dataType: 'json',\n success: function(data) {\n callback(data);\n },\n error: function(err) {\n console.log('Could not retrieve listing: ', err);\n }\n });\n }", "static async getListing(id) {\n const result = await db.query(\n `SELECT id, host_username, title, description, price\n FROM listings\n WHERE id = $1`, \n [id]\n );\n let listing = result.rows[0];\n return listing;\n }", "async getSignedAgentForListing(listing_id) {\n let listings = await this.getListingsWithId(listing_id);\n let listing = listings[0];\n //console.log(listing);\n if(listing.listing_status != 'Signed') {\n console.log(`dbAccess getAgentForListing: the named listing with id ${listing_id} is not signed, which means there is no agent to return.`);\n return [];\n }\n\n let query = 'SELECT DISTINCT users.first_name, users.last_name, users.display_name, users.email, agents.id, agents.title, agents.phone, agents.web_site from (((agents inner join bids on agents.id = bids.agent_id AND bids.bid_status=\"Signed\") INNER JOIN listings ON bids.listing_id = ?) INNER JOIN users on users.agent_id = agents.id)';\n let args = [listing_id];\n const rows = await this.connection.query(query, args);\n return rows;\n }", "findBookingsByListing(listingId, status) {\n return new Promise((resolve, reject) => {\n //console.log(\"SERVICE err: \" + err); \n Booking.findBookingByListingId(listingId, status, (err, res) => {\n //console.log(\"SERVICE err: \" + err);\n if (err) {\n reject(err);\n } else {\n resolve(res);\n }\n });\n });\n }", "function showBookings() {\n var localBookings = loadLocalBookings();\n if (localBookings.length > 0) {\n localBookings.forEach(function (booking) {\n $(\"#bookingList\").append($(\"<li>\").text(booking.name + ': ' + booking.number + ' from ' + booking.checkin + ' to ' + booking.checkout));\n });\n $(\"#currentBookings\").show();\n } else {\n $(\"#currentBookings\").hide();\n }\n }", "async function buy(buyerID, listingID) {\n let sellerID = await itemListings.once('value').then(data => data.val())\n .then(items => items[listingID].sellerID)\n\n return Promise.all([\n itemsBought.child(buyerID).child(listingID).set(true),\n itemsSold.child(sellerID).child(listingID).set(true),\n itemListings.child(listingID).child('forSale').set(false)\n ])\n}", "one(id) {\n return fetch(`${BASE_URL}/listings/${id}`, {\n credentials: \"include\"\n }).then(res => res.json());\n }", "function loadLocalBookings() {\n if (Cookie.get(\"bookings\")) {\n return JSON.parse(Cookie.get(\"bookings\"));\n } else {\n return [];\n }\n }", "function show(req, res){\n Listing.findById(req.params.id).populate('listing'){\n if(err) return console.log(err)\n res.json(listing)\n }\n }", "function allItemsSold(sellerID) {\n return itemsSold.child(sellerID).once('value')\n .then(data => data.val())\n .then(items => Object.keys(items))\n .catch(err => [])\n}", "async listAll() {\n\t\tlet searchParams = this.type ? { type: this.type } : {};\n\t\tlet records = await StockModel\n\t\t\t.find(searchParams)\n\t\t\t.select({ 'name': 1, 'latest': 1, '_id': 0, 'type': 1 })\n\t\t\t.sort({ 'type': 'asc', 'latest': 'desc' });\n\t\treturn { 'status': 200, records };\n\t}", "function setListings (listings, date) {\n\t\t// has settings changed?\n\t\tvar listingsObj = {};\n\t\tlistingsObj[date] = listings;\n\t\t// Check if listing's date has been stored\n\t\treturn this.listings = listingsObj;\n\t}", "getAllLists(req, res, next) {\n listsHelper.getAllLists(req.reqId).then((lists) => {\n res.json({\n success: 1,\n message: responseMessages.listsFetched.success,\n data: lists,\n });\n }).catch((error) => {\n next(error);\n });\n }", "function Listing() {\n this.feeds = {}; \n this.sortIDs = {};\n this.folders = {};\n this.max = 1000;\n this.openFolders = {};\n this.scroll = false;\n this.show = 'all';\n this.init = true;\n}", "async function getNeededDailyCrafting(apikey) {\n\tlet hasCrafted = await getDailyCrafted(apikey);\n\tlet needCrafting = [];\n\t\n\tObject.keys(DAILY_CRAFTING_ITEMS).forEach(item => {\n\t\tif (!hasCrafted.includes(item)) {\n\t\t\tneedCrafting.push(DAILY_CRAFTING_ITEMS[item]);\n\t\t}\n\t});\n\t\n\treturn needCrafting;\n}", "function itemsToSell(userID) {\n let itemsToSell = [];\n var logElements = (value, key, map) => {\n if (!value.buyer && userID === value.seller) {\n itemsToSell.push(key);\n }\n }\n listing.forEach(logElements);\n // console.log(listing, availableItems)\n return itemsToSell;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add to notes when "Enter" is pressed
onKeyPressHandler(event) { if(event.key === "Enter") { this.addToNotes(); } }
[ "keyPress(e) {\n // If enter or tab key pressed on new notebook input\n if (e.keyCode === 13 || e.keyCode === 9) {\n this.addNotebook(e);\n }\n }", "function enterobs(e){\n if(e.which == 13 && !e.shiftKey){\n $('#pubob').click();\n e.preventDefault();\n }\n}", "function addToListOnEnter(e) {\r\n\tif (inputLength() > 0 && e.keyCode === 13) {\r\n\t\tadd_to_list({ id: items.length, name: input.value.trim(), bought: false });\r\n\t}\r\n}", "function onTarefaKeydown(event) {\n if(event.which === 13) {\n addTarefa($(\"#tarefa\").val());\n $(\"#tarefa\").val(\"\");\n }\n }", "function pressKey(event) {\n if (event.which == 13) {\n bot();\n questionNum++\t\t\t\t\t\t\t\t\t\t\t\t\t// increase questionNum count by 1\n }\n}", "function addNote(e) {\n let addTxt = document.getElementById(\"addTxt\");\n let addTitle = document.getElementById(\"addTitle\");\n let notes = localStorage.getItem(\"notes\");\n if (notes == null) {\n notesObject = [];\n } else {\n notesObject = JSON.parse(notes);\n }\n let myObj = {\n title: addTitle.value,\n text: addTxt.value\n }\n notesObject.push(myObj);\n localStorage.setItem(\"notes\", JSON.stringify(notesObject));\n addTxt.value = \"\";\n addTitle.value = \"\";\n showNotes();\n}", "function clickonnote(){\r\n\t\t$(\".noteheader\").click(function(){\r\n\t\t\tif(!editMode){\r\n\t\t\t\t//update activenote variable to id of note\r\n\t\t\t\tactivenote = $(this).attr(\"id\");\r\n\t\t\t\t// fill text area\r\n\r\n\t\t\t\t$(\"textarea\").val($(this).find(\".text\").text());\r\n\t\t\t\tshowHide([\"#notepad\",\"#allnotes\"], [\"#notes\" , \"#addnotes\",\"#edit\" , '#done']);\r\n\t\t\t\t$(\"textarea\").focus();\r\n\t\t\t}\r\n\t\t});\r\n\t}", "function htmlHelper(){\n\t$(\"#postcontent\").keypress(function(e) {\n if(e.which == 13) {\n var currentHTML = document.getElementById(\"postcontent\").value;\n var currentHTML = currentHTML + \"\\n<br /><br />\"\n document.getElementById(\"postcontent\").value = currentHTML;\n }\n});\n}", "function updChatroomMsgEnter(state){\n $('.messages').on('keypress','#text', function (e) {\n var key = e.which;\n if(key === 13) // the enter key code\n {\n event.preventDefault();\n setUpdatedMessages(state,$('#text').val(),$('.conversation'));\n $('#text').val('');\n }\n });\n}", "function clearInput() {\n\tif (e.key === 'Enter' && todoInput.value.length > 0) {\n\t\t// When there is a keypress, it will run this function which will create a new list\n\t\t// The function will grab the value of the text entered\n\t\tcreateNewTodoItem(todoInput.value);\n\t}\n}", "function submitOnEnter(event){\n\tif (event.keyCode == 13 && !event.shiftKey) {\n\t\tevent.preventDefault();\n\t\tnewMessage();\n\t}\n}", "function updTitleEnter(state){\n $('.delete_update').on('keypress', '#updateTitle', function (e) {\n var key = e.which;\n if(key === 13) // the enter key code\n {\n event.preventDefault();\n setTitleValue(state,$('#updateTitle'),$('.delete_update'));\n $('#updateTitle').val('');\n }\n });\n}", "function renameEnter(self) {\n\tif (window.event.keyCode == 13) { // 13 = enter key\n\t renameBlurred(self);\n\t}\n }", "function onAddLine() {\n addLine()\n document.querySelector('[name=\"text\"]').value = 'TYPE SOMETHING'\n renderMeme()\n}", "function addOnKeyPressedListener(interpreter) {\n $(document).keypress(function(event){\n if (interpreter.keyPressedListenerActive) {\n event.preventDefault();\n if (event.keyCode == ENTER_KEY_CODE) {\n interpreter.keyPressedListenerActive = false;\n return;\n }\n // alert(String.fromCharCode(event.which));\n interpreter.commands = interpreter.commands + String.fromCharCode(event.which);\n interpreter.nextCommand(RunningMethodEnum.VISUALIZE);\n }\n });\n}", "function showModal(modal) {\n modal.style.display = \"inline-block\";\n window.onkeypress = function(event) {\n if (event.keyCode == 13) {\n event.preventDefault();\n console.log(modal);\n if (modal == signInModal) {\n getInputForSignIn();\n } else if (modal == createAccountModal) {\n getInputForNewUser();\n }\n }\n }\n}", "function updCatEnter(state){\n $('.delete_update').on('keypress', '#updateCat', function (e) {\n var key = e.which;\n if(key === 13) // the enter key code\n {\n event.preventDefault();\n setCatValue(state,$('#updateCat'),$('.delete_update'));\n $('#updateCat').val('');\n }\n });\n}", "function VerificarEnter(evt) {\r\n var charCode=(evt.which)?evt.which:evt.keyCode\r\n if(charCode==13){\r\n return false;\r\n }\r\n return true;\r\n }", "function journalEntry() {\r\n let journalEntry = prompt(` Okay ${userName} , Reflect on why you chose what you did. Describe how that rating makes you feel,why you chose that, how it makes you feel to have that rating, and plans for the upcoming days either change it or keep it the same! Please press the button under PRESS Here to log your answer !`, \" Please press the button under PRESS HERE after completing this entry!\");\r\n console.log(` You journal entry was: ${journalEntry}`);\r\n return journalEntry;\r\n // Enter in as much text as necessary about what you learned, how you felt, and plans for the upcoming days\r\n\r\n // what do I do with what I have here, \r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DrawOrbs function with assigned properties by using the word "this." and the variable following afterwards.
function DrawOrbs() { this.x = random(0, width); this.y = random(0, height); this.display = function() { // Prefered to use a stroke instead of a fill here since there is enough noise with both the moving orbs and the mouse. fill(random(400), random(300), 190); noStroke(); push(); translate(this.x, this.y); sphere(20, 10, 10); pop(); } // Again incorporating the use of assigned properties to make the orbs move back and forth and cling to each other. This creates the appearance of them spinning out of control for its x and y axis. this.move = function() { this.x = this.x + random(-10, 10); this.y = this.y + random(-5, 5); } /* end sketch: Particles */ }
[ "draw(){\n\n for(let i=0; i<this.belt.length;i++){\n this.belt[i].draw();\n }\n }", "display() {\n //set the color\n stroke(this.element*255) ;\n //draw the point\n point(this.identity.x,this.identity.y)\n }", "drawNote() {\n push();\n colorMode(HSB, 360, 100, 100);\n stroke(this.color, 100, 100, 100);\n fill(this.color, 100, 100, 100);\n let v = this;\n let v2 = createVector(v.x + 5, v.y - 15);\n circle(v.x, v.y, 7);\n strokeWeight(3);\n line(v.x + 3, v.y, v2.x, v2.y);\n quad(v2.x, v2.y, v2.x + 5, v2.y + 2, v2.x + 6, v2.y, v2.x, v2.y - 2);\n pop();\n }", "function createDoorInView(object){\n \n var door = new Path.Rectangle({\n topLeft: [object.initialPoint.x*ratio, object.initialPoint.y*ratio],\n bottomRight: [object.finalPoint.x*ratio, object.finalPoint.y*ratio],\n strokeColor: 'red',\n fillColor: 'red'\n });\n\n return door; \n}", "function Area(theX0, theY0, theX1, theY1, theColor, theBase, theTooltipText, theOnClickAction, theOnMouseoverAction, theOnMouseoutAction)\n{ this.ID=\"Area\"+_N_Area; _N_Area++; _zIndex++;\n this.X0=theX0;\n this.Y0=theY0;\n this.X1=theX1;\n this.Y1=theY1;\n this.Color=theColor;\n this.Base=theBase;\n this.Cursor=_cursor(theOnClickAction);\n this.SetVisibility=_SetVisibility;\n this.SetColor=_SetColor;\n this.SetTitle=_SetTitle;\n this.MoveTo=_MoveTo;\n this.ResizeTo=_AreaResizeTo;\n this.Delete=_Delete;\n this.EventActions=\"\";\n if (_nvl(theOnClickAction,\"\")!=\"\") this.EventActions+=\"onClick='\"+_nvl(theOnClickAction,\"\")+\"' \";\n if (_nvl(theOnMouseoverAction,\"\")!=\"\") this.EventActions+=\"onMouseover='\"+_nvl(theOnMouseoverAction,\"\")+\"' \";\n if (_nvl(theOnMouseoutAction,\"\")!=\"\") this.EventActions+=\"onMouseout='\"+_nvl(theOnMouseoutAction,\"\")+\"' \";\n var dd, ll, rr, tt, bb, ww, hh;\n if (theX0<=theX1) { ll=theX0; rr=theX1; }\n else { ll=theX1; rr=theX0; }\n if (theY0<=theY1) { tt=theY0; bb=theY1; }\n else { tt=theY1; bb=theY0; }\n ww=rr-ll; hh=bb-tt;\n if (theBase<=tt)\n _DiagramTarget.document.write(\"<div id='\"+this.ID+\"' style='position:absolute;left:\"+ll+\"px;top:\"+theBase+\"px; width:\"+ww+\"px; height:\"+hh+\"px; z-index:\"+_zIndex+\"; font-size:1pt; line-height:1pt;' title='\"+_nvl(theTooltipText,\"\")+\"'>\");\n else\n _DiagramTarget.document.write(\"<div id='\"+this.ID+\"' style='position:absolute;left:\"+ll+\"px;top:\"+tt+\"px; width:\"+ww+\"px; height:\"+Math.max(hh, theBase-tt)+\"px; z-index:\"+_zIndex+\"; font-size:1pt; line-height:1pt;' title='\"+_nvl(theTooltipText,\"\")+\"'>\");\n if (theBase<=tt)\n { if ((theBase<tt)&&(ww>0))\n _DiagramTarget.document.write(\"<div \"+this.EventActions+\"style='\"+_cursor(theOnClickAction)+\"position:absolute;left:0px;top:0px;font-size:1pt;line-height:1pt;'><img src='o_\"+theColor+\".gif' width=\"+ww+\"px height=\"+eval(tt-theBase)+\"px style='vertical-align:bottom'></div>\");\n if (((theY0<theY1)&&(theX0<theX1))||((theY0>theY1)&&(theX0>theX1)))\n _DiagramTarget.document.write(\"<div \"+this.EventActions+\"style='\"+_cursor(theOnClickAction)+\"position:absolute;left:0px;top:\"+eval(tt-theBase)+\"px;font-size:1pt;line-height:1pt;'><img src='q_\"+theColor+\".gif' width=\"+ww+\"px height=\"+hh+\"px style='vertical-align:bottom'></div>\");\n if (((theY0>theY1)&&(theX0<theX1))||((theY0<theY1)&&(theX0>theX1)))\n _DiagramTarget.document.write(\"<div \"+this.EventActions+\"style='\"+_cursor(theOnClickAction)+\"position:absolute;left:0px;top:\"+eval(tt-theBase)+\"px;font-size:1pt;line-height:1pt;'><img src='p_\"+theColor+\".gif' width=\"+ww+\"px height=\"+hh+\"px style='vertical-align:bottom'></div>\");\n }\n if ((theBase>tt)&&(theBase<bb))\n { dd=Math.round((theBase-tt)/hh*ww);\n if (((theY0<theY1)&&(theX0<theX1))||((theY0>theY1)&&(theX0>theX1)))\n { _DiagramTarget.document.write(\"<div \"+this.EventActions+\"style='\"+_cursor(theOnClickAction)+\"position:absolute;left:0px;top:0px;font-size:1pt;line-height:1pt;'><img src='b_\"+theColor+\".gif' width=\"+dd+\"px height=\"+eval(theBase-tt)+\"px style='vertical-align:bottom'></div>\");\n _DiagramTarget.document.write(\"<div \"+this.EventActions+\"style='\"+_cursor(theOnClickAction)+\"position:absolute;left:\"+dd+\"px;top:\"+eval(theBase-tt)+\"px;font-size:1pt;line-height:1pt;'><img src='q_\"+theColor+\".gif' width=\"+eval(ww-dd)+\"px height=\"+eval(bb-theBase)+\"px style='vertical-align:bottom'></div>\");\n }\n if (((theY0>theY1)&&(theX0<theX1))||((theY0<theY1)&&(theX0>theX1)))\n { _DiagramTarget.document.write(\"<div \"+this.EventActions+\"style='\"+_cursor(theOnClickAction)+\"position:absolute;left:0px;top:\"+eval(theBase-tt)+\"px;font-size:1pt;line-height:1pt;'><img src='p_\"+theColor+\".gif' width=\"+eval(ww-dd)+\"px height=\"+eval(bb-theBase)+\"px style='vertical-align:bottom'></div>\");\n _DiagramTarget.document.write(\"<div \"+this.EventActions+\"style='\"+_cursor(theOnClickAction)+\"position:absolute;left:\"+eval(ww-dd)+\"px;top:0px;font-size:1pt;line-height:1pt;'><img src='d_\"+theColor+\".gif' width=\"+dd+\"px height=\"+eval(theBase-tt)+\"px style='vertical-align:bottom'></div>\");\n }\n }\n if (theBase>=bb)\n { if ((theBase>bb)&&(ww>0))\n _DiagramTarget.document.write(\"<div \"+this.EventActions+\"style='\"+_cursor(theOnClickAction)+\"position:absolute;left:0px;top:\"+hh+\"px;font-size:1pt;line-height:1pt;'><img src='o_\"+theColor+\".gif' width=\"+ww+\"px height=\"+eval(theBase-bb)+\"px style='vertical-align:bottom'></div>\");\n if (((theY0<theY1)&&(theX0<theX1))||((theY0>theY1)&&(theX0>theX1)))\n _DiagramTarget.document.write(\"<div \"+this.EventActions+\"style='\"+_cursor(theOnClickAction)+\"position:absolute;left:0px;top:0px;font-size:1pt;line-height:1pt;'><img src='b_\"+theColor+\".gif' width=\"+ww+\"px height=\"+hh+\"px style='vertical-align:bottom'></div>\");\n if (((theY0>theY1)&&(theX0<theX1))||((theY0<theY1)&&(theX0>theX1)))\n _DiagramTarget.document.write(\"<div \"+this.EventActions+\"style='\"+_cursor(theOnClickAction)+\"position:absolute;left:0px;top:0px;font-size:1pt;line-height:1pt;'><img src='d_\"+theColor+\".gif' width=\"+ww+\"px height=\"+hh+\"px style='vertical-align:bottom'></div>\");\n }\n _DiagramTarget.document.writeln(\"</div>\");\n}", "fields() {\n // sets \"this.current\" to fields\n this.current = \"fields\";\n // draws the grass\n background(104, 227, 64);\n \n // draws a path\n this.path(width/2, 0);\n \n // draws a pile of rocks or a well\n if (this.well) {\n this.makeWell();\n } else {\n this.rocks();\n }\n\n // this draws a flower patch\n for (let i = 0; i < 200; i += 25) {\n for (let j = 0; j < 100; j += 20) {\n this.flower(i + 100, j + 450);\n }\n }\n }", "draw() {\r\n context.strokeStyle = \"#fafafa\";\r\n context.fillStyle = \"#10e831\";\r\n if (this.status == \"infected\") context.fillStyle = \"#e60202\";\r\n context.beginPath();\r\n // Calls the 'arc' method and inputs the x and y coordinates, radius, 0 and PI*2 = 360 degrees\r\n context.arc(this.x,this.y,this.r,0,Math.PI*2);\r\n // Calls the 'fill' method\r\n context.fill();\r\n // Calls the 'stroke' method\r\n context.stroke();\r\n }", "function drawResults(obj) {\n\n //Clear the contents of contentsWrapper\n contentsWrapper.innerHTML = '';\n\n //If the object from our lookup exists, write out its properties\n if(obj) {\n for(var prop in obj) {\n if(obj.hasOwnProperty(prop)) {\n contentsWrapper.appendChild(createElementEditor(prop, obj));\n }\n }\n //Add an additional horizontal line\n contentsWrapper.appendChild($.create('hr'));\n }\n\n //Add the property adder elements\n contentsWrapper.appendChild(createElementAdder()); \n}", "function Rectangulo(x, y, ancho, alto)\n{\n\n this.x = x;\n this.y = y;\n this.ancho = ancho;\n this.alto = alto;\n\n}", "makeThenRenderAGObject(obj_type, obj_left, obj_top) {\n let obj_buffer;\n let obj_buffer_ID;\n switch (obj_type) {\n case 'enemy':\n obj_buffer = new AGObject(\"AGgegner\", new Vector3((obj_left / this._scale), 1, (obj_top / this._scale)), new Vector3(1, 0, 0), new Vector3(1, 1, 1));\n obj_buffer_ID = getIdByReference(obj_buffer);\n getReferenceById(obj_buffer_ID).tag = \"ENEMY\";\n getReferenceById(obj_buffer_ID).setSpeedSkalar(0);\n break;\n case 'wall':\n obj_buffer = new AGObject(\"Structure\", new Vector3((obj_left / this._scale), 1.0, (obj_top / this._scale)), new Vector3(1, 0, 0), new Vector3(1, 1, 1));\n obj_buffer_ID = getIdByReference(obj_buffer);\n getReferenceById(obj_buffer_ID).tag = \"WALL\";\n break;\n case 'portal':\n obj_buffer = new AGPortal(\"Portal\", new Vector3((obj_left / this._scale), 1.0, (obj_top / this._scale)), new Vector3(1, 0, 0), new Vector3(1, 1, 1));\n obj_buffer_ID = getIdByReference(obj_buffer);\n break;\n case 'exit':\n obj_buffer = new AGRoomExit(\"Exit\", new Vector3((obj_left / this._scale), 1.0, (obj_top / this._scale)), new Vector3(1, 0, 0), new Vector3(1, 1, 1));\n obj_buffer_ID = getIdByReference(obj_buffer);\n break;\n case 'generic':\n obj_buffer = new AGObject(\"Generic\", new Vector3((obj_left / this._scale), 1.0, (obj_top / this._scale)), new Vector3(1, 0, 0), new Vector3(1, 1, 1));\n obj_buffer_ID = getIdByReference(obj_buffer);\n getReferenceById(obj_buffer_ID).collidable = false;\n getReferenceById(obj_buffer_ID).tag = \"GENERIC\";\n }\n getReferenceById(this._AGroomID).add(obj_buffer_ID);\n this.renderAGObject(obj_buffer_ID);\n\n this.refreshObjectSelect();\n this.listItems();\n this.listConditions();\n\n return obj_buffer_ID;\n }", "function drawDoor() {\n //grey color\n penRGB(170, 170, 170, 1);\n penWidth(4);\n //starts where it ended after it drew the roof, so moves to where the door where will be located\n moveToDoorLocation();\n //the curve on the door\n moveForward(15);\n arcLeft(180, 5);\n moveForward(15);\n}", "function drawCenterOrb (r, fill, stroke, strokeWidth, teamTitle, strokeOpacity){\n\t\tvar role = paper.circle(centerX, centerY, r).animate({fill: fill, stroke: stroke, \"stroke-width\": strokeWidth, \"stroke-opacity\": strokeOpacity}, 1000);\n\t\t// add text to orb\n\t\tvar tt = paper.text(centerX, centerY, teamTitle);\n\t\ttt.attr({ \"font-size\": (baseSize * 2.2), \"font-family\": \"BebasNeue, Arial, Helvetica, sans-serif\", \"fill\" : \"#24201f\", \"width\" : (baseSize * 3) });\n\t}", "function drawVerticalDoors() {\n fill(360, 360, 360);\n door1 = new VerticalDoor(width / 4, 0);\n door2 = new VerticalDoor(width / 2, 0);\n door3 = new VerticalDoor((width * 3) / 4, 0);\n\n door4 = new VerticalDoor(width / 4 - 20, 1);\n door5 = new VerticalDoor(width / 2 - 30, 1);\n door6 = new VerticalDoor((width * 3) / 4 + 50, 1);\n\n door7 = new VerticalDoor(width / 4, 2);\n door8 = new VerticalDoor(width / 2, 2);\n door9 = new VerticalDoor((width * 3) / 4, 2);\n\n door10 = new VerticalDoor(width / 4 - 30, 3);\n door11 = new VerticalDoor(width / 2 + 50, 3);\n door12 = new VerticalDoor((width * 3) / 4 + 20, 3);\n\n door13 = new VerticalDoor(width / 4 + 20, 4);\n door14 = new VerticalDoor(width / 2, 4);\n door15 = new VerticalDoor((width * 3) / 4 + 30, 4);\n\n door16 = new VerticalDoor(width / 4 - 30, 5);\n door17 = new VerticalDoor(width / 2, 5);\n door18 = new VerticalDoor((width * 3) / 4, 5);\n\n door19 = new VerticalDoor(width / 4, 6);\n door20 = new VerticalDoor(width / 2, 6);\n door21 = new VerticalDoor((width * 3) / 4, 6);\n\n verticalDoorList.push(door1);\n verticalDoorList.push(door2);\n verticalDoorList.push(door3);\n verticalDoorList.push(door4);\n verticalDoorList.push(door5);\n verticalDoorList.push(door6);\n verticalDoorList.push(door7);\n verticalDoorList.push(door8);\n verticalDoorList.push(door9);\n verticalDoorList.push(door10);\n verticalDoorList.push(door11);\n verticalDoorList.push(door12);\n verticalDoorList.push(door13);\n verticalDoorList.push(door14);\n verticalDoorList.push(door15);\n verticalDoorList.push(door16);\n verticalDoorList.push(door17);\n verticalDoorList.push(door18);\n verticalDoorList.push(door19);\n verticalDoorList.push(door20);\n verticalDoorList.push(door21);\n}", "function draw_s() {\n ctx.beginPath()\n canvas_arrow(ctx, passthroughCoords.x - 2, passthroughCoords.y - 2, refractedCoords.x + 2, refractedCoords.y + 2)\n ctx.stroke()\n }", "function Rectangulo() {\n this.ancho=0;\n this.alto=0;\n \n this.setAncho=function(ancho) {\n this.ancho=ancho;\n }\n \n this.setAlto=function(alto) {\n this.alto=alto;\n } \n \n this.getArea=function() {\n return this.ancho * this.alto;\n }\n}", "function drawRectParams() {\n new_shape = new Rectangle(startX, startY, currentX, currentY, getColor());\n drawRectShape(new_shape)\n}", "makeWell() {\n stroke(116, 122, 117);\n strokeWeight(2);\n fill(147, 153, 148);\n ellipse(125, 75, this.pxl, this.pxl);\n fill(0, 0, 255);\n ellipse(125, 75, this.pxl - 10, this.pxl - 10);\n }", "drawLobbyView() {\n this.drawState();\n\n this.ctx.font = '20px Arial';\n this.ctx.fillStyle = '#FFF';\n this.ctx.textAlign = 'center';\n this.ctx.fillText('Waiting on another player...', this.canvas.width / 2,\n this.canvas.height / 2 - 60);\n this.ctx.fillStyle = '#000';\n }", "draw() {\n\t\tthis.components.forEach( component => component.draw() );\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Invokes numerization for all available TracklistNodes (usually one of such).
function numerize() { for(trackListNode of getTracklistNodes()) numerizeTracklist(trackListNode) }
[ "function numerizeTracklist(trackListNode) {\n currentlyModifyingAnyTracklist = true\n\n let songNumber = 0\n for(songNode of trackListNode.children) {\n let iconNode = getIconNode(songNode)\n if(iconNode === null) continue // = IconNode not found. Shouldn't happen.\n\n songNumber++\n\n if(hasClass(iconNode, 'spoticon-track-16')) { // = Not numerized yet\n iconNode.classList = '' // Removes icon class (.spoticon-track-16)\n iconNode.innerHTML = NUMBER_FORMAT.replace('%num%', songNumber)\n }\n\n }\n\n currentlyModifyingAnyTracklist = false\n}", "function attachListenersAndNumerizeDocument() {\n waitForTracklist(() => { // At least one tracklist loaded\n numerize()\n attachTracklistModificationListeners(numerize)\n })\n}", "function harvest(){\n nutrients += nutrientsPerClick;\n updateLabels();\n}", "function getTracklistNodes() {\n return document.querySelectorAll('.tracklist')\n}", "function addNodeCountsToTree() {\n\t'use strict';\n\t// Iterate through all the queue nodes.\n\t$('#exploreList').children('ul').children('li').each(function() {\n\t\tvar queueId = $(this).attr('id');\n\t\t// Set that to this so we can use it in the callback.\n\t\tvar that = this;\n\t\t$.get(\n\t\t\tstarexecRoot + 'services/cluster/queues/details/nodeCount/' + queueId,\n\t\t\t'',\n\t\t\tfunction(numberOfNodes) {\n\t\t\t\tlog('numberOfNodes: ' + numberOfNodes);\n\t\t\t\t// Insert the node count span inside the node list.\n\t\t\t\t$(that)\n\t\t\t\t.prepend('<span class=\"nodeCount\">(' + numberOfNodes + ')</span>');\n\t\t\t},\n\t\t\t'json'\n\t\t);\n\t});\n}", "function _processNodesCnt() {\n if (firstCntFlag) {\n _processNodesGlobalCnt();\n firstCntFlag = false;\n }\n\n const {nodeMap} = processedGraph;\n Object.keys(nodeMap).forEach((id) => {\n if (isNaN(id)) return;\n const node = nodeMap[id];\n const iterator = node.scope.split(SCOPE_SEPARATOR);\n\n if (!node.parent) return;\n do {\n const name = iterator.join(SCOPE_SEPARATOR);\n const scopeNode = nodeMap[name];\n if (_checkShardMethod(node.parallel_shard)) {\n if (scopeNode.specialNodesCnt.hasOwnProperty('hasStrategy')) {\n scopeNode.specialNodesCnt['hasStrategy']++;\n } else {\n scopeNode.specialNodesCnt['hasStrategy'] = 1;\n }\n }\n if (node.instance_type !== undefined) {\n if (scopeNode.specialNodesCnt.hasOwnProperty(node.instance_type)) {\n scopeNode.specialNodesCnt[node.instance_type]++;\n } else {\n scopeNode.specialNodesCnt[node.instance_type] = 1;\n }\n }\n iterator.pop();\n } while (iterator.length);\n });\n}", "function updateNumbers() {\n // look how I loop through all tiles\n tileSprites.forEach(function (item) {\n // retrieving the proper value to show\n var value = fieldArray[item.pos];\n // showing the value\n item.getChildAt(0).text = value;\n // tinting the tile\n item.tint = colors[value]\n });\n }", "function display_All()\n{\n\t\t\ti = 0;\n\t\t\twhile (i < trueNodeids.length) {\n\t\t\t\tconsole.log(trueNodeids[i].id);\n\t\t\t\ti++;\n\t\t\t}\n}", "checkTicks() { // CHECK\n for(var prop in this.connected_routers_list) {\n //update when shutdown\n if (this.recieved_list[this.tick][prop] == undefined && this.recieved_list[this.tick-1][prop] == undefined) {\n this.setCostInfinite(prop);\n }\n\n //update when a router from shut-down to start\n if (this.recieved_list[this.tick][prop] != undefined) {\n this.connected_routers_list[prop] = 1;\n if (this.connected_routers_list[prop] == Number.MAX_VALUE) {\n this.connected_routers_list[prop] = x.routers[prop].connected_routers_list[this.id];\n }\n }\n } \n }", "function updateNumbering(){\n var counter = 1;\n var sortedIDs = $('#sortable_rf').sortable('toArray');\n for(var i = 0; i<sortedIDs.length; i++){\n var question = sortedIDs[i];\n if(question != \"newquestion\" && question != \"newlayout\" && question != \"\") {\n var title = $(\"#\"+question).find(\".question_headline\").find(\"b\").html();\n var number = title.substr(0, title.indexOf('.'));\n number = parseInt(number);\n if(!isNaN(number)){\n var newTitle = counter + \".\" + title.substr(title.indexOf('.')+1);\n counter++;\n $(\"#\"+question).find(\".question_headline\").find(\"b\").html(newTitle);\n }\n }\n }\n}", "function onCheckboxUnitNumbersClicked(e) {\n\tDisplayCanvas.drawUnitNumbers = ViewController.checkboxUnitNumbers.checked;\n}", "function showNumbersOfallCoupons() {\n for(var i = 0 ; i < selectedElementIs.allNumbersOfCoupons.length ; i++) {\n selectedElementIs.allNumbersOfCoupons[i].classList.remove('hide');\n } \n }", "function increaseVertexCount() {\n let vertexCount = retrieveVertexCount();\n if (vertexCount < 100) {\n ++vertexCount;\n document.getElementById(\"vertices\").value = vertexCount.toString();\n document.getElementById(\"vertices\").dispatchEvent(new Event(\"change\"));\n }\n}", "function showNewNumbers(certainRoutine) {\n if (certainRoutine.DOMR.selected) {\n certainRoutine.indicatorDOMR.innerHTML = certainRoutine.moneyR;\n };\n}", "function increaseStepCount() {\n lx.stepCount++;\n }", "_processNodes(){\n this.shadowRoot\n .querySelector('slot')\n .assignedNodes()\n .forEach((n) => this._processNode(n));\n }", "function startAllNeko(allNekos) {\n allNekos.forEach(neko => {\n if (neko.id <= playerlvl) {\n neko.startTimer();\n }\n })\n for (let i = 0; i < playerlvl; i++) {\n showGottenCats(i);\n }\n showNekoToBuy();\n }", "forEachNode(callback) {\n for (const element in this.graph) {\n callback(element)\n }\n }", "addNodes(layerIndex, numNodesAdded = 1) {\n const jsonLayerIndex = Object.keys(this.layers)[layerIndex];\n this.layers[jsonLayerIndex].neurons += numNodesAdded;\n console.log(this.layers);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call the server to update the map for an array of tiles
function forceUpdateTiles(tiles) { if (! (tiles instanceof Array)) { tiles = new Array(tiles); } ajaxGet({ url: "http://192.241.227.45/api/mapdata/"+join(tiles), requestDetails: tiles, success: receiveMapData }); }
[ "function updateMap(data, canvas) {\n\t//TODO\n}", "rescaleTiles() {}", "function updateOSMTiles(request) {\n if (request === undefined) {\n request = {};\n }\n\n if (!m_zoom) {\n m_zoom = m_this.map().zoom();\n }\n\n if (!m_lastVisibleZoom) {\n m_lastVisibleZoom = m_zoom;\n }\n\n /// Add tiles that are currently visible\n m_this._addTiles(request);\n\n /// Update the zoom\n if (m_lastVisibleZoom !== m_zoom) {\n m_lastVisibleZoom = m_zoom;\n }\n\n m_this.updateTime().modified();\n }", "function reloadMap() {\n map.invalidateSize();\n}", "renderTiles() {\n for (const [key, value] of config.tiles.entries()) {\n for (const tile of value) {\n const tileToAdd = new _tile.TileSprite({\n game: this.game,\n location: { x: tile.x, y: tile.y },\n scale: tile.scale,\n tileName: tile.tileName\n });\n this.game.layerManager.layers.get('environmentLayer').add(tileToAdd);\n }\n }\n }", "reload(newData) {\n this.mapData = newData;\n console.log('New Dataset: ', this.mapData);\n console.log('Reloading the map using a new dataset');\n this.render();\n }", "function displayPageTiles(e){\n\t$.ajax({\n\t\turl: pageEditorScript,\n\t\tdata: {getPageTiles:\"true\",pageName:pageNameSelect.val()},\n\t\tsuccess: success,\n\t\tdataType: 'json'\n\t});\n\tfunction success(data){\n\t\t// Remove prevously existing editable tiles before new ones are added\n\t\t$(document).find($(pageEditorTileContainer).remove());\n\t\t\n\t\tvar i = 0;\n\t\tvar tile = pageEditorDOM[2];\n\t\tconsole.log(data);\n\t\t\n\t\tfor(i=0; i<data.length;i++){\n\t\t\t$(tile).attr(\"id\",data[i].id);\n\t\t\t$(tile).find(\".idInput\").val(data[i].id);\n\t\t\t$(tile).find(\".categoryInput\").val(data[i].category);\n\t\t\t$(tile).find(\".pageNameInput\").val(data[i].pageName);\n\t\t\t$(tile).find(\".tileLayoutInput\").val(data[i].layout);\n\t\t\t$(tile).find(\".tileOrderInput\").val(data[i].order);\n\t\t\t$(tile).find(\".col12Input\").val(data[i].col12);\n\t\t\t$(tile).find(\".col1Input\").text(data[i].col1);\n\t\t\t$(tile).find(\".col2Input\").text(data[i].col2);\n\t\t\t$(tile).clone().appendTo(content);\n\t\t}\n\t}\n}", "function drawMap() {\n map = document.createElement(\"div\");\n var tiles = createTiles(gameData);\n for (var tile of tiles) {\n map.appendChild(tile);\n }\n document.body.appendChild(map);\n }", "function displayMap(){\n var coordinates = infoForMap();\n createMap(coordinates);\n}", "function refresh() {\n map.remove();\n mapView();\n createRoute();\n busLocation();\n}", "function updateEarthquakesData (region, zoom) {\n return dispatch => {\n // First, reset earthquakes data and abort all the old requests.\n earthquakeApi.abortAllRequests()\n dispatch({\n type: RESET_EARTHQUAKES\n })\n // Process region, get tiles. Remove unnecessary ones (y values < 0 or > max value, we don't display map there).\n const tiles = tilesList(region, zoom).filter(t => !tileYOutOfBounds(t))\n // Then retrieve all the cached data tiles.\n console.time('Earthquake cached tiles processing')\n const cachedEarthquakes = earthquakeApi.getTilesFromCache(tiles)\n dispatch(receiveEarthquakes(cachedEarthquakes))\n console.timeEnd('Earthquake cached tiles processing')\n // Finally request new data tiles.\n const tilesToDownload = tiles.filter(t => !earthquakeApi.isInCache(t))\n console.log('Earthquake data tiles to download:', tilesToDownload.length)\n tilesToDownload.forEach((tile, idx) =>\n dispatch(requestEarthquakes(tile))\n )\n }\n}", "refreshMap() {\n this.removeAllMarkers();\n this.addNewData(scenarioRepo.getAllEvents(currentScenario));\n this.showAllMarkers();\n }", "function redraw() {\n updateMapUnits();\n calcFog();\n updateMap();\n updateControlPanel();\n}", "replaceTilesetSource({ id, features }) {\n const formData = new FormData()\n formData.append(\n 'file',\n features.map(JSON.stringify).join('\\n'),\n 'data.geojson.ld'\n )\n\n return axios({\n url: `https://api.mapbox.com/tilesets/v1/sources/${config.mapbox.username}/${id}`,\n method: 'PUT',\n headers: {\n ...formData.getHeaders(),\n },\n params: {\n access_token: config.mapbox.accessToken,\n },\n data: formData,\n })\n }", "async function updateMarkers() {\n if (markerListCache.length > 0) {\n markerListCache.forEach((item) => {\n if (jQuery(`#events ul #${item.id}`).length === 0) {\n jQuery(\n `<li id=${item.id\n }><b><a href=\"#\" class=\"time-marker\">${item.time_marker\n }</a></b>${item.name\n }</li>`,\n ).appendTo('#events ul');\n }\n });\n } else {\n $.ajax({\n type: 'GET',\n url: `${baseRemoteURL}markers`,\n dataType: 'json',\n async: true,\n cache: true,\n success(data) {\n markerListCache = data;\n data.forEach((item) => {\n if (jQuery(`#events ul #${item.id}`).length === 0) {\n jQuery(\n `<li id=${item.id\n }><b><a href=\"#\" class=\"time-marker\">${item.time_marker\n }</a></b>${item.name\n }</li>`,\n ).appendTo('#events ul');\n }\n });\n },\n });\n }\n jQuery('.time-marker').on('click', function () {\n jumpToTime(this.text);\n johng.updateClock();\n johng.play();\n });\n}", "function updateMap() {\n\tif (myKeyWords == \"\") {\n\t\tfor (var i = 0; i < MAX_K; i++){\n\t\t\tkNearMarkers[i].setVisible(false);\n\t\t}\n\t\treturn ;\n\t}\n\t$.post(\"/search/\", {\n\t\tuserPos:myMarker.getPosition().toUrlValue(),\n\t\tkeyWords:myKeyWords,\n\t}, function(data, status){\n\t\t/* Cancel all the old k-near-markers */\n\t\tfor (var i = 0; i < MAX_K; i++){\n\t\t\tkNearMarkers[i].setVisible(false);\n\t\t}\n\t\t\n\t\t/* Return result from django backend */\n\t\tvar dataJSON = $.parseJSON(data);\n\t\t\n\t\t$(\"#BestMap\").attr(\"src\", dataJSON.BestMap);\n\t\t\n\t\t/* Display the new k-near-markers*/\n\t\t$.each(dataJSON.Pos, function(i, item){\n\t\t\tif (i < MAX_K){\n\t\t\t\t//alert(item.Lat + ';' + item.Lng);\n\t\t\t\tkNearMarkers[i].setPosition({lat:item.Lat, lng:item.Lng});\n\t\t\t\tkNearMarkers[i].setVisible(true);\n\t\t\t\tkNearMarkers[i].setTitle(item.Name + \"\\nAddr: \" + item.Addr \n\t\t\t\t+ \".\\nPCode: \" + item.Pcode);\n\t\t\t\t\n\t\t\t\tif (i < MAX_PANEL) {\n\t\t\t\t\t$(\"#name\"+i).text(item.Name);\n\t\t\t\t\t$(\"#info\"+i).text(\"Address: \" + item.Addr + \". PCode: \" + item.Pcode);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t//$( \"#rtnMsg\" ).text( data );\n\t});\n\t//$( \"#test_input\" ).text( this.value );\n}", "function onClickChange(i,j){\n console.log(\"merp i = \"+i+\", j = \"+j)\n if (editTables) {\n //TODO edit table ids\n } else {\n // toggle map block\n mapModified = true;\n console.log(map);\n map[i][j] = mapSyms[(mapSyms.indexOf(map[i][j])+1)%4];\n console.log(map);\n updateMap(); \n }\n \n}", "function setSizes() {\n if (!currentMap) return;\n\n const viewMaxWidth = canvasElement.width - dpi(40);\n const viewMaxHeight = canvasElement.height - dpi(40);\n const tileWidth = Math.floor(viewMaxWidth / currentMap.cols);\n const tileHeight = Math.floor(viewMaxHeight / currentMap.rows);\n\n tileSize = Math.min(tileWidth, tileHeight);\n viewWidth = tileSize * currentMap.cols;\n viewHeight = tileSize * currentMap.rows;\n viewX = (canvasElement.width - viewWidth) / 2;\n viewY = (canvasElement.height - viewHeight) / 2;\n}", "function updateNumbers() {\n // look how I loop through all tiles\n tileSprites.forEach(function (item) {\n // retrieving the proper value to show\n var value = fieldArray[item.pos];\n // showing the value\n item.getChildAt(0).text = value;\n // tinting the tile\n item.tint = colors[value]\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assigns value for the property that has the given key, and exists under the sub chart
handleSubChartPropertyChange(key, value) { const state = this.state; state.configuration.charts[0][key] = value; this.setState(state); this.props.onConfigurationChange(state.configuration); }
[ "set(key, value = null) {\n // If only argument is an Object, merge Object with internal data\n if (key instanceof Object && value == null) {\n const updateObj = key;\n Object.assign(this.__data, updateObj);\n this.__fullUpdate = true;\n return;\n }\n\n // Add change to internal updates set\n this.__updates.add(key);\n\n // Set internal value selected by dot-prop key\n DotProp.set(this.__data, key, value);\n }", "function setExprProp(eID, {key, value}) {\n\t\tCalc.setExpression({\n\t\t\tid: eID,\n\t\t\t[key]: value\n\t\t});\n\t}", "handleMainPropertyChange(key, value) {\n const state = this.state;\n state.configuration[key] = value;\n this.setState(state);\n this.props.onConfigurationChange(state.configuration);\n }", "updateInfo(key, newValue) {\n let info = this.props.info;\n info[key] = newValue;\n this.props.updateShipInfo(info);\n }", "setValueToId (item, key, id) {\n debug('setValueToId(%O, %O, %O)', item, key, id)\n let value = this.objFor.get(id)\n if (value) {\n debug('.. set to %o', value)\n item[key] = value\n } else {\n let frs = this.forwardRefs.get(id)\n if (!frs) {\n frs = new Set()\n this.forwardRefs.set(id, frs)\n }\n frs.add({ item, key })\n debug('.. forward refs = %o', frs)\n }\n }", "set(propObj, value) {\n propObj[this.id] = value;\n return propObj;\n }", "static setSubhash (key, val) {\n\t\tconst nxtHash = Hist.util.setSubhash(window.location.hash, key, val);\n\t\tHist.cleanSetHash(nxtHash);\n\t}", "onPropertySet(room, property, value, identifier) {\n room[prop] = value;\n }", "function setDepartmentAnalyticsMapValue(data) {\n var analyticsDate = data.analyticsDate.getTime(),\n departmentAnalyticsMap = data.departmentAnalyticsMap,\n userDepartmentID = data.userDepartmentID,\n pq = data.pq,\n dataChanged = data.dataChanged,\n trainedThisWeek = data.trainedThisWeek,\n user = data.user,\n departmentsParentMap = data.departmentsParentMap;\n if (userDepartmentID) { // if id is not undefined\n if (!departmentAnalyticsMap[userDepartmentID]) {\n departmentAnalyticsMap[userDepartmentID] = {\n date: {},\n highest_pq: {\n score: Number.MIN_VALUE\n },\n lowest_pq: {\n score: Number.MAX_VALUE\n },\n user_trained_this_week: []\n };\n departmentAnalyticsMap[userDepartmentID].date[analyticsDate] = {\n userCount: 1,\n dataChanged: dataChanged,\n pq: pq\n }\n }\n else if (typeof departmentAnalyticsMap[userDepartmentID].date[analyticsDate] === \"undefined\") { // when department record for given date doesn't exist\n departmentAnalyticsMap[userDepartmentID].date[analyticsDate] = {\n userCount: 1, // sets user count to one\n dataChanged: dataChanged,\n pq: pq\n };\n }\n else {\n departmentAnalyticsMap[userDepartmentID].date[analyticsDate].userCount++;\n departmentAnalyticsMap[userDepartmentID].date[analyticsDate].pq += pq;\n departmentAnalyticsMap[userDepartmentID].date[analyticsDate].dataChanged = departmentAnalyticsMap[userDepartmentID].date[analyticsDate].dataChanged || dataChanged;\n }\n\n if (commonUtils.getDateDifference(analyticsTillDate, new Date(analyticsDate)) <= 7 && trainedThisWeek) {\n departmentAnalyticsMap[userDepartmentID].user_trained_this_week.push(user.id);\n }\n if (user && user.get(\"pq_score\") > departmentAnalyticsMap[userDepartmentID].highest_pq.score) {\n departmentAnalyticsMap[userDepartmentID].highest_pq.score = user.get(\"pq_score\");\n departmentAnalyticsMap[userDepartmentID].highest_pq.user = user;\n }\n if (user && user.get(\"pq_score\") < departmentAnalyticsMap[userDepartmentID].lowest_pq.score) {\n departmentAnalyticsMap[userDepartmentID].lowest_pq.score = user.get(\"pq_score\");\n departmentAnalyticsMap[userDepartmentID].lowest_pq.user = user;\n }\n\n // if this department is a sub department of any department\n if(departmentsParentMap[userDepartmentID]){\n // add this data in it's parent department analytics map also\n setDepartmentAnalyticsMapValue({\n departmentAnalyticsMap: departmentAnalyticsMap,\n userDepartmentID: departmentsParentMap[userDepartmentID], // parent department id\n analyticsDate: data.analyticsDate,\n pq: pq,\n dataChanged: data.dataChanged,\n trainedThisWeek: trainedThisWeek,\n user: user,\n departmentsParentMap : departmentsParentMap\n });\n }\n }\n }", "function setStateProp(index, {key, value}) {\n\t\tlet state = Calc.getState();\n\t\tstate.expressions.list[index][key] = value;\n\t\tCalc.setState(state, {allowUndo: true});\n\t}", "async saveStarProperty(x, y, z, starNumber, keypath, value) {\n if (keypath == '') {\n // This is the whole star\n await this.publishKeypath(x + '.' + y + '.' + z + '.' + starNumber, value)\n } else {\n // This is a property\n await this.publishKeypath(x + '.' + y + '.' + z + '.' + starNumber + '.' + keypath, value)\n }\n }", "function populateDocumentWithKeyValue (document, key, value) {\n if (value && Object.getPrototypeOf(value) === Object.prototype) {\n populateDocumentWithObject(document, key, value);\n } else if (!(value instanceof RegExp)) {\n insertIntoDocument(document, key, value);\n }\n}", "modifyCurrentlySelectedComponent(property, value) {\n const selectedComponent = globalScope.getCurrentlySelectedComponent();\n\n if (selectedComponent.objectType === 'Node') {\n const nodeId = selectedComponent.id;\n const nodeIndex = this.findNodeIndexById(nodeId);\n globalScope.allNodes[nodeIndex][property] = value;\n return;\n }\n for (const key in globalScope) {\n const component = globalScope[key];\n if (Array.isArray(component) && component.length) {\n component.forEach((obj, index) => {\n if (obj === selectedComponent) {\n component[index][property] = value;\n }\n });\n }\n }\n }", "function setValueIfNotExists(obj, key, val) {\n if (obj === undefined)\n return;\n if (!(key in obj))\n obj[key] = val;\n}", "function assign(key, val, obj) {\n if (typeof key == 'string') {\n obj[key] = val;\n return;\n }\n\n Object.keys(key).forEach(function (k) {\n return obj[k] = key[k];\n });\n}", "update(_path, needValueType = false){\n if(_path){\n for(var [key,value] of _path.valueMap){\n var valuetype;\n if (valuetype = this.valueMap.get(key)){\n valuetype.update(value);\n }else{\n valuetype = new ValueType();\n if(!value)\n console.log(_path);\n valuetype.update(value);\n this.valueMap.set(key,valuetype);\n }\n \n }\n\n if(needValueType){\n this._valueType.update(_path._valueType);\n }\n }\n }", "get(key) {\n const setting = super.get(key);\n if (!setting) {\n return null;\n }\n return setting.getValue();\n }", "function calcProp(ka, p) {\n var val = ka[p];\n if (isKeepAssigned(val)) {\n recalc(val);\n } else {\n val.val = findFirstProp(ka.objs, p);\n }\n}", "function addArrayProperty(obj, key, arr) {\n obj[key] = arr\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test if collision with Dino
collision(dino){ if (!this.img||!dino.img) return false; if(!((this.y>(dino.y+dino.h))||(!this.left&&((this.x>=dino.x+dino.w-25)||(this.x<=dino.x+25)))||(this.left&&((this.x<=dino.x+25)||(this.x>=dino.x+dino.w-25))))){ if(dino.shield) { setTimeout(()=>{dino.shield=false},500); return false; } return true; } }
[ "function detect_collision(obj1, obj2) {\r\n\tif ((obj1.x + obj1.width > obj2.x) &&\r\n\t\t(obj1.x < obj2.x + obj2.width) &&\r\n\t\t(obj1.y + obj1.height > obj2.y) &&\r\n\t\t(obj1.y < obj2.y + obj2.height)) {\r\n\t\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}", "function checkCollision(n1, n2){\r\n p1 = getPlayer(n1);\r\n p2 = getPlayer(n2);\r\n if(n1 != n2)\r\n var d0 = Math.sqrt( ((p1.cx - p2.cx)*(p1.cx - p2.cx)) +\r\n ((p1.cy - p2.cy)*(p1.cy - p2.cy)))\r\n\r\n var len = p1.trail.length;\r\n if(n1 === n2) len = len-10;\r\n for(var i = 0; i < len; i++){\r\n var pos = p1.trail[i];\r\n var d = Math.sqrt( ((pos.cx - p2.cx)*(pos.cx - p2.cx)) +\r\n ((pos.cy - p2.cy)*(pos.cy - p2.cy)))\r\n\r\n if(d < 5 || d0 < 5 && p2.dead === false){\r\n\r\n if(p2.dead === false && p2.number < 5) endingSoundEffects[selectedplayers[n2-1]].play();\r\n if(p2.dead === false && p2.number === 5) endingSoundEffects[selectedplayers[0]].play();\r\n p2.halt();\r\n p2.dead = true;\r\n console.log(\"Player \" + n2 + \" hit player \" + n1 + \"'s trail!\");\r\n\r\n }\r\n\r\n }\r\n\r\n}", "detectCollisions() {\n const sources = this.gameObjects.filter(go => go instanceof Player);\n const targets = this.gameObjects.filter(go => go.options.hasHitbox);\n\n for (const source of sources) {\n for (const target of targets) {\n /* Skip source itself and if source or target is destroyed. */\n if (\n source.uuid === target.uuid ||\n source.isDestroyed ||\n target.isDestroyed\n )\n continue;\n this.checkCollision(source, target);\n }\n }\n }", "checkCollisions(unit, detectCollision) {\n // check neighborhood for collisions\n return this.searchNeighborhood(unit, (u) => {\n return u.id !== unit.id && detectCollision(unit, u);\n });\n }", "function isColliding(x1, y1, x2, y2, sr){\n var dx = x2 - x1;\n var dy = y2 - y1;\n var dr = sr + 50;\n\n if(dx === 0 && dy === 0){\n return false;\n } else {\n return (Math.pow(dx, 2) + Math.pow(dy, 2)) < Math.pow(dr, 2);\n }\n}", "isCollide(potato) {\n\n\n // Helper Function to see if objects overlap\n const overLap = (objectOne, objectTwo) => {\n\n // Check X-axis if they dont overlap\n if (objectOne.left > objectTwo.right || objectOne.right < objectTwo.left) {\n return false;\n }\n // Check y-axis if they dont overlap\n // 100 \n // 200 ObjectTwo Bottom\n // 300 ObjectOne Top\n if (objectOne.top > objectTwo.bottom || objectOne.bottom < objectTwo.top) {\n return false;\n }\n return true;\n }\n\n let collision = false;\n\n this.eachObject((object) => {\n if (overLap(object, potato)) {\n collision = true\n }\n\n });\n\n return collision\n\n\n }", "collide(other) {\n // Don't collide if inactive\n if (!this.active || !other.active) {\n return false;\n }\n\n // Standard rectangular overlap check\n if (this.x + this.width > other.x && this.x < other.x + other.width) {\n if (this.y + this.height > other.y && this.y < other.y + other.height) {\n return true;\n }\n }\n return false;\n }", "function checkCollisions() {\n\t// check lTraffic\n\tvar numObs = lTraffic.length;\n\tvar i = 0;\n\tfor (i = 0; i < numObs; i++){\n\t\tif (rectOverlap(userCar, lTraffic[i])) {\n\t\t\thandleCollision();\n\t\t}\n\t}\n\t// TODO check rTraffic\n\tnumObs = rTraffic.length;\n\tfor (i = 0; i < numObs; i++) {\n\t\tif (rectOverlap(userCar, rTraffic[i])) {\n\t\t\thandleCollision();\n\t\t}\n\t}\n\t// TODO check bottom peds\n\t// TODO check top peds\n}", "hasCollision() {\n return this.collision != null && this.collision != undefined;\n }", "collide(rect) {\n return (this.left < rect.right && this.right > rect.left &&\n this.top < rect.bottom && this.bottom > rect.top);\n }", "function checkEnergyCollision() {\r\n energies.forEach(function (e) {\r\n if ((player.X < e.x + energyRadius) &&\r\n (player.X + player.width > e.x) &&\r\n (player.Y < e.y + energyRadius) &&\r\n (player.Y + player.height > e.y)) {\r\n e.onCollide();\r\n //startSound();\r\n }\r\n })\r\n}", "function collision(x1, y1, radius1, x2, y2, radius2) {\n return Math.hypot(x1 - x2, y1 - y2) < radius1 + radius2 ? true : false;\n}", "function checkHit() {\r\n \"use strict\";\r\n // if torp left and top fall within the ufo image, its a hit!\r\n let ymin = ufo.y;\r\n let ymax = ufo.y + 65;\r\n let xmin = ufo.x;\r\n let xmax = ufo.x + 100;\r\n\r\n\r\n console.log(\"torp top and left \" + torpedo.y + \", \" + torpedo.x);\r\n console.log(\"ymin: \" + ymin + \"ymax: \" + ymax);\r\n console.log(\"xmin: \" + xmin + \"xmax: \" + xmax);\r\n console.log(ufo);\r\n\r\n if (!bUfoExplode) {\r\n // not exploded yet. Check for hit...\r\n if ((torpedo.y >= ymin && torpedo.y <= ymax) && (torpedo.x >= xmin && torpedo.x <= xmax)) {\r\n // we have a hit.\r\n console.log(\" hit is true\");\r\n\r\n bUfoExplode = true; // set flag to show we have exploded.\r\n }// end if we hit\r\n\r\n }// end if not exploded yet\r\n\r\n // reset fired torp flag\r\n bTorpFired = false;\r\n\r\n // call render to update.\r\n render();\r\n\r\n}// end check hit", "function collides(obj, obstacles){\n for (var idx in obstacles){\n if (mayCollide(obj, obstacles[idx])) // algoritmo veloce ma soggetto a falsi positivi\n if (reallyCollides(obj, obstacles[idx])) // algoritmo lento ma preciso\n return idx; // collisione!\n }\n // Nessuna collisione\n return -1;\n}", "checkCollisions() {\n console.log(\n \"Collisions not defined for Agent at x=\"\n + this.pos.x + \", y=\" + this.pos.y);\n }", "function collitest() {\r\n var topGap = 0; // écart entre le tornaTop et le missiTop\r\n var tornaPos = $(\"#tornado\").position(); // récup de la position de l'avion\r\n var missiPos = $(\"#missile\").position(); // récup de la position du missile\r\n var tornaTop = parseInt(tornaPos.top); // récup du top de l'avion\r\n var missiTop = parseInt(missiPos.top); // récup du top du missile\r\n var missiLeft = parseInt(missiPos.left); // récup de la partie gauche du missile\r\n\r\n if (missiLeft > 87 && missiLeft < 150) {\r\n // test de collision du nez de l'avion qui déclenche un DOH! en cas d'impact\r\n topGap = tornaTop - missiTop; // calcul de l'écart vertical entre l'avion et le missile\r\n\r\n if (topGap < -16 && topGap > -48) {\r\n // trigger pour le déclenchement de la collision du nez\r\n dohSound.play(); // déclenchement du DOH\r\n }\r\n }\r\n\r\n if (missiLeft < 86) {\r\n // si l'impact a lieu entre l'arriere de la verriere et les réacteurs on entend le beep.mp3\r\n topGap = tornaTop - missiTop; // calcul de l'écart vertical entre l'avion et le missile\r\n\r\n if (topGap < 28 && topGap > -92) {\r\n // trigger pour le déclenchement de la collision du reste de l'avion\r\n crashSound.play(); // déclenchement du crash.mp3\r\n }\r\n }\r\n}", "function checkColision(){\n return obstacles.obstacles.some(obstacle => {\n if(obstacle.y + obstacle.height >= car.y && obstacle.y <= car.y + car.height){\n if(obstacle.x + obstacle.width >= car.x && obstacle.x <= car.x + car.width){\n console.log(\"colision\")\n return true;\n }\n }\n return false;\n });\n}", "_setupCollision () {\n this.PhysicsManager.getEventHandler().on(this.PhysicsManager.getEngine(), 'collisionStart', (e) => {\n\n for (let pair of e.pairs) {\n let bodyA = pair.bodyA\n let bodyB = pair.bodyB\n\n if (bodyB === this.body) {\n this.onCollisionWith(bodyA)\n }\n }\n })\n }", "function playerShipAndAsteroidCollisionDetection(elapsedTime){\r\n\t\tif(myShip.getSpecs().invincible == false){\r\n\t\t\tfor(var i = 0; i < myAsteroid.getAsteroids().length; i++){\r\n\t\t\t\tvar asteroid = myAsteroid.getAsteroids()[i];\r\n\t\t\t\tvar xDiff = myShip.getSpecs().center.x - asteroid.center.x;\r\n\t\t\t\tvar yDiff = myShip.getSpecs().center.y - asteroid.center.y;\r\n\r\n\t\t\t\tvar distance = Math.sqrt((xDiff * xDiff) + (yDiff*yDiff));\r\n\r\n\t\t\t\tif(distance < myShip.getSpecs().radius-10 + asteroid.ballRadius){\r\n\t\t\t\t\t\r\n\t\t\t\t\tparticleGenerator.createShipExplosions(elapsedTime,myShip.getSpecs().center);\r\n\r\n\r\n\t\t\t\t\tmyShip.getSpecs().hit = true;\r\n\t\t\t\t\tmyShip.getSpecs().center.x = canvas.width+20;\r\n\t\t\t\t\tmyShip.getSpecs().center.y = canvas.height+20;\r\n\t\t\t\t\tmyShip.getSpecs().reset = true;\r\n\t\t\t\t\tplayerShipDestroyedAudio.play();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Supply the number of keys in the datastore to the callback function.
function length(callback) { var self = this; var promise = self.keys().then(function(keys) { return keys.length; }); executeCallback(promise, callback); return promise; }
[ "function keysCounter(obj) {\n // your code here\n var counter = 0;\n counter = Object.keys(obj).length;\nreturn counter;\n // code ends here\n}", "function getLength(data) {\n\treturn Object.keys(data).length;\n}", "function counterCallback(callback, count) {\n\treturn (function() {\n\t\tcount--;\n\t\tif (count == 0)\n\t\t\tcallback.apply(arguments);\n\t});\n}", "function updateKeys(addKey){\n var keyCount = parseInt(totalKeys);\n \n if(addKey == true){\n keyCount += 1;\n //notify(\"+1 Box Key\");\n // alert(keyCount);\n \n }\n else{\n if(keyCount<1){ \n notify(\"Need a key!\");\n return false;\n }\n else{\n keyCount -= 1;\n totalKeys=keyCount;\n notify(\"-1 Box Key\")\n $(\".keyCounter\").html('');\n $(\".keyCounter\").html(\"Keys: \"+ totalKeys);\n //create cookie to store number of keys owned\n document.cookie = \"keys=\"+parseInt(totalKeys)+\"; expires=Thu, 18 Dec 2019 12:00:00 UTC; path=/\";\n return true;\n }\n }\n totalKeys=keyCount;\n $(\".keyCounter\").html('');\n $(\".keyCounter\").html(\"Keys: \"+ totalKeys);\n //create cookie to store number of keys owned\n document.cookie = \"keys=\"+parseInt(totalKeys)+\"; expires=Thu, 18 Dec 2019 12:00:00 UTC; path=/\";\n // notify(\"cookie made\");\n \n }", "function updateNitems(add=true){\n\tif(add){\n\t\tnItems++;\n\t}else{\n\t\tnItems--;\n\t}\n\tdocument.getElementById( \"counter\" ).innerHTML =nItems+\" items\";\n}", "getCount(){\r\n\t\tvar playerCountRef = database.ref('playerCount');\r\n\t\tplayerCountRef.on(\"value\", function (data) {\r\n\t\t\tplayerCount = data.val();\r\n\t\t})\r\n\t}", "function getLength(arr, cb) {\n\tcb(arr.length);\n}", "function numGroups(callback) {\n chrome.storage.local.get(\"number\", function(data) {\n numGroups = data.number;\n callback(numGroups);\n });\n}", "function getAllOptionsCount(response, numItems, offset) {\n var sql = \"SELECT COUNT(*) FROM options\";\n\n connectionPool.query(sql, function(err, result) {\n\n if (err) {\n response.status(HTTP_STATUS.INTERNAL_SERVER_ERROR)\n response.json({ 'error': true, 'message': +err })\n return;\n\n }\n\n let total = result[0]['COUNT(*)']\n\n getAllOptions(response, total, numItems, offset)\n });\n}", "function num_keys(obj) {\n\treturn Object.keys(obj).length\n}", "function updateNumberOfPlayers(){\n\n // this is the real number of players\n numberOfPlayers = inPlayerId - 1;\n}", "function getJsonLength(jsonData) {\n var jsonLength = 0;\n for (var item in jsonData) {\n jsonLength++;\n }\n return jsonLength;\n}", "getCount(callback) {\n let count = {\n active: 0,\n completed: 0,\n total: 0\n }\n\n this.items.forEach(item => {\n if(item.completed) {\n count.completed++\n } else {\n count.active++\n }\n count.total++\n })\n\n if(typeof callback === 'function') {\n callback(count)\n }\n\n return count\n }", "function keysLongerThan(coll, num) {\n var output = {};\n each(coll, function(e, key) {\n if (key.toString().length > num) {\n output[key] = e;\n }\n });\n return output;\n}", "function getObjectLength(object) {\n // YOUR CODE BELOW HERE //\n \n var count = 0 //initialize a variable\n for (var key in object) { //iterate through the given object\n count++; //count each key/value and store the value in count variable\n }\n \n return count //return the number of key/value pairs\n // YOUR CODE ABOVE HERE //\n}", "getNumSongs(data) {\n let num = 0;\n data.sets.set.forEach((set) => num += set.song.length)\n return num;\n }", "function getAllRecordsInDB() {\n PiDictDB.transaction(function(tx) {\n tx.executeSql(\"SELECT * FROM tblPhraseEntities\", [], function(tx, result) {\n if(result.rows.length>0)\n {\n\t\t\t\tnewwordsCount = result.rows.length;\n chrome.browserAction.setBadgeText({\"text\": \"\"+newwordsCount});\n chrome.browserAction.setBadgeBackgroundColor({\"color\": [255, 0, 0, 255]});\n }\n },onError);\n });\n}", "async function getStoreSize(store,current){\n const doc = await store.doc(current).get();\n return sizeOf(doc.data());\n}", "_setMembersForKeys (keys, callback) {\n async.map(keys, (roomKey, callback) => {\n let cursor = 0\n const members = []\n\n async.doWhilst(cb => {\n this.redis.sscan(roomKey, cursor, 'COUNT', MEMBERS_SSCAN_COUNT, (err, result) => {\n if (err) return cb(err)\n const [newCursor, newMembers] = result\n cursor = newCursor\n members.push(...newMembers)\n cb()\n })\n }, () => cursor !== '0', err => {\n if (err) return callback(err)\n callback(null, members)\n })\n }, (err, memberGroups) => {\n if (err) return callback(err)\n callback(null, flatten(memberGroups))\n })\n }", "updateCount(count){\r\n //playerCount refers to the database counts whereas count refers to make a change to the original playerCount\r\n database.ref(\"/\").update({playerCount:count});\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Like `Array.prototype.findIndex` but returns `arr.length` instead of `1`
function findIndex(arr, test) { var index = arr.findIndex(test); return index < 0 ? arr.length : index; }
[ "function arr_findIndex(arr = [], prop = \"\", val) {\n\treturn arr.findIndex(v => { return v && v[prop] === val })\n}", "function findLastIndex(arr, fn) {\n\tfor (let i = arr.length - 1; i >= 0; --i) {\n\t\tif (fn(arr[i])) {\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn -1;\n}", "function getMatchingIndex(arr, key, value) {\n for (let i = 0; i < arr.length; i++) {\n if (arr[i][key] === value)\n return i;\n }\n return null;\n}", "function findCard(arr, card){\n for (let i = 0; i < arr.length; i++){\n if(cards[i] == card) return i;\n }\n return -1;\n}", "function search(arr, val) {\n\n let sortedArr = arr.sort((a, b) => a - b)\n\n for (let i = 0; i < sortedArr.length; i++) {\n if (sortedArr[i] === val) {\n return i;\n }\n }\n return 'value not found'\n}", "function linearSearch(searchObj, searchArr){\n\n for(let index = 0; index < searchArr.length; index++){\n if(searchArr[index] === searchObj){\n return index\n }\n }\n return undefined\n}", "function arrayContains(arr, obj){\n \tfor (var i=0; i < arr.length; i++){\n \t\tif (arr[i] == obj){\n \t\t\treturn i;\n \t\t}\n \t}\n \treturn false;\n }", "function searchLinear(array, target){\n\tfor(let i = 0;i<array.length;i++){\n\t\tif(target == array[i]){\n\t\t\treturn i;\n\t\t}\n\t}\n\n\treturn -1\n}", "function find(arr, callback){\n for (let i=0; i<arr.length; i++){\n if (callback(arr[i], i, arr)) return arr[i];\n }\n return undefined;\n}", "function getIndices(arr, el) {\n\tconst a = [];\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tif (arr[i] === el) {\n\t\t\ta.push(i)\n\t\t}\n\t}\n\treturn a;\n}", "function inArray(value, array) {\n for (var i = 0; i < array.length; i++) {\n if (array[i] == value) return i;\n }\n return -1;\n}", "function findIndexOfItem(array, item){\r\n for (var x = 0; x < array.length; x++) {\r\n if (array[x][1] == item[1]) {\r\n return x;\r\n }\r\n}\r\n }", "function indexOfElement(arrayContainer, element){\n\t//loop thru elements of container\n\tvar index = 0;\n\tfor( ; index < arrayContainer.length; index++ ){\n\t\t//compare currently iterated array entry to the given element\n\t\tif( arrayContainer[index] == element ){\n\t\t\t//if found, return index\n\t\t\treturn index;\n\t\t}\n\t}\n\t//not found, return -1\n\treturn -1;\n}", "function search_in_array(element,array){\r\n\r\n var found = 0;\r\n \r\n for(i=0;i<array.length;i++)\r\n {\r\n if(array[i] == element)\r\n {\r\n found = 1;\r\n return 1;\r\n }\r\n }\r\n\r\n if(found == 0){\r\n return 0;\r\n }\r\n\r\n}", "function find(arr, searchValue){\n\treturn arr.filter(i=>{\n\t\treturn i===searchValue;\n\t})[0];\n}", "function findIndexInDidArrayMatchingSelection() {\t\n\t\tvar i=0;\n\t\twhile(i<detailIdJson.did_array.length) {\n\t\t\tif(detailIdJson.did_array[i].color==self.color() &&\n\t\t\t detailIdJson.did_array[i].size ==self.size() &&\n\t\t\t detailIdJson.did_array[i].sex ==self.sex() )\n\t\t\t\tbreak;\n\t\t\ti++;\n\t\t}\n\t\tif(i==detailIdJson.did_array.length)\n\t\t{\n\t\t\treturn -1;\n\t\t} else {\n\t\t\treturn i;\n\t\t}\t\n\t}", "function getCutoffIndex(array, value) {\n for (var index = 0; index < array.length; ++index) {\n if (array[index] === value) {\n return index + 1;\n }\n }\n\n return 0;\n }", "function indexEqualsValue(a) {\n const value = [...a].filter((x, i)=> x===i)[0]\n if(value){\n return value\n }\n if( a[0]===0){\n return 0;\n }\n return -1;\n}", "function checkTheIndexes(arr, index, result){\n\t//arr[[minusElement, index],[-2,2]]\n\tvar i;\n\tvar j;\n\tfor(i = 0; i < arr.length; i++){\n\t\tfor(j = 0; j < arr.length; j++){\n\t\t\tif(arr[i][1] === index){\n\t\t\t\treturn arr[i][0]\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}", "search (arr, length, value, key, keyValue) {\n\n if (length) {\n\n /*\n * Third type of search\n */\n if (key && keyValue) {\n for (let object of arr) {\n \n if (_.get(object, [key], '') === value) {\n return _.get(object, [keyValue], 0);\n }\n\n }\n }\n /*\n * Second type of search\n */\n else if (key) {\n for (let object of arr) {\n \n if (_.get(object, [key], '') === value) {\n return object;\n }\n\n }\n }\n /*\n * First type of search\n */\n else {\n for (let i = 0; i < length; i++) {\n\n if (_.get(arr, [i], '') === value) {\n return i;\n }\n\n }\n }\n\n }\n\n return false;\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw the cropped image experiment.
function croppedImage () { ctx.fillStyle = "#000" ctx.fillRect(0, 0, w, h) starfield() let img = new Image() img.src = "res/img/kerrigan.png" img.addEventListener('load', drawCropped, false) function drawCropped() { ctx.drawImage(img, 500, 500) // cropped for (let i = 0; i < 10; i++) { ctx.drawImage( img, // source 0, 0, 500, 500, // destination location i * 10, i * 10, // destination scale i * 0.2 * 170, i * 0.2 * 170 ) } } }
[ "_redraw() {\n\t\tlet p = this._points;\n\n\t\tlet leftX = p.nw.x;\n\t\tlet leftY = p.nw.y;\n\t\tlet size = this._getSize();\n\n\t\tthis._dom.cropTop.style.left = leftX + \"px\";\n\t\tthis._dom.cropTop.style.width = size.width + \"px\";\n\t\tthis._dom.cropTop.style.height = leftY + \"px\";\n\n\t\tthis._dom.cropBottom.style.left = leftX + \"px\";\n\t\tthis._dom.cropBottom.style.width = size.width + \"px\";\n\t\tthis._dom.cropBottom.style.height = (this._dim.areaHeight - p.sw.y) + \"px\";\n\n\t\tthis._dom.cropLeft.style.width = leftX + \"px\";\n\t\tthis._dom.cropLeft.style.height = this._dim.areaHeight + \"px\";\n\n\t\tthis._dom.cropRight.style.width = (this._dim.areaWidth - p.ne.x) + \"px\";\n\t\tthis._dom.cropRight.style.height = this._dim.areaHeight + \"px\";\n\n\t\tthis._dom.cropMiddle.style.width = size.width + \"px\";\n\t\tthis._dom.cropMiddle.style.height = size.height + \"px\";\n\t\tthis._dom.cropMiddle.style.left = leftX + \"px\";\n\t\tthis._dom.cropMiddle.style.top = leftY + \"px\";\n\t}", "onSkippedCrop() {\n const attachment = this.frame.state().get('selection').first().toJSON()\n this.setImageFromAttachment(attachment)\n }", "function cropCanvas(canvas, ctx) {\n var imgWidth = ctx.canvas.width;\n var imgHeight = ctx.canvas.height;\n var imageData = ctx.getImageData(0, 0, imgWidth, imgHeight),\n data = imageData.data,\n getAlpha = function (x, y) {\n return data[(imgWidth * y + x) * 4 + 3];\n },\n scanY = function (fromTop) {\n var offset = fromTop ? 1 : -1;\n\n // loop through each row\n for (var y = fromTop ? 0 : imgHeight - 1; fromTop ? (y < imgHeight) : (y > -1); y += offset) {\n\n // loop through each column\n for (var x = 0; x < imgWidth; x++) {\n if (getAlpha(x, y)) {\n return y;\n }\n }\n }\n return null; // all image is white\n },\n scanX = function (fromLeft) {\n var offset = fromLeft ? 1 : -1;\n\n // loop through each column\n for (var x = fromLeft ? 0 : imgWidth - 1; fromLeft ? (x < imgWidth) : (x > -1); x += offset) {\n\n // loop through each row\n for (var y = 0; y < imgHeight; y++) {\n if (getAlpha(x, y)) {\n return x;\n }\n }\n }\n return null; // all image is white\n };\n\n var cropTop = scanY(true),\n cropBottom = scanY(false),\n cropLeft = scanX(true),\n cropRight = scanX(false);\n\n var relevantData = ctx.getImageData(cropLeft, cropTop, cropRight - cropLeft, cropBottom - cropTop);\n canvas.width = cropRight - cropLeft + imageBorder;\n canvas.height = cropBottom - cropTop + imageBorder * 1.3;\n\n\n\n ctx.putImageData(relevantData, imageBorder / 2, imageBorder / 2);\n\n\n\n }", "display()\r\n {\r\n image(this.image,this.x, this.y, this.w,this.h);\r\n }", "initCropper(image,controlPanel = null) {\n let size = this.activeCrop.size.split('x');\n let width = Math.round(parseInt(size[0]));\n let height = Math.round(parseInt(size[1]));\n\n // Aspect ratio is worked out by dividing the width and then the height by the greatest common denominator.\n function gcd (a, b) { // recursive\n return (b === 0) ? a : gcd (b, a%b);\n }\n let r = gcd (width, height);\n //console.log( (size[0] / r) + ' / ' + (size[1] / r));\n\n let cropper = new Cropper(image, {\n viewMode: 1,\n dragMode: 'move',\n aspectRatio: (width / r) / (height / r),\n autoCropArea: 1\n });\n image.addEventListener('ready', function (e) {\n this.cropper = cropper;\n image.parentNode.style.visibility = 'visible';\n if(controlPanel !== null) {\n this.buildControlPanel(controlPanel);\n }\n }.bind(this));\n }", "initializeCropper() {\n this.image.style.display = 'block';\n\n this.cropper = new Cropper(image, {\n aspectRatio: this.aspectRatio,\n responsive: true,\n guides: true\n });\n\n window.setTimeout(this._setCropperToCoverWholeImage, 100);\n }", "_crop(section) {\n engine.trace(`cropping '${ this._name }' at { x: ${ section.x }, y: ${ section.y }, w: ${ section.w }, h: ${ section.h } }...`);\n\n return sharp(this._file)\n .extract({ left: section.x, top: section.y, width: section.w, height: section.h })\n .toBuffer()\n .then(buffer => sharp(buffer).toFile(this._file)) // only way to save back to same filename in sharp\n .catch(err => engine.error('failure cropping'))\n .finally(() => engine.trace('cropped'));\n }", "function drawRepit() {\n if ( rectToDraw.length > 0 ) {\n for ( let z = 0; z < rectToDraw.length; z++ ) {\n drawRectCard(rectToDraw[z])\n }\n\n window.requestAnimationFrame(drawRepit)\n }\n }", "display() {\n let coin = c.getContext(\"2d\");\n var img = document.createElement(\"IMG\");\n img.src = \"images/Coin20.png\";\n coin.drawImage(img, this.x, this.y, this.width, this.width);\n }", "function applyCropping(obj){\n\t\tobj.on(\"mousedblclick\", () => {\n\t\t\tobj.cropPhotoStart()\n\t\t\tobj.activeCrop.initEventListeners()\n\t\t})\n\t\tobj.initEventListeners()\n\t\tobj.setFitting(\"cover\");\n\t}", "function addCropMarks(page) {\n if ( !window.showCrop ) return;\n \n const cropImage = 'https://outfit-v2-exports-production.s3-accelerate.amazonaws.com/media_library_items/bdb964a7c7fdc5ebc8bbde9204b62464/crop.svg';\n const cropMarks = document.createElement('div');\n cropMarks.classList.add('crop-marks');\n cropMarks.innerHTML = `\n <img style=\"height: 28.81px; width: 28.81px; position: absolute; top: 0; left: 0;\" src=\"${cropImage}\">\n <img style=\"height: 28.81px; width: 28.81px; transform: rotate(90deg); position: absolute; top: 0; right: 0;\" src=\"${cropImage}\">\n <img style=\"height: 28.81px; width: 28.81px; transform: rotate(180deg); position: absolute; bottom: 0; right: 0;\" src=\"${cropImage}\">\n <img style=\"height: 28.81px; width: 28.81px; transform: rotate(270deg); position: absolute; bottom: 0; left: 0;\" src=\"${cropImage}\">\n `;\n \n page.appendChild(cropMarks);\n }", "function clearCanvas() {\n context.clearRect(0, 0, canvas.width, canvas.height);\n pointCount = 0;\n drawImage();\n }", "function displayGridPaper()\r\n{\r\n for(var row = 0; row < noRows; row++)\r\n {\r\n for(var col = 0; col < noCols; col++)\r\n {\r\n var x = col * squareSize;\r\n var y = row * squareSize;\r\n\r\n cv.rect(x, y, squareSize, squareSize);\r\n }\r\n }\r\n}", "function setOriginal() {\n\n let cnv = document.getElementById('imgHtml');\n let cnx = cnv.getContext('2d');\n\n cnx.clearRect(0, 0, cnv.width, cnv.height);\n cnx.beginPath();\n\n cnx.moveTo(0, 0);\n cnx.stroke();\n\n imgNormal(backup.original);\n\n}", "capture(){\n // Create a hidden canvas of the appropriate size\n let output = document.createElement(\"canvas\");\n output.setAttribute(\"height\", this.height);\n output.setAttribute(\"width\", this.width);\n output.style.display = \"none\";\n\n let outputCtx = output.getContext(\"2d\");\n\n // Draw each canvas to the hidden canvas in order of z index\n for(let z=0; z < privateProperties[this.id].canvases.length; z++){\n outputCtx.drawImage(privateProperties[this.id].canvases[i], 0, 0);\n }\n\n // Get the image data\n let dataUrl = output.toDataURL();\n\n // Save the image as a png\n let a = document.createElement(\"a\");\n a.href = dataUrl;\n a.download = \"ScreenShot\" + (new Date().getDate())+\".png\";\n document.body.appendChild(a);\n a.click();\n a.remove();\n }", "function viewOriginalImg() {\r\n\tvar linePics = [\"org1_line\",\"org2_line\",\"org3_line\",\"org4_line\",\"org5_line\"];\r\n\tvar barPics = [\"org1_bar\",\"org2_bar\",\"org3_bar\",\"org4_bar\",\"org5_bar\"];\r\n\r\n\tvar pic; //pic = pic id name\r\n\t\r\n\tif(document.getElementById(\"lineBtn\").style.background === \"white\") { //line chart\r\n\t\tpic = linePics[getM()-1];\r\n\t\telement = document.getElementById(pic);\r\n\t} else { //bar chart\r\n\t\tpic = barPics[getM()-1];\r\n\t\telement = document.getElementById(pic);\r\n\t}\r\n\r\n\t//hide all other pictures and display selected one\r\n\tif(element.style.display == 'none'){\r\n\t\telement.style.display='block';\r\n\t\telement.style.border='1px solid black';\r\n\t\telement.style.position='absolute';\r\n\t\telement.style.right='150px';\r\n\t\telement.style.background='black';\r\n\t\t\r\n\t\tfor(var i = 0; i < linePics.length; i++) {\r\n\t\t\tif(linePics[i] !== pic)\r\n\t\t\t\tdocument.getElementById(linePics[i]).style.display='none';\r\n\t\t}\r\n\t\t\r\n\t\tfor(var i = 0; i < barPics.length; i++) {\r\n\t\t\tif(barPics[i] !== pic)\r\n\t\t\t\tdocument.getElementById(barPics[i]).style.display='none';\r\n\t\t}\r\n\t\t\r\n\t\tdocument.getElementById(\"origBtn\").style.background = \"white\"\r\n\t\tdocument.getElementById(\"origBtn\").style.color = \"black\"\r\n\t} else {\r\n\t\tcloseAllScreenshots();\r\n\t\t\r\n\t\tdocument.getElementById(\"origBtn\").style.background = \"rgba(255,255,255,0.4)\"\r\n\t\tdocument.getElementById(\"origBtn\").style.color = \"white\"\r\n\t}\r\n}", "function draw() {\n // clear the canvas\n canvas.width = canvas.width;\n drawBlocks();\n drawGrid();\n }", "function overlay()\r\n{\r\n img[i].resize(vScale, vScale);\r\n img[i].loadPixels();\r\n loadPixels();\r\n\r\n for (var y = 0; y < img[i].height; y++) {\r\n for (var x = 0; x < img[i].width; x++) {\r\n \r\n var index = (x + y * img[i].width)*4\r\n var r = img[i].pixels[index+0];\r\n var g = img[i].pixels[index+1];\r\n var b = img[i].pixels[index+2];\r\n \r\n var bright = (r+g+b)/3;\r\n \r\n var threshold = 35;\r\n \r\n var checkIndex = x + y * cols;\r\n \r\n if (bright < threshold)\r\n {\r\n boxes[checkIndex].checked(false);\r\n } else {\r\n boxes[checkIndex].checked(true);\r\n }\r\n\r\n noStroke();\r\n rectMode(CENTER);\r\n rect(x*vScale, y*vScale, vScale, vScale);\r\n }\r\n } \r\n}", "function draw_s() {\n ctx.beginPath()\n canvas_arrow(ctx, passthroughCoords.x - 2, passthroughCoords.y - 2, refractedCoords.x + 2, refractedCoords.y + 2)\n ctx.stroke()\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
6. Define a function called isDivisible that takes two arguments and returns a boolean. Return true if the first argument is divisible by the second; otherwise, return false.
function isDivisible(argument1, argument2) { if ((argument1/argument2) % 2 === 0){ return true; } else { return false; } }
[ "function dividesEvenly(a, b) {\n\tif (a%b === 0) {\n\t\treturn true;\n\t} else return false;\n}", "function divisible7and5(number){\n\tif((number % 7 === 0) & (number % 5 === 0))\n\t{\n\t\tconsole.log(true);\n\t}\n\telse\n\t{\n\t\tconsole.log(false);\n\t}\n}", "function divisibleByB(a, b) {\n\treturn a - a % b + b;\n}", "function areBothOdd(num1, num2) {\n // your code here\n return ((num1 % 2) && (num2 % 2) !== 0) ? true : false;\n}", "function isXEvenlyDivisibleByY(x, y) {\n if ( x % y === 0) {\n\t return true;\n\t} else {\n\t return false;\n\t}\n}", "function isDiv (number) {\n var number;\n if (number % 3 === 0 && number % 5 === 0) {\n \treturn \"BOTH\";\n \t} \n\telse if (number % 3 === 0) { \n return \"THREE\";\n \t} \n\telse if (number % 5 === 0){\n return \"FIVE\";\n \t}\n \telse {\n return number;\n }\n}", "function evenNumbers(numbers) {\n return numbers % 2 == 0;\n\n}", "function is_odd_or_div_by_7(number)\n{\n\treturn(number % 7 == 0 || number % 2 != 0)\n}", "function multipleOfFive(num){\n return num%5 === 0 \n}", "function divisible(arr) {\n\tlet sum = 0;\n\tlet prod = 1;\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tsum += arr[i];\n\t\tprod *= arr[i];\n\t}\n\n\tif (prod % sum === 0) {\n\t\treturn true;\t\t\t\n\t} else return false;\n}", "function isWhole(a, b, c, d) {\n return ((a + b + c + d) / 4) % 1 === 0;\n // let avg = sum / arguments.length;\n // return (avg % 1 === 0)\n}", "function threeOdds(number1, number2) {\n var count = 0;\n for (i = number1 + 1; i < number2; i++) {\n if (i % 2 !== 0) {\n count++\n }\n }\n if (count > 2) {\n return true;\n } else {\n return false\n }\n}", "function divisibleBy(numbers, divisor) {\n return numbers.filter(x => x % divisor === 0);\n}", "function hasDivisableBy5(array) {\n\tvar bool = false;\n\tarray.forEach(function(number) {\n\t\tif(number % 5 === 0) {\n\t\t\tbool = true;\n\t\t} \n\t});\n\treturn bool;\n}", "function abcmath(a, b, c) {\n\treturn ((a * b) % c === 0);\n}", "function is_even(num){\n if(num % 2 == 0){\n return true;\n }\n return false;\n}", "function complicatedMath(n1,n2,n3,n4){\n return (n1+n2) % (n3-n4)\n}", "function isEitherEven(num1, num2) {\n // your code here\n return ((num1 % 2) === 0 || (num2 % 2) === 0) ? true : false;\n}", "function isOdd(n) {if(!isNaN(n)){return n % 2 !== 0}}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Modal code Scene Modal: Edit a Scene
function openSceneModal(sceneID) { if (sceneMap.has(sceneID)) { // components let sceneModalTitle = document.getElementById('scene-modal-title'); let sceneModalBody = document.getElementById('scene-modal-body'); let sceneModalFooter = document.getElementById('scene-modal-footer'); let sceneComponentTitle = document.getElementById(`${sceneID}-title`); let sceneNameDiv = document.getElementById('scene-name'); let sceneIDDiv = document.getElementById('scene-id'); let sceneDescriptionDiv = document.getElementsByClassName('ql-editor')[0]; // fetching details sceneDetails = sceneMap.get(sceneID); // filling scene details sceneModalTitle.innerText = sceneDetails['name']; sceneNameDiv.value = sceneDetails['name']; sceneIDDiv.innerText = sceneDetails['id']; sceneDescriptionDiv.innerHTML = sceneDetails['description']; // save details let saveButton = document.createElement('button'); saveButton.id = 'save-scene-details-button'; saveButton.className = 'button is-info'; saveButton.innerText = 'Save Details'; saveButton.onclick = function() { let updatedDetails = { name: sceneNameDiv.value, id: sceneIDDiv.innerText, description: sceneDescriptionDiv.innerHTML }; sceneMap.set(sceneID, updatedDetails); // setting text of scene sceneComponentTitle.innerText = updatedDetails['name']; closeSceneModal(); }; sceneModalFooter.innerHTML = ''; sceneModalFooter.appendChild(saveButton); // data set, toggle display on let modal = document.getElementById('scene-modal'); modal.style.display = 'block'; } }
[ "function openEditChoicesForSceneModal(sceneID) {\n if (sceneMap.has(sceneID)) {\n // components\n let modalTitle = document.getElementById('edit-choices-for-scene-modal-title');\n let modalBody = document.getElementById('edit-choices-for-scene-modal-body');\n let modalFooter = document.getElementById('edit-choices-for-scene-modal-footer');\n\n // set the title\n let sceneName = sceneMap.get(sceneID)['name'];\n modalTitle.innerText = `${sceneName} choices`;\n modalBody.innerHTML = '';\n\n // display all the forward choices with edit and delete options\n let choiceCount = 0;\n\n if (forwardChoiceMap.has(sceneID)) {\n for (let [key, value] of forwardChoiceMap.get(sceneID)) {\n let choices = value['choices'];\n\n for (let choice of choices) {\n let choiceID = choice['choiceID'];\n\n if (choiceMap.has(choiceID)) {\n let choiceDetails = choiceMap.get(choiceID);\n \n const id = choiceDetails['id'];\n const name = choiceDetails['name'];\n const description = choiceDetails['description'];\n const toSceneID = choiceDetails['toSceneID'];\n const toSceneName = sceneMap.get(toSceneID)['name'];\n\n // create a div and append\n let choiceDiv = document.createElement('div');\n choiceDiv.className = 'notification is-light is-danger'\n\n let content = `\n <div class='level'>\n <div class='level-left'>\n <div class='tags has-addons'>\n <span class='tag is-danger is-rounded'>${id}</span>\n <span class='tag is-white is-rounded'>${name}</span>\n </div>\n </div>\n <div class='level-right'>\n <div class='button level-item is-small is-rounded' id='${choiceID + '-edit-button'}'>Edit</div>\n <div class='button level-item is-small is-rounded' id='${choiceID + '-delete-button'}'>Delete</div>\n </div>\n </div>\n <div class='level'>\n <div class='level-left'>\n <strong>To Scene ID:</strong>\n <div class=\"tags has-addons\" style=\"margin-left: 15px;\">\n <span class=\"tag is-rounded is-info\">${toSceneID}</span>\n <span class=\"tag is-rounded is-white\">${toSceneName}</span>\n </div>\n </div>\n </div>\n <div class='notification is-light is-danger has-text-centered'>\n ${(description === '')?'No description for the choice':description}\n </div>\n `;\n \n choiceDiv.innerHTML = content;\n\n modalBody.appendChild(choiceDiv);\n\n let editButton = document.getElementById((choiceID + '-edit-button'));\n editButton.onclick = function() {\n closeEditChoicesForSceneModal();\n openChoiceModal(choiceID);\n };\n\n let deleteButton = document.getElementById((choiceID + '-delete-button'));\n deleteButton.onclick = function() {\n closeEditChoicesForSceneModal();\n deleteChoice(choiceID);\n openEditChoicesForSceneModal(sceneID);\n };\n\n choiceCount++;\n }\n }\n }\n }\n\n if (choiceCount == 0)\n modalBody.innerHTML = `<div class=\"notification is-light is-danger\">No <strong>choices</strong> are associated with this scene.</div>`;\n\n let modal = document.getElementById('edit-choices-for-scene-modal');\n modal.style.display = 'block';\n }\n}", "_addRestoreButton(){\n this.add(this.options, 'restore').name('Restore').onChange((value) => {\n if (this.isView3D) {\n this.threeRenderer.center3DCameraToData(this.dataHandler);\n }else{\n this.threeRenderer.center2DCameraToData(this.dataHandler);\n }\n });\n }", "function goToEdit() {\n\thideCardContainer();\n\thideArrows();\n\thideFlashcard();\n\thideInput();\n\thideScoreboard();\n\n\tdisplayEditContainer();\n\tdisplayEditControls();\n\tupdateEditTable();\n\tupdateDeckName();\n}", "function openEditor() {\n let card = cards.get(editId)\n $(\".card-editor-container\").removeClass(\"invisible\")\n $(\"#card-text-input\").val(card.text)\n $(\"#card-text-input\").focus()\n\n // Reattach the card that should be edited\n card.node.appendTo($(\".card-editor-card-display\"))\n }", "editMentor() {}", "function updateDescription(scene) {\n const textTag = document.getElementById(\"text\");\n textTag.innerText = scene.text;\n}", "function Edit (view, clb) {\n\n view.on('edit', function () {\n\n var editNode = document.createElement('div');\n editNode.setAttribute('x-context', 'edit');\n\n ContentElement(\n {\n el: editNode,\n id: view.getId(),\n storage: view.storage,\n templates: view.templates\n },\n function () {\n dialog(editNode).overlay().show();\n }\n );\n\n });\n\n clb();\n}", "function AbrirModalsEditarNutricionista(){\n $('#modals_nutricionista_editar').modal({backdrop:'static',keyboard:false});\n $('#modals_nutricionista_editar').modal('show');\n \n}", "sceneSwitcher(t, args) {\n if (args.prep) {\n // fade out\n this.ecs.getSystem(System.Fade).request(1, 500);\n // ask for the legit scene switch\n let nextArgs = {\n prep: false,\n increment: args.increment,\n };\n this.firer.dispatch({\n name: Events.EventTypes.SwitchScene,\n args: nextArgs,\n }, 500);\n }\n else {\n // do the legit scene switch\n let increment = args.increment || 1;\n this.sceneManager.switchToRelative(increment);\n }\n }", "function presentScene(scene) {\n currentScene = scene;\n __presentScene(scene.nativeScene);\n}", "function loadModifyCode(scene) {\r\n loadScriptWithinContext(\"../modify.mjs\", scene);\r\n}", "editProgram(event) {\n event.preventDefault();\n const { dispatch, match: { params: { idLanding } } } = this.props;\n const { selectedId, program } = this.state;\n dispatch(actions.editElement('programas', selectedId, program, actions.fetchPrograms(idLanding)));\n this.closeModal('modalEdit');\n }", "function openModal(self) {\n\n console.log(self.bloqueEdit.data.title, this);\n self.controladorHTML.modalEdit.container.className = 'dia-show dia dia-nuevo-evento-container dia-defecto-container';\n self.controladorHTML.modalEdit.title.value = self.bloqueEdit.data.title;\n self.controladorHTML.modalEdit.id.value = self.bloqueEdit.id;\n\n function returnHoraFormat(hh) {\n var hh = new Fecha(hh);\n var anio = hh.getFullYear();\n var dia = hh.getDate();\n var mes = hh.getMonth() < 9 ? \"0\" + (hh.getMonth() + 1) : hh.getMonth() + 1;\n var fullAnio = mes + \"/\" + dia + \"/\" + anio;\n var startMinute = hh.getMinutes();\n startMinute = startMinute <= 9 ? \"0\" + startMinute : startMinute;\n var startHour = hh.getHours();\n startHour = startHour <= 9 ? \"0\" + startHour : startHour;\n return fullAnio + ' ' + startHour + ':' + startMinute;\n }\n self.controladorHTML.modalEdit.start.value = returnHoraFormat(self.bloqueEdit.start);\n self.controladorHTML.modalEdit.end.value = returnHoraFormat(self.bloqueEdit.end);\n }", "function editNote(){\n\t\n\tvar moment = require('alloy/moment');\n\t\n\tvar note= myNotes.get(idNote);\n\tnote.set({\n\t\t\"noteTitle\": $.noteTitle.value,\n\t\t\"noteDescription\": $.noteDescription.value,\n\t\t\"date\": moment().format()\n\t}).save();\n\t\n\tvar toast = Ti.UI.createNotification({\n\t\t \t\t\t \tmessage:\"Note has been succesfully saved\",\n\t\t \t\t\tduration: Ti.UI.NOTIFICATION_DURATION_SHORT\n\t\t\t\t\t\t});\n\t\t\t\t\t\t\n\t\t\t\ttoast.show();\n\tAlloy.Collections.note.fetch();\n\t\n $.detailnote.close();\n\t\t\n}", "function changeSkinMap(){\n $('#modalSkinMap').modal('open');\n}", "function editWord() {\r\n var entry = idLookUp(parseInt(this.getAttribute('data-id'), 10));\r\n\r\n //set data key for modal\r\n document.querySelector(\"#edit-confirm\").setAttribute('data-id', entry.Id);\r\n\r\n //edit row\r\n var row = document.querySelector(\"#row_\" + entry.Id);\r\n\r\n //set default text in input fields to word values\r\n document.querySelector(\"#edit-text\").innerHTML = \"Edit the word \" + row.childNodes[0].innerHTML;\r\n document.getElementsByName(\"word-edit\")[0].value = row.childNodes[0].innerHTML;\r\n document.getElementsByName(\"pronunciation-edit\")[0].value = row.childNodes[1].innerHTML;\r\n document.getElementsByName(\"part-of-speech-edit\")[0].value = row.childNodes[2].innerHTML;\r\n document.getElementsByName(\"definition-edit\")[0].value = row.childNodes[3].innerHTML;\r\n}", "function setScene(sceneName) {\n scene = sceneName;\n switch (sceneName) {\n case \"main_menu\":\n mainMenuScreen();\n break;\n case \"game_level\":\n startGame(); // Sets up game variables\n break;\n case \"game_over\":\n gameOverScreen();\n break;\n default:\n console.error(\"Invalid scene name: \" + sceneName);\n break;\n }\n}", "editPointViewClick() {\n this.deselectAllTabs();\n\n this.editPointViewTab.className = \"WallEditor_EditPointViewTab selected\";\n this.viewController = this.editPointView;\n\n this.selectCurrentTab();\n }", "function happycol_presentation_theShow(args){\n\tif(args.stageManager==true){\n\t\thappycol_stageManager(args);\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Profile Info AJAX request handler (ABOVE) / Categories Section AJAX request handler (BELOW) Handle app.get("/acccategories",...). Extract categories info from database and send it to clientside to display it correctly.
function getCategoryInfo(req, res) { /* This is a nested SQL query, and the description is following: * 1) Get uid using email in session * 2) Using uid to get ccid and cnames with pcids as references. * 3) Get JOIN with ParentCategory * 4) Filter with uid again to get only corresponding uid's categories. * Then forward the result to client. */ var query = "SELECT pcid, pname, ccid, cname " + "FROM (SELECT pc.uid, pc.pcid, pc.pname, cc.ccid, cc.cname " + "FROM ParentCategory AS pc " + "LEFT JOIN (SELECT ccid, cname, pcid " + "FROM ChildCategory " + "WHERE uid=?) AS cc " + "ON pc.pcid=cc.pcid) AS category " + "WHERE uid=?"; var uid = req.body.uid; if (!uid) uid = req.session.uid; var queryVal = [uid, uid]; database.query(req, res, query, queryVal, getCategoryInfoHandler, function(){}); }
[ "function updateCat() {\n\tfunction getCatCallback(event) {\n\t\tvar jsonData = JSON.parse(event.target.responseText);\n\t\tfor(var c in jsonData) {\n\t\t\tvar newCatDiv = document.createElement(\"div\");\n\t\t\tvar label = document.createElement(\"label\");\n\t\t\tvar input = document.createElement(\"input\");\n\t\t\tlabel.appendChild(document.createTextNode(jsonData[c]));\n\t\t\tlabel.setAttribute(\"for\", (jsonData[c]+\"checkbox\"));\n\t\t\tnewCatDiv.appendChild(label);\n\t\t\tinput.setAttribute(\"type\", \"checkbox\");\n\t\t\tinput.setAttribute(\"value\", jsonData[c]);\n\t\t\tinput.setAttribute(\"id\", (jsonData[c]+\"checkbox\"));\n\t\t\tinput.setAttribute(\"checked\", \"checked\");\n\t\t\tnewCatDiv.appendChild(input);\n\t\t\tcatDivPt1.appendChild(newCatDiv);\n\t\t\tdocument.getElementById(jsonData[c]+\"checkbox\").addEventListener(\"click\", updateCatDisplays, false);\n\n\t\t\tvar newOption = document.createElement(\"option\");\n\t\t\tnewOption.appendChild(document.createTextNode(jsonData[c]));\n\t\t\teditCatSelect.appendChild(newOption);\n\n\t\t\tnewOption = document.createElement(\"option\");\n\t\t\tnewOption.appendChild(document.createTextNode(jsonData[c]));\n\t\t\tcategorySelect.appendChild(newOption);\n\t\t}\n\t\tvar newCatDiv = document.createElement(\"div\");\n\t\tvar label = document.createElement(\"label\");\n\t\tvar input = document.createElement(\"input\");\n\t\tlabel.appendChild(document.createTextNode(\"uncategorized\"));\n\t\tlabel.setAttribute(\"for\", \"uncategorizedcheckbox\");\n\t\tnewCatDiv.appendChild(label);\n\t\tinput.setAttribute(\"type\", \"checkbox\");\n\t\tinput.setAttribute(\"value\", \"uncategorized\");\n\t\tinput.setAttribute(\"id\", \"uncategorizedcheckbox\");\n\t\tinput.setAttribute(\"checked\", \"checked\");\n\t\tnewCatDiv.appendChild(input);\n\t\tcatDivPt1.appendChild(newCatDiv);\n\t\tdocument.getElementById(\"uncategorizedcheckbox\").addEventListener(\"click\", updateCatDisplays, false);\n\n\t\t// lists categories in the drop-down menus \n\t\t// in the popup and in the edit category section\n\t\tvar newOption = document.createElement(\"option\");\n\t\tnewOption.appendChild(document.createTextNode(\"none\"));\n\t\tnewOption.setAttribute(\"selected\", \"selected\");\n\t\tcategorySelect.appendChild(newOption);\n\t\t\n\t\tcatDivPt1.style.display = \"block\";\n\t\tcatDivPt2.style.display = \"block\";\n\n\t\tupdateCatDisplays();\n\t}\n\n\t// clears all category checkboxes\n\twhile (catDivPt1.firstChild) {\n\t\tcatDivPt1.firstChild.removeEventListener(\"click\", updateCatDisplays);\n\t catDivPt1.removeChild(catDivPt1.firstChild);\n\t}\n\t// clears all categories listed in edit category section\n\twhile (editCatSelect.firstChild) {\n\t editCatSelect.removeChild(editCatSelect.firstChild);\n\t}\n\t// clears all categories listed in popup\n\twhile (categorySelect.firstChild) {\n\t categorySelect.removeChild(categorySelect.firstChild);\n\t}\n\t// if a user is currently logged in, loads categories that user has\n\tif(currentUser != \"\") {\n\t\tvar secXmlHttp = new XMLHttpRequest();\n\t\tsecXmlHttp.open(\"POST\", \"getcategories_ajax.php\", true);\n\t\tsecXmlHttp.setRequestHeader(\"Content-Type\", \"application/x-www-form-urlencoded\");\n\t\tsecXmlHttp.addEventListener(\"load\", getCatCallback, false);\n\t\tsecXmlHttp.send();\n\t}\n\telse {\n\t\tcatDivPt1.style.display = \"none\";\n\t\tcatDivPt2.style.display = \"none\";\n\t}\n}", "function selectCategory(event)\n{\n var category = jQuery(this).attr('ref');\n if (null != categoryTreeCash[category])\n {\n _updateSubCategoryPad(category, categoryTreeCash[category]);\n }\n else\n {\n jQuery.ajax({\n url: '/cash-register/index/get-categories/category/' + category,\n type: \"GET\",\n dataType: \"html\",\n success: function(response) {\n updateSubCategoryPad(response, category);\n },\n error: function(xhr, status) {\n alert('ERROR ' + status);\n }\n });\n }\n}", "function loadCategoriesAndNews(){\r\n\t$.ajax({\r\n\t type: \"GET\",\r\n\t url: wp_service_route_categories + \"?limit=\" + category_no_limit,\r\n\t dataType: \"json\",\r\n\t success: function (data) {\t \t\r\n\t \t$.each(data,function(i,category){\r\n\t \t\t$(\".top_nav\").append($(\"<li/>\").append($(\"<a/>\", {\r\n\t \t\t \"href\": \"#cat=\" + category.id,\r\n\t \t\t \"class\": \"nav_link\",\r\n\t \t\t \"text\": category.title\r\n\t \t\t})));\r\n\t \t\t$(\".top_nav\").append($(\"<li/>\", { \"class\": \"divider-vertical\" }));\r\n\t \t});\r\n\t \tif (window.location.toString().indexOf(\"#cat=\", 0) > 0){\r\n\t \t\tvar current_doc = \"\";\r\n\t \t\tcurrent_doc = window.location.toString().substring(window.location.toString().lastIndexOf(\"#cat=\")+5,window.location.toString().length).toLowerCase();\r\n\t \t\tswitch(current_doc)\r\n\t \t\t{\r\n\t \t\t\tcase \"\":\r\n\t \t\t\t\tloadDoc(\"home.html\");\r\n\t \t\t\t\tsetActiveClass(\"home\");\r\n\t \t\t\t\tbreak;\r\n\t \t\t\tcase \"home\":\r\n\t \t\t\t\tloadDoc(\"home.html\");\r\n\t \t\t\t\tsetActiveClass(\"home\");\r\n\t \t\t\t\tbreak;\r\n\t \t\t\tcase \"aboutus\":\r\n\t \t\t\t\tloadDoc(\"aboutus.html\");\r\n\t \t\t\t\tsetActiveClass(\"\");\r\n\t \t\t\t\tbreak;\r\n\t \t\t\tcase \"contactus\":\r\n\t \t\t\t\tloadDoc(\"contactus.html\");\r\n\t \t\t\t\tsetActiveClass(\"\");\r\n\t \t\t\t\tbreak;\r\n\t \t\t\tdefault:\r\n\t \t\t\t\tloadDoc(\"news.html\");\r\n\t \t\t\t\tsetActiveClass(current_doc);\r\n\t \t\t\t\tbreak;\r\n\t \t\t}\r\n\t \t}\r\n\t \telse if (window.location.toString().indexOf(\"#newsid=\", 0) > 0){\r\n\t \t\tloadDoc(\"news_detail.html\");\r\n\t \t}\r\n\t \telse {\r\n\t \t\tloadDoc(\"home.html\");\r\n\t \t\tsetActiveClass(\"home\");\r\n\t \t} \r\n\t },\r\n\t error: function(){\r\n\t \tloadDoc(\"error.html\");\r\n\t }\r\n\t});\r\n}", "function fetchcategories() {\n API.getCategories().then(res => {\n const result = res.data.categories;\n console.log(\"RESULT: \", result);\n // alert(result[1].name);\n if (res.data.success == false) {\n } else {\n\n setFetchedCategories(res.data.categories);\n }\n }).catch(error => console.log(\"error\", error));\n }//end of fetch categories from backend", "function loadCategory (url) {\n\t$.getJSON( url + '/main_page/build_category', function(data){\n\t\t// console.log(data);\n\t\t// console.log(data[1].type);\n\t\t// console.log(data.length);\n\n\t\t// ALL VIDEOS\n\t\tvar outputVideo = '';\n\t\tfor (var i=0; i < data.length; i++) {\n\t\t\toutputVideo += generateVideoTags(data[i],url);\n\t\t};\n\n\t\t// CATEGORIES\n\t\tvar outputType = \"<p class=\\\"lead\\\"></p><div id=\\\"category\\\" class=\\\"list-group\\\">\";\n\t\toutputType += \"<a href=\\\"nominations.html\\\" class=\\\"list-group-item\\\" style=\\\"color:red\\\">Athlete Nominations</a>\";\n\t\toutputType += \"<a href=\\\"all_type.html\\\" class=\\\"list-group-item\\\">Trending</a>\";\n\t\toutputType += \"<a href=\\\"\" + data[0].type + \".html\\\" class=\\\"list-group-item\\\">\" + data[0].type + \"</a>\";\n\t\tfor (var i=1; i < data.length; i++) {\n\t\t\tif(data[i].type != data[i-1].type){\n\t\t\t\toutputType += \"<a href=\\\"\"+ data[i].type +\".html\\\" class=\\\"list-group-item\\\">\";\n\t\t\t\toutputType += data[i].type;\n\t\t\t\toutputType += \"</a>\";\n\t\t\t}\n\t\t}\n\t\t\toutputType += \"</div>\";\n\t\t\t// console.log(outputVideo);\n\n\t\t\t// LOAD\n\t\t\t$('#list_category').html(outputType);\n\t\t\t$('#list_video').html(outputVideo);\n\t\t\t\n\t\t$('#list_category').mouseenter(loadVideoByCategory(data, url));\n\t\n\t}) // getJSON end \n}", "function populateTable() {\n $.ajax({\n url: '/api/categories',\n type: 'GET',\n success: (res) => {\n if (res.code !== 200) {\n confirm(res.msg);\n return;\n }\n\n let categories = res.data;\n if (categories.length === 0) {\n return;\n }\n processTableHTML(categories);\n }\n });\n}", "function retrieveLcDetails_FromMongoDB(Lc_Id, Client_Request, currentUser, currentUserType) {\n\n var xmlhttp;\n var httpRequestString = webServerPrefix;\n\n xmlhttp = new XMLHttpRequest();\n httpRequestString += \"Client_Request=\" + Client_Request;\n httpRequestString += \"&\";\n httpRequestString += \"Lc_Id=\" + Lc_Id;\n\n xmlhttp.open(\"POST\", httpRequestString, true);\n xmlhttp.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n xmlhttp.setRequestHeader(\"accept\", \"application/json\");\n\n // Wait for Async response and Handle it in web page\n\n xmlhttp.onreadystatechange = function () {\n\n if (this.status == 200) {\n\n if (this.readyState == 4) {\n\n //Parse the JSON Response Object\n\n responseObject = JSON.parse(this.response);\n\n if (bDebug == true) {\n\n alert(\"All the LC Details for LC Id => \" + Lc_Id + \" : \" + responseObject);\n }\n\n // Check the inclusiveness of Lc-Id ( to see if it belongs to Current User )\n\n if (currentUser != null && currentUser != undefined && currentUserType != null && currentUserType != undefined) {\n\n if (currentUser == responseObject[currentUserType]) {\n\n fillTheLCStatusDetailsPage(responseObject);\n\n } else {\n\n alert(\"LC_Id : \" + Lc_Id +\" doesn't belong to Current user : \" + currentUser);\n }\n\n } else {\n\n alert(\"Incorrect User Name/Type in current User Context\");\n }\n\n } else {\n\n if (bDebug == true) {\n\n alert(\"Intermediate Success Response while placing RetrieveLCDetails call :=> Status : \" + this.status + \" readyState : \" + this.readyState);\n }\n }\n\n } else {\n\n alert(\"Failure to place RetrieveLCDetails call :=> Status : \" + this.status + \" readyState : \" + this.readyState);\n }\n\n };\n\n if (bDebug == true) {\n\n alert(\"Retrieving the LC detais from mongoDB => httpRequest : \" + httpRequestString);\n }\n xmlhttp.send();\n\n }", "function updateCategories(data){\n let categoryLinks = document.querySelectorAll(\"nav.categoryNav > ul\");\n\n for(const linkSection of categoryLinks) {\n $(linkSection).empty();\n\n for (const category of data) {\n $(linkSection).append(`<li><a href=\"searchProducts.php?cat=${category.CategoryID}\">${category.CategoryName}</a></li>`);\n }\n\n }\n}", "function getCatalog() {\n btAPI = \"https://www.berkeleytime.com/api/grades/grades_json/?form=long\";\n const request = $.ajax({url: btAPI}).done(function (response) {\n var catalog = response.courses;\n\n // Creates map from key to course_id, for faster retrieval\n toCourseIDS = new Map();\n for(let key in catalog) {\n var value = catalog[key];\n\n // Key is a combination of course Abbr/Number/Title\n var courseTitle = value.title;\n var courseAbbr = value.abbreviation.replace(new RegExp(\"\\\\s+\", \"g\"), \"\");\n var courseNum = value.course_number;\n var courseKey = courseAbbr + courseNum + courseTitle.toLowerCase().replace(new RegExp(\"\\\\s+\", \"g\"), \"\");\n\n toCourseIDS.set(courseKey, value.id);\n }\n\n addInfo();\n })\n .fail(function (Response) {\n // Fails to get catalog, continue to RMP with dummy map\n toCourseIDS = new Map();\n addInfo();\n });;\n}", "function getCourses() {\n //create data object which will act as payload in AJAX request to server side code\n var data = {};\n //check if there is a URL param to act as a filter server side\n if (getParameterByName('c') != undefined) {\n //if there is a URL param called c add it to the data payload\n data.c = getParameterByName('c');\n }\n //send AJAX request to server to retrieve courses\n $.ajax({\n url: 'php/getCourses.php',\n type: 'post',\n dataType: 'json',\n data: data,\n success: function(data) {\n\n /*\n data model returned is an array of objects. each object is modelled like so:\n {\n courseTypeId:NUMBER,\n courseTypeTitle:STRING,\n courses:ARRAY[\n {\n courseId:NUMBER,\n courseTitle:STRING\n }\n ]\n }\n */\n\n //clear the course select menu of exisitng options\n $('#course').html('');\n //start adding elements to the #course select menu\n $('#course').append('<option value=\"\">Select a course...</option>');\n //loop thru each object in the array of results of AJAX request\n var numCourseTypes = data.length;\n for (var i = 0; i < numCourseTypes; i++) {\n //start concatenating the optgroup string\n var optGroup = '<optgroup label=\"' + data[i].courseTypeTitle + '\">';\n //now loop thru each course in the objects's courses array\n var numCourses = data[i].courses.length;\n for (var c = 0; c < numCourses; c++) {\n //add an option for each course\n optGroup += '<option value=\"' + data[i].courses[c].courseId + '\">' + data[i].courses[c].courseTitle + '</option>';\n }\n //complete the optgroup string\n optGroup += '</optgroup>';\n //add it to the select menu\n $('#course').append(optGroup);\n\n }\n //add 'chosen' jquery plugin functionality to the select menu\n //$('#course').chosen(config);\n $(\"#course\").selectmenu();\n },\n error: function(h, m, s) {\n console.log(m);\n }\n });\n }", "function hook_firewall_categories() {\n let cat_select = $(\"#fw_category\");\n ajaxCall('/api/firewall/category/searchNoCategoryItem', {}, function(data){\n if (data.rows !== undefined && data.rows.length > 0) {\n let color_map = {};\n for (let i=0; i < data.rows.length ; ++i) {\n if (data.rows[i].color != \"\") {\n color_map[data.rows[i].name] = data.rows[i].color;\n }\n }\n let category_count = {};\n $(\".rule\").each(function(){\n let row = $(this);\n $(this).data('category').toString().split(',').forEach(function(item){\n if (category_count[item] === undefined) {\n category_count[item] = 0 ;\n }\n category_count[item] += 1;\n if (color_map[item] !== undefined) {\n // suffix category color in the description td\n let td = row.find('td.rule-description');\n if (td.length > 0) {\n td.append($(\"<i class='fa fa-circle selector-item' title='\"+item+\"'/>\").css('color', '#'+color_map[item]));\n }\n }\n });\n });\n for (let i=0; i < data.rows.length ; ++i) {\n let opt_val = $('<div/>').html(data.rows[i].name).text();\n let option = $(\"<option/>\");\n let bgcolor = data.rows[i].color != \"\" ? data.rows[i].color : '31708f;'; // set category color\n if (category_count[data.rows[i].name] != undefined) {\n option.data(\n 'content',\n \"<span>\"+opt_val + \"</span>\"+\n \"<span style='background:#\"+bgcolor+\";' class='badge pull-right'>\"+\n category_count[data.rows[i].name]+\"</span>\"\n );\n }\n cat_select.append(option.val(opt_val).html(data.rows[i].name));\n }\n }\n cat_select.selectpicker('refresh');\n // remove text class preventing sticking badges to the right\n $('#category_block span.text').removeClass('text');\n // hide category search when not used\n if (cat_select.find(\"option\").length == 0) {\n cat_select.addClass('hidden');\n } else {\n let tmp = [];\n if (window.sessionStorage && window.sessionStorage.getItem(\"firewall.selected.categories\") !== null) {\n tmp = window.sessionStorage.getItem(\"firewall.selected.categories\").split(',');\n }\n cat_select.val(tmp);\n }\n\n cat_select.change(function(){\n if (window.sessionStorage) {\n window.sessionStorage.setItem(\"firewall.selected.categories\", cat_select.val().join(','));\n }\n let selected_values = cat_select.val();\n let no_cat = cat_select.find(\"option\")[0].value;\n $(\".rule\").each(function(){\n let is_selected = false;\n $(this).data('category').toString().split(',').forEach(function(item){\n if (selected_values.indexOf(no_cat) > -1 && item === \"\") {\n // No category for this rule\n is_selected = true;\n }\n if (selected_values.indexOf(item) > -1) {\n is_selected = true;\n }\n });\n if (!is_selected && selected_values.length > 0) {\n $(this).hide();\n $(this).find(\"input\").prop('disabled', true);\n } else {\n $(this).find(\"input\").prop('disabled', false);\n $(this).show();\n }\n });\n $(\".opnsense-rules\").change();\n });\n cat_select.change();\n $('.selector-item').tooltip();\n });\n}", "function getStaffByGender(url)\n {\n \n jQuery.getJSON( url, function( response ){\n\n var profileHTML = '<ul class=\"inst-profile\">';\n $.each(response, function(index, profile){\n if(jQuery.isEmptyObject(profile)){\n console.log(\"empty\");\n $('#new-content').html(\"No matching record available\");\n }\n else{\n \n \n //generate HTML to display added information\n profileHTML+= '<li> ' + profile.fullname + ' </li>';\n //profileHTML+= '<li>' + profile.category_name + ' </li>';\n // profileHTML+= '<li><strong>COUNTRY OF LOCATION: </strong> ' + profile.nationality + ' </li>';\n // profileHTML+= '<li><strong>STATE OF LOCATION:</strong> ' + profile.state_name + ' </li>';\n // profileHTML+= '<li><strong>LGA of Location:</strong> ' + profile.lga + ' </li>';\n // profileHTML+= '<li><strong>CITY: </strong> ' + profile.city_name + ' </li>';\n // profileHTML+= '<li><strong>INSTITUTION ADDRESS:</strong> ' + profile.inst_add + ' </li>';\n // profileHTML+= '<li><strong>INSTITUTION MOBILE: </strong> ' + profile.inst_mobile + ' </li>';\n // profileHTML+= '<li><strong>INSTITUTION LOGO:</strong> ' + ' <img class=\"headerImage mr-3\" src=\"'+logo+'\" height=\"40\" width=\"40\"></li>';\n }\n });\n profileHTML+='</ul>';\n $('#new-content').html(profileHTML);\n\n });\n \n }", "function getMembersForCategory(category, parentMemberId) {\n\tvar data = {\n\t\tcategory : category,\n\t\tparentMemberId : parentMemberId\n\t}\n\t\n\tvar postRequest = $.post('ReadMembers', data);\n\t\n\t// Populate the server response in the given response element\n\tpostRequest.done( function(responseData) {\n\t\tshowElementIfHidden(\"selectExistingMembers\");\n\t $('#' + category + 'List').html(responseData);\n\t $('#' + category).show();\n\t});\n\t\n\t// Notify user that a request to the server failed\n\tpostRequest.error( function(responseData) {\n\t\t$('#result').empty().append(\"<font size='4' color='red'>\" +\n\t\t\"There was issue processing the request. Try again or contact administrator</font>\").show();\n\t});\n}", "function displayCategoryNameInNotes() {\n\tfor (var noteId in catNA) {\n\t\t$('#notecat-' + noteId).html($('#catname-' + catNA[noteId]).html());\n\t}\n}", "function recent_activity_ajax(category_id,from_date,to_date,request) {\n jQuery(\".loading\").show();\n jQuery.ajax({\n type: \"GET\",\n url: \"/dashboard\",\n data: {\n category_id: category_id,\n from_date: from_date,\n to_date: to_date,\n request: request,\n status: \"tab_ajax\"\n },\n success: function() {\n jQuery(\".loading\").hide();\n\n }\n });\n return false;\n}", "function getCategorias(){\n $.ajax({\n url:ruta, // la URL para la petición\n data:\"categoria=null\",\n type: 'POST', // especifica si será una petición POST o GET\n dataType: 'json', // el tipo de información que se espera de respuesta\n success: function(data) { \n // código a ejecutar si la petición es satisfactoria; // la respuesta es pasada como argumento a la función\n // guardar=json;\n categorias = [];\n for (var x = 0 ; x < data.length ; x++) {\n categorias.push(new Ccategoria(data[x].id,data[x].nombre));\n }\n },\n // código a ejecutar si la petición falla;: los parámetros sonunobjeto jqXHR(extensión de XMLHttpRequest), un untexto con el estatus de la petición y un texto con la descripción del error que haya dado el servidor\n error : function(jqXHR, status, error) { \n alert('Disculpe, existió un problema'); \n }\n });\n}", "function getBlogCollectionList()\n { \n $.ajax(\"/navbar/blogcollectionlist/checkout\", {\n method: \"get\",\n })\n .done(function (data)\n {\n var $blogCollectionList = $(\"#blog-colleciton-list\");\n for (var idx = 0; idx < data.length; idx++)\n {\n $blogCollectionList.append('<li><a href=/index?pageNum=1&blogCollectionId=' + data[idx]._id+ '>' + data[idx].title + '</a></li>');\n }\n \n })\n .fail(function (xhr, status)\n {\n \n });\n }", "function req_wiki_category (string) {\r\n var url =\r\n \"https://en.wikipedia.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:\"+string+\"&cmlimit=100&cmsort=sortkey&format=json&callback=?\"; \r\n $.ajax({\r\n url: url,\r\n type: \"GET\",\r\n async: false,\r\n dataType: \"jsonp\",\r\n success: function(data)\r\n {\r\n \r\n var i = 0;\r\n var ar = new Array();\r\n for(i; i<21; i++) \r\n { \r\n \r\n //funzione per avere elementi random sulla home\r\n var item = data['query']['categorymembers'][Math.floor(Math.random()*data['query']['categorymembers'].length)];\r\n\r\n if(jQuery.inArray(item.title, ar) != -1)\r\n {\r\n while(jQuery.inArray(item.title, ar) != -1)\r\n {\r\n item = data['query']['categorymembers'][Math.floor(Math.random()*data['query']['categorymembers'].length)];\r\n }\r\n }\r\n else {\r\n ar.push(item.title);\r\n }\r\n \r\n $('#categories').append('<div class=\"col-lg-4\"><img id=\"img'+i+'\" class=\"rounded-circle\" width=\"140\" height=\"140\"><h2>'+item.title+'</h2><p><a class=\"btn btn-secondary\" id=\"cat_btn\" name=\"'+item.title+'\" href=\"http://marullo.cs.unibo.it:8000/home/search:'+item.title+'\" role=\"button\">View page &raquo;</a></p></div>'); \r\n get_img_title(item.title,item.pageid, i);\r\n }\r\n },\r\n error: function() \r\n {\r\n alert('Error: req_wiki_category');\r\n }\r\n });\r\n }", "function getPeople(){\n $.ajax({\n url:'/bios',\n type: 'GET',\n success:appendPerson\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Chapter 101 RopeGroup Reveal the twins
function C101_KinbakuClub_RopeGroup_RevealTwins() { C101_KinbakuClub_RopeGroup_TwinsRevealed = true; ActorSpecificConcealment("Heather", false); ActorSpecificConcealment("Lucy", false); }
[ "function C101_KinbakuClub_RopeGroup_WillLucyTie() {\n\tif (ActorGetValue(ActorLove) >= 3 || ActorGetValue(ActorSubmission) >= 2) {\n\t\tOverridenIntroText = GetText(\"LucyNotTieYou\");\n\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 600;\n\t} else C101_KinbakuClub_RopeGroup_PlayerTied();\n}", "function C101_KinbakuClub_RopeGroup_FriendOfAFriend() {\n\tif (ActorGetValue(ActorLove) >= 3) {\n\t\tOverridenIntroText = GetText(\"StayRightThere\");\n\t\tC101_KinbakuClub_RopeGroup_NoActor()\n\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 661;\n\t}\n}", "function C101_KinbakuClub_RopeGroup_PlayerWhimperLucy() {\n\tif (C101_KinbakuClub_RopeGroup_LucyIsAnnoyed <= 0) {\n\t\tPlayerUngag();\n\t\tActorChangeAttitude( 1, -1)\n\t} else {\n\t\tif (C101_KinbakuClub_RopeGroup_LucyIsAnnoyed >= 2 || ActorGetValue(ActorLove) >= 1) {\n\t\t\tOverridenIntroText = GetText(\"AnnoyedNoUngag\");\n\t\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 640;\n\t\t} else {\n\t\t\tPlayerUngag();\n\t\t\tOverridenIntroText = GetText(\"AnnoyedUngag\");\n\t\t}\n\t}\n}", "function C101_KinbakuClub_RopeGroup_Run() {\n\tBuildInteraction(C101_KinbakuClub_RopeGroup_CurrentStage);\n\t\n\t// changing images\n\t// Group view\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 100) {\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupAmelia.png\", 600, 20);\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupCharlotte.jpg\", 818, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupTwinLeftStart.png\", 985, 98);\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwinStatus == \"Released\" || C101_KinbakuClub_RopeGroup_RightTwinStatus == \"Released\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupTwinFree.png\", 1005, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_RightTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupTwinRightStart.png\", 847, 110);\n\t}\n\n\t// Twins image after releasing one of them\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 430) {\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwin == \"Lucy\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/LeftTwin.jpg\", 600, 0);\n\t\telse DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RightTwin.jpg\", 600, 0);\n\t}\n\tif ((C101_KinbakuClub_RopeGroup_CurrentStage >= 600 && C101_KinbakuClub_RopeGroup_CurrentStage <= 631) || (C101_KinbakuClub_RopeGroup_CurrentStage >= 700 && C101_KinbakuClub_RopeGroup_CurrentStage <= 710) || C101_KinbakuClub_RopeGroup_CurrentStage == 900) {\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinLeftStillTied.png\", 600, 167);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage <= 700) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinJustReleased.png\", 750, 5);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 710) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinReleased.png\", 750, 5);\n\t\tif (C101_KinbakuClub_RopeGroup_RightTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinRightStillTied.png\", 930, 230);\n\t}\n\n\t// During Tsuri Kinbaku (Suspension)\n\t// Suspended1\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 633) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended1BallGag.jpg\", 878, 94);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended1ClothGag.jpg\", 878, 94);\n\t}\n\t// Suspended2\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 634) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended2BallGag.jpg\", 904, 105);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended2ClothGag.jpg\", 904, 105);\n\t}\n\t// Suspended3\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 635) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended3BallGag.jpg\", 890, 105);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended3ClothGag.jpg\", 890, 105);\n\t}\n\t// Suspended4\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 636 && C101_KinbakuClub_RopeGroup_CurrentStage <= 660) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended4BallGag.jpg\", 863, 125);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended4ClothGag.jpg\", 863, 125);\n\t}\n\t// Suspended5\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 661 && C101_KinbakuClub_RopeGroup_CurrentStage <= 662) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5BallGag.jpg\", 865, 126);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5ClothGag.jpg\", 865, 126);\n\t\tif (PlayerHasLockedInventory(\"TapeGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5TapeGag.jpg\", 865, 126);\n\t}\n\n\t//Suspended\n\tif ((C101_KinbakuClub_RopeGroup_CurrentStage >= 636 && C101_KinbakuClub_RopeGroup_CurrentStage <= 642) || (C101_KinbakuClub_RopeGroup_CurrentStage >= 650 && C101_KinbakuClub_RopeGroup_CurrentStage <= 690)) {\n\t\t// Player images\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 672 && C101_KinbakuClub_RopeGroup_PlayerPose != \"\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/\" + C101_KinbakuClub_RopeGroup_PlayerPose + \".jpg\", 835, 75);\n\t\tif (PlayerHasLockedInventory(\"ChastityBelt\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended4ChastityBelt.jpg\", 880, 290);\n\t\tif (C101_KinbakuClub_RopeGroup_TsuriFrogTied) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5FrogTie.png\", 769, 231);\n\t\tif (C101_KinbakuClub_RopeGroup_FullyExposed) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5Pantieless.jpg\", 880, 294);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 662) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5LookUp.png\", 864, 136);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 671 && PlayerHasLockedInventory(\"SockGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended8S.jpg\", 888, 157);\n\t\t\n\t\t// Cassi iamges\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 662) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5Cassi1.png\", 948, 65);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 666) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_InspectBelt.jpg\", 842, 72);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 667) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_InspectKey.jpg\", 842, 72);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 668) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_RemovingBelt.jpg\", 842, 72);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 672) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_LeftHoldingTape.jpg\", 608, 70);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 673) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_Scissors.png\", 700, 77);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 674) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_KneelDown.png\", 660, 120);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 674 && ActorGetValue(ActorSubmission) >= 0) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_KneelDownCuffs.png\", 776, 403);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 675 && C101_KinbakuClub_RopeGroup_CurrentStage <= 686){\n\t\t\tif (C101_KinbakuClub_RopeGroup_PressingCassi) {\n\t\t\t\tif (ActorHasInventory(\"Cuffs\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniCuffedPressed.png\", 770, 230);\n\t\t\t\telse {\n\t\t\t\t\tif (C101_KinbakuClub_RopeGroup_fingerinsertion) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniFingerPressed.png\", 770, 230);\n\t\t\t\t\telse DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniPressed.png\", 770, 230);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (C101_KinbakuClub_RopeGroup_ForcingCassi) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniCuffedStruggle.png\", 770, 230);\n\t\t\t\telse {\n\t\t\t\t\tif (C101_KinbakuClub_RopeGroup_AnkleGrab) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniAnkleHold.png\", 770, 230);\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (ActorHasInventory(\"Cuffs\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniCuffed.png\", 825, 251);\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tif (C101_KinbakuClub_RopeGroup_fingerinsertion) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniFinger.png\", 825, 251);\n\t\t\t\t\t\t\telse DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_Cunni.png\", 825, 251);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 687) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_Done.png\", 835, 73);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 687 && ActorHasInventory(\"Cuffs\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_DoneCuffs.png\", 874, 193);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 688 && C101_KinbakuClub_RopeGroup_CurrentStage <= 689) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_DoneBelt.png\", 835, 63);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 690) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_DoneBelted.png\", 835, 66);\n\t\t\n\n\t\t// Lucy images\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 662 && C101_KinbakuClub_RopeGroup_CurrentStage <= 665) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5Lucy.png\", 629, 51);\n\t\t\n\t\t// Player arousal\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 675 && C101_KinbakuClub_RopeGroup_CurrentStage <= 680) {\n\t\t\tif (C101_KinbakuClub_RopeGroup_PreviousTime == 0) C101_KinbakuClub_RopeGroup_PreviousTime = CurrentTime;\n\t\t\tif (CurrentTime > (C101_KinbakuClub_RopeGroup_PreviousTime + 1000)) {\n\t\t\t\tC101_KinbakuClub_RopeGroup_PreviousTime = CurrentTime;\n\t\t\t\tC101_KinbakuClub_RopeGroup_PlayerArousal++;\n\t\t\t\tif (ActorGetValue(ActorSubmission) < 0) C101_KinbakuClub_RopeGroup_PlayerArousal++;\n\t\t\t\tif (PlayerHasLockedInventory(\"VibratingEgg\")) C101_KinbakuClub_RopeGroup_PlayerArousal++;\n\t\t\t}\n\t\t\tif (C101_KinbakuClub_RopeGroup_PlayerArousal > 500) {\n\t\t\t\tC101_KinbakuClub_RopeGroup_PlayerArousal = 500;\n\t\t\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 681\n\t\t\t\tOverridenIntroText = GetText(\"SuspendedOrgasm\");\n\t\t\t}\n\t\t}\n\t\t// Draw the players arousal level\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 675 && C101_KinbakuClub_RopeGroup_CurrentStage <= 681) {\n\t\t\tDrawRect(638, 48, 14, 504, \"white\");\n\t\t\tDrawRect(640, 50, 10, (500 - C101_KinbakuClub_RopeGroup_PlayerArousal), \"#66FF66\");\n\t\t\tDrawRect(640, (550 - C101_KinbakuClub_RopeGroup_PlayerArousal), 10, C101_KinbakuClub_RopeGroup_PlayerArousal, \"red\");\n\t\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 300) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Gushing.png\", 601, 2);\n\t\t}\n\t}\n\t\n\t// Images when Hether uses nipple clamps\n\tif ((C101_KinbakuClub_RopeGroup_CurrentStage >= 800 && C101_KinbakuClub_RopeGroup_CurrentStage <= 841) || C101_KinbakuClub_RopeGroup_CurrentStage == 850) {\n\t\tif (C101_KinbakuClub_RopeGroup_NipplesExposed) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/WithHeatherExposed.jpg\", 600, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_NippleClamped) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/WithHeatherNippleClamped.jpg\", 600, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_HeatherTugging) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/WithHeatherNippleTug.jpg\", 600, 0);\n\t\tif (!C101_KinbakuClub_RopeGroup_Expression == \"\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/\" + C101_KinbakuClub_RopeGroup_Expression + \".jpg\", 1040, 280);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 830) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/HeatherGone.jpg\", 600, 392);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 841) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/JennaIntervene.jpg\", 600, 0);\n\t}\n\n\t// Images during plug play\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 854 && C101_KinbakuClub_RopeGroup_Clentched) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/PluggingClentch.jpg\", 617, 354);\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 855) {\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Plugged.jpg\", 900, 110);\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Plugged\" + C101_KinbakuClub_RopeGroup_PlugMood + \".jpg\", 617, 354);\n\t}\n}", "function C101_KinbakuClub_RopeGroup_Run() {\n\tBuildInteraction(C101_KinbakuClub_RopeGroup_CurrentStage);\n\t\n\t// changing images\n\t// Group view\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 100) {\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupAmelia.png\", 600, 20);\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupCharlotte.jpg\", 818, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupTwinLeftStart.png\", 985, 98);\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwinStatus == \"Released\" || C101_KinbakuClub_RopeGroup_RightTwinStatus == \"Released\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupTwinFree.png\", 1005, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_RightTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupTwinRightStart.png\", 847, 110);\n\t}\n\n\t// Twins image after releasing one of them\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 430) {\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwin == \"Lucy\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/LeftTwin.jpg\", 600, 0);\n\t\telse DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RightTwin.jpg\", 600, 0);\n\t}\n\tif ((C101_KinbakuClub_RopeGroup_CurrentStage >= 600 && C101_KinbakuClub_RopeGroup_CurrentStage <= 631) || (C101_KinbakuClub_RopeGroup_CurrentStage >= 700 && C101_KinbakuClub_RopeGroup_CurrentStage <= 710) || C101_KinbakuClub_RopeGroup_CurrentStage == 900) {\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinLeftStillTied.png\", 600, 167);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage <= 700) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinJustReleased.png\", 750, 5);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 710) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinReleased.png\", 750, 5);\n\t\tif (C101_KinbakuClub_RopeGroup_RightTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinRightStillTied.png\", 930, 230);\n\t}\n\n\t// Images during Tsuri Kinbaku (Suspension)\n\t// Suspended1\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 633) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended1BallGag.jpg\", 878, 94);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended1ClothGag.jpg\", 878, 94);\n\t}\n\t// Suspended2\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 634) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended2BallGag.jpg\", 904, 105);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended2ClothGag.jpg\", 904, 105);\n\t}\n\t// Suspended3\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 635) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended3BallGag.jpg\", 890, 105);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended3ClothGag.jpg\", 890, 105);\n\t}\n\t// Suspended4\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 636) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended4BallGag.jpg\", 863, 125);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended4ClothGag.jpg\", 863, 125);\n\t\tif (PlayerHasLockedInventory(\"ChastityBelt\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended4ChastityBelt.jpg\", 880, 290);\n\t}\n\t\n\t// Images when Hether uses nipple clamps\n\tif ((C101_KinbakuClub_RopeGroup_CurrentStage >= 800 && C101_KinbakuClub_RopeGroup_CurrentStage <= 841) || C101_KinbakuClub_RopeGroup_CurrentStage == 850) {\n\t\tif (C101_KinbakuClub_RopeGroup_NipplesExposed) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/WithHeatherExposed.jpg\", 600, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_NippleClamped) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/WithHeatherNippleClamped.jpg\", 600, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_HeatherTugging) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/WithHeatherNippleTug.jpg\", 600, 0);\n\t\tif (!C101_KinbakuClub_RopeGroup_Expression == \"\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/\" + C101_KinbakuClub_RopeGroup_Expression + \".jpg\", 1040, 280);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 830) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/HeatherGone.jpg\", 600, 392);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 841) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/JennaIntervene.jpg\", 600, 0);\n\t}\n\n\t// Images during plug play\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 854 && C101_KinbakuClub_RopeGroup_Clentched) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/PluggingClentch.jpg\", 617, 354);\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 855) {\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Plugged.jpg\", 900, 110);\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Plugged\" + C101_KinbakuClub_RopeGroup_PlugMood + \".jpg\", 617, 354);\n\t}\n}", "function mousePressed() {\n toggle++;\n toggle = toggle % 3;\n for (var i = 0; i < tendrilsPerMonster; i++) {\n tendrils.push(new Tendril());\n }\n}", "updateWinners() {\n const winners = [...this.continuing]\n .filter(candidate => this.count[this.round][candidate] >= this.thresh[this.round]);\n if (!winners.length) return; // no winners\n\n const text = this.newWinners(winners);\n this.roundInfo[this.round].winners = text;\n }", "function C101_KinbakuClub_RopeGroup_ReleaseTwin() {\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 400) C101_KinbakuClub_RopeGroup_LeftTwinStatus = \"Released\";\n\telse C101_KinbakuClub_RopeGroup_RightTwinStatus = \"Released\";\n\tif (ActorGetValue(ActorName) == \"Lucy\") C101_KinbakuClub_RopeGroup_LucyFree = true;\n\tC101_KinbakuClub_RopeGroup_CurrentStage = 700;\n}", "function C101_KinbakuClub_RopeGroup_AddedExtras(ExtraNumber) {\n\tif (ExtraNumber == 1 && ActorGetValue(ActorSubmission) >= 3) {\n\t\tOverridenIntroText = GetText(\"NotBelted\");\n\t\tC101_KinbakuClub_RopeGroup_PlayerFreed()\n\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 691;\n\t} else {\n\t\tif (!PlayerHasLockedInventory(\"VibratingEgg\") && !PlayerHasLockedInventory(\"ButtPlug\")) {\n\t\t\tPlayerLockInventory(\"VibratingEgg\");\n\t\t\tPlayerLockInventory(\"ButtPlug\");\n\t\t} else {\n\t\t\tif (!PlayerHasLockedInventory(\"VibratingEgg\")) {\n\t\t\t\tPlayerLockInventory(\"VibratingEgg\");\n\t\t\t\tif (ExtraNumber == 1) OverridenIntroText = GetText(\"ArgueEggNBelted\");\n\t\t\t\telse OverridenIntroText = GetText(\"EggNBelted\");\n\t\t\t} else {\n\t\t\t\tif (!PlayerHasLockedInventory(\"ButtPlug\")) {\n\t\t\t\t\tPlayerLockInventory(\"ButtPlug\");\n\t\t\t\t\tif (ExtraNumber == 1) OverridenIntroText = GetText(\"ArguePlugNBelted\");\n\t\t\t\t\telse OverridenIntroText = GetText(\"PlugNBelted\");\n\t\t\t\t} else {\n\t\t\t\t\tif (ExtraNumber == 1) OverridenIntroText = GetText(\"ArgueJustBelted\");\n\t\t\t\t\telse OverridenIntroText = GetText(\"JustBelted\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tC101_KinbakuClub_RopeGroup_FullyExposed = false;\n\t\tPlayerLockInventory(\"ChastityBelt\");\n\t}\n}", "function C101_KinbakuClub_RopeGroup_HelplessStruggle() {\n\tif (Common_PlayerChaste) OverridenIntroText = GetText(\"ChasteStruggle\");\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 830) C101_KinbakuClub_RopeGroup_WaitingForMistress();\n\telse C101_KinbakuClub_RopeGroup_HelplessTime();\n}", "function C101_KinbakuClub_RopeGroup_HelplessKnot() {\n\tif (Common_PlayerChaste) OverridenIntroText = GetText(\"ChasteKnot\");\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 830) C101_KinbakuClub_RopeGroup_WaitingForMistress();\n\telse C101_KinbakuClub_RopeGroup_HelplessTime();\n}", "function showNotes() {\n\t\tnotes.forEach(function(note) {\n\t\t\t// first position the notes randomly on the page\n\t\t\tpositionNote(note);\n\t\t\t// now, animate the notes torwards the button\n\t\t\tanimateNote(note);\n\t\t});\n\t}", "function otherLoansNextLoan() {\n \n // TO DO\n // move to the next loan\n \n}", "function happycol_presentation_play(args){\n\thappycol_assignments(args, function(){\n\t\thappycol_presentation_beginShow(args);\n\t});\n\t\n}", "function completeRevealPhase () {\n /* reveal everyone's hand */\n for (var i = 0; i < players.length; i++) {\n if (players[i] && !players[i].out) {\n determineHand(i);\n showHand(i);\n }\n }\n \n /* figure out who has the lowest hand */\n recentLoser = determineLowestHand();\n console.log(\"Player \"+recentLoser+\" is the loser.\");\n \n /* look for the unlikely case of an absolute tie */\n if (recentLoser == -1) {\n console.log(\"Fuck... there was an absolute tie\");\n /* inform the player */\n \n /* hide the dialogue bubbles */\n for (var i = 1; i < players.length; i++) {\n $gameDialogues[i-1].html(\"\");\n $gameAdvanceButtons[i-1].css({opacity : 0});\n $gameBubbles[i-1].hide();\n }\n \n /* reset the round */\n $mainButton.html(\"Deal\");\n $mainButton.attr('disabled', false);\n if (players[HUMAN_PLAYER].out && AUTO_FORFEIT) {\n setTimeout(advanceGame, FORFEIT_DELAY);\n }\n return;\n }\n \n /* update behaviour */\n\tvar clothes = playerMustStrip (recentLoser);\n updateAllGameVisuals();\n \n /* highlight the loser */\n for (var i = 0; i < players.length; i++) {\n if (recentLoser == i) {\n $gameLabels[i].css({\"background-color\" : loserColour});\n } else {\n $gameLabels[i].css({\"background-color\" : clearColour});\n }\n }\n \n /* set up the main button */\n\tif (recentLoser != HUMAN_PLAYER && clothes > 0) {\n\t\t$mainButton.html(\"Continue\");\n\t} else {\n\t\t$mainButton.html(\"Strip\");\n\t}\n if (players[HUMAN_PLAYER].out && AUTO_FORFEIT) {\n setTimeout(advanceGame,FORFEIT_DELAY);\n }\n}", "function showRiddle()\n{\n\tvar riddle = document.getElementById('riddle');\n\t\n\t//Between 0 and 9\n\tvar diced = Dice.start();\n\t\n\triddle.innerHTML = MyRiddles.GetInfo(diced, \"riddle\");\n}", "function revealLyrics(title, lyrics) {\r\n qs(\"#modal h2\").innerText = title;\r\n qs(\"#modal p\").innerText = lyrics;\r\n $(\"modal\").classList.remove(\"hidden\");\r\n }", "function ctlout_advance(clipnum) {\n\toutlet(0, 'stop');\n\t// outlet(1, 'none');\n\t// outlet(0, 'dispose');\n}", "function setupJoke() {\n randomKnockKnockJoke().forEach( stageOfJoke => {\n conversationBacklog.push(stageOfJoke)\n })\n \n}", "function displayPlayingPiecesTwo() {\n document.querySelectorAll('.pieces2').forEach(function(el) {\n el.style.display = 'grid';\n });\n displayPlayAgainButton();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the error if this is an Err result, otherwise null.
getError() { return !this.isOk ? this.value : null; }
[ "function firstMessage(errors) {\n if (!Array.isArray(errors) || errors.length === 0) return null;\n\n var error = errors[0];\n if (error.message) {\n return error.message;\n } else {\n return error;\n }\n}", "function error(id) {\n var item = itemDictionary()[id];\n if (item && item.inputValue && item.inputValue.error) {\n return item.inputValue.error();\n }\n }", "error() {\n return this._send(format.apply(this, arguments), SysLogger.Severity.err);\n }", "errorView() {\n var table = this.table;\n var reg = this.getReg();\n return this.singleLine(table, reg.errorFetchingData);\n }", "function firstOk(results) {\r\n return results.find(isOk) || error(null);\r\n}", "function error(err) {\n if (error.err) return;\n callback(error.err = err);\n }", "function getErrorService() {\n // If we're sure there's a proper error service already, simply return that.\n if (cacheErrorService) {\n return cacheErrorService;\n }\n\n // Try and fetch our global error service.\n const ErrorService = global.ErrorService;\n // Ensure the fetched error service matches the expected service interface, returning `null` if not.\n if (\n !(ErrorService instanceof Object)\n || !(ErrorService.isError instanceof Function) || !(ErrorService.isErrorGroup instanceof Function)\n || !(ErrorService.createError instanceof Function) || !(ErrorService.groupErrors instanceof Function)\n ) {\n return null;\n }\n\n // We've a good error service present! Set the cached service so we can avoid some checks later on (micro-opt).\n cacheErrorService = ErrorService;\n return ErrorService;\n}", "function convertJavaErrno(errCode) {\n if (errCode === 0) {\n return null;\n }\n return ErrorCodes.get().toString(errCode);\n}", "findErrorMessage(errorCode) {\n return this.errorMessageCollection[this.languageCode][errorCode];\n }", "function getErrorField(_fieldKey) {\n\n // console.log('++++fieldKey', _fieldKey);\n\n var errorField;\n var fieldKey;\n if (_.contains(_fieldKey, 'ui-select-extended')) {\n errorField = _fieldKey.split('ui-select-extended_')[1];\n fieldKey = errorField.split('_')[0];\n } else {\n if (_fieldKey.startsWith('obs')) {\n errorField = _fieldKey.split('obs')[1];\n fieldKey = 'obs' + errorField.split('_')[0] + '_' + errorField.split('_')[1];\n }\n }\n\n var field = FormentryService.getFieldByIdKey(fieldKey, $scope.vm.tabs);\n // console.log('error Field ', field);\n return field;\n }", "getTotalError() {\n return this._totalError;\n }", "get isError() {\n return (this.flags & 4) /* NodeFlag.Error */ > 0\n }", "isErrorState() {\r\n const gl = this.gl;\r\n return gl === null || gl.getError() !== gl.NO_ERROR;\r\n }", "function getJavaErrno(ne) {\n if (ne instanceof OSException) {\n return ne.getStringCode();\n }\n return Constants.EIO;\n}", "function haveOutputErr() {\n return OUTPUT_ERROR;\n}", "get stack() {\n \t\treturn extractStacktrace(this.errorForStack, 2);\n \t}", "function getErrorMessage(errorCode) {\n var Error = {};\n Error[errorCode] = 'Please try again';\n Error[errorCode] = 'Please try again';\n Error[errorCode] = 'Database version Error';\n Error[errorCode] = 'Data too large Error';\n Error[errorCode] = 'Data quota Error';\n Error[errorCode] = 'Syntax Error';\n Error[errorCode] = 'User name is already present in the database';\n Error[errorCode] = 'Timeout Error';\n return Error[errorCode];\n }", "get message() {\n return this.result.message;\n }", "function handleGetUserMediaError (err) {\n util.trace(err)\n\n switch (err.name) {\n case 'NotFoundError':\n alert('Unable to open your call because no camera and/or microphone were found.')\n break\n case 'SecurityError':\n case 'PermissionDeniedError':\n // Do nothing; this is the same as the user canceling the call.\n break\n default:\n alert('Error opening your camera and/or microphone: ' + err.message)\n break\n }\n}", "setError(error) {\n if (error === this.getError()) return\n const { form, path } = this.props\n if (form && path) return form.setError(path, error)\n else {\n this._error = error\n this.forceUpdate()\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function creates the xhttp request "/jobpostings/displayJobPostings" and sends it to the server. The response text is put into a div with id="jobPreivew"
function loadJobs() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("jobPreview").innerHTML = this.responseText; } }; xhttp.open("GET", "/jobpostings/displayJobPostings", true); xhttp.send(); }
[ "function show_packing_jobs() {\n \tvar xhttp = new XMLHttpRequest();\n \txhttp.onreadystatechange = function () {\n \t\tif (this.readyState == 4 && this.status == 200) {\n \t\t\tvar obj = JSON.parse(this.responseText);\n \t\t\t$('#packing').append(mangaerJobCard(obj));\n \t\t\tlet status = $('#packing div:first').attr('card_status');\n \t\t\tif (status != undefined) {\n \t\t\t\t$('#show_status_Packing').text(status);\n \t\t\t\t// console.log(obj);\n \t\t\t\t// \tmangaerJobCard(obj);\n \t\t\t} else {\n \t\t\t\t$('#show_status_Packing').text('0');\n \t\t\t}\n \t\t}\n \t};\n \txhttp.open(\"GET\", baseUrl + \"Management/Management_jc_packing\", true);\n \txhttp.send();\n\n }", "function show_delevered_jobs() {\n \tvar xhttp = new XMLHttpRequest();\n \txhttp.onreadystatechange = function () {\n \t\tif (this.readyState == 4 && this.status == 200) {\n \t\t\tvar obj = JSON.parse(this.responseText);\n \t\t\t$('#delevered').append(mangaerJobCard(obj));\n \t\t\tlet status = $('#delevered div:first').attr('card_status');\n \t\t\t// \t\t console.log(status);\n \t\t\tif (status != undefined) {\n \t\t\t\t$('#show_status_Delevery').text(status);\n \t\t\t\t// console.log(obj);\n \t\t\t\t// \tmangaerJobCard(obj);\n \t\t\t} else {\n \t\t\t\t$('#show_status_Delevery').text('0');\n \t\t\t}\n\n \t\t}\n \t};\n \txhttp.open(\"GET\", baseUrl + \"Management/packed_jc\", true);\n \txhttp.send();\n\n }", "function packing_alterd_job() {\n\tlet form = new FormData();\n\tform.append('status', QC_Three_Alter);\n\n\tvar xhttp = new XMLHttpRequest();\n\txhttp.onreadystatechange = function () {\n\t\tif (this.readyState == 4 && this.status == 200) {\n\t\t\tvar obj = JSON.parse(this.responseText);\n\t\t\t$('#packing_altred_job_card_view').append(loadAlterdJobCard(obj));\n\t\t}\n\t};\n\txhttp.open(\"POST\", baseUrl + \"Qc2/rejcted_job_card_list\", true);\n\txhttp.send(form);\n}", "function show_issues(){\r\n\t\t\tvar xhttp = new XMLHttpRequest();\r\n\t\t\txhttp.onreadystatechange = function(){\r\n\t\t\t\tif(this.readyState == 4 && this.status == 200){\r\n\t\t\t\t\tdocument.getElementById('issues').innerHTML = this.responseText;\r\n\t\t\t\t}\r\n\t\t\t};\r\n\t\t\txhttp.open(\"POST\", \"getissues.php\", true);\r\n\t\t\txhttp.send();\r\n}", "function createJobs(jsongObj) {\n container.innerHTML = \"\";\n container.appendChild(createFilterElement());\n for (let i = 0; i < jsongObj.length; i++) {\n //create job div and assign job class to it\n const job = document.createElement('div');\n job.setAttribute('class', 'job');\n //create logo element and append it to the job div\n const logo = document.createElement('img');\n logo.setAttribute('src', jsongObj[i].logo);\n job.appendChild(logo);\n //create job info div\n const jobInfo = document.createElement('div');\n jobInfo.setAttribute('class', 'job-info');\n\n //-----------------------------------------\n //create top info div\n const topInfo = document.createElement('div');\n topInfo.setAttribute('class', 'top-info');\n //create company name span\n const companyName = document.createElement('span');\n companyName.setAttribute('class', 'company-name');\n companyName.textContent = jsongObj[i].company;\n topInfo.appendChild(companyName);\n //create new span\n if (jsongObj[i].new) {\n const newElement = document.createElement('span');\n newElement.setAttribute('class', 'new');\n newElement.textContent = \"New!\";\n topInfo.appendChild(newElement);\n }\n //create featured span\n if (jsongObj[i].featured) {\n const featured = document.createElement('span');\n featured.setAttribute('class', 'featured');\n featured.textContent = \"Featured\";\n topInfo.appendChild(featured);\n job.classList.add('featured');\n }\n \n jobInfo.appendChild(topInfo);\n \n //create job title element \n const position = document.createElement('h2');\n position.setAttribute('class', 'position');\n position.textContent = jsongObj[i].position;\n \n jobInfo.appendChild(position);\n\n //--------------------------------\n //create down info div\n const downInfo = document.createElement('div');\n downInfo.setAttribute('class', 'down-info');\n\n //create postedAt span\n const postedAt = document.createElement('span');\n postedAt.setAttribute('class', 'date');\n postedAt.textContent = jsongObj[i].postedAt;\n downInfo.appendChild(postedAt);\n\n //create contract span\n const contract = document.createElement('span');\n contract.setAttribute('class', 'contract');\n contract.textContent = jsongObj[i].contract;\n downInfo.appendChild(contract);\n\n //create location span\n const location = document.createElement('span');\n location.setAttribute('class', 'location');\n location.textContent = jsongObj[i].location;\n downInfo.appendChild(location);\n\n jobInfo.appendChild(downInfo);\n\n //append job info div to job div\n job.appendChild(jobInfo);\n \n //create job tags div\n const jobTags = document.createElement('div');\n jobTags.setAttribute('class', 'job-tags');\n\n //create role span\n const role = document.createElement('span');\n role.setAttribute('class', 'job-tag');\n role.setAttribute('data-role', jsongObj[i].role);\n role.textContent = jsongObj[i].role;\n jobTags.appendChild(role);\n\n //create level span\n const level = document.createElement('span');\n level.setAttribute('class', 'job-tag');\n level.setAttribute('data-level', jsongObj[i].level);\n level.textContent = jsongObj[i].level;\n jobTags.appendChild(level);\n\n //create language spans\n const langs = jsongObj[i].languages;\n langs.forEach(element => {\n const lang = document.createElement('span');\n lang.setAttribute('class', 'job-tag');\n lang.setAttribute('data-lang', element);\n lang.textContent = element;\n jobTags.appendChild(lang);\n });\n\n //create tool spans\n const tools = jsongObj[i].tools;\n tools.forEach(element => {\n const tool = document.createElement('span');\n tool.setAttribute('class', 'job-tag');\n tool.setAttribute('data-tool', element);\n tool.textContent = element;\n jobTags.appendChild(tool);\n })\n\n //append job tags div to job div\n job.appendChild(jobTags);\n\n //append job div to container\n container.appendChild(job);\n }\n\n setJobTagEvent()\n}", "function startJob(jobid,onstarted)\n{\n var req = new XMLHttpRequest();\n req.onreadystatechange = function() {\n if (req.readyState == 4 && req.status == 200)\n {\n if (onstarted != null)\n {\n onstarted(jobid);\n }\n }\n }\n req.open(\"GET\",\"/api/solve-background?token=\"+jobid,true);\n req.send();\n}", "function submitProblemFile(data,name,onsubmit)\n{\n var req = new XMLHttpRequest();\n req.onreadystatechange = function() {\n if (req.readyState == 4 && req.status == 200)\n {\n var jobid = req.responseText;\n\n if (onsubmit != null)\n {\n onsubmit(name,jobid);\n }\n }\n }\n req.open(\"POST\",\"/api/submit?jobname=\"+name,true);\n req.send(data);\n}", "function displayJobDesc(btnID, title, date, company) {\n\n $(\".job-text\").hide();\n\n document.getElementById(\"selected-job-title\").innerHTML = title;\n document.getElementById(\"date-worked\").innerHTML = date;\n document.getElementById(\"company-name\").innerHTML = company;\n document.getElementById(\"job-desc-points\").innerHTML = \"\";\n \n if (btnID == 0) {\n description = '<li>Maintenance and development of Carmenta Map Builder product and Carmenta Engine Geospatial SDK (C++)</li>';\n description += '<li>Implemented support for 3D map packaging in Map Builder</li>';\n description += '<li>API refactoring and migration handling at runtime</li>';\n description += '<li>Testing and troubleshooting on Windows, Linux and Android platforms</li>';\n description += '<li>Automated and manual test development</li>';\n description += '<li>.NET, C#, MVVM Architecture, NUnit</li>';\n description += '\\n';\n description += '<li style=\"margin-top:20px;\">MSc Thesis Project (01/2021 - 07/2021) on the topic of multi-objective optimization. Published online on <a href=\" http://hdl.handle.net/2077/69356\">GUPEA</a>.</li>';\n \n document.getElementById(\"job-desc-points\").innerHTML = description;\n }\n\n if (btnID == 1) {\n description = '<li>Recommend opportunities for test automation using SQL and Batch scripts to improve workflows</li>';\n description += '<li>Provide QA services across DOMO and GIS systems verifying alignment in data and accuracy</li>';\n description += '<li>Remote work environment using agile development methodologies (JIRA and Kanban)</li>';\n description += '<li>Develop document templates for test plans and set standards for QA testing</li>';\n description += '<li>Ensure top quality address level data for the Broadband Networks team</li>';\n description += '<li>QA network and address data to ensure they are enabled correctly in internal systems</li>';\n description += '<li>Coordinate with peers and key business stakeholders to problem solve solutions</li>';\n document.getElementById(\"job-desc-points\").innerHTML = description;\n }\n\n if (btnID == 2) {\n description = '<li>Design and develop mobile applications for iOS and Android platforms from start to finish</li>';\n description += '<li>Development using Unity, Vuforia, Google Tango and C# for augmented reality applications</li>';\n description += '<li>3D modelling and visualization using TinkerCAD and Meshlab</li>';\n description += '<li>Professional consultations with clients to ensure that applications fully meet project requirements</li>';\n document.getElementById(\"job-desc-points\").innerHTML = description;\n }\n\n if (btnID == 3) {\n description = '<li>Set up, program and calibrate dataloggers and meteorological instrumentation</li>';\n description += '<li>Develop web-based GIS app using ArcGIS Online</li>';\n description += '<li>Create province-wide nitrous oxide GIS model using georeferenced crop and soils data</li>';\n description += '<li>Modify MATLAB functions and run statistical analysis</li>';\n description += '<li>Assist in field experiments using lysimeters and micrometeorological methods</li>';\n document.getElementById(\"job-desc-points\").innerHTML = description;\n }\n\n if (btnID == 4) {\n description = '<li>Use ArcGIS to display georeferenced Water and Wastewater datasets and perform spatial queries and analysis</li>';\n description += '<li>Use Python, VBA, and ArcPy to update the GIS with accurate watermain capital planning data</li>';\n description += '<li>Calculate asset replacement costs, remaining life of assets, and perform risk analysis</li>';\n description += '<li>Input, organize, and analyze data from site visits using asset management software created by the Region</li>';\n description += '<li>Involved in the development of Condition Assessment protocols within the Region\\'s asset management group</li>';\n description += '<li>Nominated for the 2015 Co-op Student of the Year award for my work ethic and productivity</li>';\n document.getElementById(\"job-desc-points\").innerHTML = description;\n }\n\n if (btnID == 5) {\n description = '<li>Review Site Plan and Rezoning applications and provide environmental conditions of approval</li>';\n description += '<li>Review and evaluate Environmental Site Assessments (Phase I and II), Site Remediation reports and Geotechnical reports and provide input to Municipal Servicing Agreements</li>';\n description += '<li>Conduct professional site visits to monitor spills and to enforce the Storm Sewer Use By-law</li>';\n description += '<li>Represent the Environmental Services Section at numerous public outreach events to educate citizens about stormwater and water quality</li>';\n document.getElementById(\"job-desc-points\").innerHTML = description;\n }\n $(\".job-text\").fadeIn(\"slow\");\n }", "function showResults(pingdomChecks, pingdomOutages, res, req){\r\n\tvar content =\r\n '<div class = \"checks\">'+\r\n \t'<h1>Pingdom Checks</h1>'+\r\n \tpingdomChecks+\r\n \t'<h1>Outage List</h2>'+\r\n \tpingdomOutages+\r\n '</div>';\r\n\r\n output(content, res, req)\r\n}", "function renderJobsTable()\n{\n var data = globalJobList;\n var node = document.getElementById(\"jobs-table-body\");\n var tablenode = node.parentNode;\n tablenode.removeChild(node);\n\n // clear table\n {\n var n = node.firstElementChild;\n while (n != null)\n {\n var cn = n.nextElementSibling;\n node.removeChild(n)\n n = cn;\n }\n }\n\n if (data.length > 0)\n {\n for (var i = 0; i < data.length; ++i)\n {\n addJobRowAt(node,i);\n }\n }\n else\n {\n var tr = document.createElement(\"tr\");\n var td = document.createElement(\"td\"); td.setAttribute(\"colspan\",\"8\");\n var div = document.createElement(\"div\"); div.setAttribute(\"style\",\"margin : 10px 0px 10px 0px; text-align : center;\");\n div.appendChild(document.createTextNode(\"No entries\"));\n td.appendChild(div);\n tr.appendChild(td);\n node.appendChild(tr);\n\n rerenderSelection(node);\n }\n\n tablenode.appendChild(node);\n}", "#queueContent(){\n var completedID = this.serverKey + '_history';\n var completed = '<div class=\"queue_tasks\"><ul id=\"'+completedID+'\"></ul></div>';\n\n var uncompletedID = this.serverKey + '_queued';\n var uncompleted = '<div class=\"queue_tasks\"><ul id=\"'+uncompletedID+'\"></ul></div>';\n\n var currentID = this.serverKey + '_current';\n var current = '<span id=\"'+currentID+'\"></span>';\n\n var content = '<ul><li>'+ completed +'</li><hr>'+current+'<hr><li>'+ uncompleted +'</li></ul>';\n return content;\n }", "function update_queued_jobs(divid){\n var qj_url = '/job/queue';\n var qjAjax = new Ajax.Updater(divid, qj_url, {});\n}", "function featured_display() {\n\tif (window.XMLHttpRequest) {\n\t\treq = new XMLHttpRequest();\n\t} else {\n\t\treq = new ActiveXObject(\"Microsoft.XMLHTTP\");\n\t}\n\t\treq.open(\"POST\", \"/lists\", true);\n\t\treq.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\")\n\t\treq.send(\"type=featured_display\");\n\n\t\treq.onreadystatechange = function() {\n\t\tif (req.readyState==4 && req.status==200) {\n\t\t\tdocument.getElementById('featured-list').innerHTML = req.responseText;\n\t\t\t} else {\n\t\t}\n\t}\n}", "function responseReceived(e){\n document.getElementById('response').innerHTML = e.target.responseText;\n}", "function ProcessJobUpdate(page, process_name, show) {\n var id = process_name.split(\"_\")[1];\n $.ajax({\n type: \"POST\",\n url: '/Home/ProcessJobUpdate',\n data: { \"page\": page, \"processID\": id },\n success: function (data) {\n $('#fixed_info_content').html(data);\n var real_project_name = $(\"#\" + process_name + \" td\").eq(0).html();\n if (real_project_name !== null) {\n $('#fixed_info_tab').html(real_project_name);\n }\n\n //store process name (with the id)\n $('#fixed_info_tab').data(\"process_name\", process_name);\n\n if (show === true) {\n showFixedInfoTab();\n }\n },\n error: function (result) {\n alert(\"ProcessJobUpdate_err\");\n }\n });\n}", "function show_job(page, process_name) {\n // Save info of the opened tab\n msg_or_job = 'Job';\n ProcessJobUpdate(page, process_name, true);\n}", "function successFunction(res) {\n results.innerHTML = res.responseText;\n }", "function proxycontact(datein, dateout)\n{\t\n\t// instantiate XMLHttpRequest object\n\ttry\n\t{\n\t\txhr = new XMLHttpRequest();\n\t}\n\tcatch (e)\n\t{\n\t\txhr = new ActiveXObject(\"Microsoft.XMLHTTP\");\n\t}\n\t\n\t// handle old browsers\n\tif (xhr == null)\n\t{\n\t\talert(\"Ajax not supported by your browser!\");\n\t\treturn;\n\t}\n\t\n\t// construct URL\n\tvar url = \"availability.php?datein=\" + datein + \"&dateout=\" + dateout;\n\t\n\t// get the data back from proxy\n\txhr.onreadystatechange = function() {\n\t\n\t\t// only handle requests in \"loaded\" state\n\t\tif (xhr.readyState == 4)\n\t\t{\n\t\t\t// embed response in page if possible\n\t\t\tif (xhr.status == 200)\n\t\t\t{\n\t\t\t\t// hide progress\n \t\t\tdocument.getElementById(\"progress\").style.display = \"none\";\n \t\t\t\n \t\t\t// show the beginning of the table\n \t\t\t// document.getElementById('results').style.display = \"\";\n \n\t\t\t\t// to evaluate proxy's JSON response\n\t\t\t\t// example of how to parse ...\n\t\t\t\t// document.getElementById(\"checker\").innerHTML = newslocs[1][\"articles\"][1][\"title\"];\n\t\t\t\tvar vacancy = eval( xhr.responseText );\n\t\t\t\t\n\t\t\t\tvar tbllen = document.getElementById('resultsp').rows.length;\n\t\t\t\t\n\t\t\t\t// delete rows to make way for incoming\n\t\t\t\tif ( tbllen > 1) {\n\t\t\t\t\tfor (var del = 1; del < tbllen; del++) {\n\t\t\t\t\t\t\tdocument.getElementById('resultsp').deleteRow(1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// loop through the dates\n\t\t\t\tfor (var i = 1; i < vacancy[0] + 1; i++) {\n\t\t\t\t\t// how to write\n\t\t\t\t\tvar gid=document.getElementById('resultsp').insertRow(i);\n\t\t\t\t\tvar gidstyl = document.getElementById('resultsp')\n\t\t\t\t\t\n\t\t\t\t\t// write the values into the table\n\t\t\t\t\tgid.insertCell(0).innerHTML= vacancy[i][\"date\"];\n\t\t\t\t\tgidstyl.rows[i].cells[0].className = 'availtblleft';\n\t\t\t\t\t\n\t\t\t\t\t// loop through whether occupied or not\n\t\t\t\t\tfor (var j = 1, k = 0; j < 8; j++, k++) {\n\t\t\t\t\t\tif (vacancy[i][\"rooms\"][k] == \"Vacant\") {\n\t\t\t\t\t\t\t// to put the vacancy in the cell\n\t\t\t\t\t\t\tgid.insertCell(j).innerHTML= vacancy[i][\"rooms\"][k];\n\t\t\t\t\t\t\t// to make the cell pretty\n\t\t\t\t\t\t\tgidstyl.rows[i].cells[j].className = 'availtblcontvac';\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// EVENT LISTENER: to select the days we would like to stay\n\t\t\t\t\t\t\tgidstyl.rows[i].cells[j].addEventListener('click', function(event) {\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t// to make it pretty\n\t\t\t\t\t\t\t\tthis.style.backgroundColor = (this.style.backgroundColor != 'green' ? 'green' : 'white');\n\t\t\t\t\t\t\t\tthis.style.color = (this.style.color != 'white' ? 'white' : 'black');\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t// to collect the x and y value for where user clicked\n\t\t\t\t\t\t\t\tvar row = $(this).parent('tr');\n\t\t\t\t\t\t\t\tvar horizontal = $(this).siblings().andSelf().index(this);\n\t\t\t\t\t\t\t\tvar vertical = row.siblings().andSelf().index(row);\n\n\t\t\t\t\t\t\t\t// put date values into JSON, or remove them if background switched to white\n\t\t\t\t\t\t\t\troompicked[horizontal-1].datesavail[vertical-1] = (this.style.backgroundColor != 'green' ? undefined : vacancy[vertical][\"datesql\"]);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t// slide down the booking\n\t\t\t\t\t\t\t\tif (location.pathname != \"/reserve/index.php\") {\n\t\t\t\t\t\t\t\t\tdocument.getElementById('booking').style.display = \"\";\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t// and put the value into the form at the bottom of the page\n\t\t\t\t\t\t\t\tvar roompicked_text = JSON.stringify(roompicked);\n\t\t\t\t\t\t\t\tdocument.getElementById(\"jsondates\").value = roompicked_text;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t},false)\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t// to put the occupado in the cell\n\t\t\t\t\t\t\tgid.insertCell(j).innerHTML= \"Occupied\";\n\t\t\t\t\t\t\t// to make the cell pretty\n\t\t\t\t\t\t\tgidstyl.rows[i].cells[j].className = 'availtblcontocc';\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t}\n\t\t\telse\n\t\t\t\talert(\"Error with Ajax call!\");\n\t\t}\n\t\n\t};\n\txhr.open(\"GET\", url, true);\n\txhr.send(null);\n}", "function renderJobs() {\n return jobs.map(j =>\n { return <JobCard\n key={j.id}\n jobId={j.id}\n title={j.title}\n salary={j.salary}\n equity={j.equity}\n companyName={j.companyName} />});\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Turns all active blocks to 'used' and removes all 'shadows'
function makeUsed() { let blocks = document.getElementsByClassName('column'); for (let i = 0; i < blocks.length; i++) { if (blocks[i].hasAttribute('active')) { blocks[i].removeAttribute('active'); blocks[i].setAttribute('used', 'true'); } if (blocks[i].hasAttribute('shadow')) { blocks[i].removeAttribute('shadow'); } if (blocks[i].hasAttribute('pre')) { blocks[i].removeAttribute('pre'); } } }
[ "function unScareAlien(){\n aliens.forEach(alien => alien.isScared = false)\n }", "function clearBlock(){\n\tfor(var i = 0; i < 4; i++){\n\t\tif(currentBlock[i].x < 0 || currentBlock[i].y < 0){\n\t\t\tcontinue;\n\t\t}\n\t\tboardGui.rows[currentBlock[i].x].cells[currentBlock[i].y].style.backgroundColor = \"white\"; \n\t}\n}", "function UnspawnAll(){\n\t\tfor(var i = 0; i < all.Count; i++){\n\t\t\tvar obj : GameObject = all[i] as GameObject;\n\t\t\tif(obj.active)\n\t\t\t\tUnspawn(obj);\n\t\t}\n\t}", "function removeAllLights(){\r\n\r\n\tscene.remove(ambientLight);\r\n\tscene.remove(directionalLight);\r\n\tscene.remove(pointLight);\r\n\r\n}", "function cleanIntersected() {\n\n while ( intersections.length ) {\n\n let object = intersections.pop();\n object.material.emissive.r = 0;\n\n }\n\n}", "function clearBlocks(lineArray) {\n\n long.position = JSON.parse(JSON.stringify(longPos))\n tee.position = JSON.parse(JSON.stringify(teePos))\n zig.position = JSON.parse(JSON.stringify(zigPos))\n zag.position = JSON.parse(JSON.stringify(zagPos))\n square.position = JSON.parse(JSON.stringify(squarePos))\n leftLeg.position = JSON.parse(JSON.stringify(leftLegPos))\n rightLeg.position = JSON.parse(JSON.stringify(rightLegPos))\n\n shapeArray = [JSON.parse(JSON.stringify(tee)), JSON.parse(JSON.stringify(long)),\n JSON.parse(JSON.stringify(zig)), JSON.parse(JSON.stringify(zag)), JSON.parse(JSON.stringify(rightLeg)),\n JSON.parse(JSON.stringify(leftLeg)), JSON.parse(JSON.stringify(square))\n ];\n activeSquare = blockCreate(nextShape);\n var rando = random7int();\n nextShape = shapeArray[rando - 1]\n shallPass = true;\n\n if (lineArray != undefined) {\n for (var i = lineArray.length - 1; i >= 0; i--) {\n console.log(lineArray[i])\n fallenBlocks = fallenBlocks.filter(function(item) {\n return item.y != lineArray[i];\n })\n for (var j = 0; j < fallenBlocks.length; j++) {\n if (fallenBlocks[j].y < lineArray[i]) {\n fallenBlocks[j].y = fallenBlocks[j].y + 1;\n }\n }\n }\n }\n if (lineArray != undefined) {\n if (lineArray.length > 0) {\n\n for (var j = 0; j < fallenBlocks.length; j++) {\n if (fallenBlocks[j].y <= 1) {\n console.log(\"less than or equal to 1!\")\n console.log(fallenBlocks[j].y)\n gameOver();\n return;\n }\n }\n console.log(\"running update after clearBlocks\");\n setTimeout(update, 50);\n return;\n }\n } else {\n\n for (var j = 0; j < fallenBlocks.length; j++) {\n if (fallenBlocks[j].y <= 1) {\n\n console.log(\"less than or equal to 1!\")\n console.log(fallenBlocks[j].y)\n gameOver();\n return;\n }\n }\n console.log(\"running update from end of clearBlocks: \" + Date());\n setTimeout(update, 10);\n console.log(\"game loop reset\");\n return;\n }\n\n}", "unfreeze() {\r\n this.regionManagerLayer.removeClass(\"frozen\");\r\n if (this.frozenNuance !== \"\") {\r\n this.regionManagerLayer.removeClass(this.frozenNuance);\r\n }\r\n const selectedRegions = this.lookupSelectedRegions();\r\n if (selectedRegions.length > 0) {\r\n this.menu.showOnRegion(selectedRegions[0]);\r\n }\r\n this.regions.forEach((region) => {\r\n region.unfreeze();\r\n });\r\n this.isFrozenState = false;\r\n }", "deSelectBlocks() {\n this.getNavigableBlocks().setEach('isSelected', false);\n }", "function blockClassReset() {selectedBlock.attr('class', 'unselected')}", "function update() {\n\n //cast ray to go through objects\n raycaster.setFromCamera(mouse, camera);\n //array of targeted objects, ordered by distance - near to far\n var intersects = raycaster.intersectObjects( scene.children );\n //black out targeted partition of sunburst\n if (intersects.length > 0) {\n\n var targetedObject = intersects[0];\n\n //color out targeted node\n setColorHighlight(targetedObject.object.material.color);\n\n\n var targetedObjectNode = getSceneObjectNodeById(subtree.root, targetedObject.object);\n document.getElementById(\"latinWindow\").innerHTML = targetedObjectNode.latin;\n //get node of blacked out object\n var lastAccessedObjectNode = getSceneObjectNodeById(subtree.root, lastAccessedObject);\n\n //create new color by force - #000000 format to 0x000000 format\n var colors = lastAccessedObjectNode.color.split(\"#\");\n var color = (\"0x\" + colors[1]);\n \n //if I moved on another object\n if(targetedObject.object != lastAccessedObject) {\n //apply the original color\n if (lastAccessedObjectNode != null) {\n lastAccessedObjectNode.sceneObject.material.color.setHex(color);\n }\n }\n\n lastAccessedObject = targetedObject.object;\n }\n //if you run down from a node, remove highlighting and innerHTML\n else{\n var lastAccessedObjectNode = getSceneObjectNodeById(subtree.root, lastAccessedObject);\n var colors = lastAccessedObjectNode.color.split(\"#\");\n var color = (\"0x\" + colors[1]);\n if (lastAccessedObjectNode != null) {\n lastAccessedObjectNode.sceneObject.material.color.setHex(color);\n }\n //clear the display of latin name\n document.getElementById(\"latinWindow\").innerHTML = \"\";\n }\n}", "dropEmptyBlocks() {\n Object.keys(this.emptyMap).forEach((parentBlockId) => {\n const node = this.emptyMap[parentBlockId];\n if (node.updateReference !== this.updateReference) {\n node.parent.removeChild(node);\n delete this.emptyMap[parentBlockId];\n }\n });\n }", "removeAllSlots() {\n var size = this.closet_slots_faces_ids.length;\n for (let i = 0; i < size; i++) {\n this.removeSlot();\n }\n }", "standingBlock() {\n\t\tthis.updateState(KEN_SPRITE_POSITION.standingBlock, KEN_IDLE_ANIMATION_TIME, false);\n\t}", "static disable() {\n LightObjects.lightObjects = [];\n }", "clearAllObject() {\r\n this.m_drawToolList.length = 0;\r\n this.clearTechToolMousePos();\r\n }", "function clearables(){\n //remove moveable...\n _$showcase.find('.moveable').removeClass('moveable');\n \n //remove clippingable...\n _$showcase.find('.clippingable').removeClass('clippingable');\n \n //remove contextmenu...\n _$showcase.find('.contextmenu').remove();\n \n \n }", "function reset()\n{\n player.reset();\n\n phase = 0;\n canvas.sceneX = 0;\n canvas.sceneWidth = 0;\n\n var obj;\n\n for (var i = 0; i < sprites.length; i++) {\n obj = sprites[i];\n if (obj !== null) {\n obj.visible = false;\n obj.destroy();\n obj = null;\n }\n }\n\n for (var i = 0; i < backgroundItems.length; i++) {\n obj = backgroundItems[i];\n if (obj !== null) {\n obj.visible = false;\n obj.destroy();\n obj = null;\n }\n }\n\n sprites = [];\n backgroundItems = [];\n}", "function markBlock(whichBlock) {\r\n\t// the visual presentation of 'marking' \r\n\tfunction markGraphic(whichBlock, whoseColor) {\r\n\t\t$(whichBlock).toggleClass(whoseColor, true).css('opacity', '1', true).css('pointer-events', 'none');\r\n\t}\r\n\t// the logical representation of 'marking'\r\n\tvar blockSelected = blocks.filter(function (block) {\r\n\t\treturn block.name == $(whichBlock).attr(\"id\");\r\n\t});\r\n\tif (!blockSelected[0].owned) {\r\n\t\tif (playerTurn) {\r\n\t\t\tplayerTurn = !playerTurn;\r\n\t\t\tblockSelected[0].owned = true;\r\n\t\t\tblockSelected[0].owner = \"player\";\r\n\t\t\tmarkGraphic(whichBlock, playerColor);\r\n\t\t\t\r\n\t\t} else {\r\n\t\t\tplayerTurn = !playerTurn;\r\n\t\t\tblockSelected[0].owned = true;\r\n\t\t\tblockSelected[0].owner = \"computer\";\r\n\t\t\tmarkGraphic(whichBlock, computerColor);\r\n\t\t\t\r\n\t\t}\r\n\t}\r\n\tmoveCount++;\r\n\tcheckForWin();\r\n\tif(gameover == false){\r\n\t\tmoveIsMade = false;\r\n\t}\r\n\telse if(gameover == true){\r\n\t\tmoveIsMade = true;\r\n\t\tannounceWinner(winner);}\r\n}", "function clearBoxes() {\n if (boxpolys != null) {\n for (var i = 0; i < boxpolys.length; i++) {\n boxpolys[i].setMap(null);\n }\n }\n boxpolys = null;\n }", "function removeAllToolOverlays() {\n\t$('#notepad-body').find('.tools-disp').removeClass('tools-disp');\n\t$('#notepad-body').find('.expand-button i').removeClass();\n\t$('#notepad-body').find('.expand-button i').addClass('fa fa-ellipsis-h');\n\t$('#notepad-body .col-4 .color-selector').spectrum(\"destroy\");\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calcule les voisins de chaque groupe
_calculateVoisins(nbCases = 10) { let currentGroupe = null; let totalCases = nbCases * 4; // Parcourt les fiches. On enregistre le groupe courant, quand changement, on defini le groupe precedent et calcule le suivant du precedent for (let i = 0; i < totalCases + 2; i++) { let axe = Math.floor(i / nbCases) % 4; let pos = i % totalCases - (axe * nbCases); let fiche = GestionFiche.get({ axe: axe, pos: pos }); if (fiche != null && fiche.groupe != null && fiche.isTerrain()) { if (currentGroupe == null) { // initialisation currentGroupe = fiche.groupe; } if (!currentGroupe.equals(fiche.groupe)) { // Changement de groupe fiche.groupe.groupePrecedent = currentGroupe; currentGroupe.groupeSuivant = fiche.groupe; currentGroupe = fiche.groupe; } } } }
[ "_groupVitamins () {\n let mini, maxi;\n\n this.groups = {};\n this.vitamins.forEach(vit => {\n if (! this.groups[vit.color]) this.groups[vit.color] = { vitamins: [], mini: null, maxi: null };\n\n // Set mini in color group\n mini = this.groups[vit.color].mini;\n if (! mini || vit.size < mini) {\n this.groups[vit.color].mini = vit.size;\n }\n\n // Set maxi in color group\n maxi = this.groups[vit.color].maxi;\n if (! maxi || vit.size > maxi) {\n this.groups[vit.color].maxi = vit.size;\n }\n\n this.groups[vit.color].vitamins.push(vit);\n });\n\n // Create the empty groups with no vitamins\n Object.values(Vitamin.COLORS).forEach(color => {\n if (! this.groups[color]) {\n this.groups[color] = { vitamins: [], mini: null, maxi: null };\n // console.log(Texts.EMPTY_GROUP(color));\n }\n });\n\n //console.log('Grouped by colors:', this.groups);\n }", "function subtraiValorDoEmpenhoDoValorTotalDoGrupoDeEmpenhos(idDivEmpenhosPorSolicitacaoItem, valor) {\n\n var divEmpenho = $(\"#\" + idDivEmpenhosPorSolicitacaoItem);\n //pega a div do grupo do qual o empenho faz parte\n //var divGrupo = $(divEmpenho).closest(\"[name='cabecalhoDivEmpenhoSolicitacao']\");\n //var divGrupo = $(divEmpenho).parent().next(\"[name='cabecalhoDivEmpenhoSolicitacao']\");\n var divGrupo = $(divEmpenho).parent().siblings(\"[name='cabecalhoDivEmpenhoSolicitacao']\");\n\n //valor total registrado até o momento\n var campoValorTotal = $(divGrupo).find(\"#valorTotal\");\n var total = $(campoValorTotal).html();\n //subtrai o valor do empenho do total\n total = subtraiDinheiro(total, valor);\n //escreve o valor totaL no cabecalho do gurpo\n $(divGrupo).find(\"#valorTotal\").html(total);\n}", "function calcularTotalComprobacion(){\r\n\t\tvar totalComprobacion = 0;\r\n\t\t\r\n\t\tvar eur = $(\"#valorDivisaEUR\").val();\r\n\t\tvar usd = $(\"#valorDivisaUSD\").val();\r\n\t\t\r\n\t\tvar tablaLength = obtenTablaLength(\"comprobacion_table\");\r\n\t\t\r\n\t\tfor(var i = 1; i <= tablaLength; i++){\r\n\t\t\tvar divisa = parseInt($(\"#row_divisa\"+i).val());\r\n\t\t\tswitch(divisa){\r\n\t\t\t\tcase 2:\r\n\t\t\t\t\ttotalComprobacion+= (limpiaCantidad($(\"#row_totalPartida\"+i).val()) * usd);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase 3:\r\n\t\t\t\t\ttotalComprobacion+= (limpiaCantidad($(\"#row_totalPartida\"+i).val()) * eur);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tdefault:\r\n\t\t\t\t\ttotalComprobacion+= (limpiaCantidad($(\"#row_totalPartida\"+i).val()));\r\n\t\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tasignaVal(\"totalComprobacion\", totalComprobacion);\r\n\t\t\r\n\t\tasignaText(\"span_totalComprobacion\", totalComprobacion,\"number\");\r\n\t}", "function galonesnecesarios(metros) {\r\n var m2 = parseInt(metros, 10);\r\n var resultado = 0;\r\n if (m2 % 35 > 0) {\r\n resultado = Math.trunc((m2 / 35) + 1);\r\n } else {\r\n resultado = Math.trunc(m2 / 35);\r\n }\r\n return resultado;\r\n}", "calcAggregatedIgnorance() {\n if (this.debug) console.log(\"\\nCALC Aggregated Ignorance - PROJECT - >>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n var data = this.data;\n data.Ignorance = data.MdashH / (1 - data.MlH);\n if (this.debug) console.log(\"data.Ignorance: \" + data.Ignorance);\n\n // Calculate and save distributed ignorance divided by number of alternatives\n // For Distributed Ignorance table\n data.IgnoranceSplit = data.Ignorance/data.alternatives.length;\n }", "CalcularPliegos(libros, es_carbon,troquel, sobrante_tinta)\n {\n \tvar pliegos = 0;\n \tif (this.numero_tamanos * this.numero_moldes > 0) {\n \t\tif (es_carbon) /* De donde viene*/\n \t\t{\n \t\t\tpliegos = libros * this.numero_hojas / (this.numero_tamanos * this.numero_moldes);\n \t\t}\n \t\telse\n \t\t{\n \t\t\tvar sobrantes = sobrante_tinta * this.numero_tintas;\n \t\t\tif (troquel) /* De donde viene*/\n \t\t\t{\n \t\t\t\tsobrantes = sobrante_tinta;\n \t\t\t}\n \t\t\tpliegos = ((libros * this.numero_hojas / this.numero_moldes) + sobrantes) / this.numero_tamanos;\n \t\t}\n \t\tpliegos = Math.ceil(pliegos);\n \t}\n this.numero_pliegos = pliegos;\n \treturn pliegos;\n }", "function loadGroups(that) {\r\n if (that.config.groups !== undefined) {\r\n $.each(that.config.groups, function (index, value) {\r\n //Group reducing function by Size\r\n if (that.config.groups[index].context === \"context:reduce\") {\r\n that.idxGroup[index] = that.idxDimension[that.config.groups[index].dimensionid].group().reduce(\r\n function (p, v) {\r\n ++p.count;\r\n p.AvgSize = v.AvgSize;\r\n p.sumAvgSize += v[that.config.groups[index].datafield];\r\n p.avgAvgSize = p.sumAvgSize / p.count;\r\n p.fluctuation += v[that.config.groups[index].datafield] - p.lastAvgSize;\r\n p.lastAvgSize = v[that.config.groups[index].datafield];\r\n \t\t\t if(p.avgAvgSize == 0){\r\n \t\t\t\tp.fluctuationPercentage = (Math.abs(p.fluctuation) / 1) * 100;\r\n \t\t\t }\r\n \t\t\t else{\r\n \tp.fluctuationPercentage = (Math.abs(p.fluctuation) / p.avgAvgSize) * 100;\r\n }\r\n return p;\r\n },\r\n function (p, v) {\r\n --p.count;\r\n p.AvgSize = v.AvgSize;\r\n p.sumAvgSize -= v[that.config.groups[index].datafield];\r\n p.avgAvgSize = p.sumAvgSize / p.count;\r\n p.fluctuation -= v[that.config.groups[index].datafield] - p.lastAvgSize;\r\n p.lastAvgSize = v[that.config.groups[index].datafield];\r\n if(p.avgAvgSize == 0){\r\n \t\t\t\tp.fluctuationPercentage = (Math.abs(p.fluctuation) / 1) * 100;\r\n \t\t\t }\r\n \t\t\t else{\r\n \t\t\t\t p.fluctuationPercentage = (Math.abs(p.fluctuation) / p.avgAvgSize) * 100;\r\n \t\t\t }\r\n return p;\r\n },\r\n function () {\r\n return { count: 0, AvgSize: 0, sumAvgSize: 0, avgAvgSize: 0, fluctuation: 0, lastAvgSize: 0, fluctuationPercentage: 0 };\r\n }\r\n );\r\n }\r\n\r\n //Group function\r\n if (that.config.groups[index].context === \"context:groupkey\") {\r\n //that.idxGroup[index] = that.idxDimension[that.config.groups[index].dimensionid].group(function(d){return d[that.config.groups[index].datafield];});\r\n that.idxGroup[index] = that.idxDimension[that.config.groups[index].dimensionid].group(function(d){\r\n console.log(d[that.config.groups[index].datafield]);\r\n return d[that.config.groups[index].datafield];\r\n });\r\n }\r\n\r\n //Group function\r\n if (that.config.groups[index].context === \"context:group\") {\r\n that.idxGroup[index] = that.idxDimension[that.config.groups[index].dimensionid].group();\r\n }\r\n\r\n //Group Reduce Count function\r\n if (that.config.groups[index].context === \"context:reducecount\") {\r\n that.idxGroup[index] = that.idxDimension[that.config.groups[index].dimensionid].group().reduceCount(function (d) {\r\n return d3.time.month(d.dd);\r\n });\r\n }\r\n\r\n //Group Reduce Count function\r\n if (that.config.groups[index].context === \"context:reducecountkey\") {\r\n that.idxGroup[index] = that.idxDimension[that.config.groups[index].dimensionid].group().reduceCount();\r\n }\r\n\r\n //Group Reduce Sum function\r\n if (that.config.groups[index].context === \"context:reducesum\") {\r\n that.idxGroup[index] = that.idxDimension[that.config.groups[index].dimensionid].group().reduceSum(function (d) {\r\n return d[that.config.groups[index].datafield];\r\n });\r\n }\r\n });\r\n }\r\n }", "function calcular_si_mueve(element, partes) {\n switch (puzzleElegido){\ncase \"south_park\": comprovarGanado(partes, array_south_park); break;\ncase \"peter\": comprovarGanado(partes, array_peter_partido); break;\ncase \"homer\": comprovarGanado(partes, array_homer_partido); break;\ncase \"stan \": comprovarGanado(partes, erased_value_stan); break;\n }\n \n var valor_element = element.getBoundingClientRect();\n var vacio = document.getElementById(\"vacio\");\n\n\n var valor_vacio = vacio.getBoundingClientRect();\n\n if (\n seTocanAbajo(valor_element, valor_vacio, element, vacio) ||\n seTocanArriba(valor_element, valor_vacio, element, vacio) ||\n seTocanDerechaNormal(valor_element, valor_vacio, element, vacio) ||\n seTocanIzquierda(valor_element, valor_vacio, element, vacio)\n ) {\n\n var valor_anterior = Number(document.getElementById(\"mov\").innerHTML);\n document.getElementById(\"mov\").innerHTML = valor_anterior + 1;\n\n } else {\n\n flash(element.getAttribute(\"name\"))\n\n }\n\n\n}", "dividir(otroNumero){\n //Gracias al test de Carolina\n if(otroNumero.num == 0){\n return new Numero(Infinity);\n }\n //tres.dividir(dos)\n let respuesta = 0;\n for(let resto = this.num;;respuesta++){\n resto -= otroNumero.num;\n if(resto < 0){\n break;\n }\n }\n\n return new Numero(respuesta);\n }", "function diasTotal(meses) {\n\tif(meses === - 1) meses = 11;\n\n\tif(meses == 0 || meses == 2 || meses == 4 || meses == 6 || meses == 7 || meses == 9 || meses == 11) {\n\t\treturn 31;\n\n\t}else if(meses == 3 || meses == 5 || meses == 8 || meses == 10) {\n\t\treturn 30;\n\n\t}else{\n\t\treturn bisiesto() ? 29:28;\n\n\t}\n\n}", "updateGoodTypeCounts() {\n getValidGoodTypes().forEach((goodType) => {\n // Reset all calculated values from previous iteration\n this.setRoyalty(goodType.name, 0);\n this.countSubtotals[goodType.name] = 0;\n // Each player has inputs that come in a specific type. Some goods score extra when it comes to\n // determining bonuses for first and second (King and Queen). Recaclulate the total for each goodType.\n goodType.goods.forEach((targetGood) => {\n // Multiplier is relevant for royal goods.\n this.countSubtotals[goodType.name] += this.getCount(targetGood.name) * targetGood.multiplier;\n });\n });\n }", "getSumOfAgeRatios() {\n let sum = 0;\n for (let ageGroup of this.ageGroups) {\n sum += this.getAgeRatio(ageGroup);\n }\n return sum;\n }", "get totals(){\n let mr=this.mass_ratios;//alias for code reduction\n let co=this.components; //alias for code reduction\n\n //COD fractions (Chemical Oxygen Demand)\n let bsCOD = co.S_VFA + co.S_FBSO; //bio + soluble COD\n let usCOD = co.S_USO; //unbio + soluble COD\n let bpCOD = co.X_BPO; //bio + partic COD\n let upCOD = co.X_UPO; //unbio + partic COD\n let bCOD = bsCOD + bpCOD; //bio COD\n let uCOD = usCOD + upCOD; //unbio COD\n let sCOD = bsCOD + usCOD; //soluble COD\n let pCOD = bpCOD + upCOD; //partic COD\n let Total_COD = bsCOD + usCOD + bpCOD + upCOD + co.X_OHO + co.X_PAO;\n let COD={\n total: Total_COD,\n bCOD, uCOD, sCOD, pCOD,\n bsCOD, usCOD, bpCOD, upCOD,\n active: co.X_OHO + co.X_PAO,\n };\n\n //TOC all fractions (Total Organic Carbon)\n let bsOC = co.S_VFA * mr.f_C_VFA / mr.f_CV_VFA + co.S_FBSO * mr.f_C_FBSO / mr.f_CV_FBSO; //bio + soluble OC\n let usOC = co.S_USO * mr.f_C_USO / mr.f_CV_USO; //unbio + soluble OC\n let bpOC = co.X_BPO * mr.f_C_BPO / mr.f_CV_BPO; //bio + partic OC\n let upOC = co.X_UPO * mr.f_C_UPO / mr.f_CV_UPO; //unbio + partic OC\n let bOC = bsOC + bpOC; //bio OC\n let uOC = usOC + upOC; //unbio OC\n let sOC = bsOC + usOC; //soluble OC\n let pOC = bpOC + upOC; //partic OC\n let actOC = co.X_OHO * mr.f_C_OHO / mr.f_CV_OHO + //OC in active biomass (OHO)\n co.X_PAO * mr.f_C_PAO / mr.f_CV_PAO; //OC in active biomass (PAO)\n\n let Total_TOC = bsOC + usOC + bpOC + upOC + actOC;\n let TOC={\n total:Total_TOC,\n bOC, uOC, sOC, pOC,\n bsOC, usOC, bpOC, upOC,\n active: actOC,\n };\n\n //TKN all fractions (Organic Nitrogen (ON) + Inorganic Free Saline Ammonia (FSA))\n let bsON = co.S_VFA * mr.f_N_VFA / mr.f_CV_VFA + co.S_FBSO * mr.f_N_FBSO / mr.f_CV_FBSO; //bio + soluble ON\n let usON = co.S_USO * mr.f_N_USO / mr.f_CV_USO; //unbio + soluble ON\n let bpON = co.X_BPO * mr.f_N_BPO / mr.f_CV_BPO; //bio + partic ON\n let upON = co.X_UPO * mr.f_N_UPO / mr.f_CV_UPO; //unbio + partic ON\n let bON = bsON + bpON; //bio ON\n let uON = usON + upON; //unbio ON\n let sON = bsON + usON; //soluble ON\n let pON = bpON + upON; //partic ON\n let actON = co.X_OHO * mr.f_N_OHO / mr.f_CV_OHO+ //ON in active biomass (OHO)\n co.X_PAO * mr.f_N_PAO / mr.f_CV_PAO; //ON in active biomass (PAO)\n let Total_TKN = co.S_FSA + bsON + usON + bpON + upON + actON;\n let TKN={\n total:Total_TKN,\n FSA:co.S_FSA,\n ON:sON+pON,\n bON, uON, sON, pON,\n bsON, usON, bpON, upON,\n active: actON,\n }\n\n //TP all fractions (Organic P (OP) + Inorganic Phosphate (PO4))\n let bsOP = co.S_VFA * mr.f_P_VFA / mr.f_CV_VFA + co.S_FBSO * mr.f_P_FBSO / mr.f_CV_FBSO; //bio + soluble OP\n let usOP = co.S_USO * mr.f_P_USO / mr.f_CV_USO; //unbio + soluble OP\n let bpOP = co.X_BPO * mr.f_P_BPO / mr.f_CV_BPO; //bio + partic OP\n let upOP = co.X_UPO * mr.f_P_UPO / mr.f_CV_UPO; //unbio + partic OP\n let bOP = bsOP + bpOP; //bio OP\n let uOP = usOP + upOP; //unbio OP\n let sOP = bsOP + usOP; //soluble OP\n let pOP = bpOP + upOP; //partic OP\n let actOP = co.X_OHO * mr.f_P_OHO / mr.f_CV_OHO + //OP in active biomass (OHO)\n co.X_PAO * mr.f_P_PAO / mr.f_CV_PAO; //OP in active biomass (PAO)\n\n let Total_TP = co.S_OP + bsOP + usOP + bpOP + upOP + actOP;\n let TP={\n total:Total_TP,\n PO4:co.S_OP,\n OP:sOP+pOP,\n bOP, uOP, sOP, pOP,\n bsOP, usOP, bpOP, upOP,\n active: actOP,\n };\n\n //TSS all fractions (Volatile Suspended Solids (VSS) + inert Suspended Solids (iSS))\n let bVSS = co.X_BPO / mr.f_CV_BPO; //bio VSS\n let uVSS = co.X_UPO / mr.f_CV_UPO; //unbio VSS\n\n let actVSS = co.X_OHO / mr.f_CV_OHO + //OHO VSS active biomass\n co.X_PAO / mr.f_CV_PAO; //PAO VSS active biomass\n\n let Total_VSS = bVSS + uVSS + actVSS; //total VSS\n let Total_TSS = Total_VSS + co.X_iSS; //total TSS\n let TSS={\n total: Total_TSS,\n iSS: co.X_iSS,\n VSS: Total_VSS,\n bVSS,\n uVSS,\n active: actVSS,\n };\n\n //pack components\n return {COD,TKN,TP,TOC,TSS};\n }", "function calculate(Gold) {\n console.log(smallinMedium + \" \" + mediuminLarge);\n console.log(Gold);\n smallGold = Gold || {};\n smallGoldMath = Math.floor(smallGold / smallinMedium);\n smallGold %= smallinMedium;\n mediumGold = smallGoldMath;\n mediumGoldMath = Math.floor(mediumGold / mediuminLarge);\n mediumGold %= mediuminLarge;\n largeGold = mediumGoldMath;\n return smallGold\n return mediumGold\n return largeGold\n}", "calcSalaireNet(facture) {\n // facture.salaireNet = (facture.nombreHeuresNormales * facture.salaireHoraireNormal + facture.nombreHeuresMajorees * facture.salaireHoraireNormal * (1 + ((facture.taux_majore) / 100))).toFixed(2)\n // console.log('calc salaire net ' + facture.salaireNet)\n return (facture.nombreHeuresNormales * facture.salaireHoraireNormal + facture.nombreHeuresMajorees * facture.salaireHoraireNormal * (1 + ((facture.taux_majore) / 100))).toFixed(2)\n }", "function group (x, y, level) {\n var group = 1\n\n var cx = .5, cy = .5\n var diam = .5\n\n for (var i = 0; i < level; i++) {\n group <<= 2\n\n group += x < cx ? (y < cy ? 0 : 1) : (y < cy ? 2 : 3)\n\n diam *= .5\n\n cx += x < cx ? -diam : diam\n cy += y < cy ? -diam : diam\n }\n\n return group\n }", "function tasaSimple(meses, monto_total, monto_men){\n\t\n\t// var i = 0.05;\n\n\tvar resigual = monto_total / monto_men;\n\tvar res = 0;\n\ti = 0.00;\n\n\t// alert(\"resigual: \" + resigual);\n\n\tdo{\n\t\ti += 0.01;\n\t\tres = (1 - (Math.pow((1 + i), -1 * meses))) / i ;\n\t\t// alert(res);\n\t\t\n\t}while(res>resigual);\n\n\t// if ((Math.round(res* 100) / 100 ) == (Math.round(resigual* 100) / 100 ) ){\n\t// \t// alert(\"Tasa de interes : \" + i);\n\t// }else{\n\t// \t// alert(\"Tasa posible entre i: \" + i + \" y \"+ (i-0.01));\n\t// }\n\n\ti1 = (1 - (Math.pow((1 + i), -1 * meses))) / i ;\n\ti2 = (1 - (Math.pow((1 + (i-0.01)), -1 * meses))) / (i-0.01) ;\n\n\ti1dif = resigual - i1;\n\ti2dif = i2 - resigual;\n\n\tinterpol = 0.01 * i1dif / i2dif ;\n\n\ttasa_apro = i + interpol;\n\n\t//alert(\"Tasa Aproximada: \" +(Math.round(tasa_apro* 100) ));\n\n\treturn tasa_apro;\n}", "function placerPlusieursMines(Tableau) {\n for (var i = 0; i < $scope.mineNumber; i++) {\n placerMine(Tableau);\n }\n }", "lvlUp() {\n this.lvl ++;\n console.log(\"Su pokémon ha subido de nivel, el nivel es: \" + this.lvl);\n\n // Sube alguno de sus stats dependiendo de la naturaleza del pokemon\n switch (this.naturaleza) {\n case 'Audaz':\n this.stats[\"ataque\"] ++;\n console.log(\"Tu nivel de ataque es: \" + this.stats[\"ataque\"]);\n break;\n case 'Osada':\n this.stats[\"defensa\"] ++;\n console.log(\"Tu nivel de defensa es: \" + this.stats[\"defensa\"]);\n break;\n case 'Cauta':\n this.stats[\"vida\"] ++;\n console.log(\"Tu nivel de vida es: \" + this.stats[\"vida\"]);\n break;\n case 'Alegre':\n this.stats[\"velocidad\"] ++;\n console.log(\"Tu nivel de velocidad es: \" + this.stats[\"velocidad\"]);\n break;\n default:\n console.log(\"Esto es raro, tu pokémon tiene un naturaleza que no había visto antes, no sé que hacer\")\n }\n if (this.lvl === 100) {\n console.log(\"Tu pokemon ha llegado al nivel 100\");\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the context for a ChangeDetectorRef to the given instance.
function initChangeDetectorIfExisting(injector, instance, view) { if (injector && injector.changeDetectorRef != null) { injector.changeDetectorRef._setComponentContext(view, instance); } }
[ "function applyRef(instance, ref) {\n if (!ref) {\n return;\n }\n if (typeof ref === \"function\") {\n ref(instance);\n }\n else if (typeof ref === \"object\") {\n ref.current = instance;\n }\n}", "_changeContextViewPanel(context) {\n\t\tthis.setState({\n\t\t\tcurrentContextView : context\n\t\t})\n\t}", "context(newValue, oldValue) {\n // Emit context information for external paging/filtering/sorting handling\n if (!looseEqual(newValue, oldValue)) {\n this.$emit(EVENT_NAME_CONTEXT_CHANGED, newValue)\n }\n }", "constructor(context, notifier) {\n super();\n this.context = context;\n this.notifier = notifier;\n }", "onRef (ref) {\n this.childComponentFunctions = ref\n }", "function assignRef(ref, value) {\n if (ref == null) return;\n\n if (typeCheck_dist_reachUtilsTypeCheck.isFunction(ref)) {\n ref(value);\n } else {\n try {\n ref.current = value;\n } catch (error) {\n throw new Error(\"Cannot assign value \\\"\" + value + \"\\\" to ref \\\"\" + ref + \"\\\"\");\n }\n }\n}", "$registerHTTPContext() {\n this.$container.bind('Adonis/Core/HttpContext', () => HttpContext_1.HttpContext);\n }", "setProvider(provider) {\n this.provider = provider;\n }", "static initCache(context) {\n this.context = context;\n }", "bind(context) {\n\t\tif (!globalParams.modelProperty) {\n\t\t\tthrow new Error('Data key has not been set!');\n\t\t}\n\t\treturn Reflex.set(this, globalParams.modelProperty, context);\n\t}", "function SliderContext() {\n /**\n * Flag that determines if slide can or cannot be changed (for user request)\n *\n * @member SliderContext\n */\n this.canChangeSlide = true;\n /**\n * Default Slider setting object (@see Slider)\n *\n * @member SliderContext\n */\n this.defaults = null;\n /**\n * Navigation object (@see Navigation)\n *\n * @member SliderContext\n */\n this.navigation = null;\n /**\n * Slider object that this context is attached to.\n *\n * @member SliderContext\n */\n this.owner = null;\n /**\n * Flag that determines if change of a slide can or can not be scheduled.\n *\n * @member SliderContext\n */\n this.preventScheduling = false;\n /**\n * Slider setting object\n *\n * @member SliderContext\n */\n this.settings = null;\n /**\n * Instance of Timer class (@see Timer) that is used to store how much\n * time is left to change the slide.\n *\n * @member SliderContext\n */\n this.slideTimer = new Timer();\n /**\n * Instance of TimeIndicator class (@see TimeIndicator)\n *\n * @member SliderContext\n */\n this.timeIndicator = null;\n /**\n * Timers array.\n *\n * @member SliderContext\n */\n this.timers = [];\n /**\n * Last timeout identifier.\n *\n * @member SliderContext\n */\n this.timeoutId = null;\n /**\n * Transition (@see XA.component.carousels.Transitions.Transition) used while changing slides\n *\n * @member SliderContext\n */\n this.transition = null;\n /**\n * Transition settings object (@see XA.component.carousels.Transitions.TransitionSettings)\n *\n * @member SliderContext\n */\n this.transitionSettings = new XA.component.carousels.Transitions.TransitionSettings();\n /**\n * jQuery object that contains all slides\n *\n * @member SliderContext\n */\n this.$slides = null;\n /**\n * jQuery object that contains the element that wraps slides\n *\n * @member SliderContext\n */\n this.$wrapper = null;\n /**\n * Reference to method that should change current slide\n *\n * @member SliderContext\n */\n this.changeCurrentSlide = null;\n /**\n * Reference to method that should return jQuery object with current slide\n *\n * @member SliderContext\n */\n this.getCurrentSlide = null;\n\n this.timers.push(this.slideTimer);\n }", "function setDetectorVelocityFn(scope) {\n\tdetector_velocity = scope.detector_velocity_value;\n\tif ( detector_velocity > 0 ) { \n\t\tdetector_speed = (detector_velocity/1200)*3;/** Setting the detector speed based on the slider value */\n\t}\n\telse {\n\t\tdetector_speed = 0;\n\t\tdetector_container.x = detector_container.y = 0;\n\t}\n}", "install(context, controller) {\n super.install(context, controller);\n this.graphComponent = context.canvasComponent;\n this.graphComponent.addMouseMoveListener(this.onMouseMoveListener);\n this.graphComponent.addMouseDownListener(this.onMouseDownListener);\n this.graphComponent.addMouseUpListener(this.onMouseUpListener);\n this.graphComponent.addMouseDragListener(this.onMouseDragListener);\n this.state = 'start';\n }", "function setContent(target, value, options) {\n if(!options || (!options.template && !options.templateSelector)) {\n __private.Log.error(\"No valid template is specified for 'content' access point. current node:\" + __private.HTMLAPHelper.getNodeDescription(target));\n return;\n }\n\n var raiseEvent = function(childNode, evt){\n if(options && options[evt]){\n var f = __private.Utility.getValueOnPath(value, options[evt]);\n try{\n f.apply(target, [childNode, __private.HTMLKnotBuilder.getOnNodeDataContext(value)]);\n }\n catch(err) {\n __private.Log.warning(\"Raise \" + evt + \" event failed.\", err);\n }\n }\n };\n\n var template = options.template;\n var isTemplateSelector = false;\n if(options.templateSelector){\n if(!(value === null || typeof(value) === \"undefined\")){\n template = getTemplateFromSelector(options.templateSelector, target, value, true);\n }\n isTemplateSelector = true;\n }\n\n var currentContent = target.children[0]\n if(!currentContent) {\n if(value === null || typeof(value) === \"undefined\" || template === null || typeof (template) === \"undefined\") {\n return;\n }\n var n = __private.HTMLKnotBuilder.createFromTemplate(template, value, target);\n if(n) {\n raiseEvent(currentContent, \"@adding\");\n target.appendChild(n);\n if(!__private.HTMLKnotBuilder.hasDataContext(n)) {\n __private.HTMLKnotBuilder.setDataContext(n, value);\n }\n raiseEvent(n, \"@added\");\n __private.Debugger.nodeAdded(n);\n }\n }\n else{\n if(currentContent.__knot && currentContent.__knot.dataContext === value) {\n return;\n }\n if(value === null || typeof(value) === \"undefined\" || template === null || typeof (template) === \"undefined\") {\n raiseEvent(currentContent, \"@removing\");\n removeNodeCreatedFromTemplate(currentContent);\n raiseEvent(currentContent, \"@removed\");\n }\n else{\n if(isTemplateSelector || __private.HTMLKnotBuilder.isDynamicTemplate(template)) {\n removeNodeCreatedFromTemplate(currentContent);\n currentContent = null;\n if(template){\n currentContent = __private.HTMLKnotBuilder.createFromTemplate(template, value, target);\n }\n if(currentContent) {\n raiseEvent(currentContent, \"@adding\");\n target.appendChild(currentContent);\n if(!__private.HTMLKnotBuilder.hasDataContext(currentContent)) {\n __private.HTMLKnotBuilder.setDataContext(currentContent, value);\n }\n __private.Debugger.nodeAdded(currentContent);\n raiseEvent(currentContent, \"@added\");\n }\n }\n else{\n __private.HTMLKnotBuilder.setDataContext(currentContent, value);\n }\n if(currentContent) {\n if(!currentContent.__knot) {\n currentContent.__knot = {};\n }\n currentContent.__knot.dataContext = value;\n }\n }\n }\n }", "transform(ref, op) {\n var {\n current,\n affinity\n } = ref;\n\n if (current == null) {\n return;\n }\n\n var point = Point.transform(current, op, {\n affinity\n });\n ref.current = point;\n\n if (point == null) {\n ref.unref();\n }\n }", "updateCanvasInfo() {\n const canvas = this.canvas;\n canvas.element = ReactDOM.findDOMNode(canvas.ref.current);\n const computedStyle = window.getComputedStyle(canvas.element);\n canvas.computedWidth = parseFloat(computedStyle.width);\n canvas.computedHeight = parseFloat(computedStyle.height);\n canvas.boundingClientRect = canvas.element.getBoundingClientRect();\n return this;\n }", "bindDetector(md, notifiers, force = false){\n console.log(`Binding detector ${md.constructor.name}...`);\n if (!(md instanceof PositionDetector)) throw new Error(\"Detectors can only be of 'PositionDetector' type.\");\n return super.bindDetector(md, notifiers, force);\n }", "function CodeMirrorEditorContext(editor) {\r\n\t\tthis._editor = editor;\r\n\t\tthis._serverState = {};\r\n\t\tthis._serverStateListeners = [];\r\n\t\tthis._dirty = false;\r\n\t\tthis._dirtyStateListeners = [];\r\n\t}", "static setAsNode(target, context) {\n let argType = _Util_main_js__WEBPACK_IMPORTED_MODULE_1__.default.getType(target);\n switch (argType) {\n case \"String\":\n return context === undefined\n ? document.querySelector(target)\n : context.querySelector(target);\n case \"Element\":\n return target;\n case \"undefined\":\n return new DocumentFragment();\n default:\n throw new yngwie__WEBPACK_IMPORTED_MODULE_0__.Error(\"Argument cannot be a NODE\", argType);\n }\n }", "SetDistanceReferencePoint() {}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
read .we file content
readWefile (filePath, savePath, err, data) { if (err) { this._clientPool.sendTransformFailedNotify(err) } else { const arr = filePath.split('\/') const weFileName = arr.length > 1 ? arr[arr.length - 1] : 'unkown' let content try { content = this._weTransformer.transform(weFileName, data, '.') this._clientPool.sendTransformSuccessNotify(content.logs) let name = (weFileName || '').replace(/\.we$/, '.js') let bundleUrl = path.join(savePath, name); let oreoMessage = JSON.stringify(createOreoMessage('weex', content.result, content.logs, name, bundleUrl, weFileName)) this._clientPool.sendAllClientMessage(oreoMessage) helper.saveJSFile(data, content.result, name, savePath) } catch (err) { console.error('weex transform err ' + err) this._clientPool.sendTransformFailedNotify(err) } } }
[ "readText() {\n const filePath = this._fullname;\n const text = fs.readFileSync(filePath, 'utf-8');\n return text;\n }", "function readAndParseFile (file)\n{\n\tvar whichFile = doActionEx\t('DATA_READFILE',file, 'FileName', file,'ObjectName',gPRIVATE_SITE, \n\t\t\t\t\t\t\t\t'FileType', 'txt');\n\treturn (doActionEx('PAR_PARSE_BUFFER','Result', 'document', whichFile));\n}", "contentFor(page) {\n\t\tlet reader = this.readers[page.extension];\n\t\tlet pathToFile = this.pathToPageContent(page);\n\n\t\tlet content = '';\n\t\tif (typeof reader.readFile !== 'undefined') {\n\t\t\tcontent = reader.readFile(pathToFile);\n\t\t} else {\n\t\t\tcontent = fs.readFileSync(pathToFile, 'utf8');\n\t\t}\n\n\t\tif (!reader) {\n\t\t\tthrow new Error(`No reader for file extension '${page.extension}'`)\n\t\t} else if (typeof reader.read !== 'function') {\n\t\t\tthrow new Error(`Reader for file extension '${page.extension}' has no read method`);\n\t\t}\n\n\t\treturn reader.read(content);\n\t}", "readVuefile (filePath, savePath, err, data) {\n if (err) {\n this._clientPool.sendTransformFailedNotify(err)\n } else {\n this._clientPool.sendTransformSuccessNotify([])\n let oreoMessage = JSON.stringify(createOreoMessage('weex', data, '', path.parse(filePath).base, filePath, path.parse(filePath).base))\n this._clientPool.sendAllClientMessage(oreoMessage)\n }\n }", "function read_text_file_data(file) {\n var rawFile = new XMLHttpRequest();\n rawFile.open(\"GET\", file, false);\n rawFile.onreadystatechange = function() {\n if (rawFile.readyState === 4) {\n if (rawFile.status === 200 || rawFile.status == 0) {\n raw_text_file_data = rawFile.responseText;\n }\n }\n }\n rawFile.send(null);\n}", "function getBinary(file) {\n let xhr = new XMLHttpRequest();\n xhr.open(\"GET\", file, false);\n xhr.overrideMimeType(\"text/plain; charset=x-user-defined\");\n xhr.send(null);\n return xhr.responseText;\n}", "function readTextFile(file) {\r\n var rawFile = new XMLHttpRequest();\r\n rawFile.open(\"GET\", file, false);\r\n rawFile.onreadystatechange = function ()\r\n {\r\n if(rawFile.readyState === 4)\r\n {\r\n if(rawFile.status === 200 || rawFile.status == 0)\r\n {\r\n var allText = rawFile.responseText.split('\\n');\r\n document.getElementById(\"tmr\").innerHTML = allText[0];\r\n document.getElementById(\"chance\").innerHTML = allText[1];\r\n document.getElementById(\"weather\").innerHTML = allText[2];\r\n document.getElementById(\"equip\").innerHTML = allText[3];\r\n }\r\n }\r\n }\r\n rawFile.send(null);\r\n}", "function readDataFile(e) {\n var file = e.target.files[0];\n if (!file) {\n return;\n }\n\n var reader = new FileReader();\n reader.onload = function(e) {\n var contents = e.target.result;\n displayContents(contents);\n parseInputData(contents);\n };\n reader.readAsText(file);\n }", "function read(){\n\n }", "function readTextFile(file){\n\t\tvar rawFile = new XMLHttpRequest();\n\t\trawFile.open(\"GET\", file, false);\n\t\trawFile.onreadystatechange = function ()\n\t\t{\n\t\t\tif(rawFile.readyState === 4)\n\t\t\t{\n\t\t\t\tif(rawFile.status === 200 || rawFile.status == 0)\n\t\t\t\t{\n\t\t\t\t\tallText = rawFile.responseText.split(\"\\n\");\n\t\t\t\t\t//allText = rawFile.responseText.toString().split(\"\\n\");\n\t\t\t\t\tvar arr1 = [];\n\t\t\t\t\t\n\t\t\t\t\tallText.map(function(item){\n\t\t\t\t\t var tabs = item.split('\\t');\n\t\t\t\t\t arr1.push(tabs[0]);\n\t\t\t\t\t arr1.push(tabs[1]);\n\t\t\t\t\t arr1.push(tabs[2]);\n\t\t\t\t\t arr1.push(tabs[3]);\n\t\t\t\t\t arr1.push(tabs[4]);\n\t\t\t\t\t arr1.push(tabs[5]);\n\t\t\t\t\t arr1.push(tabs[6]);\n\t\t\t\t\t arr1.push(tabs[7]);\n\t\t\t\t\t arr1.push(tabs[8]);\n\t\t\t\t\t arr1.push(tabs[9]);\n\t\t\t\t\t arr1.push(tabs[10]);\n\t\t\t\t\t});\n\t\t\t\t\t//alert(arr1);\n\t\t\t\t\tinput = [];\n\t\t\t\t\tvar locs = [];\n\t\t\t\t\tvar tab = [];\n\t\t\t\t\tfor (var i = 0; i < 240; i++){\n\t\t\t\t\t\tfor (var j = 0; j<11; j++){\n\t\t\t\t\t\t\ttab[j] = arr1[11*i+j];\n\t\t\t\t\t\t};\n\t\t\t\t\t\tinput[i] = [tab[0],tab[1],tab[2],tab[3],tab[4],tab[5],tab[6],tab[7],tab[8],tab[9],tab[10]];\n\t\t\t\t\t\t\n\t\t\t\t\t};\n\t\t\t\t\tvar first = [];\n\t\t\t\t\tstimuli = [];\n\t\t\t\t\tfor (var h = 0; h < 240; h++){\n\t\t\t\t\t\tfirst = input[h];\n\t\t\t\t\t\tstimuli[h] = first;\n\t\t\t\t\t};\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\trawFile.send(null);\n\t\treturn stimuli;\n\t}", "function parseFile() {\n if (file === \"\") file = \"test.txt\";\n try { \n\tvar data = fs.readFileSync(file, 'utf8');\n\treturn data.split('\\n');\n } catch(e) {\n\tconsole.log('Error:', e.stack);\n }\n\n}", "function read_less_from_file(less_file_name) {\n log('Reading ' + less_file_name);\n\n var defer = q.defer();\n\n fs.readFile(less_file_name, 'utf8', function(error, less_data) {\n if (error) {\n defer.reject(error);\n } else {\n defer.resolve(less_data);\n }\n });\n\n return defer.promise;\n}", "loadFileToString(aFile, aCharset) {\n var data = \"\";\n var fstream = Cc[\"@mozilla.org/network/file-input-stream;1\"].createInstance(\n Ci.nsIFileInputStream\n );\n fstream.init(aFile, -1, 0, 0);\n\n if (aCharset) {\n var cstream = Cc[\n \"@mozilla.org/intl/converter-input-stream;1\"\n ].createInstance(Ci.nsIConverterInputStream);\n cstream.init(fstream, aCharset, 4096, 0x0000);\n let str = {};\n while (cstream.readString(4096, str) != 0) {\n data += str.value;\n }\n\n cstream.close();\n } else {\n var sstream = Cc[\"@mozilla.org/scriptableinputstream;1\"].createInstance(\n Ci.nsIScriptableInputStream\n );\n\n sstream.init(fstream);\n\n let str = sstream.read(4096);\n while (str.length > 0) {\n data += str;\n str = sstream.read(4096);\n }\n\n sstream.close();\n }\n\n fstream.close();\n\n return data;\n }", "function readFileHandler(err, data) {\n\t\tlogger.debug('begin readFileHandler');\n\n\t\tif (err) logger.warn(\"readFileHanlder error: \", err);\n\n\t\ttry {\n\t\t\tcontent = JSON.parse(data);\n\t\t} catch (exc) {\n\t\t\tlogger.error('JSON.parse failed: ', exc);\n\t\t\treturn;\n\t\t}\n\t\tgetAuthentication();\n\t}", "readEmailFile (callback) {\n\t\tconst inputFile = this.emailFile + '.eml';\n\t\tlet path = Path.join(process.env.CSSVC_BACKEND_ROOT, 'inbound_email', 'test', 'test_files', inputFile);\n\t\tFS.readFile(\n\t\t\tpath,\n\t\t\t'utf8',\n\t\t\t(error, emailData) => {\n\t\t\t\tif (error) { return callback(error); }\n\t\t\t\tthis.emailData = emailData;\n\t\t\t\tcallback();\n\t\t\t}\n\t\t);\n\t}", "function readWavFile(arrayBuffer) {\n const reader = new ArrayBufferReader(arrayBuffer);\n let rate = undefined;\n let samples = undefined;\n // Read ID.\n const riffId = reader.readString(4);\n if (riffId === \"RIFF\") {\n reader.littleEndian = true;\n }\n else if (riffId === \"RIFX\") {\n reader.littleEndian = false;\n }\n else {\n throw new Error('bad \"chunk id\": expected \"RIFF\" or \"RIFX\", got ' + riffId);\n }\n // Read chunk size. This is really how much is left in the entire file.\n const chunkSize = reader.readUint32();\n // Read format.\n const waveId = reader.readString(4);\n if (waveId !== \"WAVE\") {\n throw new Error('bad \"format\": expected \"WAVE\", got ' + waveId);\n }\n // Keep reading chunks.\n while (!reader.eof()) {\n // Chunk ID.\n const chunkId = reader.readString(4);\n const chunkSize = reader.readUint32();\n switch (chunkId) {\n case \"fmt \": {\n if (chunkSize !== 16) {\n throw new Error(\"Expected fmt size of 16, got \" + chunkSize);\n }\n const audioFormat = reader.readUint16();\n const channels = reader.readUint16();\n rate = reader.readUint32();\n const byteRate = reader.readUint32(); // useless...\n const blockAlign = reader.readUint16(); // useless...\n const bitDepth = reader.readUint16();\n const signed = bitDepth !== 8;\n if (audioFormat !== WAVE_FORMAT_PCM) {\n throw new Error(\"Can only handle PCM, not \" + audioFormat);\n }\n break;\n }\n case \"fact\": {\n if (chunkSize !== 4) {\n throw new Error(\"Expected fact size of 4, got \" + chunkSize);\n }\n // There is currently only one field defined for the format dependant data.\n // It is a single 4-byte value that specifies the number of samples in the\n // waveform data chunk.\n //\n // The number of samples field is redundant for sampled data, since the Data\n // chunk indicates the length of the data. The number of samples can be\n // determined from the length of the data and the container size as determined\n // from the Format chunk.\n const numSamples = reader.readUint32();\n break;\n }\n case \"data\": {\n if (chunkSize === 0) {\n // If we run into this, just read the rest of the array.\n throw new Error(\"We don't handle 0-sized data\");\n }\n samples = reader.readInt16Array(chunkSize);\n break;\n }\n }\n }\n if (samples === undefined || rate === undefined) {\n throw new Error(\"didn't get all the fields we need from WAV file\");\n }\n return new AudioFile(rate, samples);\n}", "readDataByIndex(index) {\n return this.content[index];\n }", "function read(callback) {\n fs.readFile(FILE, 'utf8', (err, data) => {\n if (err) console.log('Error:', err);\n callback(data);\n })\n}", "function parseInfo(filePath) {\r\n\tvar arr = fs.readFileSync(filePath, 'utf8').toString().split('\\r\\n');\r\n\ttitle = arr[0].split(':')[1];\r\n\tsize = arr[1].split(':')[1];\r\n\tvar result = {\r\n\t\t\"title\" : title,\r\n\t\t\"size\" : size\r\n\t};\r\n\tconsole.log(\"video info: \" + JSON.stringify(result))\r\n\treturn result;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a new identifier from the given seed (which increments every time we want a new identifier).
function generateIdentifierFromSeed(s) { // generate first char let s1 = s % USE_CHARS.length; let ret = USE_CHARS[s1]; s = Math.floor((s - s1) / USE_CHARS.length); while (s > 0) { let s2 = (s - 1) % USE_CHARS.length; ret = USE_CHARS[s2] + ret; // ensures the change is always the last char, which probably helps gzip s = Math.floor((s - (s2 + 1)) / USE_CHARS.length); } return identifierPrefix + ret; }
[ "function generateUID() {\n return String(~~(Math.random()*Math.pow(10,8)))\n}", "function _randId() {\n\t\t// Return a random number\n\t\treturn (new Date().getDate())+(''+Math.random()).substr(2)\n\t}", "generateId() {\n const newId = `dirId-${Directory.nextId}`;\n Directory.nextId++;\n return newId;\n }", "static generateId() {\n return cuid_1.default();\n }", "function makeid() {\n var text = \"\";\n var possible = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\n for (var i = 0; i < 1000; i++) {\n text += possible.charAt(Math.floor(Math.random() * possible.length));\n return text;\n }\n }", "function makeId (){\n function s4() {\n //generate random number to create a unique id for every item sent to the checkout page\n return Math.floor((1 + Math.random()) * 0x10000)\n .toString(16)\n .substring(1);\n }\n //return a random long random number generated above\n return s4() + s4() + '-' + s4() + '-' + s4() + '-' +\n s4() + '-' + s4() + s4() + s4();\n}", "function uniqueId() {\n return id++;\n }", "function _makeChangeId() {\n var arr = 'a,b,c,d,e,f,0,1,2,3,4,5,6,7,8,9'.split(',');\n var rnd = '';\n for (var i = 0; i < 40; i++) {\n rnd += arr[Math.floor(Math.random() * arr.length)];\n }\n\n return rnd;\n }", "function generate_unique_number(){\n var current_date = (new Date()).valueOf().toString();\n var random = Math.random().toString();\n return generate_hash(current_date + random);\n}", "function generateIdChar(){\n var elegibleChars = \"abcdefghijklmnopqrstubwxyz\";\n var range = elegibleChars.length;\n var num = Math.floor(Math.random() * range);\n return elegibleChars.charAt(num);\n}", "function define_id() {\n var iddef = 0;\n while ( iddef == 0 || iddef > 9999 || FIN_framework.STORYWALKERS.checkids(iddef) ) {\n iddef = Math.floor(Math.random()*10000);\n }\n return iddef;\n }", "function doGenerateUniqueID(studyID, caseID) {\n let newCID = caseID.includes('-') ? caseID.replace('-','') : caseID;\n return `${studyID}-${newCID}`\n}", "#nextId() {\n const nextId = \"id_\" + this.#currentId;\n this.#currentId++;\n return nextId;\n }", "function generateUuid() {\n let uuid = token();\n return uuid;\n}", "function generateUID(length) {\n var rtn = '';\n for (let i = 0; i < UID_LENGTH; i++) {\n rtn += ALPHABET.charAt(Math.floor(Math.random() * ALPHABET.length));\n }\n return rtn;\n}", "gen_id(type){\n\n var str_prefix = \"\";\n var num_id = null;\n var arr_elems = null;\n switch (type) {\n case 'tool': str_prefix = \"t-\"; arr_elems= this.get_nodes('tool'); break;\n case 'data': str_prefix = \"d-\"; arr_elems= this.get_nodes('data'); break;\n case 'edge': str_prefix = \"e-\"; arr_elems= this.get_edges(); break;\n }\n\n var ids_taken = [];\n for (var i = 0; i < arr_elems.length; i++) {\n ids_taken.push(parseInt(arr_elems[i]._private.data.id.substring(2)));\n }\n\n var num_id = 1;\n while (num_id <= arr_elems.length) {\n if (ids_taken.indexOf(num_id) == -1) {\n break;\n }else {\n num_id++;\n }\n }\n\n var num_zeros = 3 - num_id/10;\n var str_zeros = \"\";\n for (var i = 0; i < num_zeros; i++) {\n str_zeros= str_zeros + \"0\";\n }\n return str_prefix+str_zeros+num_id;\n }", "function uuid() {\n // get sixteen unsigned 8 bit random values\n const u = crypto.getRandomValues(new Uint8Array(16))\n\n // set the version bit to v4\n u[6] = (u[6] & 0x0f) | 0x40\n\n // set the variant bit to \"don't care\" (yes, the RFC\n // calls it that)\n u[8] = (u[8] & 0xbf) | 0x80\n\n // hex encode them and add the dashes\n let uid = ''\n uid += u[0].toString(16)\n uid += u[1].toString(16)\n uid += u[2].toString(16)\n uid += u[3].toString(16)\n uid += '-'\n\n uid += u[4].toString(16)\n uid += u[5].toString(16)\n uid += '-'\n\n uid += u[6].toString(16)\n uid += u[7].toString(16)\n uid += '-'\n\n uid += u[8].toString(16)\n uid += u[9].toString(16)\n uid += '-'\n\n uid += u[10].toString(16)\n uid += u[11].toString(16)\n uid += u[12].toString(16)\n uid += u[13].toString(16)\n uid += u[14].toString(16)\n uid += u[15].toString(16)\n\n return uid\n}", "function newZombieId() {\n\tlet id = new Date();\n\treturn id.getTime();\n}", "function toKey(seed) {\n var stringSeed = seed + ''; // Ensure the seed is a string\n var key = [];\n var smear = 0;\n var j;\n for (j = 0; j < stringSeed.length; j++) {\n key[lowbits(j)] =\n lowbits((smear ^= key[lowbits(j)] * 19) + stringSeed.charCodeAt(j));\n }\n return key;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to export the ruleset into a file
function ExportRules() { try { //update json for all rules in ruleset CurrentRuleSet.updateAll(); CurrentRuleSet.Rules.forEach(rule =>{ //convert ruleset to JSON var text = JSON.stringify(rule, null, 3); var filename = rule.title; //export/download ruleset as text/json file var blob = new Blob([text], { type: "application/json;charset=utf-8" }); saveAs(blob, filename); }); } catch (e) { alert(e); } }
[ "function exportSelectedRules() {\r\n\r\n var checkboxes = $('#ID-conditionTable .cb_export:checked');\r\n prepareExport('rules', checkboxes.length);\r\n\r\n\r\n checkboxes.each(function(index, element) {\r\n $.ajax({\r\n type : 'POST',\r\n async : checkboxes.length < PARALLEL_AJAX_REQUESTS,\r\n url : \"/tagmanager/web/getPage?TagManagementPage.mode=EDIT_CONDITION&TagManagementPage.conditionId=\" + $(element).data('tid') + \"&id=TagManagement&ds=\" + CONTAINER_ID,\r\n dataType : 'json'\r\n })\r\n .done(function(data) {\r\n var component = data.components[0];\r\n var new_obj = {\r\n conditionName : component.conditionName,\r\n //watch out: import expects predicateS (plural), but export provides predicate (singular)\r\n predicates : JSON.stringify(component.predicate)\r\n };\r\n\r\n pushToExport(new_obj, 'conditionName');\r\n });\r\n });\r\n }", "function LoadInRuleSet(){\n //selected file\n var file = document.getElementById(\"inputfile\").files[0];\n if(file){\n var reader = new FileReader();\n reader.readAsText(file, \"UTF-8\");\n reader.onload = function (evt) {\n //document.getElementById(\"importRule\").textContent = evt.target.result;\n try{\n //create object\n var newOBJ = JSON.parse(evt.target.result);\n //assign and ensure that the imported file is valid\n var importedRuleset = assignObjectToRuleset(newOBJ);\n\n importedRuleset.Rules.forEach(rule =>{\n LoadRuleObjectToWorkSpace(rule);\n });\n\n }\n catch(e){\n alert(e);\n }\n //reset file selection\n document.getElementById(\"inputfile\").value = \"\";\n }\n reader.onerror = function (evt) {\n alert(\"error reading file\");\n }\n }\n}", "function serializeTransformRule() {\n var xml = serializeRule(\"TransformRule\");\n xml.setAttribute(\"targetProperty\", $(\"#targetproperty\").val());\n return makeXMLString(xml);\n}", "function myExportAllStories(myExportFormat, myFolder){\n\tfor(myCounter = 0; myCounter < app.activeDocument.stories.length; myCounter++){\n fullName = app.activeDocument.fullName + \"\";\n\t\tmyStory = app.activeDocument.stories.item(myCounter);\n\t\tmyID = myStory.id;\n\t\tswitch(myExportFormat){\n\t\t\tcase 0:\n\t\t\t\tmyFormat = ExportFormat.textType;\n\t\t\t\tmyExtension = \".txt\"\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tmyFormat = ExportFormat.RTF;\n\t\t\t\tmyExtension = \".rtf\"\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tmyFormat = ExportFormat.taggedText;\n\t\t\t\tmyExtension = \".txt\"\n\t\t\t\tbreak;\n\t\t}\n\t\tmyFileName = fullName + \"_\" + myID + myExtension;\n\t\tmyFilePath = myFolder + \"/\" + myFileName;\n\t\tmyFile = new File(myFilePath); \n\t\t//myStory.exportFile(myFormat, myFile);\n //myStory.exportFile(myFormat, /c/temp/myFileName.replace('~/desk);\n alert(myFileName.toLowerCase().replace(\"~/desktop/\",\"\"));\n\t}\n}", "function serializeRule(tagName) {\n // Retrieve all connections\n var connections = jsPlumb.getConnections({scope: ['value', 'similarity']}, true);\n // Find the root of the linkage rule\n var root = findRootOperator(connections);\n\n // Serialize rule\n var xmlDoc = document.implementation.createDocument('', 'root', null);\n var xml = xmlDoc.createElement(tagName);\n if (root != null) {\n xml.appendChild(parseOperator(xmlDoc, root, connections));\n }\n\n return xml;\n}", "output_gram_list() {\n fs.writeFileSync(`ngram_output/${this.n}grams.json`, JSON.stringify(this.gram_list), (err) => {\n if (err) throw err;\n });\n }", "export() {\n let { output, outputFrozen } = this.appState.data.seizureData;\n\n // Generate CSV\n let csv = 'is-seizure,is-seizure-user-corrected\\n';\n\n for( let i = 0; i < output.length; i++ ) {\n csv += `${Number(outputFrozen[i])},${Number(output[i])}\\n`;\n }\n\n // Generate data URI and associated link\n let blob = new Blob([csv], {type: 'text/csv'});\n let filename = 'export.csv';\n let objectURL = window.URL.createObjectURL(blob);\n\n const a = document.createElement('a');\n a.setAttribute('download', filename);\n a.setAttribute('href', objectURL);\n\n // Trigger download\n a.click();\n\n // Clear blob from memory\n window.URL.revokeObjectURL(objectURL);\n }", "function exportGraphicFiles()\r{\r var graphics = docData.selectedDocument.allGraphics;\r $.writeln(\"exportResolution Default: \" + app.pngExportPreferences.exportResolution);\r app.pngExportPreferences.pngQuality = PNGQualityEnum.MAXIMUM; // set MAXIMUM Resolution\r app.pngExportPreferences.exportResolution = scriptSettings.exportResolution;\r $.writeln(\"exportResolution setTo: \" + app.pngExportPreferences.exportResolution);\r for (var y = 0; y < graphics.length; y++){\r var graphic = graphics[y]; \r if (graphic.itemLink != null) {\r var exportFile = new File(docData.imagesFolder + \"/\" + graphic.itemLink.name + \".png\");\r $.writeln(\"export to: \" + exportFile);\r graphic.exportFile(ExportFormat.PNG_FORMAT,exportFile);\r }\r }\r}", "function exportArtboards(){\n\n // Loop through artboards\n for(var e = 0; e < doc.artboards.length; e++){\n \n // Store artboard name\n var artBoardName = doc.artboards[e].name;\n\n // Function returns a new file name\n targetFile = getNewName(artBoardName);\n\n // Returns SVG options\n svgSaveOpts = getSVGOptions();\n\n // Make current artboard active\n doc.artboards.setActiveArtboardIndex(e);\n\n // Export file as SVG\n sourceDoc.exportFile(targetFile, ExportType.SVG, svgSaveOpts)\n }\n}", "function saveDataCreateReport() {\n console.log('Writing data to JSON...');\n const jsonFile = fileName(client,'results/','json');\n fs.writeFileSync(jsonFile, JSON.stringify(AllResults));\n console.log(`Created ${jsonFile}`);\n\n console.log('Creating A11y report...');\n var data = mapReportData(AllResults);\n var report = reportHTML(data, tests, client, runner, standard);\n var dateStamp = dateStamp();\n var name = `${client} Accessibility Audit ${dateStamp}`;\n\n console.log('Writing report to HTML...');\n const htmlFile = fileName(client,'reports/','html');\n fs.writeFileSync(htmlFile, report);\n console.log(`Created ${htmlFile}`);\n\n console.log('Creating Google Doc...');\n googleAPI.createGoogleDoc(name, report);\n }", "function outputStylesToFile(\n filename: string,\n styles: string,\n throwImmediately: boolean = false\n) {\n try {\n fs.writeFileSync(filename, styles);\n } catch (error) {\n if (\n !throwImmediately &&\n (error.code === 'ENOENT' || /ENOENT/.test(error.message))\n ) {\n mkdirp.sync(path.dirname(filename));\n outputStylesToFile(filename, styles, true);\n } else {\n throw error;\n }\n }\n}", "function saveproxyRule() {\n\tvar rules = {};\n\tvar co = 0;\n\n\t$(\"#proxy_rules_list .proxy_rule_boxes\").each(function() {\n\t\tvar url = stripHTMLTags($(this).find('.url').text());\n\t\tvar proxy_type = stripHTMLTags($(this).find('.proxy_type').prop(\"selectedIndex\"));\n\t\tvar proxy_location = stripHTMLTags($(this).find('.proxy_location').text());\t\t\n\t\tvar proxy_port = stripHTMLTags($(this).find('.proxy_port').text());\t\t\n\n\t\tvar active = stripHTMLTags($(this).find('.active').prop('checked'));\n\t\tvar global = stripHTMLTags($(this).find('.global').prop('checked'));\n\t\tvar caseinsensitive = stripHTMLTags($(this).find('.caseinsensitive').prop('checked'));\n\t\t// prepare the object\n\t\trules[co] = {id: co, url:url, proxy_type:proxy_type, proxy_location:proxy_location, proxy_port:proxy_port, active: active, global:global, caseinsensitive:caseinsensitive}\n\t\tco++;\n\t});\n\t\t\n\tlocalStorage.proxy_rules = JSON.stringify(rules);\n}", "function saveHtmlResults(html){\n let templateDir = path.join(path.resolve(__dirname,'reports','html_template'));\n\n App.Utils.Log.msg(['Saving html report to ', htmlReportingDirectory],true);\n fs.copySync(templateDir,htmlReportingDirectory);\n fs.outputFileSync(path.join(htmlReportingDirectory,'index.html'),html);\n App.Utils.Log.msg([' - COMPLETED']);\n}", "function createKML(someObject) {\n\t//fs.open(\"./kmls/tmp\");\n\tfs.exists('kml', function (exists) {\n \tif(!exists)\n \t\tfs.mkdir(\"kml\");\n\t});\n\tvar sb = \"\";\n\tsb =\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\" +\n \"<kml xmlns=\\\"http://www.opengis.net/kml/2.2\\\">\\n\" +\n \"\\t<Document>\\n\";\n\t\tvar i = 1;\n for(var index in someObject.record) { \n record = someObject.record[index];\n sb += \"\\t\\t<Placemark>\\n\";\n sb += \"\\t\\t\\t<name>point\" + i + \"</name>\\n\";\n sb += \"\\t\\t\\t<description>\" + record.type + \"</description>\\n\";\n sb += \"\\t\\t\\t<Point>\\n\";\n sb += \"\\t\\t\\t\\t<coordinates>\" + record.latitude + \",\" + record.longitude + \"</coordinates>\\n\";\n sb += \"\\t\\t\\t<Point>\\n\\t\\t</Placemark>\\n\";\n i++;\n }\n sb += \"\\t</Document>\\n\" +\n \"</kml>\\n\";\n var record = someObject.record[0];\n var filename = record.truck_id + \"-trip-id-\" + record.trip_id + \".kml\";\n\t\n\tfs.writeFile(\"kml/\"+filename, sb, function(err) {\n if(err) {\n console.log(err);\n } else {\n console.log(\"The file was saved!\");\n \t}\n\t}); \n\n}", "function writeToFile() {\n // make sure there's something to write\n if (labelsAsJSON.labels.length > 0) {\n fs.writeFile(outputFile, JSON.stringify(labelsAsJSON, null, 2), err => {\n if (err) {\n console.log(err);\n } else {\n console.log(`Labels written to ${outputFile}`);\n }\n });\n } else {\n console.error(\"Error: no labels found. File not written.\");\n }\n}", "function exportTable(){\n var exportData = \"\";\n var footData = \"\";\n var theForm = document.forms[0];\n var currTable = findTable();\n var lineBreak = getLineBreak(theForm);\n var delimiter = getDelimiter(theForm);\n var tableChildren = currTable.childNodes;\n var nChildren = tableChildren.length;\n var i;\n var footChild = -1;\n\n for (i=0; i < nChildren; i++) {\n if (tableChildren.item(i).tagName == \"THEAD\" || tableChildren.item(i).tagName == \"TBODY\") {\n exportData += exportRows(tableChildren.item(i), delimiter, lineBreak);\n\t }\n else if (tableChildren.item(i).tagName == \"TFOOT\") {\n footData += exportRows(tableChildren.item(i), delimiter, lineBreak);\n\t }\n\t else if (tableChildren.item(i).tagName == \"TR\") {\n\t exportData += exportOneRow(tableChildren.item(i), delimiter, lineBreak);\n\t }\n }\n exportData += footData;\n writeToFile(exportData);\n}", "function processTableRules(rGrp) {\r\n // debugger;\r\n for (var rNo = 0; rNo < rGrp.pathItems.length; rNo++) {\r\n var thisRule = rGrp.pathItems[rNo];\r\n setPathAttributes(thisRule);\r\n }\r\n}", "function SeqRollupRuleset(mRollupRules) \r\n{\r\n\tif (mRollupRules)\r\n\t{\r\n\t\tmRollupRules = iRules;\r\n\t}\r\n}", "_writeRoute( route ) {\n\n // transforma o json em string\n let route_str = ', '+JSON.stringify( route );\n\n // get the routes file\n const path = this.destinationPath(`src/config/routes.ts`);\n fs.readFile( path, 'utf8', ( err, data ) => {\n \n // check for errors\n if ( err ) throw new Error( err ); \n\n // get the last index of ]; \n let last_index = data.lastIndexOf('];');\n\n // set the new string\n let str = `${data.substring( 0, last_index )}${route_str}${data.substring( last_index )}`;\n str = beautify( str, { indent_size: 2 } );\n\n // write the file\n this.fs.write( path, str );\n\n // generate de docs for the new route\n this._generateDocs( route );\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Collapse other information and show cross selling section with a scrolling effect
function showCrossSelling() { if ( $('#otherInfoContentTabs').is(':visible') ) { $('#otherInfoContentTabs').collapse('hide'); } if ( $('#crossSellingSection').is(':hidden') ) { $('#crossSellingSection').collapse('show'); } $('html, body').animate({ scrollTop: $("#crossSellingSection").offset().top - 50 }, 1000); }
[ "function toggleDetailTable() {\n $('.extend-data').hide();\n $('.luft-extend-table').click(function (e) {\n $(this).parent().next().slideToggle(200);\n $(this).parent().parent().toggleClass('data-expended');\n e.preventDefault();\n });\n $('.extend-data').slideUp(200);\n }", "function showCollapsable(showThisOne){\r\n\t\tvar toggledCollapsable = showThisOne;\r\n\r\n\t\t\t\r\n\t\tif(toggledCollapsable == 1){\r\n\t\t\tcontent = content1;\r\n\t\t\t// content[0].style.height = \"500px\";\r\n\t\t}else if(toggledCollapsable == 2){\r\n\t\t\tcontent = content2;\r\n\t\t}else if(toggledCollapsable == 3){\r\n\t\t\tcontent = content3;\r\n\t\t}else if(toggledCollapsable == 4){\r\n\t\t\tcontent = content4;\r\n\t\t}else{\r\n\t\t\tcontent = content5;\r\n\t\t}\r\n\r\n\t\tif(content.style.maxHeight){\r\n\t\t\tcontent.style.maxHeight = null;\r\n\t\t}else{\r\n\t\t\tcontent.style.maxHeight = content.scrollHeight + \"px\";\r\n\t\t\t$('#chimchom2-descriptive').animate({scrollTop: jQuery(content).offset().top}, 200);\r\n\t\t}\r\n\r\n\t\tif(currentOpen !== null && currentOpen !== content){\r\n\t\tcurrentOpen.style.maxHeight = null;\r\n\t\t}\r\n\t}", "function onReadMoreClick() {\n $('#show-this-on-click').slideDown();\n $('.readless').show();\n $('.readmore').hide(); \n }", "function onLearnMoreClick(){\n $('#learnmoretext').slideDown();\n $('.learnmore').hide();\n }", "function makeDetailsVisible() {\n setDetailView(\"show-details\");\n setBlurry(\"blurred-out\");\n }", "_collapseHeading(heading) {\n heading.expanded = false;\n }", "function Expand() {\n var splitter = $('#horizontal').find('.k-splitbar');\n\n splitter.removeClass('k-collapsed');\n viewPort.expand(\"#right-pane\");\n SetDataProcessNiceScroll();\n}", "function updateScroll() {\n\t\tlet elements = container.getElementsByClassName('selected');\n\t\tif (elements.length > 0) {\n\t\t\tlet element = elements[0];\n\t\t\t// make group visible\n\t\t\tlet previous = element.previousElementSibling;\n\t\t\tif (previous && previous.className.indexOf('group') !== -1 && !previous.previousElementSibling) {\n\t\t\t\telement = previous;\n\t\t\t}\n\t\t\tif (element.offsetTop < container.scrollTop) {\n\t\t\t\tcontainer.scrollTop = element.offsetTop;\n\t\t\t} else {\n\t\t\t\tlet selectBottom = element.offsetTop + element.offsetHeight;\n\t\t\t\tlet containerBottom = container.scrollTop + container.offsetHeight;\n\t\t\t\tif (selectBottom > containerBottom) {\n\t\t\t\t\tcontainer.scrollTop += selectBottom - containerBottom;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "function rollDownInfoBox() {\n d3.select('#infobox-top')\n .transition()\n .ease(d3.easePoly)\n .duration(450)\n .style('height', '125px');\n d3.select('#infobox')\n .transition()\n .ease(d3.easePoly)\n .duration(150)\n .style('height', '582px');\n}", "function toggleDetailModule() {\n\td3.select(\"button#panel-close\").on(\"click\", function() {\n\t\td3.selectAll(\"circle\").classed(\"active\", false);\n\t\t\n\t\tcleanDetail();\n\t\tclosePanelDetail();\n\t})\n}", "function hsCollapseAllVisible() {\n $('#content .hsExpanded:visible').each(function() {\n hsCollapse($(this).children(':header'));\n });\n}", "function learnMore() {\n $('html, body').animate({\n scrollTop: $('#ps-home-description').offset().top + 'px'\n }, 'slow');\n }", "function showAtag() {\n $item.find('a').filter(function (idx) {\n return !$(this).data('rolling');\n }).css('visibility', 'visible');\n }", "function showHideReadmore() {\r\n\r\n var scrollTop = $('body').scrollTop(); \r\n if (scrollTop >= 0 ) {\r\n if (scrollTop < 100) {\r\n $('.fixed-read-more').fadeIn();\r\n }\r\n else {\r\n $('.fixed-read-more').remove();\r\n }\r\n $('.fixed-read-more').css('bottom', - scrollTop + 'px');\r\n }\r\n }", "async collapse() {\n if (await this.isExpanded()) {\n await this.toggle();\n }\n }", "function toggleCardTools() {\n if (cardTools.css('display') == 'none') {\n cardTools.slideDown(400);\n } else if (cardTools.css('display') == 'block') {\n cardTools.slideUp(150);\n }\n }", "_collapsePanel(panel) {\n panel.expanded = false;\n }", "function onReadLessClick() {\n $('#show-this-on-click').slideUp();\n $('.readless').hide();\n $('.readmore').show();\n }", "function glossaryDetails() {\n var $showBtn = $('.glossary-list .show');\n var $hideBtn = $('.glossary-list .hide');\n var $glossaryList = $('.glossary-list');\n $glossaryList.children('li').removeClass('active');\n $glossaryList.children('li').find('.content p').hide();\n $showBtn.on('click', function (e) {\n e.preventDefault();\n $glossaryList.children('li').removeClass('active');\n $(this).parents('li').addClass('active');\n\n if ($glossaryList.children('li').hasClass('active')) {\n var thisOffset = $glossaryList.position().top;\n $showBtn.parents('li').find('.content p').hide();\n $(this).parents('li').find('.content p').show();\n setTimeout(function () {\n $(this).parents('li').find('.content p').show();\n }, 4000);\n\n if ($(window).width() >= 1024) {\n $('html,body').animate({\n scrollTop: thisOffset\n }, 'slow');\n }\n }\n });\n $hideBtn.on('click', function (e) {\n e.preventDefault();\n $(this).parents('li').find('.content p').hide('slow');\n $(this).parents('li').removeClass('active');\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
OperationType : one of query mutation subscription
function parseOperationType(lexer) { var operationToken = expect(lexer, _lexer.TokenKind.NAME); switch (operationToken.value) { case 'query': return 'query'; case 'mutation': return 'mutation'; // Note: subscription is an experimental non-spec addition. case 'subscription': return 'subscription'; } throw unexpected(lexer, operationToken); }
[ "selectOperation(operation) {\n switch (operation) {\n case 'Inoltra al professore':\n this.sendToProfessor(this.state.selectedNotice);\n break;\n case 'Accetta':\n this.acceptedNotice(this.state.selectedNotice);\n break;\n case 'Non accetta':\n this.notAcceptNotice(this.state.selectedNotice);\n break;\n case 'Inoltra al DDI':\n this.sendNoticeToDDI(this.state.selectedNotice);\n break;\n case 'Pubblica bando':\n this.publishNotice(this.state.selectedNotice);\n break;\n case 'Elimina bando':\n this.deleteDraftNotice(this.state.selectedNotice);\n break;\n case 'Inoltra graduatoria':\n this.sendRankingToDDI(this.state.selectedNotice);\n break;\n default:\n break;\n }\n }", "isOperation(value) {\n if (!isPlainObject(value)) {\n return false;\n }\n\n switch (value.type) {\n case 'insert_node':\n return Path.isPath(value.path) && Node$1.isNode(value.node);\n\n case 'insert_text':\n return typeof value.offset === 'number' && typeof value.text === 'string' && Path.isPath(value.path);\n\n case 'merge_node':\n return typeof value.position === 'number' && Path.isPath(value.path) && isPlainObject(value.properties);\n\n case 'move_node':\n return Path.isPath(value.path) && Path.isPath(value.newPath);\n\n case 'remove_node':\n return Path.isPath(value.path) && Node$1.isNode(value.node);\n\n case 'remove_text':\n return typeof value.offset === 'number' && typeof value.text === 'string' && Path.isPath(value.path);\n\n case 'set_node':\n return Path.isPath(value.path) && isPlainObject(value.properties) && isPlainObject(value.newProperties);\n\n case 'set_selection':\n return value.properties === null && Range.isRange(value.newProperties) || value.newProperties === null && Range.isRange(value.properties) || isPlainObject(value.properties) && isPlainObject(value.newProperties);\n\n case 'split_node':\n return Path.isPath(value.path) && typeof value.position === 'number' && isPlainObject(value.properties);\n\n default:\n return false;\n }\n }", "isOperator (op) {\n return this.isQueryOperator(op) || this.isLogicalOperator(op);\n }", "isSelectionOperation(value) {\n return Operation.isOperation(value) && value.type.endsWith('_selection');\n }", "isNodeOperation(value) {\n return Operation.isOperation(value) && value.type.endsWith('_node');\n }", "is_op(op) {\n\t\treturn Object.keys(this.ops).includes(op);\n\t}", "function op(type, name, side = undefined) {\n return new Op(type, name, side);\n}", "function buildMutationParams(table, mutationType) {\n let query = `const ${mutationType}${table.type}Mutation = gql\\`${enter}${tab}mutation(`;\n\n let firstLoop = true;\n for (const fieldId in table.fields) {\n // if there's an unique id and creating an update mutation, then take in ID\n if (fieldId === '0' && mutationType === 'update') {\n if (!firstLoop) query += ', ';\n firstLoop = false;\n\n query += `$${table.fields[fieldId].name}: ${table.fields[fieldId].type}!`;\n }\n if (fieldId !== '0') {\n if (!firstLoop) query += ', ';\n firstLoop = false;\n\n query += `$${table.fields[fieldId].name}: ${checkForMultipleValues(table.fields[fieldId].multipleValues, 'front')}`;\n query += `${checkFieldType(table.fields[fieldId].type)}${checkForMultipleValues(table.fields[fieldId].multipleValues, 'back')}`;\n query += `${checkForRequired(table.fields[fieldId].required)}`;\n }\n }\n return query += `) {${enter}${tab}`;\n }", "visitSql_operation(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "_sub_query(request){\n let sub = new BehaviorSubject(STATUS_CONNECTED);\n this.activeSubscriptions.set(request.request_id, sub);\n\n return sub.switchMap( state => {\n return this.multiplex(\n this.activateRequest(request),\n this.deactivateRequest(request),\n this.filterRequest(request),\n state\n )\n });\n }", "isOperationList(value) {\n return Array.isArray(value) && value.every(val => Operation.isOperation(val));\n }", "visitLogical_operation(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "isTextOperation(value) {\n return Operation.isOperation(value) && value.type.endsWith('_text');\n }", "visitSubquery_operation_part(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function isOperation() {\n\t\treturn btnops.includes(track.last);\n\t}", "op (code) {\n return this.byte(code, \"op\");\n }", "isValidType(subscriber) {\n\n if (subscriber === \"CommandQuery\") {\n\n return this.subscribe_type === sub_type.SubscribeType.Commands || this.subscribe_type === sub_type.SubscribeType.Queries;\n\n } else {\n\n return this.subscribe_type === sub_type.SubscribeType.Events || this.subscribe_type === sub_type.SubscribeType.EventsStore;\n\n }\n }", "function vuexMutation(mutationName, predefinedPayload) {\n return function mutation(callbackPayload) {\n let payload = predefinedPayload ? evaluate(this, [predefinedPayload])[0] : callbackPayload;\n\n return this.$store.commit(makeMethodName(mutationName), payload);\n };\n }", "getOperationOption(type, formName, label, callback){\n let options = [];\n let operations = this.getValidOperations(type);\n for (let o in operations){\n if (!type || type.match(operations[o][1])) {\n options.push(<option value={operations[o][0]}>{operations[o][0]}</option>)\n }\n }\n\n return Utils.generateComboBox(options, formName, label, callback, this.operationValue)\n }", "constructor() { \n \n Operation.initialize(this);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates total accumulated money since midnight
function calcMoney(rate) { // number of seconds since midnight var totalSeconds = (hour() * 60 * 60) + (minute() * 60); return (totalSeconds + second()) * rate; }
[ "calTotalCharged(){\n this._totalCharged = this._costPerHour * this._hoursParked;\n }", "function calculateTotalTimeSpentToday(){\n\tvar l = Projects.length;\n\tfor(i=0;i<l;i++){\n\t\ttotalTimeSpentToday += Projects[i].timeSpentToday;\n\t\t\n\t\t//Calculate totalOvertimeSpentToday\n\t\tif(Projects[i].timeSpentToday > Projects[i].suggestedAmountToday){\n\t\t\ttotalOvertimeSpentToday += Projects[i].timeSpentToday - Projects[i].suggestedAmountToday;\n\t\t}\n\t}\n\t\n\n\t\n\tvar theDay = today.getDay();\n\tswitch(theDay) {\n\t case 0: var initialCapacity = U.profiles[Profile].workSchedule.su; break;\n\t\tcase 1: var initialCapacity = U.profiles[Profile].workSchedule.mo; break;\n\t\tcase 2: var initialCapacity = U.profiles[Profile].workSchedule.tu; break;\n\t\tcase 3: var initialCapacity = U.profiles[Profile].workSchedule.we; break;\n\t\tcase 4: var initialCapacity = U.profiles[Profile].workSchedule.th; break;\n\t\tcase 5: var initialCapacity = U.profiles[Profile].workSchedule.fr; break;\n\t\tcase 6: var initialCapacity = U.profiles[Profile].workSchedule.sa; break;\n\t default:console.log(\"TIMEPOSITIVE ERROR: Unable to determine initialCapacity.\")\n\t}\n\t\n\tvar timeLeftToday = initialCapacity - totalTimeSpentToday;\n\t//console.log(\"TIME SPENT TODAY: \" + totalTimeSpentToday);\n\t\n\tif(timeLeftToday < 0){\n\t\t//Do something if you have worked extra time today\n\t\tconsole.log(\"You worked bonus time today! Bonus: \" + (timeLeftToday * -1));\n\t}\n}", "function getDaySpent(){\n var date = sessionStorage.getItem(\"setDate\")\n\n var data = JSON.parse(localStorage.getItem(date))\n var sumAmount = 0.0\n if(data != null){\n for(transaction of data['transactions']){\n sumAmount += parseFloat(transaction['amount'])\n \n }\n }\n\n if(Number.isNaN(sumAmount)){\n return 0\n }\n return sumAmount\n}", "function caloriesBurned() {\n let calburnt = 0;\n var currentUser = JSON.parse(localStorage.getItem(\"userProfile\"));\n calburnt =\n (currentUser.weight / 2.205) *\n getmetValues(workoutType) *\n 0.0175 *\n parseInt(workoutLength);\n return Math.floor(calburnt);\n}", "entryTimeTotal({ commit }, data) {\n let time = [];\n\n data.forEach(ele => {\n time.push(ele.entries_sum);\n });\n const hours = time.reduce((acc, seconds) => {\n return acc + seconds;\n }, 0);\n\n commit(\"set_total\", hours);\n }", "function calcTotalDayAgain() {\n var eventCount = $this.find('.everyday .event-single').length;\n $this.find('.total-bar b').text(eventCount);\n $this.find('.events h3 span b').text($this.find('.events .event-single').length)\n }", "function extraer_tiempototal(horaini, horaact) {\n var diff;\n\n var fecha1 = horaini.substring(6, horaini.length - 2);\n var fecha2 = horaact.substring(6, horaini.length - 2);\n\n diff = fecha2 - fecha1;\n // calcular la diferencia en segundos\n var diffSegundos = Math.abs(diff / 1000);\n\n\n // calcular la diferencia en minutos\n var diffMinutos = Math.abs(diff / (60 * 1000));\n\n var restominutos = diffMinutos % 60;\n\n // calcular la diferencia en horas\n var diffHoras = (diff / (60 * 60 * 1000));\n\n // calcular la diferencia en dias\n var diffdias = Math.abs(diff / (24 * 60 * 60 * 1000));\n\n //console.log(\"En segundos: \" + diffSegundos + \" segundos.\");\n //console.log(\"En minutos: \" + diffMinutos + \" minutos.\");\n //console.log(\"En horas: \" + diffHoras + \" horas.\");\n //console.log(\"En dias: \" + diffdias + \" dias.\");\n\n var devolver = parseInt(diffHoras) + \"H \" + Math.round(restominutos) + \"m \";\n //console.log(devolver)\n\n var tiempototal = Math.round((parseInt(diffHoras) * 60) + restominutos);\n\n //console.log(tiempototal);\n\n return tiempototal;\n\n}", "function total() {\n\n let dayOfWeek = new Date().getDay();\n let sub = parseFloat(document.getElementById(\"subtotal\").value);\n let newsubtotal;\n let trueTotal;\n \n//Processing\n\n \n if (sub >= 50 && (dayOfWeek == 2 || dayOfWeek == 3)) {\n newsubtotal = (sub * .9);\n } else {\n newsubtotal = (sub);\n }\n \n trueTotal = (newsubtotal * 1.06);\n \n//Output\n document.getElementById(\"output\").innerHTML = \"Their total is: \" + trueTotal.toFixed(2);\n}", "updateRunningBalances() {\n\t\t// Do nothing for investment accounts\n\t\tif (\"investment\" === this.context.account_type) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.transactions.reduce((openingBalance, transaction) => {\n\t\t\ttransaction.balance = openingBalance + (transaction.amount * (\"inflow\" === transaction.direction ? 1 : -1));\n\n\t\t\treturn transaction.balance;\n\t\t}, this.openingBalance);\n\t}", "function updateTotal(playerTotal, playerHand) {\n playerTotal = getTotal(playerHand);\n return playerTotal;\n}", "function update_payment() {\n var date = new Date();\n var now = date.getTime()/1000.0;\n var delta = now - last_payment_update_time;\n last_payment_update_time = now;\n time_spent += delta;\n total_time_spent += delta;\n console.log('Time spent:' + time_spent);\n //console.log('Total time spent:' + total_time_spent++);\n console.log('Time purchased:' + time_purchased);\n console.log('++++++++++++++++++++++');\n //console.log('Total time purchased:' + total_time_purchased);\n update_display();\n}", "getTotalHours() {\n let sum = 0;\n for (let entry of this.state.entries) {\n sum += parseFloat(entry['hours']);\n }\n this.setState({ totalHours: sum });\n }", "calculateCashOnCash() { return parseFloat((this.calculateCashFlow() / this.calculateTotalCapitalRequired()).toFixed(3)) }", "daily() {\n\t\tif (this.dead) {\n\t\t\tthrow new BankError('Account is shut down');\n\t\t} else if (this.closed) {\n\t\t\tthrow new BankError('Account is currently closed');\n\t\t} else if (this.investing) {\n\t\t\tthrow new BankError('Account is currently investing, so it may not receive daily money');\n\t\t}\n\t\tlet timeRemaining = this.dailyCooldown;\n\t\tif (timeRemaining > 0) {\n\t\t\tthrow new BankError(`Wait ${fmt.time(timeRemaining)} before receiving your daily money!`);\n\t\t}\n\t\tthis.dailyReceived = Date.now();\n\t\t\n\t\tlet amt = Constants.DAILY.AMOUNT;\n\t\treturn this.recordCreditChange('daily', amt).then(() => amt);\n\t}", "function CashCalculateCashTotal() {\n var totalFacture = 0;\n var comptArgent = parseFloat($('#argnt_pamnt').val());\n var comptDebit = parseFloat($('#debit_pamnt').val());\n var credit = parseFloat($('#visa_crdt_inpt').val());\n var postDateMnt = parseFloat($('#pst_dat_mnt').val());\n\n comptArgent = isNaN(comptArgent) ? 0 : comptArgent;\n comptDebit = isNaN(comptDebit) ? 0 : comptDebit;\n credit = isNaN(credit) ? 0 : credit;\n postDateMnt = isNaN(postDateMnt) ? 0 : postDateMnt;\n\n totalFacture = comptArgent + comptDebit + credit + postDateMnt;\n\n $('#total_pamnt').val(totalFacture.toFixed(2));\n}", "function workToGetBalance() {\n payBalance += 100;\n}", "function get_time_left() {\n return (total_paid / price_per_second) - time_spent;\n}", "calculateTotalDailyRevenue(revenueArray){\n let revenue = 0;\n for(let i=0; i<24; i++){\n revenue += parseFloat(revenueArray[i]);\n console.log(revenue);\n }\n return revenue.toFixed(2);\n }", "calculateTimeSpent()\n {\n let timestamps = this.store_.getState('timestamps');\n\n console.log('** timestamps: ' + JSON.stringify(timestamps));\n\n let elapsedSecondsSigma = 0;\n timestamps.forEach(function(element){\n elapsedSecondsSigma += element.elapsedSeconds;\n });\n console.log('** elapsedSecondsSigma: ' + elapsedSecondsSigma);\n\n return elapsedSecondsSigma;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Start a grouping over the given items.
function group(items) { const by = (key) => { // create grouping with resolved keying function const keyFn = typeof key === 'function' ? key : (item) => item[key]; const groups = createGrouping(items, keyFn); // return collectors return Object.freeze({ asArrays: (0, as_arrays_js_1.asArraysFactory)(groups), asEntries: (0, as_entries_js_1.asEntriesFactory)(groups), asMap: (0, as_map_js_1.asMapFactory)(groups), asObject: (0, as_object_js_1.asObjectFactory)(groups), asTuples: (0, as_tuples_js_1.asTuplesFactory)(groups), keys: (0, keys_js_1.keysFactory)(groups) }); }; return Object.freeze({ by }); }
[ "function createGrouping(items, keyFn) {\n const groups = [];\n let idx = 0;\n for (const item of items) {\n const itemKey = keyFn(item, idx);\n idx++;\n const predicate = (g) => (0, deep_eql_1.default)(g.key, itemKey);\n const construct = () => ({ key: itemKey, items: [] });\n (0, find_or_create_js_1.findOrCreate)(groups, predicate, construct).items.push(item);\n }\n return groups;\n}", "function applyGrouping(groups) {\n var order = 0;\n groups.forEach(function (group, groupNumber) {\n group.forEach(function (player) {\n player.grouping = groupNumber;\n player.start_order = order;\n\n order++;\n });\n });\n }", "function showGroup() {\n\tvar ps = document.querySelectorAll('p, nav, section, article');\n\tvar i = 0;\n\twhile(i < ps.length) {\n\t\tgroupLength = ps[i].childNodes.length;\n\t\tif(groupLength > 1) {\n\t\t\tvar groupChild = document.createElement('span');\n\t\t\tgroupChild.classList.add('vasilis-srm-group');\n\t\t\tgroupChild.innerHTML = \" Group \" + groupLength + \" items\";\n\t\t\tps[i].appendChild(groupChild);\n\t\t}\n\t\ti++;\n\t}\n}", "groupFields (groupsArray, field, i, fieldsArray) {\n if (field.props.group === 'start') {\n this.openGroup = true\n groupsArray.push([])\n }\n\n if (this.openGroup) {\n groupsArray[groupsArray.length - 1].push(field)\n } else {\n groupsArray.push([field])\n }\n\n if (field.props.group === 'end') {\n this.openGroup = false\n }\n return groupsArray\n }", "toHtml() {\n let node = createSpan(\"group\", \"(\");\n for (const item of this.items)\n node.append(item.toHtml());\n node.append(\")\");\n if (this.count != 1)\n node.append(createElem(\"sub\", this.count.toString()));\n return node;\n }", "function group( item ) {\n\n item [ 'type' ] = TYPE.GROUP;\n item [ 'token' ] = item.uuid;\n item [ 'ts' ] = Service.$tools.getTimestamp( item.updatetime );\n \n return item;\n \n }", "groupsStartingIn (other) {\n let list = new GroupList()\n for (let group of this.groups) {\n if (group.offset.compare(other.offset) >= 0 && group.offset.compare(other.end()) < 0) list.groups.push(group)\n }\n return list\n }", "facetComplexItems(aItems) {\n let attrKey = this.attrDef.boundName;\n let filter = this.facetDef.filter;\n let idAttr = this.facetDef.groupIdAttr;\n\n let groups = (this.groups = {});\n let groupMap = (this.groupMap = {});\n this.groupCount = 0;\n\n for (let item of aItems) {\n let vals = attrKey in item ? item[attrKey] : null;\n if (vals === Gloda.IGNORE_FACET) {\n continue;\n }\n\n if (vals == null || vals.length == 0) {\n vals = [null];\n }\n for (let val of vals) {\n // skip items the filter tells us to ignore\n if (filter && !filter(val)) {\n continue;\n }\n\n let valId = val == null ? null : val[idAttr];\n // We need to use hasOwnProperty because tag nouns are complex objects\n // with id's that are non-numeric and so can collide with the contents\n // of Object.prototype.\n if (groupMap.hasOwnProperty(valId)) {\n groups[valId].push(item);\n } else {\n groupMap[valId] = val;\n groups[valId] = [item];\n this.groupCount++;\n }\n }\n }\n\n let orderedGroups = Object.keys(groups).map(key => [\n groupMap[key],\n groups[key],\n ]);\n let comparator = this.facetDef.groupComparator;\n function comparatorHelper(a, b) {\n return comparator(a[0], b[0]);\n }\n orderedGroups.sort(comparatorHelper);\n this.orderedGroups = orderedGroups;\n }", "function buildContainerGroups() {\n let container = svg\n .append('g')\n .classed('container-group', true)\n .attr('transform', `translate(${margin.left}, ${margin.top})`);\n\n container\n .append('g').classed('grid-lines-group', true);\n container\n .append('g').classed('chart-group', true);\n container\n .append('g').classed('x-axis-group', true)\n .append('g').classed('axis x', true);\n container\n .append('g').classed('y-axis-group', true)\n .append('g').classed('axis y', true);\n container\n .append('g').classed('metadata-group', true);\n }", "function groupItemsByYear(selectItems) {\n var grouped = _.groupBy(selectItems, 'year');\n return _.map(grouped, function(items, key) {\n return {\n year: key,\n items: items\n };\n });\n }", "function createItemGroup(pkg, callback){\n var item = {\n title : pkg.title,\n description : pkg.notes,\n created : pkg.metadata_created,\n url : config.ckan.server+\"/dataset/\"+pkg.name,\n ckan_id : pkg.id,\n updated : pkg.revision_timestamp,\n groups : [],\n resources : pkg.resources ? pkg.resources : [],\n organization : pkg.organization ? pkg.organization.title : \"\",\n extras : {}\n }\n\n // add extras\n if( pkg.extras ) {\n for( var i = 0; i < pkg.extras.length; i++ ) {\n if( pkg.extras[i].state == 'active' ) {\n item.extras[pkg.extras[i].key] = pkg.extras[i].value;\n }\n }\n }\n \n\n if( pkg.groups ) {\n for( var i = 0; i < pkg.groups.length; i++ ) {\n item.groups.push(pkg.groups[i].name);\n }\n }\n\n setTags(item, pkg, callback);\n}", "function groupWith(groupFn, xs) {\n return (function groupWith([x, ...xs], acc = []) {\n if(x === undefined) return acc;\n if(length(acc) === 0) return groupWith(xs, [...acc, [x]]);\n\n const [prevElem, ...rest] = reverse(acc);\n const [innerPrevElem] = reverse(prevElem);\n\n return (\n groupFn(innerPrevElem, x)\n ? groupWith(xs, [...reverse(rest), [...prevElem, x]])\n : groupWith(xs, [...acc, [x]])\n );\n })(xs);\n}", "getList(itemCollection){\n let {groupFunction, groupedByLabel, cellClass} = this.props;\n let CellClass = cellClass || Cell;\n if(groupFunction){\n const itemCollectionByGroup = _.groupBy(itemCollection, groupFunction);\n return _.map(itemCollectionByGroup, (group, groupName) => {\n const uniqueGroupId = _.uniqueId(groupName);\n const groupItems = itemCollectionByGroup[groupName];\n return(\n <div key={uniqueGroupId} className={\"cellGridGroup\"}>\n <h3>{groupedByLabel} {groupName} - Total: {_.size(groupItems)}</h3>\n <div className=\"cellList\">\n {_.map(groupItems, (item, key) => this.getCell(CellClass, key, item))}\n </div>\n </div>\n );\n })\n } else {\n return <div className=\"cellList\">\n {_.map(itemCollection, (item, key) => this.getCell(CellClass, key, item))}\n </div>\n }\n }", "function buildContainerGroups() {\n let container = svg\n .append('g')\n .classed('tooltip-container-group', true)\n .attr('transform', `translate( ${margin.left}, ${margin.top})`);\n\n container.append('g').classed('tooltip-group', true);\n }", "_groupVitamins () {\n let mini, maxi;\n\n this.groups = {};\n this.vitamins.forEach(vit => {\n if (! this.groups[vit.color]) this.groups[vit.color] = { vitamins: [], mini: null, maxi: null };\n\n // Set mini in color group\n mini = this.groups[vit.color].mini;\n if (! mini || vit.size < mini) {\n this.groups[vit.color].mini = vit.size;\n }\n\n // Set maxi in color group\n maxi = this.groups[vit.color].maxi;\n if (! maxi || vit.size > maxi) {\n this.groups[vit.color].maxi = vit.size;\n }\n\n this.groups[vit.color].vitamins.push(vit);\n });\n\n // Create the empty groups with no vitamins\n Object.values(Vitamin.COLORS).forEach(color => {\n if (! this.groups[color]) {\n this.groups[color] = { vitamins: [], mini: null, maxi: null };\n // console.log(Texts.EMPTY_GROUP(color));\n }\n });\n\n //console.log('Grouped by colors:', this.groups);\n }", "static _groupByOrderNumber(results, newLineItemState) {\n const existingItem = results.find(\n (lineItem) => lineItem.orderNumber === newLineItemState.orderNumber\n )\n\n if (existingItem) existingItem.lineItems.push(...newLineItemState.lineItems)\n else results.push(newLineItemState)\n\n return results\n }", "groupBy(func) {\n // get all unique groups\n const groups = new Set(this.result.map(row => func(row)))\n // collect all values for all groups\n this.result = [...groups].map(gr => [gr, this.result.filter(i => func(i) == gr)])\n // the result now looks like:\n /*\n [\n [group_1, [ row_1, row_2, ...]],\n [group_2, [ row_3, row_5, ...]],\n ...\n ]\n */\n return this\n }", "static generateFlatGroupListFromIniFile(inventory) {\r\n const hostsIni = loadIniFile.sync( inventory.filenameFullPath )\r\n var groupList = {}\r\n \r\n for (var groupName in hostsIni) {\r\n var _groupName = Group.normalizeGroupName(groupName)\r\n \r\n if (groupList[_groupName] === undefined) {\r\n groupList[_groupName] = new Group(inventory.name, inventory.env, groupName)\r\n }\r\n \r\n if (Group.hasHosts(groupName)) {\r\n // add hostnames\r\n for(var hostname in hostsIni[groupName]) {\r\n groupList[_groupName].hostnames.push(hostname.split(' ')[0])\r\n }\r\n }\r\n else if (Group.hasSubgroups(groupName)) {\r\n // add subgroups\r\n for(var subGroupName in hostsIni[groupName]) {\r\n groupList[_groupName].subgroups.push(subGroupName)\r\n // need to add goups here as well because they may be listed only as subgroups\r\n if (groupList[subGroupName] === undefined) {\r\n groupList[subGroupName] = new Group(inventory.name, inventory.env, subGroupName)\r\n }\r\n }\r\n } else if (Group.hasGroupVariables(groupName)) {\r\n // add variables from the hosts ini-file\r\n for (var varName in hostsIni[groupName]) {\r\n groupList[_groupName].variables[varName] = hostsIni[groupName][varName]\r\n }\r\n } else {\r\n console.log(\"During generation of flat group list, group '%s' could not be considered!\", groupName)\r\n }\r\n }\r\n\r\n // add variables and configuration from subfolder group_vars\r\n Group.internal_addVariablesFromFolder(inventory, groupList)\r\n\r\n Group.internal_addGroupAllIfNotExist(inventory, groupList)\r\n\r\n Group.internal_addGroupUngroupedIfNotExist(inventory, groupList)\r\n \r\n // console.log(\"Flat Group List: \")\r\n // console.dir(JSON.parse(JSON.stringify(groupList)), {depth: null, colors: true})\r\n return groupList\r\n }", "createGroups() {\n\t\tlet heightScale = d3.scaleLinear().domain([0, 100]).range([0, this.height - this.barGroupHeight]);\n\t\tlet widthScale = d3.scaleLinear().domain([0, 100]).range([0, this.width]);\n\t\tlet invWidth = 1.0 / this.totalBars;\n\n\t\tthis.svg.selectAll(\"g\").remove();\n\t\tlet bargroupsgroup = this.svg.append(\"g\");\n\n\t\tlet barData = [];\n\t\tlet barNames = [\"colorbar\", \"timebar\", \"branchesbar\", \"samplesbar\", \"depthbar\", \"variancebar\", \"boxIntersections\", \"objIntersections\"];\n\t\tlet sortFields = [\"color\", \"time\", \"branches\", \"samples\", \"depth\", \"variance\", \"boxIntersections\", \"objIntersections\"];\n\t\tfor (let i = 0; i < this.totalBars; ++i) {\n\t\t\tlet entry = {\n\t\t\t\t\"class\" : barNames[i],\n\t\t\t\t\"newClass\" : barNames[i],\n\t\t\t\t\"idx\" : i,\n\t\t\t\t\"width\" : this.width / this.totalBars,\n\t\t\t\t\"self\" : this,\n\t\t\t\t\"sortField\" : sortFields[i],\n\t\t\t\t\"x\": i * widthScale(100 / this.totalBars)\n\t\t\t}\n\t\t\tbarData.push(entry);\n\t\t}\n\n\t\tlet groups = bargroupsgroup.selectAll(\"g\").data(barData);\n\t\tlet enterGroups = groups.enter().append(\"g\");\n\t\tlet allGroups = groups.merge(enterGroups)\n\n\t\tallGroups.each(function(d) { this.classList.add(d.class); this.classList.add(\"b\" + d.idx); this.classList.add(\"bargroup\"); })\n\t\t\t\t.call(d3.drag().on(\"start\", this.dragstarted).on(\"drag\", this.dragged).on(\"end\", this.dragended));\n\n\n\t\tthis.svg.append(\"g\").classed(\"selectableBar overlay\", true);\n\t\t//this.update();\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
hueristic function (h cost): cost to the goal
hueuristic() { // This hueristic is simply the distance to the goal return Math.sqrt(Math.pow(this.x - goal.x, 2) + Math.pow(this.y - goal.y, 2)); }
[ "function hCost(position) {\n return Math.abs(position.x - end_position.x) + Math.abs(position.y - end_position.y);\n }", "docosts1(u,cost) {\n\t\tlet l = this.left(u); let r = this.right(u);\n\t\tlet mc = cost[u];\n\t\tif (l) {\n\t\t\tthis.docosts1(l,cost);\n\t\t\tmc = Math.min(mc, this.#dmin[l]);\n\t\t}\n\t\tif (r) {\n\t\t\tthis.docosts1(r,cost);\n\t\t\tmc = Math.min(mc, this.#dmin[r]);\n\t\t}\n\t\tthis.#dcost[u] = cost[u] - mc;\n\t\tthis.#dmin[u] = mc; // adjust this in second phase\n\t}", "static Hermite(value1, tangent1, value2, tangent2, amount) {\n const squared = amount * amount;\n const cubed = amount * squared;\n const part1 = 2.0 * cubed - 3.0 * squared + 1.0;\n const part2 = -2.0 * cubed + 3.0 * squared;\n const part3 = cubed - 2.0 * squared + amount;\n const part4 = cubed - squared;\n const x = value1.x * part1 +\n value2.x * part2 +\n tangent1.x * part3 +\n tangent2.x * part4;\n const y = value1.y * part1 +\n value2.y * part2 +\n tangent1.y * part3 +\n tangent2.y * part4;\n const z = value1.z * part1 +\n value2.z * part2 +\n tangent1.z * part3 +\n tangent2.z * part4;\n return new Vector3(x, y, z);\n }", "static Hermite(value1, tangent1, value2, tangent2, amount) {\n const squared = amount * amount;\n const cubed = amount * squared;\n const part1 = 2.0 * cubed - 3.0 * squared + 1.0;\n const part2 = -2.0 * cubed + 3.0 * squared;\n const part3 = cubed - 2.0 * squared + amount;\n const part4 = cubed - squared;\n const x = value1.x * part1 +\n value2.x * part2 +\n tangent1.x * part3 +\n tangent2.x * part4;\n const y = value1.y * part1 +\n value2.y * part2 +\n tangent1.y * part3 +\n tangent2.y * part4;\n return new Vector2(x, y);\n }", "function torchingTreesFirebrandHeight (treeHt, flameHt, flameDur) {\n const parms = [{\n a: 4.24,\n b: 0.332\n }, {\n a: 3.64,\n b: 0.391\n }, {\n a: 2.78,\n b: 0.418\n }, {\n a: 4.7,\n b: 0.0\n }]\n const ratio = flameHt <= 0 ? 0 : treeHt / flameHt\n let idx = 3\n\n if (ratio >= 1) {\n idx = 0\n } else if (ratio >= 0.5) {\n idx = 1\n } else if (flameDur < 3.5) {\n idx = 2\n }\n\n return parms[idx].a * Math.pow(flameDur, parms[idx].b) * flameHt + 0.5 * treeHt\n}", "function createHfLut(fs, hfLut, n) {\n\t//var n = 1 + Math.ceil(1.0 / p);\n\tvar b = 0.65;\n\tvar u0 = 0.0;\n\tvar u1 = 1.0;\n\tvar nn = 1;\n//\tvar fsn = fs.length;\n\tvar fis = (u1 - u0) / functionSummaries.length;\n\tfor (var i = 0; i < n; ++i) {\n\t\tvar u = (1.0 * i) / n;\n\t\tvar fic = Math.floor(functionSummaries.length * u);\n\t\tvar v = 0;\n\t\tvar fi0 = Math.max(0, fic - nn), fi1 = Math.min(functionSummaries.length - 1, fic + nn);\n\t\tfor (var fi = fi0;\n\t\t\tfi <= fi1; ++fi) {\n\t\t\tvar ficu = u0 + fis / 2 + fis * fi;\n\t\t\tvar su = b * (u - ficu) * 2.0 / fis;\n//\t\t\talert(\"\" + fi + \":\" + su);\n\t\t\tv += fs[fi] * (su < 0 ? stepf(-su) : stepf(su));\n\t\t}\n\t\thfLut[i] = v;\n\t\t\n\t\t\n\t\t\n\t}\n\thfLut[n] = hfLut[n - 1];\n//\talert(hfLut);\n}", "function countHcoverHwiMinus() {\n\t\t\tif(instantObj.noOfHcoverHWI > 0) {\n\t\t\t\tinstantObj.noOfHcoverHWI = instantObj.noOfHcoverHWI - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "function burningPileFirebrandHeight (flameHt) {\n return Math.max(0.0, 12.2 * flameHt)\n}", "function compute_LF_oAA_pH(ibu) {\n var LF_pH = 1.0;\n var pH = ibu.pH.value;\n var preBoilpH = 0.0;\n var preOrPostBoilpH = ibu.preOrPostBoilpH.value;\n\n if (ibu.pHCheckbox.value) {\n // If pre-boil pH, estimate the post-boil pH which is the\n // one we want to base losses on.\n if (preOrPostBoilpH == \"preBoilpH\") {\n preBoilpH = pH;\n pH = compute_postBoil_pH(preBoilpH);\n }\n\n // formula from blog post 'The Effect of pH on Utilization and IBUs'\n LF_pH = (1.178506 * pH) - 5.776411\n if (SMPH.verbose > 5) {\n console.log(\"pH = \" + pH + \", LF for nonIAA = \" + LF_pH.toFixed(4));\n }\n }\n\n return LF_pH;\n}", "function compute_LF_IAA_pH(ibu) {\n var LF_pH = 1.0;\n var pH = ibu.pH.value;\n var preBoilpH = 0.0;\n var preOrPostBoilpH = ibu.preOrPostBoilpH.value;\n\n if (ibu.pHCheckbox.value) {\n // If pre-boil pH, estimate the post-boil pH which is the\n // one we want to base losses on.\n if (preOrPostBoilpH == \"preBoilpH\") {\n preBoilpH = pH;\n pH = compute_postBoil_pH(preBoilpH);\n }\n\n // formula from blog post 'The Effect of pH on Utilization and IBUs'\n LF_pH = (0.071 * pH) + 0.592;\n if (SMPH.verbose > 5) {\n console.log(\"pH = \" + pH + \", LF for IAA = \" + LF_pH.toFixed(4));\n }\n }\n\n return LF_pH;\n}", "function countHcoverHwfMinus() {\n\t\t\tif(instantObj.noOfHcoverHWF > 0) {\n\t\t\t\tinstantObj.noOfHcoverHWF = instantObj.noOfHcoverHWF - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "ADDHL() {\n const a = regA[0];\n const m = MMU.rb(regHL[0]);\n regA[0] += m;\n regF[0] = (regA[0] < a) ? F_CARRY : 0;\n if (!regA[0]) regF[0] |= F_ZERO;\n if ((regA[0] ^ a ^ m) & 0x10) regF[0] |= F_HCARRY;\n return 8;\n }", "speedUp() {\n if(this.score > 30) {\n return 1.8;\n }\n if(this.score > 20) {\n return 1.7;\n }\n if(this.score > 15) {\n return 1.5;\n }\n else if(this.score > 12) {\n return 1.4;\n }\n else if(this.score > 10) {\n return 1.3;\n }\n else if(this.score > 8) {\n return 1.2;\n }\n else if(this.score > 5) {\n return 1.1;\n }\n return 1;\n }", "function countHcoverHwiPlus() {\n\t\t\tinstantObj.noOfHcoverHWI = instantObj.noOfHcoverHWI + 1;\n\t\t\tcountTotalBill();\n\t\t}", "function calculateBonus() {\n return .02 * salary;\n}", "visitCpu_cost(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function calculHtTotal(prix_ht, quantite)\n {\n \treturn parseFloat(prix_ht * quantite);\n }", "function ucs() {\n let toVisit = new PriorityQueue();\n \n // our start state, and the path to get there (which is go to start state)\n toVisit.add({\n coords: getStartState(),\n path: [getStartState()],\n cost: 0,\n heuristic_cost: 0 // the priority queue sorts by this\n })\n\n let visited = new BetterSet();\n\n return undefined;\n}", "dcost(u, c=-1) {\n\t\tif (c != -1) this.#dcost[u] = c;\n\t\treturn this.#dcost[u];\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function set the standard journal allocation credit lines
function setStandardJournalCreditLines(recBill,recJE) { //set the journal credit line for expense var arrSubTab = []; arrSubTab.push('item'); arrSubTab.push('expense'); var currentLine = recJE.getLineItemCount('line'); currentLine = (!currentLine || currentLine==0) ? 1 : currentLine + 1; var stMemo = 'System Generated from Vendor Bill #: ' + recBill.getFieldValue('transactionnumber'); var fExchRate = recBill.getFieldValue('exchangerate'); var stCurrency = recBill.getFieldValue('currency'); recJE.setFieldValue('currency',stCurrency); for(var x=0; x<arrSubTab.length; x++) { var count = recBill.getLineItemCount(arrSubTab[x]); for(var i=1; count && count!=0 && i<=count; i++) { var isExclude = recBill.getLineItemValue(arrSubTab[x],'custcol_svb_bill_distr_exclude',i); if(isExclude=='T') { continue; } var stItemId = recBill.getLineItemValue(arrSubTab[x],'item',i); var stBillLineAcct = (arrSubTab[x]=='expense') ? recBill.getLineItemValue(arrSubTab[x],'account',i) : recBill.getLineItemValue(arrSubTab[x],'custcol_svb_item_exp_account',i); var fBillLineAmt = recBill.getLineItemValue(arrSubTab[x],'amount',i); fBillLineAmt = parseFloat(fBillLineAmt); // * fExchRate; fBillLineAmt = fBillLineAmt.toFixed(2); var stBillLineDept = recBill.getLineItemValue(arrSubTab[x],'department',i); var stBillLineClass = recBill.getLineItemValue(arrSubTab[x],'class',i); var stBillLineLoc = recBill.getLineItemValue(arrSubTab[x],'location',i); recJE.setLineItemValue('line','account',currentLine,stBillLineAcct); recJE.setLineItemValue('line','credit',currentLine,fBillLineAmt); recJE.setLineItemValue('line','department',currentLine,stBillLineDept); recJE.setLineItemValue('line','class',currentLine,stBillLineClass); recJE.setLineItemValue('line','location',currentLine,stBillLineLoc); recJE.setLineItemValue('line','memo',currentLine,stMemo); nlapiLogExecution('DEBUG','setStandardJournalCreditLines','stBillLineAcct=' + stBillLineAcct + ' fBillLineAmt=' + fBillLineAmt + ' stBillLineDept=' + stBillLineDept); nlapiLogExecution('DEBUG','setStandardJournalCreditLines','stBillLineClass=' + stBillLineClass + ' stBillLineLoc=' + stBillLineLoc + ' currentLine=' + currentLine); currentLine++; } } nlapiLogExecution('DEBUG','setStandardJournalCreditLines','Count=' + recJE.getLineItemCount('line')); return recJE; }
[ "function setStandardJournalDebitLines(recBill,recJE,arrBDD)\r\n{\r\n var stMemo = 'System Generated from Vendor Bill #: ' + recBill.getFieldValue('transactionnumber');\r\n \r\n var currentLine = recJE.getLineItemCount('line');\r\n currentLine = (!currentLine || currentLine==0) ? 1 : currentLine + 1; \r\n var arrTotDbtAmt = [];\r\n var fTotalVBAmt = recBill.getFieldValue('total');\r\n fTotalVBAmt = parseFloat(fTotalVBAmt); \r\n var arrDebitLine = [];\r\n \r\n for(var i=0; i<arrBDD.length; i++)\r\n {\r\n var intTab = arrBDD[i].getValue('custrecord_svb_details_sublisttype');\r\n var intLineNo = arrBDD[i].getValue('custrecord_svb_details_line_number'); \r\n var fTotalLineAmt = arrBDD[i].getValue('custrecord_svb_details_line_amount'); \r\n var stDebitLineAcct = arrBDD[i].getValue('custrecord_svb_details_account');\r\n var fDebitLineAmt = arrBDD[i].getValue('custrecord_svb_details_foreign_amt');\r\n fDebitLineAmt = (Math.round(parseFloat(fDebitLineAmt))*100)/100; \r\n var stDebitLineDept = arrBDD[i].getValue('custrecord_svb_details_department');\r\n var stDebitLineClass = arrBDD[i].getValue('custrecord_svb_details_class');\r\n var stDebitLineLoc = arrBDD[i].getValue('custrecord_svb_details_location');\r\n nlapiLogExecution('DEBUG','setStandardJournalDebitLines','stDebitLineAcct=' + stDebitLineAcct + ' stDebitLineAmt=' + fDebitLineAmt + ' stDebitLineDept=' + stDebitLineDept);\r\n nlapiLogExecution('DEBUG','setStandardJournalDebitLines','stDebitLineClass=' + stDebitLineClass + ' stDebitLineLoc=' + stDebitLineLoc + ' currentLine=' + currentLine);\r\n \r\n //array for allocation weight\r\n if (arrDebitLine[intTab + '-' + intLineNo + '-' + fTotalLineAmt] == null || arrDebitLine[intTab + '-' + intLineNo + '-' + fTotalLineAmt] == undefined) \r\n {\r\n arrDebitLine[intTab + '-' + intLineNo + '-' + fTotalLineAmt] = [];\r\n }\r\n arrDebitLine[intTab + '-' + intLineNo + '-' + fTotalLineAmt].push({account: stDebitLineAcct, debit: fDebitLineAmt, department: stDebitLineDept, classification: stDebitLineClass, location: stDebitLineLoc, memo: stMemo});\r\n }\r\n \r\n for(line in arrDebitLine)\r\n {\r\n var arrPerLine = arrDebitLine[line];\r\n var fTotalVBAmt = line.split('-')[2];\r\n fTotalVBAmt = parseFloat(fTotalVBAmt);\r\n var fTotDbAmt = 0.00;\r\n \r\n for(var i=0; i<arrPerLine.length; i++)\r\n {\r\n var objJEDetails = arrPerLine[i];\r\n \r\n //set journal debit lines\r\n recJE.setLineItemValue('line','account',currentLine,objJEDetails.account); \r\n recJE.setLineItemValue('line','debit',currentLine,objJEDetails.debit);\r\n recJE.setLineItemValue('line','department',currentLine,objJEDetails.department);\r\n recJE.setLineItemValue('line','class',currentLine,objJEDetails.classification);\r\n recJE.setLineItemValue('line','location',currentLine,objJEDetails.location);\r\n recJE.setLineItemValue('line','memo',currentLine,objJEDetails.memo);\r\n \r\n fTotDbAmt += objJEDetails.debit;\r\n \r\n currentLine ++;\r\n }\r\n \r\n //make an adjustment on the last line if the not balance journal is within the tolerance of 0.01 due to rounding off \r\n fTotDbAmt = (Math.round(parseFloat(fTotDbAmt) * 100))/100;\r\n nlapiLogExecution('DEBUG','setStandardJournalDebitLines','fTotDbAmt=' + fTotDbAmt + ' fTotalVBAmt=' + fTotalVBAmt);\r\n \r\n //adjust if there are rounding issue\r\n recJE = adjustJEByTolerance(recJE,fTotDbAmt,fTotalVBAmt)\r\n }\r\n \r\n nlapiLogExecution('DEBUG','setStandardJournalDebitLines','Count=' + recJE.getLineItemCount('line'));\r\n return recJE;\r\n}", "function createAllocJournalEntry(recBill,IS_INTERCO,stTrigFrom)\r\n{\r\n nlapiLogExecution('DEBUG','createAllocJournalEntry','BEGIN - Create Allocation Journal Entry');\r\n \r\n var stBillsSubs = recBill.getFieldValue('subsidiary'); \r\n var intItemCount = recBill.getLineItemCount('item');\r\n var intExpCount = recBill.getLineItemCount('expense'); \r\n var stJEId = null;\r\n \r\n //search the newly created distribution details\r\n var arrBDD = getBillDistributionDetails(recBill.getId());\r\n \r\n if(!arrBDD)\r\n {\r\n return;\r\n }\r\n \r\n if(IS_INTERCO!='T')\r\n {\r\n //create the record\r\n var recJE = nlapiCreateRecord('journalentry');\r\n \r\n //set the journal header\r\n recJE.setFieldValue('subsidiary',stBillsSubs);\r\n recJE.setFieldValue('custbody_svb_vend_bill_link',recBill.getId());\r\n recJE.setFieldValue('approved','T');\r\n \r\n //set the credit based from item and expense tab\r\n recJE = setStandardJournalCreditLines(recBill,recJE);\r\n \r\n //set the debit based from distribution details\r\n recJE = setStandardJournalDebitLines(recBill,recJE,arrBDD); \r\n \r\n try\r\n {\r\n //save the transaction\r\n stJEId = nlapiSubmitRecord(recJE,true,true);\r\n nlapiLogExecution('DEBUG','createJournalEntry','stJEId=' + stJEId);\r\n }\r\n catch(e)\r\n {\r\n var stErrDetails = 'Error in creating allocation journal entry. Details: ' + e.toString();\r\n nlapiSubmitField('vendorbill',recBill.getId(),'custbody_svb_error_logs',stErrDetails);\r\n throw nlapiCreateError('Error',stErrDetails,true);\r\n }\r\n \r\n if(stTrigFrom!='suitelet')\r\n {\r\n if(stJEId)\r\n {\r\n nlapiSubmitField('vendorbill',recBill.getId(),['custbody_svb_allocation_journal','custbody_svb_error_logs'],[[stJEId],'']);\r\n }\r\n }\r\n else\r\n {\r\n recBill.setFieldValues('custbody_svb_allocation_journal',[stJEId]);\r\n recBill.setFieldValue('custbody_svb_error_logs','');\r\n }\r\n nlapiLogExecution('DEBUG','Create Standard Journal Entry','stJEId=' + stJEId);\r\n }\r\n else\r\n {\r\n var stFrmSubs = recBill.getFieldValue('subsidiary');\r\n var stPeriod = recBill.getFieldValue('postingperiod');\r\n var stDate = recBill.getFieldValue('trandate');\r\n var arrSort = sortDistributionDetails(arrBDD,stBillsSubs);\r\n var arrUniqToSubs = arrSort[0];\r\n var arrSortedBDD = arrSort[1];\r\n var arrJEIDs = [];\r\n nlapiLogExecution('DEBUG','Create IC Journal Entry','arrUniqToSubs=' + JSON.stringify(arrUniqToSubs)); \r\n \r\n for(var i=0; i<arrUniqToSubs.length; i++)\r\n {\r\n var recICJE = nlapiCreateRecord('intercompanyjournalentry');\r\n var stCurrToSubs = arrUniqToSubs[i];\r\n \r\n //set the ic journal header\r\n recICJE.setFieldValue('subsidiary',stFrmSubs);\r\n recICJE.setFieldValue('tosubsidiary',stCurrToSubs);\r\n recICJE.setFieldValue('custbody_svb_vend_bill_link',recBill.getId());\r\n recICJE.setFieldValue('approved','T');\r\n \r\n //set date and posting period on IC JE based on vendor bill values\r\n recICJE.setFieldValue('trandate',stDate);\r\n recICJE.setFieldValue('postingperiod',stPeriod);\r\n \r\n for(line in arrSortedBDD)\r\n {\r\n var arrLines = arrSortedBDD[line]; \r\n var arrParentLine = arrLines[0];\r\n \r\n for(var x=1; x<arrLines.length; x++)\r\n { \r\n var arrToSubsidiaries = arrSortedBDD[line][x];\r\n var arrToSub = arrToSubsidiaries[0];\r\n var stToSub = arrToSubsidiaries[1];\r\n var objToDetails = arrToSubsidiaries[2]; \r\n \r\n if(stCurrToSubs!=stToSub)\r\n {\r\n continue;\r\n }\r\n \r\n recICJE = setICJEParentLines(recBill,recICJE,arrParentLine,stFrmSubs,objToDetails); \r\n recICJE = setICJEToSubsidiaryLines(recBill,recICJE,arrToSub,stCurrToSubs,objToDetails); \r\n }\r\n }\r\n \r\n try\r\n {\r\n //save the je\r\n stJEId = nlapiSubmitRecord(recICJE,true,true);\r\n }\r\n catch(e)\r\n {\r\n //reverse all the ICJE that is recently created\r\n if(arrJEIDs.length>0)\r\n {\r\n for(var i=0; i<arrJEIDs.length; i++)\r\n {\r\n var stAllocJrnlId = arrJEIDs[i];\r\n nlapiSubmitField('journalentry',stAllocJrnlId,'reversaldate',nlapiDateToString(new Date()));\r\n }\r\n }\r\n \r\n var stErrDetails = 'Error in creating allocation journal entry. Details: ' + e.toString();\r\n nlapiSubmitField('vendorbill',recBill.getId(),'custbody_svb_error_logs',stErrDetails);\r\n throw nlapiCreateError('Error',stErrDetails,true);\r\n }\r\n \r\n //push the jeid to array\r\n arrJEIDs.push(stJEId);\r\n \r\n nlapiLogExecution('DEBUG','Create IC Journal Entry','To Subsidiary:' + stCurrToSubs + '-> stJEId=' + stJEId);\r\n }\r\n \r\n if(stTrigFrom!='suitelet')\r\n {\r\n if(arrJEIDs.length>0)\r\n {\r\n nlapiSubmitField('vendorbill',recBill.getId(),['custbody_svb_allocation_journal','custbody_svb_error_logs'],[arrJEIDs,'']);\r\n }\r\n }\r\n else\r\n {\r\n recBill.setFieldValues('custbody_svb_allocation_journal',arrJEIDs);\r\n recBill.setFieldValue('custbody_svb_error_logs','');\r\n }\r\n }\r\n nlapiLogExecution('DEBUG','createAllocJournalEntry','END - Create Allocation Journal Entry');\r\n \r\n return recBill;\r\n}", "function createCreditNoteDetailLine()\n{\n\ttry\n\t{\n\t\t// create credit note line\n\t\tcreditNoteRecord.selectNewLineItem('item');\n\t\tcreditNoteRecord.setCurrentLineItemValue('item', 'item', COMMISSIONITEMINTID); \n\t\tcreditNoteRecord.setCurrentLineItemValue('item', 'amount', comTotal);\n\t\tcreditNoteRecord.setCurrentLineItemValue('item', 'taxcode', TAXINTID);\n\t\tcreditNoteRecord.commitLineItem('item');\n\t\t\n\t}\n\tcatch(e)\n\t{\n\t\terrorHandler(\"createCreditNoteDetailLine\", e);\t\t\t\t\n\t} \n\n}", "function reverseAllocJournalEntry(arrAllocJrnl)\r\n{\r\n //var arrAllocJrnl = recBill.getFieldValues('custbody_svb_allocation_journal'); \r\n if(arrAllocJrnl)\r\n {\r\n for(var i=0; i<arrAllocJrnl.length; i++)\r\n {\r\n var stAllocJrnlId = arrAllocJrnl[i];\r\n nlapiSubmitField('journalentry',stAllocJrnlId,['reversaldate','custbody_svb_vend_bill_link'],[nlapiDateToString(new Date()),'']);\r\n }\r\n } \r\n}", "function createJournalDisriCommission()\n{\t\n\tvar journalDesc = '';\n\t\n\ttry\n\t{\n\t\tjournalDesc = 'Top up Distributor Commission for Distributor: ' + distributorName;\n\t\t\n\t\t//format : createJournal(totalValue, debitAccount, creditAccount, dept, location, subsidiary, jClass, invDate, desc, entity, vatCode)\n\t\tdistriCommJRNL = createJournal(comTotal, COMMISSIONACCOUNTINTID,TOPUPBANKACCOINTINTID, 0, journalLocationIntID, 0, 0, usageDate, journalDesc, simPartnerIntID,0);\n\n\t}\n\tcatch(e)\n\t{\n\t\terrorHandler(\"createJournalDisriCommission\", e);\t\t\n\t}\n\n}", "function createBillDistributionDetails(recBill,subtab,arrBDSLines,stAllocToFollow,line,isParent)\r\n{\r\n var objBDS = {};\r\n var isSuccess = null;\r\n var fExchRate = recBill.getFieldValue('exchangerate');\r\n var stParentSubs = recBill.getFieldValue('subsidiary');\r\n \r\n //check if the line is recently adjusted its scheduled distribution details\r\n if(stAllocToFollow)\r\n {\r\n var arrOldDetails = JSON.parse(stAllocToFollow); //TBD\r\n \r\n for(var i=0; arrOldDetails && i<arrOldDetails.length; i++)\r\n {\r\n var arrDetails = arrOldDetails[i];\r\n var objOldDetails = convertBDSArrayToObject(arrDetails);\r\n \r\n var fOldAllocWt = objOldDetails.allocwt;\r\n fOldAllocWt = parseFloat(fOldAllocWt)/100;\r\n \r\n if(subtab == EXPENSE)\r\n {\r\n objOldDetails.expcat = recBill.getLineItemValue('expense','category',line);\r\n objOldDetails.expacct = recBill.getLineItemValue('expense','account',line);\r\n objOldDetails.lineamt = recBill.getLineItemValue('expense','amount',line);\r\n }\r\n else\r\n {\r\n objOldDetails.itemid = recBill.getLineItemValue('item','item',line);\r\n objOldDetails.expacct = recBill.getLineItemValue('item','custcol_svb_item_exp_account',line);\r\n objOldDetails.itemqty = recBill.getLineItemValue('item','quantity',line);\r\n objOldDetails.lineamt = recBill.getLineItemValue('item','amount',line); \r\n }\r\n \r\n objOldDetails.foramt = fOldAllocWt * parseFloat(objOldDetails.lineamt);\r\n objOldDetails.amount = (objOldDetails.foramt * fExchRate).toFixed(2);\r\n \r\n createUpdateBDSRecord(objOldDetails);\r\n }\r\n }\r\n else\r\n {\r\n objBDS.destsubs = arrBDSLines.getValue('custrecord_svb_line_subsidiary');\r\n objBDS.tranid = recBill.getId();\r\n objBDS.tranidtext = recBill.getId();\r\n objBDS.sublist = subtab;\r\n objBDS.linenum = line;\r\n objBDS.parentlink = arrBDSLines.getValue('custrecord_svb_line_parent_link');\r\n objBDS.destdept = arrBDSLines.getValue('custrecord_svb_line_department');\r\n objBDS.destclass = arrBDSLines.getValue('custrecord_svb_line_class');\r\n objBDS.destloc = arrBDSLines.getValue('custrecord_svb_line_location');\r\n objBDS.interaracct = arrBDSLines.getValue('custrecord_svb_line_intercomp_account');\r\n objBDS.interapacct = arrBDSLines.getValue('custrecord_svb_line_intercomp_ap_account');\r\n objBDS.destacct = arrBDSLines.getValue('custrecord_svb_line_account');\r\n objBDS.intercust = arrBDSLines.getValue('custrecord_svb_line_intercomp_customer');\r\n objBDS.intervend = arrBDSLines.getValue('custrecord_svb_line_intercomp_vendor');\r\n var fAllocWt = arrBDSLines.getValue('custrecord_svb_line_allocation_weight');\r\n fAllocWt = parseFloat(fAllocWt);\r\n objBDS.allocwt = fAllocWt;\r\n \r\n var isSourceAcct = arrBDSLines.getValue('custrecord_svb_use_source_accounts','custrecord_svb_line_parent_link');\r\n //nlapiLogExecution('DEBUG','createBillDistributionDetails','stBillId=' + stBillId + ' stSVBParent=' + stSVBParent + ' stDestSubs=' + stDestSubs + ' stDept=' + stDept);\r\n //nlapiLogExecution('DEBUG','createBillDistributionDetails','stClass=' + stClass + ' stLoc=' + stLoc + ' stDestSubs=' + stDestSubs + ' stInterCoAcct=' + stInterCoAcct);\r\n //nlapiLogExecution('DEBUG','createBillDistributionDetails','stDestAcct=' + stDestAcct + ' stInterCoCust=' + stInterCoCust + ' stInterCoVend=' + stInterCoVend + ' fAllocWt=' + fAllocWt);\r\n \r\n //vendor bill line\r\n var fAmount = 0.00;\r\n var fAllocAmt = 0.00;\r\n \r\n if(subtab == EXPENSE)\r\n {\r\n objBDS.expcat = recBill.getLineItemValue('expense','category',line);\r\n objBDS.expacct = recBill.getLineItemValue('expense','account',line);\r\n objBDS.lineamt = recBill.getLineItemValue('expense','amount',line);\r\n }\r\n else\r\n {\r\n objBDS.itemid = recBill.getLineItemValue('item','item',line);\r\n objBDS.expacct = recBill.getLineItemValue('item','custcol_svb_item_exp_account',line);\r\n objBDS.itemqty = recBill.getLineItemValue('item','quantity',line);\r\n objBDS.lineamt = recBill.getLineItemValue('item','amount',line); \r\n }\r\n nlapiLogExecution('DEBUG','isParent','objBDS.destsubs=' + objBDS.destsubs + ' line=' + line + ' isParent=' + isParent);\r\n \r\n var stMachine = (subtab == EXPENSE) ? 'expense' : 'item';\r\n \r\n //department, class and location should be sourced on the line if subsidiary is parent\r\n if(isParent)\r\n {\r\n nlapiLogExecution('DEBUG','isParent','line=' + line);\r\n objBDS.destdept = recBill.getLineItemValue(stMachine,'department',line);\r\n objBDS.destclass = recBill.getLineItemValue(stMachine,'class',line);\r\n objBDS.destloc = recBill.getLineItemValue(stMachine,'location',line);\r\n nlapiLogExecution('DEBUG','isParent','objBDS.destdept=' + objBDS.destdept + ' objBDS.destclass=' + objBDS.destclass + ' objBDS.destloc=' + objBDS.destloc);\r\n }\r\n \r\n //if source account on the distribution is checked then get the account on the vendor bill line account\r\n var isSourceAcct = arrBDSLines.getValue('custrecord_svb_use_source_accounts','custrecord_svb_line_parent_link');\r\n if(isSourceAcct=='T')\r\n {\r\n objBDS.destacct = objBDS.expacct;\r\n }\r\n \r\n //calculate the allocated amount\r\n fAmount = (objBDS.lineamt) ? parseFloat(objBDS.lineamt) : 0.00;\r\n fAllocAmt = (fAmount * fAllocWt/100);\r\n fAllocAmt = (Math.round(fAllocAmt * 100))/100;\r\n objBDS.foramt = fAllocAmt;\r\n objBDS.amount = (fAllocAmt * fExchRate).toFixed(2);\r\n \r\n //create the distribution details record \r\n createUpdateBDSRecord(objBDS);\r\n //nlapiLogExecution('DEBUG','Bill Distribution Details Created','isSuccess=' + isSuccess);\r\n }\r\n return isSuccess;\r\n}", "function setCredits() {\n currentCredits = accruedCredits;\n showCredits(currentCredits, creditsRecorded);\n updateCombined(accruedCredits - lastCredits);\n lastCredits = accruedCredits;\n}", "function set_new_patron_defaults(prs) {\n if (!$scope.patron.passwd) {\n // passsword may originate from staged user.\n $scope.generate_password();\n }\n $scope.hold_notify_type.phone = true;\n $scope.hold_notify_type.email = true;\n $scope.hold_notify_type.sms = false;\n\n // staged users may be loaded w/ a profile.\n $scope.set_expire_date();\n\n if (prs.org_settings['ui.patron.default_ident_type']) {\n // $scope.patron needs this field to be an object\n var id = prs.org_settings['ui.patron.default_ident_type'];\n var ident_type = $scope.ident_types.filter(\n function(type) { return type.id() == id })[0];\n $scope.patron.ident_type = ident_type;\n }\n if (prs.org_settings['ui.patron.default_inet_access_level']) {\n // $scope.patron needs this field to be an object\n var id = prs.org_settings['ui.patron.default_inet_access_level'];\n var level = $scope.net_access_levels.filter(\n function(lvl) { return lvl.id() == id })[0];\n $scope.patron.net_access_level = level;\n }\n if (prs.org_settings['ui.patron.default_country']) {\n $scope.patron.addresses[0].country = \n prs.org_settings['ui.patron.default_country'];\n }\n }", "function createJournalVoucherCommission()\n{\n\tvar journalDesc = '';\n\tvar total = 0;\n\t\n\ttry\n\t{\n\t\tjournalDesc = journalVoucherDesc;\n\t\t\n\t\t// work out the voucher commission\n\t\t// after removing the % sign from the percentage\n\t\tvoucherCommission = parseFloat(voucherCommission)/100;\n\t\ttotal = topUpValue * voucherCommission;\n\t\ttotal = Math.round(total*100)/100;\n\n\t\t\n\t\t// totalValue, toAcc, fromAcc, dept, location, subsidiary, jClass, invDate, desc, entity, vatCode\n\t\tvoucherJRNL = createJournal(total, voucherCommIntID, incomeAccountIntID, 0, journalLocationIntID, 0,0, usageDate, journalDesc,0,0);\n\t\t\n\t}\n\tcatch(e)\n\t{\n\t\terrorHandler(\"createJournalVoucherCommission\", e);\t\t\n\t}\n\t\n}", "function creditCARow(row){ \n if (formatAmount(document.getElementById('amtCreditCA_'+row),'CA')){ \n CCT.index.creditCARow(row,gOldCACreditAmt[row],document.getElementById('emailCreditCA_'+row).value\n ,document.getElementById('notesCreditCA_'+row).value,creditCARowCallback);\n \n document.getElementById(\"mCreditCATableDiv\").style.display = 'none';\n errorMessage(\"Crediting ...\",\"CreditCA\",\"Message\");\n document.mForm.mCreditButton.disabled = true; \n } \n }", "onCreditAdd() {\n\t\tconst newCredit = new Credit(this.props.uuidGenerator.generate());\n\t\tthis.order.credits.push(newCredit);\n\t}", "insertCredit(person, amount) {\n person.takeMoney(amount)\n this.credits += amount\n if(this.credits>0){\n this.status = 'credited'\n }\n }", "function setAllCCN(cc)\n{\n\tif (checklocked() == false && trade_itemIDs.length)\n\t{\n\t\tvar idxs = eval('type' + TRADE + '_idxs');\n\t\tvar base_links = (getIDXLength(SALE) * 2);\n\t\tvar data = '';\n\t\tvar timeaddeds = new Array();\n\t\tfor (var i=0; i<idxs.length; i++)\n\t\t{\n\t\t\t// idx=idxs[i]; linkID=base_links+(i*3)+1\n\t\t\tidx = idxs[i];\n\t\t\tlinkID = (base_links + (i * 3) + 1);\n\t\t\tchange_ccn(\n\t\t\t\tTRADE,\n\t\t\t\ti,\n\t\t\t\tidx,\n\t\t\t\t(cc==CASH ? 'ccn-cash.gif' : 'ccn-credit.gif'),\n\t\t\t\tlinkID,\n\t\t\t\tcc,\n\t\t\t\ttrade_itemIDs[idx],\n\t\t\t\tfalse,\n\t\t\t\ttrue\n\t\t\t);\n\t\t\tdata = data+'0|'+cc+'|'+trade_prices[idx]+((i+1)<idxs.length?'||':'');\n\t\t\ttimeaddeds[i] = eval('timeadded' + TRADE)[i];\n\t\t}\n\n\t\tpost_data(TRADE,-1,'ini_price_manual|ini_trade_type|ini_price',data,timeaddeds.join('|'));\n\t\tupdateShownPrices(TRADE);\n\t}\n}", "function SetSupervisor(vbRec,vbOwner,vbAmount,approverLevel,approver,k) {\n\tvar appDelegate = getDelegateApprover(approver);\n\tvar amntFilter = new Array();\n\tvar amntColumn = new Array();\n\tamntFilter[0] = new nlobjSearchFilter('internalid',null,'is',approverLevel);\n\tamntColumn[0] = new nlobjSearchColumn('custrecord_spk_apl_mxm_apvlmt');\n\tvar rec_amnt = nlapiSearchRecord('customrecord_spk_apl_lvl',null,amntFilter,amntColumn);\n\tif(rec_amnt) {\n\t\t/****** Getting the supervisor Approval limit and comparing with Bill amount to determine the flow ******/\t\t\t\t\t\n\t\tvar approvalLimit = parseFloat(rec_amnt[0].getValue('custrecord_spk_apl_mxm_apvlmt'));\n\t\tnlapiLogExecution('DEBUG', 'Approver limit is', approvalLimit);\n\t\tif(vbAmount > approvalLimit) {\n\t\t\tfor(var i = 1;i <= 100; i++) {\n\t\t\t\t// Creating an Entry of the supervisor based on the Bill Amount\n\t\t\t\tif(i == 1) {\n\t\t\t\t\tvar mtrxFlag = false;\n\t\t\t\t\tvar apMtrxCount = vbRec.getLineItemCount('recmachcustrecord_spk_apvmtx_tranno');\n\t\t\t\t\tnlapiLogExecution('DEBUG', 'apMtrxCount is', apMtrxCount);\n\t\t\t\t\tvar updatedTitle = '';\n\t\t\t\t\tfor(var m = 1;m<= apMtrxCount; m++) {\n\t\t\t\t\t\tvar mtrxApp = vbRec.getLineItemValue('recmachcustrecord_spk_apvmtx_tranno','custrecord_spk_apvmtx_apvr',m);\n\t\t\t\t\t\tvar mtrxTitle = vbRec.getLineItemValue('recmachcustrecord_spk_apvmtx_tranno','custrecord_spk_apvmtx_apvrl',m);\n\t\t\t\t\t\tvar sprvsrApp = vbRec.getLineItemValue('recmachcustrecord_spk_apvmtx_tranno','custrecord_spk_apvmtx_delgtof',m);\n\t\t\t\t\t\tif((mtrxApp == approver && !sprvsrApp)|| (mtrxApp == appDelegate && sprvsrApp == approver)) {\n\t\t\t\t\t\t\tupdatedTitle = mtrxTitle + ',' + 'Supervisor' ;\n\t\t\t\t\t\t\tvbRec.setLineItemValue('recmachcustrecord_spk_apvmtx_tranno','custrecord_spk_apvmtx_apvrl',m,updatedTitle);\n\t\t\t\t\t\t\tmtrxFlag = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif(mtrxFlag == false) {\n\t\t\t\t\t\tk = k+1;\n\t\t\t\t\t\tvbRec.selectNewLineItem('recmachcustrecord_spk_apvmtx_tranno');\n\t\t\t\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_seq', k);\n\t\t\t\t\t\tif(appDelegate) {\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apvr',appDelegate);\n\t\t\t\t\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_delgtof', approver);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\n\t\t\t\t\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apvr', approver);\n\t\t\t\t\t\t}\t\t\t\t\t\t\t\t\n\t\t\t\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apvrl','Supervisor');\n\t\t\t\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apmanager',nlapiGetUser());\n\t\t\t\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_invown',vbOwner);\n\t\t\t\t\t\tvbRec.commitLineItem('recmachcustrecord_spk_apvmtx_tranno');\n\t\t\t\t\t\t//return k;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t// Check for Active Invoice Owner & Approvers\n\t\t\t\t\tvar f2 = new Array();\n\t\t\t\t\tf2[0] = new nlobjSearchFilter('custrecord_spk_ioa_invown',null,'is',approver);\n\t\t\t\t\tf2[1] = new nlobjSearchFilter('isinactive',null,'is','F');\t\t\t\t\t\t\t\t\n\t\t\t\t\tvar col2 = new Array();\n\t\t\t\t\tcol2[0] = new nlobjSearchColumn('custrecord_spk_ioa_apvr');\n\t\t\t\t\tcol2[1] = new nlobjSearchColumn('custrecord_spk_ioa_apvlvl');\n\t\t\t\t\tvar InvOwnresults = nlapiSearchRecord('customrecord_spk_inv_own_apvr',null,f2,col2);\t\t\n\t\t\t\t\tif(InvOwnresults) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tvar approver = InvOwnresults[0].getValue('custrecord_spk_ioa_apvr');\n\t\t\t\t\t\t\tvar delegateApp = getDelegateApprover(approver);\n\t\t\t\t\t\t\tvar approverLevel = InvOwnresults[0].getValue('custrecord_spk_ioa_apvlvl');\n\t\t\t\t\t\t\tvar approvalFilter = new Array();\n\t\t\t\t\t\t\tvar approvalColumn = new Array();\n\t\t\t\t\t\t\tapprovalFilter[0] = new nlobjSearchFilter('internalid',null,'is',approverLevel);\n\t\t\t\t\t\t\tapprovalColumn[0] = new nlobjSearchColumn('custrecord_spk_apl_mxm_apvlmt');\n\t\t\t\t\t\t\tvar amntRec = nlapiSearchRecord('customrecord_spk_apl_lvl',null,approvalFilter,approvalColumn);\n\t\t\t\t\t\t\tif(amntRec) {// Determining the approval limit based on level of the approver\n\t\t\t\t\t\t\t\tvar approvalLimit = parseFloat(amntRec[0].getValue('custrecord_spk_apl_mxm_apvlmt'));\n\t\t\t\t\t\t\t\tvar currentTitle = '';\n\t\t\t\t\t\t\t\tvar supervisorFlag = false;\n\t\t\t\t\t\t\t\tvar mtrxCount = vbRec.getLineItemCount('recmachcustrecord_spk_apvmtx_tranno');\n\t\t\t\t\t\t\t\tnlapiLogExecution('DEBUG', 'mtrxCount5 is', mtrxCount);\n\t\t\t\t\t\t\t\tfor(var m1 = 1;m1<= mtrxCount; m1++) {\n\t\t\t\t\t\t\t\t\tvar mtrxAprvr = vbRec.getLineItemValue('recmachcustrecord_spk_apvmtx_tranno','custrecord_spk_apvmtx_apvr',m1);\n\t\t\t\t\t\t\t\t\tvar mtrxTitle = vbRec.getLineItemValue('recmachcustrecord_spk_apvmtx_tranno','custrecord_spk_apvmtx_apvrl',m1);\n\t\t\t\t\t\t\t\t\tvar dlgte_sprvsr = vbRec.getLineItemValue('recmachcustrecord_spk_apvmtx_tranno','custrecord_spk_apvmtx_delgtof',m1);\n\t\t\t\t\t\t\t\t\tif((mtrxAprvr == approver && !dlgte_sprvsr) || (mtrxAprvr == delegateApp && dlgte_sprvsr == approver)) {\n\t\t\t\t\t\t\t\t\t\tcurrentTitle = mtrxTitle + ',' + 'Supervisor' ;\n\t\t\t\t\t\t\t\t\t\tvbRec.setLineItemValue('recmachcustrecord_spk_apvmtx_tranno','custrecord_spk_apvmtx_apvrl',m1,currentTitle);\n\t\t\t\t\t\t\t\t\t\tsupervisorFlag = true;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif(supervisorFlag == false) {\t\n\t\t\t\t\t\t\t\t\tk = k+1;\n\t\t\t\t\t\t\t\t\tvbRec.selectNewLineItem('recmachcustrecord_spk_apvmtx_tranno');\n\t\t\t\t\t\t\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_seq', k);\n\t\t\t\t\t\t\t\t\tif(delegateApp) {\n\t\t\t\t\t\t\t\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apvr',delegateApp);\n\t\t\t\t\t\t\t\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_delgtof', approver);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apvr', approver);\n\t\t\t\t\t\t\t\t\t}\t\n\t\t\t\t\t\t\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apvrl','Supervisor');\n\t\t\t\t\t\t\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apmanager',nlapiGetUser());\n\t\t\t\t\t\t\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_invown',vbOwner);\n\t\t\t\t\t\t\t\t\tvbRec.commitLineItem('recmachcustrecord_spk_apvmtx_tranno');\n\t\t\t\t\t\t\t\t\t//return k;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif(vbAmount <= approvalLimit) {\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch (e) {\n\t\t\t\t\t\t\tnlapiLogExecution('ERROR', e.name || e.getCode(), e.message || e.getDetails());\t\t\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}\t\t\t\t\t\t\n\t\telse {\n\t\t\tvar currentTitle = '';\n\t\t\tvar supervisorFlag = false;\n\t\t\tvar mtrxCount = vbRec.getLineItemCount('recmachcustrecord_spk_apvmtx_tranno');\n\t\t\tnlapiLogExecution('DEBUG', 'mtrxCount11 is', mtrxCount);\n\t\t\tfor(var m2 = 1;m2<= mtrxCount; m2++) {\n\t\t\t\tvar mtrxAprvr = vbRec.getLineItemValue('recmachcustrecord_spk_apvmtx_tranno','custrecord_spk_apvmtx_apvr',m2);\n\t\t\t\tvar mtrxTitle = vbRec.getLineItemValue('recmachcustrecord_spk_apvmtx_tranno','custrecord_spk_apvmtx_apvrl',m2);\n\t\t\t\tvar sprvsrDlgte = vbRec.getLineItemValue('recmachcustrecord_spk_apvmtx_tranno','custrecord_spk_apvmtx_delgtof',m2);\n\t\t\t\tif((mtrxAprvr == approver && !sprvsrDlgte) || (mtrxAprvr == appDelegate && sprvsrDlgte == approver)) {\n\t\t\t\t\tcurrentTitle = mtrxTitle + ',' + 'Supervisor' ;\n\t\t\t\t\tvbRec.setLineItemValue('recmachcustrecord_spk_apvmtx_tranno','custrecord_spk_apvmtx_apvrl',m2,currentTitle);\n\t\t\t\t\tsupervisorFlag = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(supervisorFlag == false) {\n\t\t\t\tk = k+1;\n\t\t\t\tvbRec.selectNewLineItem('recmachcustrecord_spk_apvmtx_tranno');\n\t\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_seq', k);\n\t\t\t\tif(appDelegate) {\n\t\t\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apvr',appDelegate);\n\t\t\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_delgtof', approver);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apvr', approver);\n\t\t\t\t}\t\n\t\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apvrl','Supervisor');\n\t\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apmanager',nlapiGetUser());\n\t\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_invown',vbOwner);\n\t\t\t\tvbRec.commitLineItem('recmachcustrecord_spk_apvmtx_tranno');\n\t\t\t\t//return k;\n\t\t\t}\n\t\t}\n\t}\n\treturn k;\n}", "function setLineLockState(i, state) {\n\tif(state == false) {\n\t\tgetFormElementByName(0, 'ref[]', i).value = '';\n\t}\n\n\tgetFormElementByName(0, 'artikelcode[]', i).readOnly = state;\n\tgetFormElementByName(0, 'artikelcode[]', i).readOnly = state;\n\tgetFormElementByName(0, 'omschrijving[]', i).readOnly = state;\n\tgetFormElementByName(0, 'aantal[]', i).readOnly = state;\n\tgetFormElementByName(0, 'prijs[]', i).readOnly = state;\n\n\tif(state == true) {\n\t\tdocument.getElementById('unlock_' + (i + 1)).style.display = 'block';\n\t} else {\n\t\tdocument.getElementById('unlock_' + (i + 1)).style.display = 'none';\n\t}\n}", "function createVoucherReport(journal, report, docNumber, rowsToProcess) {\n\n //Each voucher on a new page\n report.addPageBreak();\n\n var date = \"\";\n var doc = \"\"; \n var desc = \"\";\n var totDebit = \"\";\n var totCredit = \"\";\n var line = 0;\n var totTransaction = calculateTotalTransaction(docNumber, journal, report); //Calculate the total value of the transaction\n\n /* Calculate the total number of pages used to print each voucher */\n var totRows = calculateTotalRowsOfTransaction(docNumber, journal, report);\n if (totRows > generalParam.numberOfRows) {\n var totalPages = Banana.SDecimal.divide(totRows, generalParam.numberOfRows);\n totalPages = parseFloat(totalPages);\n totalPages += 0.499999999999999;\n var context = {'decimals' : 0, 'mode' : Banana.SDecimal.HALF_UP}\n totalPages = Banana.SDecimal.round(totalPages, context);\n } else {\n var totalPages = 1;\n }\n\n //Define table info: name and columns\n var tableInfo = report.addTable(\"table_info\");\n var col1 = tableInfo.addColumn(\"col1\");\n var col2 = tableInfo.addColumn(\"col2\");\n var col3 = tableInfo.addColumn(\"col3\");\n var col4 = tableInfo.addColumn(\"col4\");\n var col5 = tableInfo.addColumn(\"col5\");\n var col6 = tableInfo.addColumn(\"col6\");\n var col7 = tableInfo.addColumn(\"col7\");\n var col8 = tableInfo.addColumn(\"col8\");\n var col9 = tableInfo.addColumn(\"col9\");\n var col10 = tableInfo.addColumn(\"col10\");\n var col11 = tableInfo.addColumn(\"col11\");\n\n //Define table transactions: name and columns\n\n if (Banana.document.table('ExchangeRates')) {\n var table = report.addTable(\"table\");\n var ct1 = table.addColumn(\"ct1\");\n var ct2 = table.addColumn(\"ct2\");\n var ct3 = table.addColumn(\"ct3\");\n var ct4 = table.addColumn(\"ct4\");\n var ct5 = table.addColumn(\"ct5\");\n var ct5 = table.addColumn(\"ct6\");\n var cts1 = table.addColumn(\"cts1\");\n var ct4 = table.addColumn(\"ct7\");\n var cts2 = table.addColumn(\"cts2\");\n var ct5 = table.addColumn(\"ct8\");\n var cts3 = table.addColumn(\"cts3\");\n var ct6 = table.addColumn(\"ct9\");\n } else {\n var table = report.addTable(\"table\");\n var c1 = table.addColumn(\"c1\");\n var c2 = table.addColumn(\"c2\");\n var c3 = table.addColumn(\"c3\");\n var cs1 = table.addColumn(\"cs1\");\n var c4 = table.addColumn(\"c4\");\n var cs2 = table.addColumn(\"cs2\");\n var c5 = table.addColumn(\"c5\");\n var cs3 = table.addColumn(\"cs3\");\n var c6 = table.addColumn(\"c6\");\n }\n\n //Define table signatures: name and columns\n var tableSignatures = report.addTable(\"table_signatures\");\n var colSig1 = tableSignatures.addColumn(\"colSig1\");\n var colSig2 = tableSignatures.addColumn(\"colSig2\");\n var colSig3 = tableSignatures.addColumn(\"colSig3\");\n var colSig4 = tableSignatures.addColumn(\"colSig4\");\n var colSig5 = tableSignatures.addColumn(\"colSig5\");\n var colSig6 = tableSignatures.addColumn(\"colSig6\");\n\n //Select from the journal all the given rows, take all the needed data, calculate totals and create the vouchers print\n for (j = 0; j < rowsToProcess.length; j++) {\n for (i = 0; i < journal.rowCount; i++) {\n if (i == rowsToProcess[j]) {\n var tRow = journal.row(i);\n date = tRow.value(\"Date\");\n }\n }\n }\n\n /* 1. Print the date and the voucher number */\n printInfoVoucher(tableInfo, report, docNumber, date, totalPages);\n\n /* 2. Print the all the transactions data */\n printTransactions(table, journal, line, rowsToProcess);\n \n /* 3. Print the total line */\n printTotal(table, totDebit, totCredit, report, totalPages, totTransaction);\n \n /* 4. Print the signatures line */\n printSignatures(tableSignatures, report);\n\n currentPage++;\n}", "function removeLockedLines() {\n\tvar aantalRegels = countNumberOfItems(0, 'artikelcode[]');\n\n\tfor(var i = aantalRegels - 1; i >= 0;i --) {\n\t\tif(getFormElementByName(0, 'artikelcode[]', i).readOnly) {\n\t\t\tsetLineLockState(i, false);\n\n\t\t\tgetFormElementByName(0, 'artikelcode[]', i).value = '';\n\t\t\tgetFormElementByName(0, 'omschrijving[]', i).value = '';\n\t\t\tgetFormElementByName(0, 'aantal[]', i).value = '';\n\t\t\tgetFormElementByName(0, 'prijs[]', i).value = '';\n\t\t}\n\t}\n}", "function creditUSRow(row){ \n if (formatAmount(document.getElementById('amtCreditUS_'+row),'US')){\n CCT.index.creditUSRow(row,gOldUSCreditAmt[row],document.getElementById('emailCreditUS_'+row).value\n ,document.getElementById('notesCreditUS_'+row).value,creditUSRowCallback);\n \n document.getElementById(\"mCreditUSTableDiv\").style.display = 'none';\n errorMessage(\"Crediting ...\",\"CreditUS\",\"Message\");\n document.mForm.mCreditButton.disabled = true; \n }\n }", "function getJournal() {\n\n var journal = Banana.document.journal(Banana.document.ORIGINTYPE_CURRENT, Banana.document.ACCOUNTTYPE_NORMAL);\n var len = journal.rowCount;\n var transactions = []; //Array that will contain all the lines of the transactions\n var requiredVersion = \"9.0.0\";\n \n for (var i = 0; i < len; i++) {\n\n var line = {}; \n var tRow = journal.row(i);\n\n if (tRow.value(\"JDate\") >= param.startDate && tRow.value(\"JDate\") <= param.endDate) {\n\n line.date = tRow.value(\"JDate\");\n line.account = tRow.value(\"JAccount\");\n line.vatcode = tRow.value(\"JVatCodeWithoutSign\");\n line.vattaxable = tRow.value(\"JVatTaxable\");\n line.vatamount = tRow.value(\"VatAmount\");\n line.vatposted = tRow.value(\"VatPosted\");\n line.amount = tRow.value(\"JAmount\");\n line.amountaccountcurrency = tRow.value(\"JAmountAccountCurrency\");\n line.transactioncurrencyconversionrate = tRow.value(\"JTransactionCurrencyConversionRate\");\n line.doc = tRow.value(\"Doc\");\n line.description = tRow.value(\"Description\");\n line.transactioncurrency = tRow.value(\"JTransactionCurrency\");\n line.isvatoperation = tRow.value(\"JVatIsVatOperation\");\n line.amounttransactioncurrency = tRow.value(\"JAmountTransactionCurrency\");\n \n //We take only the rows with a VAT code and then we convert values from base currency to CHF\n if (line.isvatoperation) {\n\n if (line.transactioncurrency === \"CHF\") {\n line.exchangerate = Banana.SDecimal.divide(1,line.transactioncurrencyconversionrate);\n }\n else {\n\n //Starting from the date of the line.date (ex. 2015-10-13)\n var date = line.date.split(\"-\"); //es. [2015,10,13]\n var year = date[0];\n var month = date[1];\n\n //We set the date as the 15 of the month\n var stringDate = year + \"-\" + month + \"-15\"; //es. 2015-10-15\n\n //Read from the ExchangeRates table and find the row with the date of 15th of the month\n var dateExchangeRates = \"\";\n try {\n dateExchangeRates = Banana.document.table(\"ExchangeRates\").findRowByValue(\"Date\", stringDate).value(\"Date\");\n } catch(e){\n //The row doesn't exists\n }\n\n if (dateExchangeRates === stringDate) { // there is the 15th of the month\n // should be 15 of the month\n if (Banana.compareVersion && Banana.compareVersion(Banana.application.version, requiredVersion) >= 0) {\n //Return Object with properties 'date' and 'exchangeRate'\n line.exchangerate = Banana.document.exchangeRate(\"CHF\", stringDate).exchangeRate;\n } else {\n //Return value\n line.exchangerate = Banana.document.exchangeRate(\"CHF\", stringDate);\n }\n //Banana.console.log(\"[Y] \" + line.date + \"; \" + stringDate + \"; \" + line.exchangerate);\n\n // /* possible future API then return the date */\n // if (typeof line.exchangerate === \"object\") {\n // line.exchangerate = line.exchangerate.exchangeRate;\n // line.exchangerateDate = line.exchangerate.date;\n // }\n\n }\n else { // there is not the 15th of the month\n // should be the previous? the transaction date?\n if (Banana.compareVersion && Banana.compareVersion(Banana.application.version, requiredVersion) >= 0) {\n //Return Object with properties 'date' and 'exchangeRate'\n line.exchangerate = Banana.document.exchangeRate(\"CHF\", line.date).exchangeRate;\n } else {\n //Return value\n line.exchangerate = Banana.document.exchangeRate(\"CHF\", line.date);\n }\n //Banana.console.log(\"[N] \" + line.date + \" : \" + line.exchangerate); \n }\n }\n\n line.vattaxableCHF = convertBaseCurrencyToCHF(line.vattaxable, line.exchangerate);\n line.vatamountCHF = convertBaseCurrencyToCHF(line.vatamount, line.exchangerate);\n line.vatpostedCHF = convertBaseCurrencyToCHF(line.vatposted, line.exchangerate);\n line.amountCHF = convertBaseCurrencyToCHF(line.amount, line.exchangerate);\n\n transactions.push(line); \n }\n }\n }\n return transactions;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
AdditiveExpression : MultiplicativeExpression | AdditiveExpression ADDITIVE_OPERATOR Literal > Literal ADDITIVE_OPERATOR Literal ADDITIVE_OPERATOR Literal
AdditiveExpression() { return this._BinaryExpression( "MultiplicativeExpression", "ADDITIVE_OPERATOR" ); }
[ "function parseAdditive() {\n var token, left, right, r;\n\n left = parseMultiplicative();\n token = lexer.peek();\n if (matchOp(token, '+') || matchOp(token, '-')) {\n token = lexer.next();\n right = parseAdditive();\n\n // Addition and subtraction is left associative:\n // a-b-c should be (a-b)-c and not a-(b-c)\n if (right.value === '+' || right.value === '-') {\n r = right;\n while (r.content[0].subtype === 'naryOperator') {\n r = r.content[0];\n }\n\n r.content[0] = new MathLib.Expression({\n subtype: token.value === '+' ? 'naryOperator' : 'binaryOperator',\n content: [left, r.content[0]],\n value: token.value,\n name: token.value === '+' ? 'plus' : 'minus'\n });\n return right;\n } else {\n return new MathLib.Expression({\n subtype: token.value === '+' ? 'naryOperator' : 'binaryOperator',\n value: token.value,\n name: token.value === '+' ? 'plus' : 'minus',\n content: [left, right]\n });\n }\n }\n return left;\n }", "RelationExpression() {\n return this._BinaryExpression(\"AdditiveExpression\", \"RELATIONAL_OPERATOR\");\n }", "enterAdditiveOperator(ctx) {\n\t}", "constructor(add_op, mul_op, add_id, mul_id, add_inv, mul_inv, eq_rel) {\n super(eq_rel);\n\n let add_group = new Group(add_op, add_id, add_inv, eq_rel);\n let mul_group = new Group(mul_op, mul_id, mul_inv, eq_rel);\n \n this.add = function(... elements) {return(add_group.multiply(... elements))};\n this.additive_id = function() {return(add_group.id())};\n this.additive_inv = function(element) {return(add_group.inv(element))};\n\n this.multiply = mul_group.multiply;\n this.multiplicative_id = mul_group.id;\n this.multiplicative_inv = mul_group.inv;\n }", "visitArith_expr(ctx) {\r\n console.log(\"visitArith_expr\");\r\n let length = ctx.getChildCount();\r\n let value = this.visit(ctx.term(0));\r\n for (var i = 1; i * 2 < length; i = i + 1) {\r\n if (ctx.getChild(i * 2 - 1).getText() === \"+\") {\r\n value = {\r\n type: \"BinaryExpression\",\r\n operator: \"+\",\r\n left: value,\r\n right: this.visit(ctx.term(i)),\r\n };\r\n } else if (ctx.getChild(i * 2 - 1).getText() === \"-\") {\r\n value = {\r\n type: \"BinaryExpression\",\r\n operator: \"-\",\r\n left: value,\r\n right: this.visit(ctx.term(i)),\r\n };\r\n }\r\n }\r\n return value;\r\n }", "visitRelational_operator(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function parseMultiplicative() {\n var token, left, right, r;\n\n left = parseExponentiation();\n token = lexer.peek();\n if (matchOp(token, '*') || matchOp(token, '/')) {\n token = lexer.next();\n\n right = parseMultiplicative();\n\n // Multiplication and division is left associative:\n // a/b/c should be (a/b)/c and not a/(b/c)\n if (right.subtype === 'naryOperator' || right.subtype === 'binaryOperator') {\n r = right;\n while (r.content[0].subtype === 'naryOperator' || r.content[0].subtype === 'binaryOperator') {\n r = r.content[0];\n }\n\n r.content[0] = new MathLib.Expression({\n subtype: token.value === '*' ? 'naryOperator' : 'binaryOperator',\n content: [left, r.content[0]],\n value: token.value,\n name: token.value === '*' ? 'times' : 'divide'\n });\n return right;\n } else {\n return new MathLib.Expression({\n subtype: token.value === '*' ? 'naryOperator' : 'binaryOperator',\n value: token.value,\n name: token.value === '*' ? 'times' : 'divide',\n content: [left, right]\n });\n }\n }\n return left;\n }", "EqualityExpression() {\n return this._BinaryExpression(\"RelationExpression\", \"EQUALITY_OPERATOR\");\n }", "exitAdditiveOperator(ctx) {\n\t}", "parseEquation() {\n let lhs = [this.parseTerm()];\n while (true) {\n const next = this.tok.peek();\n if (next == \"+\") {\n this.tok.consume(next);\n lhs.push(this.parseTerm());\n }\n else if (next == \"=\") {\n this.tok.consume(next);\n break;\n }\n else\n throw new ParseError(\"Plus or equal sign expected\", this.tok.pos);\n }\n let rhs = [this.parseTerm()];\n while (true) {\n const next = this.tok.peek();\n if (next === null)\n break;\n else if (next == \"+\") {\n this.tok.consume(next);\n rhs.push(this.parseTerm());\n }\n else\n throw new ParseError(\"Plus or end expected\", this.tok.pos);\n }\n return new Equation(lhs, rhs);\n }", "function appendNumberOrOperator(value) {\n resultInput.value += value;\n}", "function appendOperator(operator) {\n appendNumberOrOperator(operator);\n}", "function parseExponentiation() {\n var token, left, right;\n\n left = parseUnary();\n token = lexer.peek();\n if (matchOp(token, '^')) {\n token = lexer.next();\n\n right = parseExponentiation();\n\n // Exponentiation is right associative\n // a^b^c should be a^(b^c) and not (a^b)^c\n return new MathLib.Expression({\n subtype: 'binaryOperator',\n value: '^',\n content: [left, right],\n name: 'pow'\n });\n }\n return left;\n }", "addAndThenExpression() {\n const thenExpression = AndThenExpression.new({\n leftExpression: this.assertionExpression,\n rightExpression: null,\n })\n\n this.assertionExpression = thenExpression\n }", "function ExprTail() {\n var node = new Node('ExprTail');\n p.child.push(node);\n p = node;\n if (word == '+' || word == '-') {\n p.operator = word;\n word = nextWord();\n if (!Term()) {\n return false;\n } else {\n p = node;\n return ExprTail();\n }\n }\n return true;\n }", "addWithEachExpression({ eachCompiledExpression: eachCompiledExpression }) {\n const withEachExpression = WithEachExpression.new({\n eachCompiledExpression: eachCompiledExpression\n })\n\n this.addAssertion({ assertion: withEachExpression })\n }", "function addWithSideEffect(a, b) {\n const result = a + b;\n console.log(\"Returning \" + result);\n return result;\n}", "factor() {\n const token = this.currentToken;\n\n if (token.type === tokens.plus) {\n this.eat(tokens.plus);\n return new UnaryOp(token, this.factor());\n }\n\n if (token.type === tokens.minus) {\n this.eat(tokens.minus);\n return new UnaryOp(token, this.factor());\n }\n\n if (token.type === tokens.integerConst) {\n this.eat(tokens.integerConst);\n return new Num(token);\n }\n\n if (token.type === tokens.realConst) {\n this.eat(tokens.realConst);\n return new Num(token);\n }\n\n if (token.type === tokens.lparen) {\n this.eat(tokens.lparen);\n const result = this.expr();\n this.eat(tokens.rparen);\n return result;\n }\n\n const node = this.variable();\n return node;\n }", "addOrExpression() {\n const andExpression = OrExpression.new({\n leftExpression: this.assertionExpression,\n rightExpression: null,\n })\n\n this.assertionExpression = andExpression \n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Applies the given fact (with zero hypotheses) to the workspace (a proved theorem with one hypothesis, representing a workinprogress). The workpath points to a subexpression of the work's only hypothesis. The factPath points to a subexpression of the fact's statement. These two subexpressions will be unified; then the fact (and the required pushup procedures) will be added to the beginning of the work's proof, and the work's hypthesis will be updated.
function applyFact(work, workPath, fact, factPath) { if (!Array.isArray(factPath) || (factPath.length != 1) || ((factPath[0] != 1) && (factPath[0] != 2))) { throw new Error("factPath must be [1] or [2] for now."); } var varMap = getMandHyps(work, workPath, fact, factPath); if (DEBUG) {console.log("# MandHyps: " + JSON.stringify(varMap));} // If that didn't throw, we can start mutating // PushUpScratchPad var pusp = {}; pusp.newSteps = []; if (DEBUG) console.log("Vars from " + JSON.stringify(fact)); eachVarOnce([fact.Core[Fact.CORE_STMT]], function(v) { var newV = varMap[v]; if (DEBUG) {console.log("v=" + v + ", newV=" + varMap[v]);} if (newV == undefined) { newV = work.nameVar(newDummy()); varMap[v] = newV; } if (DEBUG) {console.log("v=" + v + ", newV=" + varMap[v]);} pusp.newSteps.push(newV); }); pusp.newSteps.push(nameDep(work, fact)); // Now on the stack: an instance of fact, with factPath equalling a // subexp of work. // #. invoke sequence of pushup theorems, ensuring presence in Deps pusp.tool = globalSub(fact, varMap, work); // what's on the stack pusp.toolPath = clone(factPath); // path to subexp A pusp.goal = clone(work.Core[Fact.CORE_HYPS][0]); // what to prove pusp.goalPath = clone(workPath); // path to subexp B // invariant: subexp A == subexp B function checkInvariant() { if (DEBUG) { console.log("Check invariant: \n" + JSON.stringify(zpath(pusp.tool, pusp.toolPath)) + "\n" + JSON.stringify(zpath(pusp.goal, pusp.goalPath))); console.log(" pusp: ", JSON.stringify(pusp)); } if (JSON.stringify(zpath(pusp.tool, pusp.toolPath)) != JSON.stringify(zpath(pusp.goal, pusp.goalPath))) { throw new Error("Invariant broken!"); } } var pushUps = getPushUps(work, workPath, fact.Skin.TermNames[fact.Core[Fact.CORE_STMT][0]], factPath[0]); // Now apply the pushups from the bottom up, and finally detach. pushUps.forEach(function(pu) { if (DEBUG) checkInvariant(); pu(pusp, work); }) // Now we have a complete pusp, so apply it to the workspace. // don't delete any steps pusp.newSteps.unshift(0); // keep the "hyps.0". pusp.newSteps.unshift(1); work.Tree.Proof.splice.apply(work.Tree.Proof, pusp.newSteps); // #. update DV list fact.Core[Fact.CORE_FREE].forEach(function(freeList) { var origTermVar = freeList[0]; var newExp = varMap[origTermVar]; // NOTE: this creates freelists even for binding vars. They will be // omitted in the ghilbert serialization (Context.toString) eachVarOnce([newExp], function(newV) { freeList.slice(1).forEach(function(origBV) { var bV = varMap[origBV]; if (newV == bV) { // Shouldn't happen; this is checked for in mandHyps throw new Error("Freeness violation!"); } work.ensureFree(newV, bV); }); }); }); // TODO: // #. Add explanatory comments to Skin.Delimiters return work; }
[ "function ground(work, dirtFact) {\n // verify that the hyp is an instance of the dirt\n var varMap = getMandHyps(work, [], dirtFact, []);\n if (DEBUG) {console.log(\"# ground MandHyps: \"+JSON.stringify(varMap));}\n work.Core[Fact.CORE_HYPS].shift();\n var newSteps = [];\n eachVarOnce([dirtFact.Core[Fact.CORE_STMT]], function(v) {\n var newV = varMap[v];\n if (newV == undefined) {\n newV = work.nameVar(newDummy());\n varMap[v] = newV;\n }\n newSteps.push(newV);\n });\n newSteps.push(nameDep(work, dirtFact));\n\n // remove hyp step\n work.Tree.Proof.shift();\n // Replace with proof of hyp instance\n work.Tree.Proof.unshift.apply(work.Tree.Proof, newSteps);\n if (DEBUG) {console.log(\"# Work before canon:\" + JSON.stringify(work));}\n work = canonicalize(work);\n if (DEBUG) {console.log(\"# Work after canon:\" + JSON.stringify(work));}\n return work;\n }", "function getPushUps(work, workPath, toolOp, toolArg) {\n // This looks a lot more complicated than it is. Here's the concept: at\n // each level of the goal tree, we need to query for and apply a pushUp\n // theorem. However, in order to know *which* pushUp theorem to apply,\n // we need both the goal's operator at the level above, and the result\n // of the pushUp query from the level below.\n // Each query is [goalOp, goalArgNum, toolOp, toolArgNum];\n var pushUps = []; // pushUp results, from the bottom up\n var queries = []; // goalOps and argNums from the top down\n var term = work.Core[Fact.CORE_HYPS][0];\n workPath.forEach(function(z) { // walk down, filling in the first half of the queries\n var op = work.Skin.TermNames[term[0]];\n queries.push([op, z]);\n term = term[z];\n });\n while (queries.length > 0) { // walk back up, finishing and executing the queries\n var q = queries.pop();\n q.push(toolOp);\n q.push(toolArg);\n var pu = scheme.queryPushUp(q);\n pushUps.push(pu.pushUp.bind(pu));\n toolOp = pu.parentArrow.name;\n toolArg = (pu.isCovar ? 2 : 1);\n }\n // Now, since the invariant holds and goalPath = [], and\n // tool[toolPath[0]] == goal, so just detach.\n var detacher = scheme.queryDetach([toolOp, [toolArg]]);\n pushUps.push(detacher.detach.bind(detacher));\n return pushUps;\n }", "function applyInference(work, infFact) {\n var varMap = getMandHyps(work, [], infFact, []);\n if (DEBUG) {console.log(\"# Inf MandHyps: \" + JSON.stringify(varMap));}\n var newSteps = [];\n // Need a mandhyp step for each var appearing in the stmt which does NOT\n // appear in the hyps.\n var varToStepIndex = {};\n eachVarOnce([infFact.Core[Fact.CORE_STMT]], function(v) {\n var newV = varMap[v];\n if (DEBUG) {console.log(\"v=\" + v + \", newV=\" + varMap[v]);}\n if (newV == undefined) {\n newV = work.nameVar(newDummy());\n varMap[v] = newV;\n }\n if (DEBUG) {console.log(\"v=\" + v + \", newV=\" + varMap[v]);}\n varToStepIndex[v] = newSteps.length;\n newSteps.push(newV);\n });\n eachVarOnce(infFact.Core[Fact.CORE_HYPS], function(v) {\n if (varToStepIndex.hasOwnProperty(v)) {\n newSteps[varToStepIndex[v]] = \"\";\n }\n });\n newSteps = newSteps.filter(function(x) { return x !== \"\";});\n // preserve \"hyps.0\"\n newSteps.unshift(work.Tree.Proof.shift());\n newSteps.push(nameDep(work, infFact));\n newSteps.push.apply(newSteps, work.Tree.Proof);\n work.setProof(newSteps);\n var newHyp = globalSub(infFact, varMap, work,\n infFact.Core[Fact.CORE_HYPS][0]);\n if (DEBUG) {console.log(\"# Inf newHyp: \" + JSON.stringify(newHyp));}\n work.setHyps([newHyp]);\n return work;\n }", "function getMandHyps(work, hypPath, fact, stmtPath) {\n var debugPath = [];\n var nonDummy = {};\n var dummyMap = {};\n eachVarOnce([work.Core[Fact.CORE_STMT]], function(v) {\n nonDummy[v] = true;\n });\n // from fact vars to work exps\n var varMap = {};\n var workExp = zpath(work.Core[Fact.CORE_HYPS][0], hypPath);\n var factExp = zpath(fact.Core[Fact.CORE_STMT], stmtPath);\n if (workExp == undefined) {\n throw new Error(\"Bad work path:\\n\" + hypPath + \"\\n\" +\n JSON.stringify(work));\n }\n if (factExp == undefined) {\n throw new Error(\"Bad fact path:\\n\" + stmtPath + \"\\n\" +\n JSON.stringify(fact));\n }\n function assertEqual(msgTag, thing1, thing2) {\n if (thing1 !== thing2) {\n throw new Error(\"Unification error: \" + msgTag + \" @ \" +\n JSON.stringify(debugPath) +\n \"\\nWork: \" + JSON.stringify(workExp) +\n \"\\nFact: \" + JSON.stringify(factExp) +\n \"\\nWant: \" + thing1 + \" === \" + thing2);\n }\n }\n\n function checkVarMapForFreeness(varMap) {\n fact.Core[Fact.CORE_FREE].forEach(function(freeList) {\n var newExp = varMap[freeList[0]];\n if (newExp == undefined) {\n return;\n }\n var varsAppearing = {};\n eachVarOnce([newExp], function(v) {\n varsAppearing[v] = true; // TODO: what if binding??\n });\n freeList.slice(1).forEach(function(freeVar) {\n var newVar = varMap[freeVar];\n if (Array.isArray(newVar)) {\n // This should not be possible.\n throw new Error(\"Substituting term for binding var?!\");\n }\n if (varsAppearing[newVar]) {\n throw new Error(\n \"Freeness Violation:\\n Found var \" + newVar +\n \" (was \" + freeVar +\")\\n in exp \" +\n JSON.stringify(newExp) +\n \" (was \" + freeList[0] +\")\");\n }\n });\n });\n }\n function mapVarTo(factVarName, workExp) {\n varMap[factVarName] = workExp;\n }\n function recurse(workSubExp, factSubExp, alreadyMapped) {\n if (!alreadyMapped && !Array.isArray(factSubExp) &&\n (varMap[factSubExp] != undefined)) {\n factSubExp = varMap[factSubExp];\n alreadyMapped = true;\n }\n if (alreadyMapped) {\n while (dummyMap[factSubExp]) {\n factSubExp = dummyMap[factSubExp];\n }\n }\n while (dummyMap[workSubExp]) {\n workSubExp = dummyMap[workSubExp];\n }\n\n if ((hypPath.length == 0) &&\n (stmtPath != null) &&\n (stmtPath.length == 0) &&\n Array.isArray(workSubExp) &&\n (workSubExp[0] == work.Tree.Definiendum)) {\n // When grounding a defthm, the statement left on the stack\n // doesn't match the Core's STMT until the substitution is\n // applied.\n // TODO: but we *should* be checking the consistency of the\n // substitution....\n return;\n }\n\n if (!Array.isArray(factSubExp)) {\n if (alreadyMapped) {\n if (!nonDummy[factSubExp]) {\n if (factSubExp != workSubExp) {\n dummyMap[factSubExp] = workSubExp;\n }\n } else if (Array.isArray(workSubExp)) {\n // A mapped, nondummy, nonarray var should be an array exp.\n // This isn't going to work.\n assertEqual(\"mappedA\", factSubExp, workSubExp)\n } else if (!nonDummy[workSubExp]) {\n if (factSubExp != workSubExp) {\n dummyMap[workSubExp] = factSubExp;\n }\n } else {\n // A mapped, nondummy, nonarray var should be a nondummy,\n // nonarray var. They'd better be the same.\n assertEqual(\"mapped\", factSubExp, workSubExp);\n }\n } else {\n mapVarTo(factSubExp, workSubExp);\n }\n } else {\n var op = factSubExp[0];\n var factContext = alreadyMapped ? work : fact;\n var factTerm = factContext.Skin.TermNames[op];\n var factTermFreeMap = factContext.FreeMaps[op];\n if (factTerm == undefined) {\n throw new Error(\"No factTerm\\n\" +\n JSON.stringify(fact) + \"\\n\" +\n JSON.stringify(factSubExp));\n }\n if (!Array.isArray(workSubExp)) {\n // Work is var, Fact is exp.\n if (nonDummy[workSubExp]) {\n assertEqual(\"shrug\", workSubExp, factSubExp);\n } else {\n var newExp = [];\n newExp.push(work.nameTerm(factTerm, factTermFreeMap));\n for (var i = 1; i < factSubExp.length; i++) {\n newExp.push(work.nameVar(newDummy()));\n }\n dummyMap[workSubExp] = newExp;\n workSubExp = newExp;\n }\n }\n if (Array.isArray(workSubExp)) {\n // exp - exp\n var workTerm = work.Skin.TermNames[workSubExp[0]];\n assertEqual(\"term\", workTerm, factTerm);\n assertEqual(\"arity\", workSubExp.length, factSubExp.length);\n for (var i = 1; i < workSubExp.length; i++) {\n debugPath.push(i);\n // TODO: possible infinite loop here on bad unification\n recurse(workSubExp[i], factSubExp[i], alreadyMapped);\n debugPath.pop();\n }\n }\n }\n }\n recurse(workExp, factExp, false);\n undummy(work, dummyMap);\n //console.log(\"Unified: \" + JSON.stringify(varMap));\n for (x in varMap) if (varMap.hasOwnProperty(x)) {\n varMap[x] = undummy(varMap[x], dummyMap);\n }\n checkVarMapForFreeness(varMap);\n return varMap;\n }", "function canonicalize(work) {\n var out = new Fact();\n function mapTerm(t) {\n if (!work.FreeMaps[t]) {\n throw new Error(\"canon \" + JSON.stringify(work));\n }\n return out.nameTerm(work.Skin.TermNames[t], work.FreeMaps[t]);\n }\n function mapExp(exp) {\n if (Array.isArray(exp) && (exp.length > 0)) {\n var t = mapTerm(exp[0]);\n var mapped = exp.slice(1).map(mapExp);\n mapped.unshift(t);\n return mapped;\n } else if (typeof exp == 'number') {\n return out.nameVar(\"V\" + exp);\n } else {\n return exp;\n }\n }\n for (var i = 0; i < work.Core[Fact.CORE_HYPS].length; i++) {\n out.Core[Fact.CORE_HYPS][i] = mapExp(work.Core[Fact.CORE_HYPS][i]);\n out.Skin.HypNames[i] = \"Hyps.\" + i;\n }\n out.setStmt(mapExp(work.Core[Fact.CORE_STMT]));\n if (DEBUG) {\n console.log(\"\\nwork=\" + JSON.stringify(work) +\n \"\\nfact=\" +JSON.stringify(out));\n }\n\n // Remove spurious free vars.\n var varsSeen = {};\n eachVarOnce(work.Core[Fact.CORE_HYPS],function(v) {\n varsSeen[v] = true;});\n eachVarOnce([work.Core[Fact.CORE_STMT]],function(v) {\n varsSeen[v] = true;});\n\n // Remove freelist entries where the first var is a binding var.\n var bindingVars = {};\n work.Core[Fact.CORE_FREE].forEach(function(freeList) {\n freeList.slice(1).forEach(function(v) {bindingVars[v] = 1;});\n });\n work.Core[Fact.CORE_FREE].forEach(function(freeList) {\n var termVar = mapExp(freeList[0]);\n if (varsSeen[termVar] && !bindingVars[termVar]) {\n freeList.slice(1).forEach(function(v) {\n if (varsSeen[v]) {\n out.ensureFree(termVar, mapExp(v));\n }\n });\n }\n });\n\n out.setProof(work.Tree.Proof.map(mapExp));\n if (work.Tree.Proof.length == 0) {\n out.setCmd(\"stmt\");\n } else if (typeof(work.Tree.Definiendum) == 'number') {\n out.setCmd(\"defthm\");\n } else {\n out.setCmd(\"thm\");\n }\n \n out.setName(fingerprint(out.getMark()));\n out.Tree.Deps = work.Tree.Deps.map(function(d) {\n return [clone(d[0]), d[1].map(mapTerm)];\n });\n if (work.Tree.Definiendum != undefined) {\n out.Tree.Definiendum = mapTerm(work.Tree.Definiendum);\n }\n\n for (var n = 0; n < out.Skin.VarNames.length; n++) {\n out.Skin.VarNames[n] = \"V\" + n;\n }\n return out;\n }", "function forEachGroundableFact(work, cb) {\n allKnownFacts.forEach(function(f) {\n if (f.Core[Fact.CORE_HYPS].length == 0) {\n try {\n if (work.Core[Fact.CORE_HYPS][0] !== 1) {\n //XXX TODO: infinite recurse bug here, not trying.\n getMandHyps(work, [], f, []);\n }\n nextTick(cb.bind(null,work,f));\n } catch(e) {\n // TODO: should not be using exceptions for this\n }\n }\n });\n }", "function simplifyPathExpression(graph, p) {\n\n let reduced =\n _(p)\n .groupBy('compositionNode.id') // We group path that go to the same target\n .map(x => // For each of these groups\n ({\n compositionNode: x[0].compositionNode, // Merge target interactions by taking the first\n condition: _(x).pluck('condition').map(y => _.unique(y, z => (z.node.id + \" \" + z.index))).value() // Merge conditions, and remove duplicates conditions from paths\n })\n )\n .flatten()\n // Now the condition for each target is an array (disjunction) of paths (conjunction)\n .forEach(x => {\n\n\n let allConds =\n _(x.condition)\n .flatten()\n .map(c => ({\n cond: c,\n stringRep: (c.node.id + \" \" + c.index)\n }))\n .unique('stringRep')\n .value();\n\n if (allConds.length == 0) {\n x.simplifiedCond = null;\n } else {\n if (allConds.length == 1) { // We do not have to create a new Synthetic node in this case\n x.simplifiedCond = x.condition[0][0];\n } else {\n\n let satProblem =\n _(x.condition)\n .map(y => (\n _(y)\n .map(c => (c.node.id + \" \" + c.index))\n .value()))\n .value();\n\n\n // console.log(\"hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh\");\n // console.log(_.pluck(allConds,'stringRep'));\n // console.log(satProblem);\n // console.log(\"iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii\");\n let solution = sat.solvePath(_.pluck(allConds, 'stringRep'), satProblem);\n // console.log(solution);\n // console.log(\"jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj\");\n\n let newNode =\n graph\n .addNode({\n type: 'InteractionInstance',\n content: {\n type: 'InteractionNative',\n content: \"TBD\"\n }\n });\n\n let allEdgesToConds =\n _(allConds)\n .map((c, index) => ({\n cond: c.cond,\n stringRep: c.stringRep,\n edge: graph.addEdge({\n type: 'InteractionInstanceOperand',\n from: {\n index: (index + 1),\n node: newNode,\n ports: {type:'InterfaceAtomic',direction:'in',data:{type:'DataAtomic',name:'Activation'}}\n },\n to: c.cond\n })\n }))\n .value();\n\n let code = _(solution)\n .map(s => {\n let solcode = \"if( \";\n solcode = solcode +\n _(s)\n .map((value, index) => ('( <%=a' + (index + 1) + '%>' + ' === ' + (value ? 'active' : 'inactive') + ' )'))\n .join(' && ');\n solcode = solcode + \") {\\n <%=a0%> = active;\\n} else {\\n <%=a0%> = inactive;\\n}\";\n return solcode;\n })\n .join(\"\\n\");\n\n // console.log(code);\n newNode.content.content = code;\n newNode.ports = [{type:'InterfaceAtomic',direction:'out',data:{type:'DataAtomic',name:'Activation'}}].concat(_.map(allConds, {type:'InterfaceAtomic',direction:'in',data:{type:'DataAtomic',name:'Activation'}}));\n\n // console.log('ffffffffffffffffffffffffffffffffffffffffffffffffff');\n\n x.simplifiedCond = {\n index: 0,\n node: newNode,\n ports: {type:'InterfaceAtomic',direction:'out',data:{type:'DataAtomic',name:'Activation'}}\n };\n\n }\n }\n\n\n\n })\n .value();\n\n // compositionNode\n\n // returns something which contains a key \"simplified cond\" which is a graph node that regroupd all conditions\n\n return reduced;\n}", "function adjustTask( task, state, handicap, highesthandicap ) {\n //\n if( state.adjustments ) {\n return state.adjustments;\n }\n\n // Make a new array for it\n var newTask = state.adjustments = _clonedeep(task);\n\n // reduction amount (%ish)\n var maxhtaskLength = task.distance / (highesthandicap/100);\n var mytaskLength = maxhtaskLength * (handicap/100);\n var mydifference = task.distance - mytaskLength;\n var spread = 2*(newTask.legs.length-1)+2; // how many points we can spread over\n var amount = mydifference/spread;\n\n // how far we need to move the radius in to achieve this reduction\n var adjustment = Math.sqrt( 2*(amount*amount) );\n\n // Now copy over the points reducing all symmetric\n newTask.legs.slice(1,newTask.legs.length-1).forEach( (leg) => {\n if( leg.type == 'sector' && leg.direction == 'symmetrical') {\n leg.r2 += adjustment;\n }\n else {\n console.log( \"Invalid handicap distance task: \"+leg.toString() );\n }\n });\n\n // For scoring this handicap we need to adjust our task distance as well\n newTask.distance = mytaskLength;\n return newTask;\n}", "function makeWorkPath() {\r\n\tvar idMk = charIDToTypeID( \"Mk \" );\r\n\t\tvar desc92 = new ActionDescriptor();\r\n\t\tvar idnull = charIDToTypeID( \"null\" );\r\n\t\t\t\tvar ref34 = new ActionReference();\r\n\t\t\t\tvar idPath = charIDToTypeID( \"Path\" );\r\n\t\t\t\tref34.putClass( idPath );\r\n\t\tdesc92.putReference( idnull, ref34 );\r\n\t\tvar idFrom = charIDToTypeID( \"From\" );\r\n\t\t\t\tvar ref35 = new ActionReference();\r\n\t\t\t\tvar idcsel = charIDToTypeID( \"csel\" );\r\n\t\t\t\tvar idfsel = charIDToTypeID( \"fsel\" );\r\n\t\t\t\tref35.putProperty( idcsel, idfsel );\r\n\t\tdesc92.putReference( idFrom, ref35 );\r\n\t\tvar idTlrn = charIDToTypeID( \"Tlrn\" );\r\n\t\tvar idPxl = charIDToTypeID( \"#Pxl\" );\r\n\t\tdesc92.putUnitDouble( idTlrn, idPxl, 2 );\r\n\texecuteAction( idMk, desc92, DialogModes.NO );\r\n}", "moveWorkToTop(workToMove) {\n // REMOVE THE WORK IF IT EXISTS\n this.removeWork(workToMove);\n\n // AND THEN ADD IT TO THE TOP OF THE STACK\n this.prependWork(workToMove);\n }", "constructPath(cameFrom, goal) {\n let path = this.board.getNeighborTiles(goal[0], goal[1]);\n let pos = goal;\n while (pos !== null) {\n path.unshift(pos);\n pos = cameFrom[pos]; // set the pos to prev pos\n }\n\n return path;\n }", "function handleSquish(ball, wasCollisionWithWall, collisionAngle, tangVelocity, perpSpeedI, perpSpeedF, time, deltaTime, handleContinuedSquish) {\n var duration, halfDuration, progress, weight1, weight2, squishStrength, minRx, endTime, handledPositioning, avgSpeed;\n handledPositioning = false;\n if (SQUISH_ENABLED) {\n if (ball.squish.isSquishing) {\n if (handleContinuedSquish) {\n // Continue the old squish\n duration = ball.squish.endTime - ball.squish.startTime;\n halfDuration = duration * 0.5;\n progress = time - ball.squish.startTime;\n if (progress > duration) {\n // Done squishing\n ball.squish.isSquishing = false;\n ball.squish.currentRx = ball.radius;\n } else {\n if (progress < halfDuration) {\n // Compressing\n weight2 = progress / halfDuration;\n weight2 = util.applyEasing(weight2, SQUISH_COMPRESS_EASING_FUNCTION);\n weight1 = 1 - weight2;\n ball.squish.currentRx = util.getWeightedAverage(\n ball.radius,\n ball.squish.minRx,\n weight1,\n weight2);\n handledPositioning = true;\n } else {\n // Expanding\n weight2 = (progress - halfDuration) / halfDuration;\n weight2 = util.applyEasing(weight2, SQUISH_EXPAND_EASING_FUNCTION);\n weight1 = 1 - weight2;\n ball.squish.currentRx = util.getWeightedAverage(\n ball.squish.minRx,\n ball.radius,\n weight1,\n weight2);\n handledPositioning = true;\n }\n // While squishing, slide the ball in the direction tangent to the collision\n ball.pos.x += ball.squish.tangVelocity.x * deltaTime;\n ball.pos.y += ball.squish.tangVelocity.y * deltaTime;\n }\n }\n } else if (typeof collisionAngle !== 'undefined') {\n squishStrength = Math.abs(perpSpeedF - perpSpeedI);\n squishStrength = wasCollisionWithWall ? squishStrength : squishStrength * PARAMS.INTRA_BALL_COLLISION_SQUISH_STRENGTH_COEFF;\n avgSpeed = (Math.abs(perpSpeedI) + Math.abs(perpSpeedF)) / 2;\n if (squishStrength) {\n // Start a new squish\n minRx = getSquishMinRx(squishStrength, ball.radius);\n endTime = getSquishEndTime(ball.radius, minRx, avgSpeed, time);\n ball.squish.isSquishing = true;\n ball.squish.rotation = collisionAngle;\n ball.squish.currentRx = ball.radius;\n ball.squish.minRx = minRx;\n ball.squish.tangVelocity = tangVelocity;\n ball.squish.startTime = time;\n ball.squish.endTime = endTime;\n ball.rotation = ball.squish.rotation * RAD_TO_DEG;\n }\n }\n }\n return handledPositioning;\n }", "synchronizeCase(testcase, relativePath) {\n return __awaiter(this, void 0, void 0, function* () {\n const basename = this.slugify(testcase.title);\n const exists = (this.testFiles[testcase.case_id] !== undefined);\n let featurePath = path.resolve(this.config.featuresDir + '/' + relativePath, basename + '.feature');\n const stepDefinitionsExtension = this.config.stepDefinitionsTemplate ?\n path.extname(this.config.stepDefinitionsTemplate).substr(1) : '';\n let stepDefinitionsPath = path.resolve(this.config.stepDefinitionsDir + '/' + relativePath, basename + '.' + stepDefinitionsExtension);\n featurePath = yield uniquefilename.get(featurePath, {});\n stepDefinitionsPath = yield uniquefilename.get(stepDefinitionsPath, {});\n // If the testcase is not on the filesystem, create the desired directory structure\n if (!exists) {\n mkdirp.sync(this.config.featuresDir + '/' + relativePath);\n }\n const gherkin = this.formatter.formatLinesFromTestrail(testcase);\n const remoteFileContent = this.getFeatureFileContent(testcase, gherkin);\n if (!exists) {\n fs.writeFileSync(featurePath, remoteFileContent);\n this.debug('Wrote .feature file');\n if (this.config.stepDefinitionsTemplate) {\n const content = this.getTestFileContent(gherkin, this.config.stepDefinitionsTemplate);\n if (content !== null) {\n mkdirp.sync(this.config.stepDefinitionsDir + '/' + relativePath);\n fs.writeFileSync(stepDefinitionsPath, content);\n }\n this.output(' ' + chalk.green(`Creating ${basename}`));\n }\n }\n else {\n featurePath = this.testFiles[testcase.case_id];\n const localFileContent = fs.readFileSync(featurePath).toString().trim();\n const fileChanged = this.hasGherkinContentChanged(localFileContent, remoteFileContent, true);\n const diffDescription = fileChanged ? chalk.underline('is different') + ' than' : 'is the same as';\n this.debug(`Existing .feature file ${diffDescription} the TestRail version`);\n if (!fileChanged) {\n this.skippedCount = this.skippedCount + 1;\n return Promise.resolve();\n }\n else if (this.config.overwrite.local === true) {\n this.output(' ' + chalk.green(`Overwriting ${basename}`));\n fs.writeFileSync(featurePath, remoteFileContent);\n return Promise.resolve();\n }\n else if (this.config.overwrite.local === 'ask') {\n this.showDiff(basename, localFileContent, remoteFileContent);\n if ((yield this.promptForConfirmation('Do you want to overwrite the local version ?')) === true) {\n fs.writeFileSync(featurePath, remoteFileContent);\n this.output(' ' + chalk.green(`Updated ${basename}`));\n }\n else {\n this.output(' ' + chalk.yellow(`Skipping ${basename}`));\n }\n }\n else if (this.config.overwrite.remote === true) {\n this.output(' ' + chalk.green(`Pushing ${basename} to TestRail`));\n yield this.pushTestCaseToTestRail(testcase, localFileContent);\n }\n else if (this.config.overwrite.remote === 'ask') {\n this.showDiff(basename, remoteFileContent, localFileContent);\n if ((yield this.promptForConfirmation('Do you want to override the TestRail version ?')) === true) {\n this.output(' ' + chalk.green(`Pushing ${basename} to TestRail`));\n yield this.pushTestCaseToTestRail(testcase, localFileContent);\n }\n else {\n this.output(' ' + chalk.yellow(`Skipping ${basename}`));\n }\n }\n else {\n this.output(' ' + chalk.yellow(`Skipping ${basename}`));\n return Promise.resolve();\n }\n }\n });\n }", "async function addWork(_work) {\n const new_work = new Work({\n work: _work.work,\n });\n return await new_work.save();\n}", "function pathSolver(path) {\n return path;\n}", "function changeStep(ind) {\r\n\r\n var sO = CurStepObj;\r\n var fO = CurFuncObj;\r\n\r\n // If we are going to a next step while we are just going through \r\n // new output grid selection menu, abandon current step\r\n //\r\n if (sO.stageInStep < StageInStep.ConfigStarted) {\r\n\r\n CurFuncObj.curStepNum = ind;\r\n drawStep(CurFuncObj.allSteps[ind]);\r\n return;\r\n }\r\n\r\n // STEP : Actually change the step\r\n //\r\n if (ind < CurFuncObj.allSteps.length) {\r\n\r\n\t// Remove any highlighted expression and grid highlight from the \r\n\t// current step because we are going to change this step. Not doing\r\n\t// so will keep highlights in grid (even in other steps)\r\n\t//\r\n\tremoveExprAndGridHighlight();\r\n\t//\r\n CurFuncObj.curStepNum = ind;\r\n drawStep(CurFuncObj.allSteps[ind]);\r\n\r\n } else {\r\n alert(\"Step does not exist\");\r\n }\r\n\r\n}", "function updatePathForm(playground) {\n\n\t// alle Pfade holen und nach ID sortieren\n\tvar allPaths = playground.paths;\n\tallPaths.sort(function Numsort(path1, path2){\n\t\treturn parseInt(path2.id)-parseInt(path1.id);\n\t});\n\t\n\t// alle Pfade löschen\n\t$('tr').remove('.pathRow');\n\t$('tr').remove('#pathCreateRow');\n\t\n\t// Anlegen\n\tcreatePathCreateRow(playground);\n\t\n\t// für jeden Pfad\n\tfor(var i = 0; i < allPaths.length; i++) {\t\t\n\t\t// füge eine neue Zeile hinzu\n\t\tcreatePathRow(playground, allPaths[i]);\n\t}\t\n}", "performReduction() {\n //console.log(\"called performReduction\");\n var reduced_expr = this.reduce();\n if (reduced_expr !== undefined && reduced_expr != this) { // Only swap if reduction returns something > null.\n\n console.warn('performReduction with ', this, reduced_expr);\n\n if (!this.stage) return Promise.reject();\n\n this.stage.saveState();\n Logger.log('state-save', this.stage.toString());\n\n // Log the reduction.\n let reduced_expr_str;\n if (reduced_expr === null)\n reduced_expr_str = '()';\n else if (Array.isArray(reduced_expr))\n reduced_expr_str = reduced_expr.reduce((prev,curr) => (prev + curr.toString() + ' '), '').trim();\n else reduced_expr_str = reduced_expr.toString();\n Logger.log('reduction', { 'before':this.toString(), 'after':reduced_expr_str });\n\n var parent = this.parent ? this.parent : this.stage;\n if (reduced_expr) reduced_expr.ignoreEvents = this.ignoreEvents; // the new expression should inherit whatever this expression was capable of as input\n parent.swap(this, reduced_expr);\n\n // Check if parent expression is now reducable.\n if (reduced_expr && reduced_expr.parent) {\n var try_reduce = reduced_expr.parent.reduceCompletely();\n if (try_reduce != reduced_expr.parent && try_reduce !== null) {\n Animate.blink(reduced_expr.parent, 400, [0,1,0], 1);\n }\n }\n\n if (reduced_expr)\n reduced_expr.update();\n\n return Promise.resolve(reduced_expr);\n }\n return Promise.resolve(this);\n }", "function _pushToDraftFromFileSystemForCapability(capabilityObject, configuration, apiCli, modeFlags, apicdevportal) {\r\n\tlogger.entry(\"_pushToDraftFromFileSystemForCapability\", capabilityObject, configuration, apiCli, modeFlags, apicdevportal);\r\n\t\r\n\t// initial results with just bsrURI\r\n\tvar theResults = ttResults.createBSResultsItem(capabilityObject.bsBsrURI, \"\", \"\", capabilityObject.bsBsrURI, true);\r\n\r\n\tvar data = capabilityObject.versions;\r\n\t\r\n\tvar promise = null;\r\n\t\r\n\t// check we have versions\r\n\tif(!data.length || data.length === 0) {\r\n\t\tlogger.info(logger.Globalize.formatMessage(\"flowNoVersions\"));\t\r\n\t\t// return failure directly\r\n\t\ttheResults.success = false;\r\n\t\tpromise = theResults;\r\n\t} else {\r\n\t \tlogger.info(logger.Globalize.formatMessage(\"flowFetchedVersions\", capabilityObject.versions.length));\r\n\t \t\r\n\t \t// for each version do the processing, because one product per version we handle each one\r\n\t\t// use reduce so it waits until the promise for an item resolves before processing the next item\r\n\t\tpromise = Promise.reduce(data, function(total, bsrURI, index, length) {\r\n\t\t\tlogger.entry(\"_transferToDraftForCapability_reduce_callback\", total, bsrURI, index, length);\r\n\t\t\tlogger.info(logger.Globalize.formatMessage(\"flowProcessingVersion\", (index + 1), length));\r\n\t\t\t// pass in the total so it can set the capability details upon load\r\n\t\t\tvar versionPromise = _pushProductToDraftsPublishStoreResult(capabilityObject.bsBsrURI, bsrURI, total, modeFlags, apiCli, apicdevportal).then(function(bs){\r\n\t \t\t\tlogger.entry(\"_transferToDraftForCapability_reduce_transfer_callback\", bs);\r\n\t\t\t\t\r\n\t \t\t\t// return the business service results\r\n\t\t\t\tlogger.exit(\"_transferToDraftForCapability_reduce_transfer_callback\", bs);\r\n\t\t\t\treturn bs;\r\n\t\t\t});\r\n\t\t\tlogger.exit(\"_transferToDraftForCapability_reduce_callback\", versionPromise);\r\n\t\t\treturn versionPromise;\r\n\t\t}, theResults).then(function(total){\r\n\t\t\tlogger.entry(\"_transferToDraftForCapability_reduce_done_callback\", total);\r\n\t\t\tlogger.info(logger.Globalize.formatMessage(\"flowProcessedVersions\"));\r\n\t\t\tlogger.exit(\"_transferToDraftForCapability_reduce_done_callback\", total);\r\n\t\t\treturn total;\r\n\t\t}).caught(function(error){\r\n\t\t\tlogger.entry(\"_transferToDraftForCapability_error\", error);\r\n\t\t\t// log the error and the failure, then return\r\n\t\t\tlogger.error(\"\", error);\r\n\t\t\t// cannot store under version because we have none\r\n\t\t\ttheResults.success = false;\r\n\t\t\tlogger.exit(\"_transferToDraftForCapability_error\", theResults);\r\n\t\t\treturn theResults;\r\n\t\t});\t\r\n\t}\r\n\t// return \r\n\tlogger.exit(\"_transferToDraftForCapability_versions_callback\", promise);\r\n\treturn promise;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to take the chords, see which keys they are in, and return the keys
function giveKeys(chords){ var addKey = true; var retKeys = []; for(var key in keys){ for(var chord in chords){ //TESTING ONLY --- //$('div#testDiv p#testP').append(' --- Testing' + ' ' + chords[chord] + ' in ' + keys[key] + ', and the result is: ' + jQuery.inArray(chords[chord],keys[key])); //testing// if(jQuery.inArray(chords[chord],keys[key])===-1) { addKey = false; } } if(addKey===true){ retKeys.push(key); } addKey = true; } return retKeys; }
[ "function getChord() {\n //get all playing keys\n var keys = document.querySelectorAll(\".key.playing\");\n\n //if less than 2 keys there is no chord, return blank\n if (keys.length < 2) {\n return \"\";\n }\n\n //get bass note (lowest playing note)\n var bass = keys[0].dataset.note;\n //get indicies of currently playing notes\n var indicies = [];\n for (i = 0; i < keys.length; i++) {\n indicies.push(keys[i].dataset.pos);\n }\n\n //test every note as a potential root in order\n for (i = 0; i < keys.length; i++) {\n //set current root to test\n var root = i;\n\n //get intervals of all notes from root; stored as a set\n let intervals = new Set();\n for (j = 0; j < indicies.length; j++) {\n //get interval between root and current note\n //if current note is < root shift it an octave up for calculations\n if ((indicies[j] % 12) < (indicies[root] % 12)) {\n var interval = Math.abs(((indicies[j] % 12) + 12) - (indicies[root] % 12));\n }\n else {\n var interval = Math.abs((indicies[j] % 12) - (indicies[root] % 12));\n }\n //mudolo to remove compound intervals\n interval = interval % 12;\n //add interval to set of intervals\n intervals.add(interval);\n }\n\n //loop through every chord in the chord db\n for (j = 0; j < chords.length; j++) {\n //if match found return chord\n if (chordEq(chords[j].intervals, intervals)) {\n //add root note and notation to chord display\n var chord = keys[root].dataset.note + chords[j].notation;\n //if bass note is different from the root add it\n if (bass != keys[root].dataset.note) {\n chord += \"\\\\\" + bass;\n }\n\n return chord\n }\n }\n }\n \n //nothing found; return blank\n return \"\";\n}", "function collectChords(){\n\t\tvar chords = [];\n\t\tfor(i=1;i<numChords+1;i++){\n\t\t\tif($('input[name=\"' + ordinal(i) + 'Chord\"]').val() !== ''){\n\t\t\t\tchords.push($('input[name=\"' + ordinal(i) + 'Chord\"]').val().toLowerCase());\n\t\t\t}\n\t\t}\n\t\treturn chords;\n\t}", "function getPressedKeys() {\n //holds all the keys that are pressed down\n let pressed = [];\n //itterates over every key in 'keysDown'\n for (var key in keysDown){\n if (keysDown.hasOwnProperty(key)) {\n //if key is held down, add it to 'pressed'\n if (keysDown[key] === true){\n pressed.push(key);\n }\n }\n }\n return pressed;\n}", "function _getSelectedTilesKeys() {\n var tilesKeys = [];\n var nbSelectedtiles = lv_cockpits.winControl.selection.count();\n for (var tileIterator = 0; tileIterator < nbSelectedtiles; tileIterator++) {\n var currentItem = lv_cockpits.winControl.selection.getItems()._value[tileIterator];\n tilesKeys.push(currentItem.key);\n }\n\n return tilesKeys;\n }", "changeKeyFromChord(chord=this.lastChord) {\n // common key modulation\n let keys = this.chordToKeys[chord.toString()]\n\n if (!keys) {\n // chord doesn't have key, eg. A#m\n return\n }\n\n keys = keys.filter(key => key.name() != this.keySignature.name())\n if (!keys.length) {\n // some chords are only in one key\n return\n }\n\n let newKey = keys[this.generator.int() % keys.length]\n\n // console.warn(`Going from ${this.keySignature.name()} to ${newKey.name()}`)\n this.keySignature = newKey\n this.scale = this.keySignature.defaultScale()\n this.chords = null\n }", "function listKeys() {\n let keyString = \"\";\n for (let key in flower) {\n keyString += key + \", \";\n }\n return keyString;\n}", "function getAllChords(inputScale){\n\tvar allChords = [];\n\tvar chordSeeds = chordmaker.chords; // TODO -- this.chordmaker?\n\n\t// for each pitch in input scale, get array of possible chords\n\tfor (var i = 0; i < inputScale.length; i++) {\n\t\tvar thisMode = getMode(inputScale, i);\n\t\t\n\t\t// for each type of chord defined above, get chord and push to allChords array\n\t\tfor(type in chordSeeds) {\n\t\t\tif (chordSeeds.hasOwnProperty(type)) {\n\t\t\t\t\n\t\t\t\tvar thisChord = [];\n\t\t \t// for each interval in the given chord type, get the note and push to this chord\n\t\t\t\tfor (var j = 0; j < chordSeeds[type].length; j++) {\n\t\t\t\t\t// TODO -- 0 v 1 indexing jankiness\n\t\t\t\t\tvar noteInt = chordSeeds[type][j] - 1;\n\t\t\t\t\t// console.log(noteInt);\n\n\t\t\t\t\tvar thisNote = thisMode[noteInt];\n\t\t\t\t\tthisChord.push(thisNote);\n\t\t\t\t}\n\t\t\t\tallChords.push(thisChord);\n\t\t }\n\t\t}\n\t}\n\tconsole.log(allChords);\n\treturn allChords;\n}", "function getNeighbourLetters(l)\r\n{\r\n var neighbourLetters=[''], count=0, row, column,colspan, rowspan,tillRow, tillColumn;\r\n \r\n //Getting character\r\n for(var i=0; i<keyboard.length; i++)\r\n {\r\n if(keyboard[i].value == l)\r\n {\r\n row=parseInt(keyboard[i].row);\r\n column=parseInt(keyboard[i].column);\r\n rowspan = parseInt(keyboard[i].rowspan);\r\n colspan = parseInt(keyboard[i].colspan);\r\n break;\r\n }\r\n }\r\n \r\n //--Character has rowspan and colspan greater than 1, find all neighbours--//\r\n if(rowspan > 1 || colspan > 1)\r\n {\r\n tillRow = row + rowspan -1;\r\n tillColumn = column + colspan -1;\r\n \r\n for(var r=row; r<=tillRow; r++)\r\n {\r\n for(var c = column; c<=tillColumn; c++)\r\n {\r\n for(var i=0; i<keyboard.length; i++)\r\n {\r\n if((keyboard[i].row==r && keyboard[i].column==tillColumn+1) || (keyboard[i].row==r && keyboard[i].column==column-keyboard[i].colspan) || (keyboard[i].row==row-keyboard[i].rowspan && keyboard[i].column==c) || (keyboard[i].row==tillRow+1 && keyboard[i].column==c))\r\n {\r\n if($.inArray((keyboard[i].value),neighbourLetters) == -1)\r\n {\r\n neighbourLetters[count] = keyboard[i].value;\r\n count++;\r\n }\r\n }\r\n \r\n if((r+1)>tillRow)\r\n {\r\n if((keyboard[i].row==tillRow+1 && keyboard[i].column==c))\r\n { \r\n if($.inArray((keyboard[i].value),neighbourLetters) == -1)\r\n {\r\n neighbourLetters[count] = keyboard[i].value;\r\n count++;\r\n }\r\n }\r\n }\r\n \r\n if((c+1)>tillColumn)\r\n {\r\n if((keyboard[i].row==r && keyboard[i].column==tillColumn+1))\r\n {\r\n if($.inArray((keyboard[i].value),neighbourLetters) == -1)\r\n {\r\n neighbourLetters[count] = keyboard[i].value;\r\n count++;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n else //--Character has rowspan and colspan equal to 1, find all neighbours--//\r\n {\r\n for(var i=0; i<keyboard.length; i++)\r\n {\r\n //--Character is a neighbour to 'l'--//\r\n if((keyboard[i].row==row-1 && keyboard[i].column==column) || (keyboard[i].row==row && keyboard[i].column==column+1) || (keyboard[i].row==row && keyboard[i].column==column-1) || (keyboard[i].row==row+1 && keyboard[i].column==column))\r\n {\r\n if($.inArray((keyboard[i].value),neighbourLetters) == -1)\r\n {\r\n neighbourLetters[count] = keyboard[i].value;\r\n count++;\r\n }\r\n }else if(keyboard[i].colspan>1 || keyboard[i].rowspan>1)//--Character is not an immediate neighbour to 'l', but check whether with rowspan and colspan it becomes a neighbour--//\r\n {\r\n var tillColumn2, tillRow2;\r\n tillRow2 = parseInt(keyboard[i].row) + parseInt(keyboard[i].rowspan) -1;\r\n tillColumn2 = parseInt(keyboard[i].column) + parseInt(keyboard[i].colspan) -1;\r\n for(var r=keyboard[i].row; r<=tillRow2; r++)\r\n {\r\n for(var c = keyboard[i].column; c<=tillColumn2; c++)\r\n {\r\n for(var k=0; k<keyboard.length; k++)\r\n {\r\n if((keyboard[k].row==r && keyboard[k].column==tillColumn2+1) || (keyboard[k].row==r && keyboard[k].column==c-1) || (keyboard[k].row==r-1 && keyboard[k].column==c) || (keyboard[k].row==tillRow2+1 && keyboard[k].column==c))\r\n {\r\n if(keyboard[k].value==l)\r\n {\r\n if($.inArray((keyboard[i].value),neighbourLetters) == -1)\r\n {\r\n neighbourLetters[count] = keyboard[i].value;\r\n count++;\r\n }\r\n }\r\n }\r\n \r\n if((r+1)>tillRow2)\r\n {\r\n if((keyboard[k].row==tillRow2+1 && keyboard[k].column==c))\r\n { \r\n if((keyboard[k].row==row-1 && keyboard[k].column==column) || (keyboard[k].row==row && keyboard[k].column==column+1) || (keyboard[k].row==row && keyboard[k].column==column-1) || (keyboard[k].row==row+1 && keyboard[k].column==column))\r\n {\r\n if(keyboard[k].value==l)\r\n {\r\n if($.inArray((keyboard[i].value),neighbourLetters) == -1)\r\n {\r\n neighbourLetters[count] = keyboard[i].value;\r\n count++;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n \r\n if((c+1)>tillColumn2)\r\n {\r\n if((keyboard[k].row==r && keyboard[k].column==tillColumn2+1))\r\n {\r\n if(keyboard[k].value == l)\r\n {\r\n if($.inArray((keyboard[i].value),neighbourLetters) == -1)\r\n {\r\n neighbourLetters[count] = keyboard[i].value;\r\n count++;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return neighbourLetters;\r\n}", "function printChords(inp){\n var result = [\"\",\"\"]; //output lines\n var str = inp; //local copy of input for modifying\n var offset = 0; //offset caused by pasting the last chord (e.g. Esus2 shifts the following E 5 characters over)\n\n while(str.indexOf(\"[\") != -1){\n //all chords are of the format [chord], find it by finding [ and ]\n var leftBrace = str.indexOf(\"[\");\n var rightBrace = str.indexOf(\"]\");\n\n //take the lyrics from start to [\n result[0] += str.substring(0,leftBrace);\n\n //pad spaces to where the chord belongs on the chord line\n for(i = offset; i < leftBrace; i++)\n result[1] += \" \";\n if(leftBrace < offset) result[1] += \" \"; //if no padding was added (two chords in a row), add a space\n\n //get the chord from between the braces\n result[1] += str.substring(leftBrace+1, rightBrace);\n offset = rightBrace-leftBrace;\n\n //str = remainder of string after ]\n str = str.substring(rightBrace+1, 999).trim();\n }\n result[0] += str;\n console.log(result[1] .green);\n console.log(result[0] .yellow);\n}", "function findDoor(map){\n\tfor(let r=0;r<map.length;r++){\n\t\tfor(let c=0;c<map[0].length;c++){\n\t\t\tif(map[r][c] == '/'){\n\t\t\t\treturn [c,r];\n\t\t\t}\n\t\t}\n\t}\n}", "function keys(obj) {\n //return Object.keys(obj);\n var output = [];\n each(obj, function(elem, key) {\n output.push(key);\n });\n return output;\n}", "function keyboardRow(arr) {\r\n // -------------------- Your Code Here --------------------\r\nvar row1 = 'QWERTYUIOP';\r\nvar row2 = 'ASDFGHJKL';\r\nvar row3 = 'ZXCVBNM';\r\nvar currentRow;\r\nvar trackObj = {};\r\n\r\nfor (let i = 0; i < arr.length; i++) {\r\n \r\n var word = arr[i];\r\n var firstLetter = word[0];\r\n \r\n if (row1.indexOf(firstLetter) !== -1){\r\n currentRow = row1;\r\n } else if (row2.indexOf(firstLetter) !== -1){\r\n currentRow = row2;\r\n } else if (row3.indexOf(firstLetter) !== -1){\r\n currentRow = row3;\r\n }\r\n \r\n // check if the word belongs to row1 || row2 || row3\r\n\r\n \r\n \r\n}\r\n\r\n\r\n\r\n // -------------------- End Code Area ---------------------\r\n}", "function keyMatches(got, wanted) {\n for (var i=0; i<wanted.length; ++i)\n {\n var matches = true;\n for (var j=0; j<wanted[i].length; ++j)\n {\n if (!(wanted[i][j] == 0 || wanted[i][j] == got[j]))\n {\n matches = false;\n }\n }\n if (matches)\n {\n return true;\n }\n }\n return false;\n}", "function emitKeySequence(keys) {\r\n var i;\r\n for (i = 0; i < keys.length; i++)\r\n emitKey(keys[i], 1);\r\n for (i = keys.length - 1; i >= 0; i--)\r\n emitKey(keys[i], 0);\r\n}", "function lookForWhatToMove(key) {\n var coord = \"\";\n for(var r = 0; r < dim_max; r++) {\n for(var c = 0; c < dim_max; c++) {\n if(m[r][c] == 16) {\n //console.log(key);\n switch(key) {\n //a, left\n case 65:\n case 37: if(validate(r, c+1)) coord = r+\";\"+c +\"$\"+ r+\";\"+(c+1); break;\n //w, up\n case 87:\n case 38: if(validate(r+1, c)) coord = r+\";\"+c +\"$\"+ (r+1)+\";\"+c; break;\n //d, right\n case 68:\n case 39: if(validate(r, c-1)) coord = r+\";\"+c +\"$\"+ r+\";\"+(c-1); break;\n //s, down\n case 83:\n case 40: if(validate(r-1, c)) coord = r+\";\"+c +\"$\"+ (r-1)+\";\"+c; break;\n }\n }\n }\n }\n //what is coord?\n //coord = \"emptyCellRow;emptyCellCol$foundCellRow;foundCellCol\"\n return coord;\n}", "function hastableKeys(dict)\n {\n var ids = [];\n\n for (var id in dict)\n {\n if (dict.hasOwnProperty(id))\n ids.push(id);\n }\n\n return ids;\n }", "function findCadence(chords) {\n\tif (chords[chords.length - 2] === \"V\" && chords[chords.length - 1] === \"I\") {\n\t\treturn \"perfect\";\n\t} else if (chords[chords.length - 2] === \"IV\" && chords[chords.length - 1] === \"I\") {\n\t\treturn \"plagal\";\n\t} else if (chords[chords.length - 2] === \"V\" && chords[chords.length - 1] !== \"I\") {\n\t\treturn \"interrupted\";\n\t} else if (chords[chords.length - 1] === \"V\") {\n\t\treturn \"imperfect\";\n\t} else return \"no cadence\";\n}", "function getBasicChord(chord) {\n\tchordNotes = [1, 5, 8, 10];\n\treturn chordNotes.map(rel => getIntervalNote(chord + chordData.baseOctave, rel));\n}", "function pianoClickBlack(ctx){\r\n\t//to give chord name for each tuts\r\n\t//make array and fill with black tuts chord name\r\n\tvar keyName2=[\"C#\",\"D#\",\"F#\",\"G#\",\"A#\",\"C#'\",\"D#'\",\"F#'\",\"G#'\",\"A#'\",\"C#''\",\"D#''\",\"F#''\",\"G#''\",\"A#''\",\"C#'''\",\"D#'''\",\"F#'''\",\"G#'''\",\"A#'''\"];\r\n\tvar keyNameNumber2 = 0;\r\n\tvar textPosition2 = 46;\r\n\tfor(xBlackTuts=32;xBlackTuts<1550 && keyNameNumber2<20;xBlackTuts+=56){\r\n\t\tif(xBlackTuts != 144 && xBlackTuts != 368 && xBlackTuts != 536 && xBlackTuts != 760 && xBlackTuts != 928 & xBlackTuts != 1152 && xBlackTuts != 1320){\r\n\t\t\tctx.fillStyle='black';\r\n\t\t\tctx.fillRect(xBlackTuts,250,45,180);\r\n\t\t\tctx.font = \"12px Arial\";\r\n\t\t\tctx.fillStyle = \"white\";\r\n\t\t\tctx.fillText(keyName2[keyNameNumber2],textPosition2,390);\r\n\t\t\tkeyNameNumber2+=1;\r\n\t\t}\r\n\t\ttextPosition2+=56;\r\n\t}\r\n\t\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
12db lowpass biquad coefficients
function coeff_biquad_lowpass12db(freq, gain) { var w = 2.0 * Math.PI * freq / samplerate; var s = Math.sin(w); var c = Math.cos(w); var q = gain; var alpha = s / (2.0 * q); var scale = 1.0 / (1.0 + alpha); var a1 = 2.0 * c * scale; var a2 = (alpha - 1.0) * scale; var b1 = (1.0 - c) * scale; var b0 = 0.5 * b1; var b2 = b0; return [0, 0, 0, 0, b0, b1, b2, a1, a2]; }
[ "SolveBend_PBD_Triangle() {\n const stiffness = this.m_tuning.bendStiffness;\n for (let i = 0; i < this.m_bendCount; ++i) {\n const c = this.m_bendConstraints[i];\n const b0 = this.m_ps[c.i1].Clone();\n const v = this.m_ps[c.i2].Clone();\n const b1 = this.m_ps[c.i3].Clone();\n const wb0 = c.invMass1;\n const wv = c.invMass2;\n const wb1 = c.invMass3;\n const W = wb0 + wb1 + 2.0 * wv;\n const invW = stiffness / W;\n const d = new b2_math_js_1.b2Vec2();\n d.x = v.x - (1.0 / 3.0) * (b0.x + v.x + b1.x);\n d.y = v.y - (1.0 / 3.0) * (b0.y + v.y + b1.y);\n const db0 = new b2_math_js_1.b2Vec2();\n db0.x = 2.0 * wb0 * invW * d.x;\n db0.y = 2.0 * wb0 * invW * d.y;\n const dv = new b2_math_js_1.b2Vec2();\n dv.x = -4.0 * wv * invW * d.x;\n dv.y = -4.0 * wv * invW * d.y;\n const db1 = new b2_math_js_1.b2Vec2();\n db1.x = 2.0 * wb1 * invW * d.x;\n db1.y = 2.0 * wb1 * invW * d.y;\n b0.SelfAdd(db0);\n v.SelfAdd(dv);\n b1.SelfAdd(db1);\n this.m_ps[c.i1].Copy(b0);\n this.m_ps[c.i2].Copy(v);\n this.m_ps[c.i3].Copy(b1);\n }\n }", "function lagrangeCoefficients(idx) {\n const res = Array(idx.length)\n const w = idx.reduce((w, id) => w * id, 1n)\n for (let i = 0; i < idx.length; i++) {\n let v = idx[i]\n for (let j = 0; j < idx.length; j++) {\n if (j != i) {\n v *= idx[j] - idx[i]\n }\n }\n res[i] = new math.Fr(v).invert().multiply(w).value\n }\n return res\n}", "function alldB() {\n\t\t\t\tins[0] = p.newdefault(x1, y1, \"inlet\");\n\t\t\t\tdbtoas[0] = p.newdefault(x1, y2, \"mindB\", mindB);\n\t\t\t\ttriggers[0] = p.newdefault(x1, y3, \"t\", \"l\", \"target\");\n\t\t\t\tappends[0] = p.newdefault(x1+20, y4, \"append\", 0);\t\t\t\n\t\t\t\tout = p.newdefault(x1, y5, \"outlet\");\n\t\t\t\tp.connect(ins[0], 0, dbtoas[0], 0);\n\t\t\t\tp.connect(dbtoas[0], 0, triggers[0],0);\n\t\t\t\tp.connect(triggers[0], 1, appends[0], 0);\n\t\t\t\tp.connect(appends[0], 0, out, 0);\n\t\t\t\tp.connect(triggers[0], 0, out, 0);\t\t\n\t}", "function getAnchoBandaMinimoQPSK(Fb) {\n B=Fb/2\n return B;\n}", "function binb(x, len) {\n var j, i, l,\n W = new Array(80),\n hash = new Array(16),\n //Initial hash values\n H = [\n new int64(0x6a09e667, -205731576),\n new int64(-1150833019, -2067093701),\n new int64(0x3c6ef372, -23791573),\n new int64(-1521486534, 0x5f1d36f1),\n new int64(0x510e527f, -1377402159),\n new int64(-1694144372, 0x2b3e6c1f),\n new int64(0x1f83d9ab, -79577749),\n new int64(0x5be0cd19, 0x137e2179)\n ],\n T1 = new int64(0, 0),\n T2 = new int64(0, 0),\n a = new int64(0, 0),\n b = new int64(0, 0),\n c = new int64(0, 0),\n d = new int64(0, 0),\n e = new int64(0, 0),\n f = new int64(0, 0),\n g = new int64(0, 0),\n h = new int64(0, 0),\n //Temporary variables not specified by the document\n s0 = new int64(0, 0),\n s1 = new int64(0, 0),\n Ch = new int64(0, 0),\n Maj = new int64(0, 0),\n r1 = new int64(0, 0),\n r2 = new int64(0, 0),\n r3 = new int64(0, 0);\n\n if (sha512_k === undefined) {\n //SHA512 constants\n sha512_k = [\n new int64(0x428a2f98, -685199838), new int64(0x71374491, 0x23ef65cd),\n new int64(-1245643825, -330482897), new int64(-373957723, -2121671748),\n new int64(0x3956c25b, -213338824), new int64(0x59f111f1, -1241133031),\n new int64(-1841331548, -1357295717), new int64(-1424204075, -630357736),\n new int64(-670586216, -1560083902), new int64(0x12835b01, 0x45706fbe),\n new int64(0x243185be, 0x4ee4b28c), new int64(0x550c7dc3, -704662302),\n new int64(0x72be5d74, -226784913), new int64(-2132889090, 0x3b1696b1),\n new int64(-1680079193, 0x25c71235), new int64(-1046744716, -815192428),\n new int64(-459576895, -1628353838), new int64(-272742522, 0x384f25e3),\n new int64(0xfc19dc6, -1953704523), new int64(0x240ca1cc, 0x77ac9c65),\n new int64(0x2de92c6f, 0x592b0275), new int64(0x4a7484aa, 0x6ea6e483),\n new int64(0x5cb0a9dc, -1119749164), new int64(0x76f988da, -2096016459),\n new int64(-1740746414, -295247957), new int64(-1473132947, 0x2db43210),\n new int64(-1341970488, -1728372417), new int64(-1084653625, -1091629340),\n new int64(-958395405, 0x3da88fc2), new int64(-710438585, -1828018395),\n new int64(0x6ca6351, -536640913), new int64(0x14292967, 0xa0e6e70),\n new int64(0x27b70a85, 0x46d22ffc), new int64(0x2e1b2138, 0x5c26c926),\n new int64(0x4d2c6dfc, 0x5ac42aed), new int64(0x53380d13, -1651133473),\n new int64(0x650a7354, -1951439906), new int64(0x766a0abb, 0x3c77b2a8),\n new int64(-2117940946, 0x47edaee6), new int64(-1838011259, 0x1482353b),\n new int64(-1564481375, 0x4cf10364), new int64(-1474664885, -1136513023),\n new int64(-1035236496, -789014639), new int64(-949202525, 0x654be30),\n new int64(-778901479, -688958952), new int64(-694614492, 0x5565a910),\n new int64(-200395387, 0x5771202a), new int64(0x106aa070, 0x32bbd1b8),\n new int64(0x19a4c116, -1194143544), new int64(0x1e376c08, 0x5141ab53),\n new int64(0x2748774c, -544281703), new int64(0x34b0bcb5, -509917016),\n new int64(0x391c0cb3, -976659869), new int64(0x4ed8aa4a, -482243893),\n new int64(0x5b9cca4f, 0x7763e373), new int64(0x682e6ff3, -692930397),\n new int64(0x748f82ee, 0x5defb2fc), new int64(0x78a5636f, 0x43172f60),\n new int64(-2067236844, -1578062990), new int64(-1933114872, 0x1a6439ec),\n new int64(-1866530822, 0x23631e28), new int64(-1538233109, -561857047),\n new int64(-1090935817, -1295615723), new int64(-965641998, -479046869),\n new int64(-903397682, -366583396), new int64(-779700025, 0x21c0c207),\n new int64(-354779690, -840897762), new int64(-176337025, -294727304),\n new int64(0x6f067aa, 0x72176fba), new int64(0xa637dc5, -1563912026),\n new int64(0x113f9804, -1090974290), new int64(0x1b710b35, 0x131c471b),\n new int64(0x28db77f5, 0x23047d84), new int64(0x32caab7b, 0x40c72493),\n new int64(0x3c9ebe0a, 0x15c9bebc), new int64(0x431d67c4, -1676669620),\n new int64(0x4cc5d4be, -885112138), new int64(0x597f299c, -60457430),\n new int64(0x5fcb6fab, 0x3ad6faec), new int64(0x6c44198c, 0x4a475817)\n ];\n }\n\n for (i = 0; i < 80; i += 1) {\n W[i] = new int64(0, 0);\n }\n\n // append padding to the source string. The format is described in the FIPS.\n x[len >> 5] |= 0x80 << (24 - (len & 0x1f));\n x[((len + 128 >> 10) << 5) + 31] = len;\n l = x.length;\n for (i = 0; i < l; i += 32) { //32 dwords is the block size\n int64copy(a, H[0]);\n int64copy(b, H[1]);\n int64copy(c, H[2]);\n int64copy(d, H[3]);\n int64copy(e, H[4]);\n int64copy(f, H[5]);\n int64copy(g, H[6]);\n int64copy(h, H[7]);\n\n for (j = 0; j < 16; j += 1) {\n W[j].h = x[i + 2 * j];\n W[j].l = x[i + 2 * j + 1];\n }\n\n for (j = 16; j < 80; j += 1) {\n //sigma1\n int64rrot(r1, W[j - 2], 19);\n int64revrrot(r2, W[j - 2], 29);\n int64shr(r3, W[j - 2], 6);\n s1.l = r1.l ^ r2.l ^ r3.l;\n s1.h = r1.h ^ r2.h ^ r3.h;\n //sigma0\n int64rrot(r1, W[j - 15], 1);\n int64rrot(r2, W[j - 15], 8);\n int64shr(r3, W[j - 15], 7);\n s0.l = r1.l ^ r2.l ^ r3.l;\n s0.h = r1.h ^ r2.h ^ r3.h;\n\n int64add4(W[j], s1, W[j - 7], s0, W[j - 16]);\n }\n\n for (j = 0; j < 80; j += 1) {\n //Ch\n Ch.l = (e.l & f.l) ^ (~e.l & g.l);\n Ch.h = (e.h & f.h) ^ (~e.h & g.h);\n\n //Sigma1\n int64rrot(r1, e, 14);\n int64rrot(r2, e, 18);\n int64revrrot(r3, e, 9);\n s1.l = r1.l ^ r2.l ^ r3.l;\n s1.h = r1.h ^ r2.h ^ r3.h;\n\n //Sigma0\n int64rrot(r1, a, 28);\n int64revrrot(r2, a, 2);\n int64revrrot(r3, a, 7);\n s0.l = r1.l ^ r2.l ^ r3.l;\n s0.h = r1.h ^ r2.h ^ r3.h;\n\n //Maj\n Maj.l = (a.l & b.l) ^ (a.l & c.l) ^ (b.l & c.l);\n Maj.h = (a.h & b.h) ^ (a.h & c.h) ^ (b.h & c.h);\n\n int64add5(T1, h, s1, Ch, sha512_k[j], W[j]);\n int64add(T2, s0, Maj);\n\n int64copy(h, g);\n int64copy(g, f);\n int64copy(f, e);\n int64add(e, d, T1);\n int64copy(d, c);\n int64copy(c, b);\n int64copy(b, a);\n int64add(a, T1, T2);\n }\n int64add(H[0], H[0], a);\n int64add(H[1], H[1], b);\n int64add(H[2], H[2], c);\n int64add(H[3], H[3], d);\n int64add(H[4], H[4], e);\n int64add(H[5], H[5], f);\n int64add(H[6], H[6], g);\n int64add(H[7], H[7], h);\n }\n\n //represent the hash as an array of 32-bit dwords\n for (i = 0; i < 8; i += 1) {\n hash[2 * i] = H[i].h;\n hash[2 * i + 1] = H[i].l;\n }\n return hash;\n }", "function bezierCurve(u, q){\n\tvar B = bern3;\n\tvar n = 4;\n\n\tvar p = vec3(0,0,0);\n\n\tfor(var i=0; i<n; i++){\n\t\tp = add(p, scale(B(i, u), q[i]));\n\n\t}\n\n\treturn p;\n}", "function polyCSubQ(r) {\r\n for (var i = 0; i < paramsN; i++) {\r\n r[i] = byteopsCSubQ(r[i]);\r\n }\r\n return r;\r\n}", "process(inputBuffer, outputBuffer) {\n var x;\n var y = [];\n var b1, b2, a1, a2;\n var xi1, xi2, yi1, yi2, y1i1, y1i2;\n\n for (var i = 0; i < inputBuffer.length; i++) {\n x = inputBuffer[i];\n // Save coefficients in local variables\n b1 = this.coefficients[0].b1;\n b2 = this.coefficients[0].b2;\n a1 = this.coefficients[0].a1;\n a2 = this.coefficients[0].a2;\n // Save memories in local variables\n xi1 = this.memories[0].xi1;\n xi2 = this.memories[0].xi2;\n yi1 = this.memories[0].yi1;\n yi2 = this.memories[0].yi2;\n\n // Formula: y[n] = x[n] + b1*x[n-1] + b2*x[n-2] - a1*y[n-1] - a2*y[n-2]\n // First biquad\n y[0] = x + b1 * xi1 + b2 * xi2 - a1 * yi1 - a2 * yi2;\n\n for (var e = 1; e < this.numberOfCascade; e++) {\n // Save coefficients in local variables\n b1 = this.coefficients[e].b1;\n b2 = this.coefficients[e].b2;\n a1 = this.coefficients[e].a1;\n a2 = this.coefficients[e].a2;\n // Save memories in local variables\n y1i1 = this.memories[e - 1].yi1;\n y1i2 = this.memories[e - 1].yi2;\n yi1 = this.memories[e].yi1;\n yi2 = this.memories[e].yi2;\n\n y[e] = y[e - 1] + b1 * y1i1 + b2 * y1i2 - a1 * yi1 - a2 * yi2;\n }\n\n // Write the output\n outputBuffer[i] = y[this.numberOfCascade - 1] * this.coefficients.g;\n\n // Update the memories\n this.memories[0].xi2 = this.memories[0].xi1;\n this.memories[0].xi1 = x;\n\n for (var p = 0; p < this.numberOfCascade; p++) {\n this.memories[p].yi2 = this.memories[p].yi1;\n this.memories[p].yi1 = y[p];\n }\n }\n }", "function bernsteinBasis(N, tt) {\n const n = N-1;\n const t = tt/n; //this basis goes from 0 to 1 for some reason\n //const t = tt;\n\n var sol = [];\n for(var i = 0; i <= n; i++) {\n const val = choose(n, i)*Math.pow(t,i)*Math.pow(1-t,n-i);\n sol.push(val);\n }\n\n return sol;\n}", "function newPhase() {\n\t// expand non-trivial outer blossoms with z == 0\n\tq.clear(); blist.clear();\n\tfor (let b = bloss.firstOuter(); b; b = bloss.nextOuter(b)) {\n\t\tif (z[b] == 0 && b > g.n) blist.enq(b);\n\t\tsteps++;\n\t}\n\twhile (!blist.empty()) {\n\t\tlet b = blist.deq();\n\t\tlet subs = bloss.expand(b); \n\t\tfor (let sb = subs.first(); sb; sb = subs.next(sb)) {\n\t\t\tif (z[sb] == 0 && sb > g.n) blist.enq(sb);\n\t\t\tsteps++;\n\t\t}\n\t}\n\n\t// set state and link for remaining blossoms \n\tfor (let b = bloss.firstOuter(); b; b = bloss.nextOuter(b)) {\n\t\tbloss.state(b, match.at(bloss.base(b)) ? 0 : +1);\n\t\tbloss.link(b,[0,0])\n\t\tsteps++;\n\t}\n\t// and add eligible edges to q\n\tfor (let b = bloss.firstOuter(); b; b = bloss.nextOuter(b))\n\t\tif (bloss.state(b) == +1) add2q(b);\n\tif (trace) {\n\t\tlet s = bloss.blossoms2string(1);\n\t\tif (s.length > 2) traceString += ` ${s}\\n`;\n\t}\n}", "function polyToBytes(a) {\r\n var t0, t1;\r\n var r = new Array(384);\r\n var a2 = polyCSubQ(a); // Returns: a - q if a >= q, else a (each coefficient of the polynomial)\r\n // for 0-127\r\n for (var i = 0; i < paramsN / 2; i++) {\r\n // get two coefficient entries in the polynomial\r\n t0 = uint16(a2[2 * i]);\r\n t1 = uint16(a2[2 * i + 1]);\r\n\r\n // convert the 2 coefficient into 3 bytes\r\n r[3 * i + 0] = byte(t0 >> 0); // byte() does mod 256 of the input (output value 0-255)\r\n r[3 * i + 1] = byte(t0 >> 8) | byte(t1 << 4);\r\n r[3 * i + 2] = byte(t1 >> 4);\r\n }\r\n return r;\r\n}", "function nttBaseMul(a0, a1, b0, b1, zeta) {\r\n var r = new Array(2);\r\n r[0] = nttFqMul(a1, b1);\r\n r[0] = nttFqMul(r[0], zeta);\r\n r[0] = r[0] + nttFqMul(a0, b0);\r\n r[1] = nttFqMul(a0, b1);\r\n r[1] = r[1] + nttFqMul(a1, b0);\r\n return r;\r\n}", "function polyAdd(a, b) {\r\n var c = new Array(384);\r\n for (var i = 0; i < paramsN; i++) {\r\n c[i] = a[i] + b[i];\r\n }\r\n return c;\r\n}", "function polyCompress(a, paramsK) {\r\n var t = new Array(8);\r\n a = polyCSubQ(a);\r\n var rr = 0;\r\n var r = new Array(paramsPolyCompressedBytesK768);\r\n for (var i = 0; i < paramsN / 8; i++) {\r\n for (var j = 0; j < 8; j++) {\r\n t[j] = byte(((a[8 * i + j] << 4) + paramsQ / 2) / paramsQ) & 15;\r\n }\r\n r[rr + 0] = t[0] | (t[1] << 4);\r\n r[rr + 1] = t[2] | (t[3] << 4);\r\n r[rr + 2] = t[4] | (t[5] << 4);\r\n r[rr + 3] = t[6] | (t[7] << 4);\r\n rr = rr + 4;\r\n }\r\n return r;\r\n}", "function indcpaRejUniform(buf, bufl) {\r\n var r = new Array(384).fill(0); // each element is uint16 (0-65535)\r\n var val0, val1; // d1, d2 in kyber documentation\r\n var pos = 0; // i\r\n var ctr = 0; // j\r\n\r\n // while less than 256 (the length of the output array: a(i,j))\r\n // and if there's still elements in the input buffer left\r\n while (ctr < paramsN && pos + 3 <= bufl) {\r\n\r\n // compute d1 and d2\r\n val0 = (uint16((buf[pos]) >> 0) | (uint16(buf[pos + 1]) << 8)) & 0xFFF;\r\n val1 = (uint16((buf[pos + 1]) >> 4) | (uint16(buf[pos + 2]) << 4)) & 0xFFF;\r\n\r\n // if d1 is less than 3329\r\n if (val0 < paramsQ) {\r\n // assign to d1\r\n r[ctr] = val0;\r\n // increment position of output array\r\n ctr = ctr + 1;\r\n }\r\n if (ctr < paramsN && val1 < paramsQ) {\r\n r[ctr] = val1;\r\n ctr = ctr + 1;\r\n }\r\n\r\n // increment input buffer index by 3\r\n pos = pos + 3;\r\n }\r\n\r\n var result = new Array(2);\r\n result[0] = r; // returns polynomial NTT representation\r\n result[1] = ctr; // ideally should return 256\r\n return result;\r\n}", "function polyInvNttToMont(r) {\r\n return nttInv(r);\r\n}", "backprop_aggregation(grad) {\n // a(inputs) = sum(inputs*weights);\n // since derivative of sum is equal to sum of derivatives\n // inner function, we can focus on inputs*weights.\n // this means each gradient is now just input*weights\n // so we are looking at a linear function a(w, i) = iw again.\n // thus a'(w) = i*w\n // (da/dW)\n let weight_grads = numeric.mul(this.inputs, grad);\n // (da/dI)\n let input_grads = numeric.mul(this.weights, grad); // for further backprop\n return [input_grads, weight_grads];\n }", "function PHSK_BFeld( draht, BPoint) {\n\tif ( GMTR_MagnitudeSquared( GMTR_CrossProduct( GMTR_VectorDifference(draht.a ,draht.b ),GMTR_VectorDifference(draht.a ,BPoint ) )) < 10E-10)\n\t\treturn new Vec3 (0.0, 0.0, 0.0);\n\n\n\tlet A = draht.a;\n\tlet B = draht.b;\n\tlet P = BPoint;\n\t\n\tlet xd = -(GMTR_DotProduct(A,A) - GMTR_DotProduct(A,B) + GMTR_DotProduct(P , GMTR_VectorDifference(A,B))) / (GMTR_Distance(A,B));\n\tlet x = xd / (GMTR_Distance(A,B));\n\tlet yd = xd + GMTR_Distance(A,B);\n\t\n\tlet F1 = (yd / GMTR_Distance(P,B)) - (xd / GMTR_Distance(P,A));\n\tlet F2 = 1 / (GMTR_Distance(P,GMTR_VectorAddition(A,GMTR_ScalarMultiplication( GMTR_VectorDifference(B,A), x))));\n\tlet F3 = GMTR_CrossProductNormal( GMTR_VectorDifference(A,B),GMTR_VectorDifference(A,P) );\n\n\treturn GMTR_ScalarMultiplication(F3,F1*F2);\n}", "function polyToMsg(a) {\r\n var msg = new Array(32);\r\n var t;\r\n var a2 = polyCSubQ(a);\r\n for (var i = 0; i < paramsN / 8; i++) {\r\n msg[i] = 0;\r\n for (var j = 0; j < 8; j++) {\r\n t = (((uint16(a2[8 * i + j]) << 1) + uint16(paramsQ / 2)) / uint16(paramsQ)) & 1;\r\n msg[i] |= byte(t << j);\r\n }\r\n }\r\n return msg;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
3. Create a function that returns the sum of two numbers that are arguments. Then console.log the function with the variables from step two as your two arguments.
function addSum(a,b){ var answer = a + b; //4. Create a function that returns the difference of two numbers that are arguments. Then console.log the function with the variables from step two as your two arguments. console.log (answer); }
[ "function consoleSum(x, y) {\r\n var sum = x + y;\r\n console.log(sum);\r\n}", "function add(num1, num2){\n     console.log(\"Summing Numbers!\");\n     console.log(\"num1 is: \" + num1);\n console.log(\"num2 is: \" + num2);\n     var sum = num1 + num2;\n     return sum;\n }", "function add33(a,b){\n console.log(arguments);\n return a+b;\n}", "function addNumbers(num1, num2){ \n//arguments je koytai thak na keno \n// console.log(arguments[1]);\n// arguments e push/pop kicchu nai arrayr moto;\n//arguments holo array like object;\nlet result = 0;\n for(const num of arguments){\n // console.log(num);\n result = result + num; \n }\n // arguments.push(45); \n //kaj korbena oporer line;\n // const result = num1 + num2;\n return result; \n //when your function does not return any data/value then output shows this point as undefined;\n}", "function suma(n1, n2){\n return n1 + n2\n}", "function addTwoAndAlert(num1,num2){\n let answer = num1 + num2\n alert(answer)\n}", "function sumEvenArguments(){\n\treturn [].slice.call(arguments).filter(i=>{\n\t\treturn (!(i%2));\n\t}).reduce((acc,next)=>{\n\t\treturn acc+next;\n\t});\n}", "function fourNums(n1, n2, n3, n4){\n console.log (n1 + n2 - n3 - n4)\n}", "function someName(numberOne, otherNumber){\n // return the sum of numberOne, 10, and otherNumber\n return numberOne + 10 + otherNumber;\n}", "function simpleSum(num1, num2) {\n var sum = num1 + num2;\n return sum;\n}", "function skaiciavimai(x,y,z) {\n console.log(x+2, y+4, z*2);\n}", "function piSum3(a, b) {\n return sum(\n x => 1.0 / (x * (x + 2)), //piTerm\n a,\n x => x + 4, //piNext\n b\n );\n}", "function displayTotal(stepTotal) {\n console.log(`${stepTotal} Steps`);\n}", "function spausdinti(a, b, c) {\n console.log(a, b, c);\n }", "function add(numA, numB) {\n return numA + numB;\n}", "function mySubtractFunction(number1, number2) {\n console.log(number1 - number2);\n}", "function add2(n) {\n const two = 2\n return n + two\n\n // Feel free to move things around!\n}", "function sumEvenArgs(...args){\n return args.filter(val => val % 2 === 0).reduce((acc, next) => acc + next, 0);\n}", "function sumArgs() {\r\n return [].reduce.call(arguments, function(a, b) {\r\n return a + b;\r\n });\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Abstracted reducer for the shortlist
function reduceShortlist(acc, crt) { if (crt.id.pubchem.length > 1) { acc.tmi.push(crt); return acc; }; acc.req.push(crt.id.pubchem[0]); return acc; }
[ "function reducer2(a, e) {\n var summ = 0;\n if (typeof a == \"string\") { // this handles the initial case where the first element is used\n summ = a.length; // as the starting value.\n }\n else {\n summ = a;\n }\n return summ + countLetters(e);\n}", "function buildReducer(reducer, store, useTag) {\n /**\n * Expects an object or a function as the reducer argument. If an\n * object then it should be tagged as $$combine, $$extend, etc. This\n * is checked below.\n **/\n if (!(0, _lodash.isPlainObject)(reducer) && !(0, _lodash.isFunction)(reducer)) throw new Error('reslice.buildReducer: expected object or function, got: ' + (typeof reducer === 'undefined' ? 'undefined' : _typeof(reducer)));\n /**\n * Combining reducers. Recursively build nested reducers and use the\n * redux combineReducers fuction to combine them in the normal way.\n * The result is used to create a new tree object for the combined\n * function. This is then processed below.\n **/\n if (reducer.$$combine) {\n /**\n * If a combined reducer is a simple function then wrap the reducer\n * with a filter function that checks on the action tag. If it\n * is not, then it is not wrapped, so that actions continue to\n * propogate down the state tree.\n **/\n var filterReducer = function filterReducer(reducer) {\n var _reducer = buildReducer(reducer, store, myTag);\n if ((0, _lodash.isFunction)(reducer)) return function (state, action) {\n for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {\n args[_key2 - 2] = arguments[_key2];\n }\n\n if (!action.$$tag || action.$$tag === state.$$tag) return _reducer.apply(undefined, [state, action].concat(args));\n return state;\n };\n return _reducer;\n };\n\n var myTag = $$tag++;\n reducer = {\n $$reducer: (0, _redux.combineReducers)((0, _lodash.mapValues)(reducer.$$reducers, function (r) {\n return filterReducer(r);\n })),\n $$selectors: reducer.$$selectors,\n $$actions: reducer.$$actions,\n $$tag: myTag\n };\n }\n /**\n * Extending a reducer. Recursively build the reducer that is being\n * extended, then generate a new tree object where the reducer function\n * invokes the extension or the underlying reducer. This is then processed\n * below.\n **/\n else if (reducer.$$extend) {\n var _reducer = buildReducer(reducer.$$reducer, store);\n var _extension = reducer.$$extension;\n reducer = {\n $$reducer: function $$reducer(state, action) {\n for (var _len3 = arguments.length, args = Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {\n args[_key3 - 2] = arguments[_key3];\n }\n\n /**\n * Redux initialise actions do not go through the\n * extending function.\n **/\n if (action.type.startsWith('@@')) return _reducer.apply(undefined, [state, action].concat(args));\n /**\n * If the action has the global tag or the matching\n * tag, then run the action through the extending\n * function. If this yields a result then make sure\n * the prototype is set and return that result; also\n * propogate the new state into the reducer so that\n * getSlice() behaves correctly.\n **/\n if (!action.$$tag || action.$$tag === state.$$tag) {\n var newState = _extension.apply(undefined, [state, action].concat(args));\n if (newState) {\n setPrototypeOf(newState, Object.getPrototypeOf(state));\n _reducer.setLastState(newState);\n return newState;\n }\n }\n /**\n * Otherwise, process through the underlying reducer.\n **/\n return _reducer.apply(undefined, [state, action].concat(args));\n },\n $$selectors: reducer.$$reducer.$$selectors,\n $$actions: reducer.$$reducer.$$actions,\n $$tag: _reducer.$$tag\n };\n }\n /**\n * Binding to a reducer function. This is left as-is to be processed\n * below.\n **/\n else if (reducer.$$bind) {\n var _reducer2 = reducer.$$reducer;\n reducer = {\n $$reducer: function $$reducer(state, action) {\n for (var _len4 = arguments.length, args = Array(_len4 > 2 ? _len4 - 2 : 0), _key4 = 2; _key4 < _len4; _key4++) {\n args[_key4 - 2] = arguments[_key4];\n }\n\n if (!action.$$tag || action.$$tag === state.$$tag) return _reducer2.apply(undefined, [state, action].concat(args));\n return state;\n },\n $$selectors: reducer.$$selectors,\n $$actions: reducer.$$actions,\n $$tag: $$tag++\n };\n }\n /**\n * Binding to a mapped reducer. The trick here is to create a factory\n * that creates per-key instances of the underlying reducer, and then\n * wrap that reducer with a function that invokes said reducer with\n * the factory as the third argument.\n **/\n else if (reducer.$$mapped) {\n var reducerForKey = function reducerForKey(key, initialiser) {\n var keyReducer = mapped[key];\n if (!keyReducer) mapped[key] = keyReducer = buildReducer(child, store);\n if (initialiser) {\n /**\n * Check for initialiser case in which case create a\n * new slice and optionally initialise it.\n **/\n var slice = keyReducer(undefined, { type: '@@redux/INIT' });\n var init = initialiser(slice);\n return init ? keyReducer(slice, init) : slice;\n }\n return keyReducer;\n };\n\n var wrapper = function wrapper(state, action) {\n var res = inner(state, action, reducerForKey);\n return shallowEqual(res, state) ? state : res;\n };\n\n var mapped = {};\n var inner = reducer.$$reducer;\n var child = reducer.$$child;\n\n reducer = {\n $$reducer: wrapper,\n $$selectors: reducer.$$selectors,\n $$actions: reducer.$$actions,\n $$tag: $$tag++\n };\n }\n /**\n * If the reducer is simply a function then treat it as bound to empty\n * collections of selectors and reducers.\n **/\n else if ((0, _lodash.isFunction)(reducer)) {\n reducer = {\n $$reducer: reducer,\n $$selectors: {},\n $$actions: {},\n $$tag: useTag || $$tag++\n };\n } else\n /**\n * Any other case is an error.\n **/\n throw new Error(\"reslice.buildReducer: unexpected tree object\");\n\n /**\n * Here lies the point whence ReSlice has to have a logically\n * distinct copy of a reducer function for each position in the\n * state tree at which the reducer is used (which may be more\n * than once).\n *\n * We need to be able to keep track of the last state returned\n * by this instance of a reducer in the tree. To this end, use\n * a generator function that returns a closure on a variable\n * used to save this state.\n **/\n function wrapReducer() {\n var lastState = null;\n var prototype = {\n getRoot: function getRoot() {\n return store.getState();\n },\n globalAction: globalAction,\n $$tag: reducer.$$tag\n };\n /**\n * Generate a prototype that contains the selectors and\n * actions (assumes distinct names). Selector functions are\n * wrapped so the slice becomes the first argument to the\n * selector. Action creators are wrapped so that \"this\" is\n * the slice, and if the action returns a thunk, then the\n * thunk is wrapped so that it will be called with a\n * \"getSlice\" function that returns the last state (and\n * such that \"this\" is explicitely null).\n **/\n (0, _lodash.each)(reducer.$$selectors, function (selector, name) {\n if ((0, _lodash.isFunction)(selector)) {\n /**\n * If the selector has a $$factory property then call\n * that to create the selector. This allows selector\n * memoization on a per-slice basis, rather than\n * globally. Also, since we have a .getRoot() \n * methods on slices, which may return different results\n * even if the particular slice changes, we need to\n * default the outer level of memoization in reslice.\n **/\n if (selector.$$factory) selector = selector.$$factory();\n prototype[name] = function () {\n for (var _len5 = arguments.length, args = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {\n args[_key5] = arguments[_key5];\n }\n\n args.push(seseq++);\n return selector.apply(undefined, [this].concat(args));\n };\n }\n });\n (0, _lodash.each)(reducer.$$actions, function (creator, name) {\n if ((0, _lodash.isFunction)(creator)) prototype[name] = function () {\n for (var _len6 = arguments.length, args = Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {\n args[_key6] = arguments[_key6];\n }\n\n var action = creator.apply(this, args);\n if ((0, _lodash.isFunction)(action)) return function (dispatch, getState) {\n return action.call(null, dispatch, function () {\n return lastState;\n });\n };\n if (action.$$tag === undefined) return Object.assign({}, action, { $$tag: prototype.$$tag });\n return action;\n };\n });\n prototype.action = function (action) {\n if (action.$$tag !== undefined) throw new Error(\"reslice.action: action already has a tag: \" + action.$$tag);\n return Object.assign({}, action, { $$tag: prototype.$$tag });\n };\n /**\n * This is the actual reducer function that will be returned. Before\n * doing so, add a property which is a function that can be called\n * from outside to change the lastState; this is needed by the code\n * in extendReducer.\n **/\n var $$reducer = function $$reducer(state, action) {\n if (action.$$tag === undefined) if (!action.type.startsWith('@@')) throw new Error(\"reslice.reduce: $$tag is undefined: \" + JSON.stringify(action));\n var newState = reducer.$$reducer(state, action);\n /**\n * If the new state does not have a tag then it lacks the prototype,\n * so extend the prototype chain of the new object with the prototypes\n * derived above from the actions and selectors.\n **/\n if (newState.$$tag === undefined) {\n var newproto = Object.assign(Object.create(Object.getPrototypeOf(newState)), prototype);\n setPrototypeOf(newState, newproto);\n lastState = newState;\n }\n return newState;\n };\n prototype.reducer = function (action) {\n return $$reducer(this, action);\n };\n $$reducer.setLastState = function (state) {\n lastState = state;\n };\n return $$reducer;\n }\n wrapReducer.$$tag = reducer.$$tag;\n return wrapReducer();\n}", "compress(upto) {\n let remap = new BranchRemapping\n let items = [], events = 0\n for (let i = this.items.length - 1; i >= 0; i--) {\n let item = this.items[i]\n if (i >= upto) {\n items.push(item)\n } else if (item.step) {\n let step = item.step.map(remap.remap), map = step && step.posMap()\n remap.movePastStep(item, map)\n if (step) {\n let selection = item.selection && item.selection.type.mapToken(item.selection, remap.remap)\n items.push(new StepItem(map.invert(), item.id, step, selection))\n if (selection) events++\n }\n } else if (item.map) {\n remap.add(item)\n } else {\n items.push(item)\n }\n }\n this.items = items.reverse()\n this.events = events\n }", "function singlePeerExpandedReducer(state, action) {\n const { expandedItems = [], focalIndex } = state\n\n function isaParent(item) {\n return item.contents === undefined\n }\n\n function parentOf(itemIndex, allItems) {\n if (itemIndex <= 0) return undefined\n\n const itemDepth = allItems[itemIndex].depth\n let pIndex = itemIndex - 1\n while (pIndex >= 0) {\n const pDepth = allItems[pIndex].depth\n if (isaParent(allItems[pIndex]) && pDepth === itemDepth - 1) {\n return pIndex\n }\n pIndex = pIndex - 1\n }\n return undefined\n }\n\n function removeExpandedPeersOf(itemIndex, expandedItems, allItems) {\n if (isaParent(allItems[itemIndex])) return expandedItems\n\n const depth = allItems[itemIndex].depth\n const parent = parentOf(itemIndex, allItems)\n\n return expandedItems.filter((i) => {\n const iDepth = allItems[i].depth\n // things at different levels are not peers by definition, so keep\n if (iDepth !== depth) return true\n\n // if item is a parent, then keep\n if (isaParent(allItems[i])) return true\n\n // if item has same parent, then it is a peer by definition, so remove\n const iParent = parentOf(i, allItems)\n if (iParent === parent) return false\n\n return true\n })\n }\n\n if (action.type === expandableActionTypes.toggle_index) {\n let nextExpandedItems = []\n let nextFocalIndex = focalIndex\n const closeIt = expandedItems.includes(action.index)\n if (closeIt) {\n if (!isaParent(action.allItems[action.index])) {\n // leaf node, so update focal index\n nextFocalIndex = focalIndex === action.index ? undefined : focalIndex\n }\n if (expandedItems.length > 1) {\n nextExpandedItems = expandedItems.filter((i) => i !== action.index)\n }\n } else {\n // openIt\n nextFocalIndex = isaParent(action.allItems[action.index])\n ? focalIndex\n : action.index\n nextExpandedItems = [\n ...removeExpandedPeersOf(action.index, expandedItems, action.allItems),\n action.index\n ]\n }\n return { expandedItems: nextExpandedItems, focalIndex: nextFocalIndex }\n }\n}", "function shortener(used, field, idx) {\n\n idx = idx || 0;\n if (idx >= field.length) {\n if (field === shortener.alpha) {\n return null;\n }\n return shortener(used, shortener.alpha, 0);\n }\n\n\n if (used.indexOf(field[idx]) === -1) {\n return field[idx]\n }\n\n if (used.indexOf(field[idx].toUpperCase()) === -1) {\n return field[idx]\n }\n\n return shortener(used, field, idx + 1);\n}", "function mapReduce(f, a, seed) {\n\t\n\tfor (var i=0;i<a.length;i++){\n\t\tif (typeof a[i] != \"string\"){\n\t\t\ta[i] = a[i].toString()\n\t\t}\n\t\ta[i]=f(a[i]);\n\n\t}\n\tfor (var i=1;i<a.length;i++){\n\t\tif (typeof seed != \"undefined\"){\n\t\t\tfor (i=0;i<a.length;i++){\n\t\t\t\tseed = seed + f(a[i]);\n\t\t\t}\n\t\treturn seed;\n\t\t}\n\t\telse {\n\t\t\tif (typeof a[i] == \"string\"){\n\t\t\t\ta[0] = a[0]+a[i];\n\t\t\t}\n\t\t\telse {\n\t\t\t\ta[i] = a[i].toString();\n\t\t\t\ta[0] = a[0]+a[i];\n\t\t\t\t\n\t\t\t}\n\t\t}\n\n\t}\n\treturn a[0];\n\n}", "extraReducers(builder) {\n builder.addCase(fetchNotifications.fulfilled, (state, action) => {\n // push the return array of action.payload into the current state array first\n // state.push(...action.payload);\n // state.forEach(notification => {\n // // all read notifications are no longer new\n // notification.isNew = !notification.read\n // })\n\n // notifications entity is no longer an array....KNOW YOUR ENTITY STRUCTURE BEFORE APPLY REDUCER FUNCS!\n // change the isNew in the new notification first\n Object.values(state.entities).forEach(notification => {\n notification.isNew = !notification.read;\n })\n\n // upsert: accept an array of entities or an object, shallowly insert it\n // upsertting the new notifications into the entity\n notificationsAdaptor.upsertMany(state, action.payload)\n\n // sort every date in the state \n // they are pre-sorted any time\n // state.sort((a, b) => b.date.localeCompare(a.date))\n })\n }", "function keywordReducer(keywords, result) {\n Object.keys(result.keywords_result || {}).forEach(k => {\n keywords[k] = keywords[k] || [];\n keywords[k].push(...result.keywords_result[k]);\n });\n return keywords;\n}", "static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('shortlink_shortlink', 'list', kparams);\n\t}", "function mapReduce (mapper, reducer, list) {\n return new Promise((resolve, reject) => {\n Promise.all(list.map(mapper)).then(results => {\n reducer(results).then(resolve)\n })\n })\n}", "function reduce(wordAndOccurence){\n\tvar word; // used to store the word\n\tvar occurence = 0;// used to store the occurence of the word\n\t\n\tfor (var key in wordAndOccurence){ // we loop on \"wordAndOccurence\"\n\t\tword = key; // we know that it's only one word so we get it for later\n\t\t/*var numberOccurence = wordAndOccurence[key]; // we store the array of the occurences to be used in the following loop\n\t\tfor (var i=0, l=numberOccurence.length; i<l; i++){\n\t\t\toccurence += numberOccurence[i]; //we add every occurence into the final result\n\t\t}*/\n\t\t\n\t\t// after edit, the previous commented part was my vision of the 'normal' function, but now i didn't manage to get an array of occurences\n\t\t// the way i did it in shuffleAndSort, so basically i only have {word: occurence} and not {word: [occurence]}\n\t\toccurence += wordAndOccurence[key]; \n\t}\n\t\n\toutputWriter(word, occurence); //call the output writer to display the results\n}", "function reducer (normalized, old = Map(), n = 0) {\n const reduced = normalized.reduce(\n (acc, instance) => acc.mergeWith((prev, next) => prev + next, instance),\n old\n );\n const newCount = n + normalized.size;\n\n // Filter out zero-valued props\n const filtered = reduced.filter(val => val > 0);\n\n return List.of(filtered, newCount);\n}", "function mapDispatchToProps(dispatch){\n return {\n getRecipesAction : (searchTerm) => {\n dispatch(getRecipes(searchTerm)) \n }\n }\n }", "getFilters(key, appliedFilters) {\n let filters = [];\n //let appliedFilters = Object.assign({}, this.state.appliedFilters);\n return Object.keys(appliedFilters).map(k => { \n let next = appliedFilters[k];\n if (next && next.willFilter && next.willFilter.length > 0 ) {\n let will = next.willFilter.indexOf(key);\n if (will >= 0) return appliedFilters[k];\n }\n });\n }", "static flatten_do_list_array(arr, result=[]){\n for(let i = 0; i < arr.length; i++){\n let elt = arr[i]\n if (Instruction.is_no_op_instruction(elt)) {} //get rid of it, including empty nested arrays\n else if (Instruction.is_oplet_array(elt)) { result.push(elt) }\n else if (Instruction.is_data_array(elt)) { result.push(elt) } //do not flatten!\n else if (Array.isArray(elt)) { Job.flatten_do_list_array(elt, result) }\n else if (elt instanceof Instruction) { result.push(elt) }\n else if (typeof(elt) === \"string\") { result.push(elt) }\n else if (typeof(elt) === \"function\") { result.push(elt) }\n else if (is_iterator(elt)) { result.push(elt) }\n else if (Instruction.is_start_object(elt)) { result.push(elt) }\n else { throw(TypeError(\"Invalid do_list item at index: \" + i + \"<br/>of: \" + elt)) }\n }\n return result\n }", "caseFuncsToReducer({$initState:initState,...caseMap}){\n return (state = initState, action) => {\n const reducer = caseMap[action.type];\n \n return reducer ? reducer(state, action) : state;\n };\n }", "applyNodeFilters(name: string, node: NodeInterface): NodeInterface {\n return this.filters.reduce((nextNode, filter) => {\n // Allow null to be returned\n if (nextNode && typeof filter.node === 'function') {\n return filter.node(name, nextNode);\n }\n\n return nextNode;\n }, node);\n }", "function shortLinkFormatToData(shortLinkData) {\n var data = {\n \"units\": []\n };\n\n let unitIdString = shortLinkData[0][0].toString();\n\n let baseUnitId = unitIdString.substr(0, unitIdString.length -1);\n let rarity = unitIdString.substr(unitIdString.length -1);\n let unitFound = null;\n for (let i = 1; i <= 5; i++) {\n if (units[baseUnitId + i]) {\n unitFound = units[baseUnitId + i];\n }\n }\n if (!unitFound) {\n Modal.showMessage(\"Wrong link data\", \"Unknown unit id\");\n return;\n }\n\n var unit = {};\n unit.id = unitFound.id;\n if (rarity != 6 && unitFound.max_rarity != rarity) {\n Modal.showMessage(\"Unsupported unit rarity\", \"FFBE Equip only support max rarity units. Max unit rarity will be displayed\");\n unit.rarity = unitFound.max_rarity;\n } else {\n unit.rarity = rarity;\n }\n if (unit.rarity == 7) {\n unit.level = shortLinkData[0][1]\n }\n\n unit.goal = \"Maximize P_DAMAGE\";\n unit.pots = {\n \"hp\":shortLinkData[0][2][0],\n \"mp\":shortLinkData[0][2][1],\n \"atk\":shortLinkData[0][2][2],\n \"def\":shortLinkData[0][2][3],\n \"mag\":shortLinkData[0][2][4],\n \"spr\":shortLinkData[0][2][5]\n }\n\n unit.esperId = esperNameById[shortLinkData[1][0]];\n unit.esperPinned = false;\n unit.items = shortLinkData[2].map((id, index) => {\n if (id) {\n return {\"id\":id.toString(), \"slot\": index, \"pinned\": false}\n }\n }).filter(out => out);\n if (shortLinkData[3] && shortLinkData[3].length > 0) {\n unit.itemEnchantments = {};\n if (shortLinkData[3][0] && shortLinkData[3][0].size > 0) {\n unit.itemEnchantments[0] = shortLinkData[3][0].map(id => itemEnhancementBySkillId[id]);\n }\n if (shortLinkData[3][1] && shortLinkData[3][1].size > 0) {\n unit.itemEnchantments[1] = shortLinkData[3][1].map(id => itemEnhancementBySkillId[id]);\n }\n }\n\n data.units.push(unit);\n\n data.itemSelector = {\n \"mainSelector\": \"all\",\n \"additionalFilters\": [\"excludeNotReleasedYet\"]\n }\n\n data.version = 2;\n return data;\n}", "visitConcatenation(ctx) {\n\t return this.visitChildren(ctx);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
helper function to that given a letter and a frequency:f will make f copies of the current set and return a new and for each copy, will append the letter f times should return 'a', 'aa', 'aaa'
function addLettersToSetHelper(letter, frequency, currSet) { var letToAppend = ''; var retSet = new Set(); for (var j = 0; j < frequency; j++) { var tempSet = currSet.clone(); letToAppend += letter; var setToAdd = addLettersToSet(letToAppend, tempSet); retSet.addEach(setToAdd); }; return retSet; }
[ "function display_letter_frequency(a,dom) {\n\t var table = \"<table>\";\n \tfor ( var x in a) {\n \t\ttable += \"<tr><td>\" + x + \"</td><td>\" + a[x] + \"</td></tr>\";\n \t}\n \ttable += \"</table>\";\n \tdom.innerHTML = table;\n\t\n}", "function repeatChar(string,char){\n string= string.toLowerCase()\n string= string.split(\"\")\n var result = string.reduce(function(num,str){\n\nif ( str===char){\n ++num\n}return num\n\n } ,0)\n return result\n}", "function construct_letter_array() {\n\tvar letter_array = [];\n\tfilter_letters.split(\"\").forEach( function( item ) {\n\t\tif ( letter_array[ item ] ) {\n\t\t\tletter_array[ item ] = letter_array[ item ] + 1;\n\t\t} else {\n\t\t\tletter_array[ item ] = 1;\n\t\t}\t\n\t}) ;\t\n\treturn letter_array;\n}", "function makeAnagram(a, b) {\n let count = 0;\n\n //track all the letters that are the longer string and then compare them to the letters from the short string.\n let freq = {};\n\n const longStr = a.length > b.length ? a : b;\n const shortStr = longStr === a ? b : a;\n\n // Log all chars from the long string into an object\n for (let char of longStr) {\n freq[char] >= 0 ? (freq[char] += 1) : (freq[char] = 0);\n }\n\n // see if the character is found in longString --> if so. add to count and subtract from obj\n for (let char of shortStr) {\n if (freq[char] >= 0) {\n count++;\n freq[char] -= 1;\n }\n }\n // The count variable is the common letters between each string\n // subtract count from the length of each string and add result together\n const deletions = longStr.length - count + shortStr.length - count;\n console.log(deletions);\n return deletions;\n}", "function buildFreqs(digit) {\n let digitStr = digit.toString();\n let frequencies = new Map();\n for (let oneDigit of digitStr) {\n let valCount = frequencies.get(oneDigit) || 0;\n frequencies.set(oneDigit, valCount + 1);\n }\n return frequencies;\n}", "function longest_substring_with_k_distinct(str, k) {\n if( k === 0 || str.length === 0) return 0;\n // TODO: Write code here\n let windowStart = 0,\n windowEnd = 0,\n maxLen = 0,\n frequency = {};\n\n \n for(windowEnd; windowEnd < str.length; windowEnd++){\n if(!(str[windowEnd] in frequency)){\n frequency[str[windowEnd]] = 0;\n }\n frequency[str[windowEnd]] += 1;\n // console.log(frequency[]);\n }\n console.log(frequency['a']);\n maxLen = Math.max(maxLen, windowEnd - windowStart);\n\n return maxLen;\n}", "function anagramHelper(str, current, anagrams) {\n if (!str.length && current.length) {\n anagrams.push(current);\n } else {\n for (let i = 0; i < str.length; i++) {\n // base letter, slice and concat\n const newStr = str.slice(0, i).concat(str.slice(i+1));\n const newAna = current.concat(str[i]);\n anagramHelper(newStr, newAna, anagrams);\n }\n }\n}", "function addLettersToSet(letters, set) {\n\tvar setToRet = new Set();\n\tset.forEach(function(key) {\n\t\tsetToRet.add(key + letters);\n\t});\n\treturn setToRet;\n}", "function repeatChar(str,char){\n\tvar count=0;\n\tvar str1= str.split(\"\");\n var rep = str1.reduce((x,y)=> {\n if (y == char){\n return\tcount = count + 1\n }});\n return count;\n }", "function reducer2(a, e) {\n var summ = 0;\n if (typeof a == \"string\") { // this handles the initial case where the first element is used\n summ = a.length; // as the starting value.\n }\n else {\n summ = a;\n }\n return summ + countLetters(e);\n}", "function anagrams(str) {\n if (str.length === 1) {\n return [str];\n } else {\n const allAnagrams = [];\n for (let i = 0; i < str.length; i += 1) {\n const letter = str[i];\n const short = str.substr(0, i) + str.substr(i + 1, str.length - 1);\n const shortAnagrams = anagrams(short);\n for (let j = 0; j < shortAnagrams.length; j += 1) {\n allAnagrams.push(letter + shortAnagrams[j]);\n }\n }\n return [...new Set(allAnagrams)];\n }\n}", "function fillDisplayWord (letter) {\n\n}", "function main(wordArray){\n let map = new Map();\n wordList = [];\n\n for(let string of wordArray){\n let counter = 1;\n\n if(map.has(string)){\n let wordCount = map.get(string);\n\n map.set(string, wordCount + 1);\n }else{\n map.set(string, counter);\n }\n }\n wordList = Array.from(map).sort((a, b) => b[1] - a[1]);\n wordList.forEach((word)=> {\n console.log(`${word[0]} -> ${word[1]} times`);\n });\n}", "function start(){\n\tvar div = \"\";\n\tfor ( i = 0; i < 25; i++) {\n\t\tvar element = \"let\" + i;\n\t\tdiv = div + '<div class = \"letter\" onclick = \"check('+i+')\" id=\"'+element+'\">'+letters[i]+'</div>';\n\t\tif ((i + 1) % 7 == 0) div = div + '<div style = \"clear:both;\"></div>';\n\t}\n\tdocument.getElementById(\"alphabet\").innerHTML = div;\n\tgenerateWord();\n}", "function repeatedChars(arrayOfStrings) {\n if (arrayOfStrings === undefined || arrayOfStrings === []) return [];\n\n let lowerCaseStrings = arrayOfStrings.map(string => string.toLowerCase());\n\n let uniqueChars = getUniqueChars(lowerCaseStrings);\n\n let appearances = [];\n\n uniqueChars.forEach(char => {\n let charApperance = minimuNumberOfApperances(char, lowerCaseStrings);\n appearances.push(...(new Array(charApperance).fill(char)));\n });\n\n return appearances.sort();\n}", "function createString(number,letter){\n let result = \"\"\n for (let i=0; i<number; i++){\n result +=letter\n }\n return result\n}", "function startWithA(characters) {\n let nameA = [];\n let count = 0;\n characters.forEach(function (array) {\n if (array.name.startsWith(\"A\")) {\n nameA.push(array.name);\n count += 1;\n }\n });\n // console.log(nameA);\n return count;\n}", "function mapping(letters) {\n\tlet y = letters.reduce((acc, elem) => {\n acc[elem] = elem.toUpperCase();\n return acc;\n}, {})\n\treturn y;\n}", "function stackLetters (alphabet) {\n for (var i=0; i < alphabet.length; i++) {\n \tstack += alphabet[i]\n \tconsole.log(stack)\n };\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine whether the given properties match those of a `AwsCloudMapServiceDiscoveryProperty`
function CfnVirtualNode_AwsCloudMapServiceDiscoveryPropertyValidator(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('attributes', cdk.listValidator(CfnVirtualNode_AwsCloudMapInstanceAttributePropertyValidator))(properties.attributes)); errors.collect(cdk.propertyValidator('ipPreference', cdk.validateString)(properties.ipPreference)); errors.collect(cdk.propertyValidator('namespaceName', cdk.requiredValidator)(properties.namespaceName)); errors.collect(cdk.propertyValidator('namespaceName', cdk.validateString)(properties.namespaceName)); errors.collect(cdk.propertyValidator('serviceName', cdk.requiredValidator)(properties.serviceName)); errors.collect(cdk.propertyValidator('serviceName', cdk.validateString)(properties.serviceName)); return errors.wrap('supplied properties not correct for "AwsCloudMapServiceDiscoveryProperty"'); }
[ "function CfnVirtualNode_DnsServiceDiscoveryPropertyValidator(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('hostname', cdk.requiredValidator)(properties.hostname));\n errors.collect(cdk.propertyValidator('hostname', cdk.validateString)(properties.hostname));\n errors.collect(cdk.propertyValidator('ipPreference', cdk.validateString)(properties.ipPreference));\n errors.collect(cdk.propertyValidator('responseType', cdk.validateString)(properties.responseType));\n return errors.wrap('supplied properties not correct for \"DnsServiceDiscoveryProperty\"');\n}", "function CfnMesh_MeshServiceDiscoveryPropertyValidator(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('ipPreference', cdk.validateString)(properties.ipPreference));\n return errors.wrap('supplied properties not correct for \"MeshServiceDiscoveryProperty\"');\n}", "function CfnGatewayRoute_GatewayRouteMetadataMatchPropertyValidator(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('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('prefix', cdk.validateString)(properties.prefix));\n errors.collect(cdk.propertyValidator('range', CfnGatewayRoute_GatewayRouteRangeMatchPropertyValidator)(properties.range));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n errors.collect(cdk.propertyValidator('suffix', cdk.validateString)(properties.suffix));\n return errors.wrap('supplied properties not correct for \"GatewayRouteMetadataMatchProperty\"');\n}", "function CfnVirtualNode_AwsCloudMapInstanceAttributePropertyValidator(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('key', cdk.requiredValidator)(properties.key));\n errors.collect(cdk.propertyValidator('key', cdk.validateString)(properties.key));\n errors.collect(cdk.propertyValidator('value', cdk.requiredValidator)(properties.value));\n errors.collect(cdk.propertyValidator('value', cdk.validateString)(properties.value));\n return errors.wrap('supplied properties not correct for \"AwsCloudMapInstanceAttributeProperty\"');\n}", "function CfnRoute_GrpcRouteMetadataMatchMethodPropertyValidator(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('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('prefix', cdk.validateString)(properties.prefix));\n errors.collect(cdk.propertyValidator('range', CfnRoute_MatchRangePropertyValidator)(properties.range));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n errors.collect(cdk.propertyValidator('suffix', cdk.validateString)(properties.suffix));\n return errors.wrap('supplied properties not correct for \"GrpcRouteMetadataMatchMethodProperty\"');\n}", "function CfnRoute_GrpcRouteMatchPropertyValidator(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('metadata', cdk.listValidator(CfnRoute_GrpcRouteMetadataPropertyValidator))(properties.metadata));\n errors.collect(cdk.propertyValidator('methodName', cdk.validateString)(properties.methodName));\n errors.collect(cdk.propertyValidator('port', cdk.validateNumber)(properties.port));\n errors.collect(cdk.propertyValidator('serviceName', cdk.validateString)(properties.serviceName));\n return errors.wrap('supplied properties not correct for \"GrpcRouteMatchProperty\"');\n}", "function CfnGatewayRoute_GrpcGatewayRouteMatchPropertyValidator(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('hostname', CfnGatewayRoute_GatewayRouteHostnameMatchPropertyValidator)(properties.hostname));\n errors.collect(cdk.propertyValidator('metadata', cdk.listValidator(CfnGatewayRoute_GrpcGatewayRouteMetadataPropertyValidator))(properties.metadata));\n errors.collect(cdk.propertyValidator('port', cdk.validateNumber)(properties.port));\n errors.collect(cdk.propertyValidator('serviceName', cdk.validateString)(properties.serviceName));\n return errors.wrap('supplied properties not correct for \"GrpcGatewayRouteMatchProperty\"');\n}", "function CfnDataSource_OpenSearchServiceConfigPropertyValidator(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('awsRegion', cdk.requiredValidator)(properties.awsRegion));\n errors.collect(cdk.propertyValidator('awsRegion', cdk.validateString)(properties.awsRegion));\n errors.collect(cdk.propertyValidator('endpoint', cdk.requiredValidator)(properties.endpoint));\n errors.collect(cdk.propertyValidator('endpoint', cdk.validateString)(properties.endpoint));\n return errors.wrap('supplied properties not correct for \"OpenSearchServiceConfigProperty\"');\n}", "function CfnGatewayRoute_GatewayRouteHostnameMatchPropertyValidator(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('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('suffix', cdk.validateString)(properties.suffix));\n return errors.wrap('supplied properties not correct for \"GatewayRouteHostnameMatchProperty\"');\n}", "function CfnVirtualService_VirtualServiceSpecPropertyValidator(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('provider', CfnVirtualService_VirtualServiceProviderPropertyValidator)(properties.provider));\n return errors.wrap('supplied properties not correct for \"VirtualServiceSpecProperty\"');\n}", "function CfnRoute_HttpQueryParameterMatchPropertyValidator(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('exact', cdk.validateString)(properties.exact));\n return errors.wrap('supplied properties not correct for \"HttpQueryParameterMatchProperty\"');\n}", "function cfnRouteHttpQueryParameterMatchPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_HttpQueryParameterMatchPropertyValidator(properties).assertSuccess();\n return {\n Exact: cdk.stringToCloudFormation(properties.exact),\n };\n}", "function CfnGatewayRoute_HttpQueryParameterMatchPropertyValidator(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('exact', cdk.validateString)(properties.exact));\n return errors.wrap('supplied properties not correct for \"HttpQueryParameterMatchProperty\"');\n}", "function CfnAccessPoint_AliasPropertyValidator(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('status', cdk.validateString)(properties.status));\n errors.collect(cdk.propertyValidator('value', cdk.validateString)(properties.value));\n return errors.wrap('supplied properties not correct for \"AliasProperty\"');\n}", "function cfnGatewayRouteHttpQueryParameterMatchPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_HttpQueryParameterMatchPropertyValidator(properties).assertSuccess();\n return {\n Exact: cdk.stringToCloudFormation(properties.exact),\n };\n}", "function CfnMultiRegionAccessPointPolicyPropsValidator(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('mrapName', cdk.requiredValidator)(properties.mrapName));\n errors.collect(cdk.propertyValidator('mrapName', cdk.validateString)(properties.mrapName));\n errors.collect(cdk.propertyValidator('policy', cdk.requiredValidator)(properties.policy));\n errors.collect(cdk.propertyValidator('policy', cdk.validateObject)(properties.policy));\n return errors.wrap('supplied properties not correct for \"CfnMultiRegionAccessPointPolicyProps\"');\n}", "function CfnRoute_TcpRouteMatchPropertyValidator(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('port', cdk.validateNumber)(properties.port));\n return errors.wrap('supplied properties not correct for \"TcpRouteMatchProperty\"');\n}", "function cfnGatewayRouteGatewayRouteHostnameMatchPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_GatewayRouteHostnameMatchPropertyValidator(properties).assertSuccess();\n return {\n Exact: cdk.stringToCloudFormation(properties.exact),\n Suffix: cdk.stringToCloudFormation(properties.suffix),\n };\n}", "function CfnRoute_HttpPathMatchPropertyValidator(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('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n return errors.wrap('supplied properties not correct for \"HttpPathMatchProperty\"');\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
remove "&nbsp" form the start of screenDown
function removeNbsp () { if (screenDown.innerHTML == "&nbsp;") screenDown.innerHTML = ""; }
[ "function setNbsp () {\n\t\tif (screenDown.innerHTML == \"\") screenDown.innerHTML = \"&nbsp\";\n\t}", "function DEL () {\n\t\tscreenDown.innerHTML = screenDown.innerHTML.slice(0,-1);\n\t\tsetNbsp();\n\t}", "function blank() {\n putstr(padding_left(seperator, seperator, sndWidth));\n putstr(\"\\n\");\n }", "function removePrevInfo () {\n let d = document.getElementById('distanceWritePrevInfo').textContent;\n if (d === '-200' || d === '-100' || d === '0'){\n document.getElementById('distanceWritePrevInfo').innerHTML='&nbsp;'\n }\n }", "function clearScreen(){ displayVal.textContent = null}", "function clear() {\n\t\t$('.pad').empty();\n\t}", "function clearDisplay(val){\n\t\tprimaryOutput.innerHTML = \"\";\t\n\t\tif (val === \"AC\") {\n\t\t\ttotal = 0;\n\t\t\tsecondaryOutput.innerHTML = \"\";\n\t\t\tsecondaryOutput.style.right = \"0px\";\n\t\t\tlastOperator.length = 0;\n\t\t}\n\t}", "function backspace_function() {\r\n\tvar backspace_beginning_char = textarea_element.selectionStart;\r\n\tif (backspace_beginning_char > 0 && backspace_beginning_char == textarea_element.selectionEnd) {\r\n\t\tbackspace_beginning_char--;\r\n\t}\r\n\ttextarea_element.setRangeText(\"\", backspace_beginning_char, textarea_element.selectionEnd, \"end\");\r\n\ttextarea_element.focus();\r\n\tscroll_to_cursor();\r\n\tupdate_printable_table();\r\n}", "function clearScreen()\n{\n document.body.removeChild( document.getElementById( \"space\" ) );\n document.getElementById( \"messages\" ).removeChild( document.getElementById( \"messages\" ).lastChild );\n}", "function cleanText(screenplay) {\n // First cycle to remove all blanks\n let _s;\n screenplay.forEach((s, index, array) => {\n _s = s.replace(/\\s\\s+|\\r\\n/g, \"\");\n array[index] = trim(_s);\n array.splice(index, s);\n });\n\n // Second cycle to remove all the empty elements from the array\n // It can be optimized but I couldn't quite manage how to do that\n // (Two forEach are a bit overkill)\n screenplay.forEach((s, index, array) => {\n if (s === \"\") {\n console.log(\"Linea Vuota\");\n array.splice(index, 1);\n }\n });\n}", "function del(e) {\n current = display.innerHTML;\n if (calcReset) {\n current = '';\n calcReset = false;\n } else {\n current = current.slice(0, -1);\n }\n display.textContent = current;\n }", "function disableBackspace() {\n _isBackspaceEnabled = false;\n}", "function stripSpaces(value){ return value.strip(); }", "function spaces(n) {\n var string= '';\n for (var i = 0; i < n; i++) {\n string += '&nbsp;';\n };\n return string;\n }", "function DocEdit_removeSpaceFromTableCell(sel)\n{\n var dom = dw.getDocumentDOM();\n\n if (sel[0] == sel[1] && sel[0] > 7)\n {\n if (!docEdits.allSrc)\n {\n docEdits.allSrc = dom.documentElement.outerHTML;\n }\n\n var tagName = String(dom.getSelectedNode().tagName).toUpperCase();\n\n if (docEdits.allSrc.substring(sel[0]-7,sel[1]) == \">&nbsp;\" && tagName == \"TD\")\n {\n sel[0] -= 6;\n }\n }\n\n return sel;\n}", "function clearEntry() {\n changeDisplay('0');\n }", "function cleancard()\n { \n $('#cardtop div,li,h5,img').html('')\n $('#cards1 h5,img,p').html('')\n \n }", "function clearTerminal() {\n deleteAllChilds(consoleArea);\n let div = document.createElement('div');\n div.classList.add('current-line');\n let img = document.createElement('img');\n img.setAttribute('src', './img/logo-blue.png');\n let newTextarea = document.createElement('textarea');\n div.appendChild(img).classList.add('line-marker');\n newTextarea.id = 'console-input';\n newTextarea.setAttribute('autocomplete', \"off\");\n newTextarea.setAttribute('autocorrect', \"off\");\n newTextarea.setAttribute('autocapitalize', \"off\");\n newTextarea.setAttribute('spellcheck', \"false\");\n div.appendChild(newTextarea);\n return div;\n }", "function clearScreen() {\n calculator.displayValue = '0';\n calculator.firstOperand = null;\n calculator.waitForNextOperand = false;\n calculator.operator = null;\n calculator.inBaseTen = true;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This clears all existing inputs in the output layer
clearAllInputsOutputLayer(){ for(var i = 0; i < neuralNet.layers[2].neurons.length; i++){ neuralNet.layers[2].neurons[i].receivedInputs = []; neuralNet.layers[2].neurons[i].receivedWeights = []; } }
[ "reset(){\n this._input = null;\n this._output = null;\n }", "clearAllErrorsInputLayer(){\n for(var i = 0; i < neuralNet.layers[0].neurons.length; i++){\n neuralNet.layers[0].neurons[i].receivedErrors = [];\n neuralNet.layers[0].neurons[i].receivedWeightsError = [];\n }\n }", "function clearInputs() {\n var i;\n controlElem.value = '';\n for (i = 0; i < dilutions.length; i += 1) {\n dilElems[i].value = '';\n }\n updateResults();\n }", "function clear() {\n clearCalculation();\n clearEntry();\n resetVariables();\n operation = null;\n }", "function clear() {\n\t\tgenerations = [];\n\t\tfittest = [];\n\t}", "clearAll() {\n this._stack.length = 0;\n\n // stuff the stack to mimic always needed registers\n for (let i = 0; i < MINIMUM_STACK; i++) {\n this._stack.push(0);\n }\n\n this._lastX = 0;\n this._clearMemory();\n }", "resetNodes() {\n for (let layer = 0; layer < this.nodes.length; layer++) {\n for (let node = 0; node < this.nodes[layer].length; node++) {\n this.nodes[layer][node].input = 0;\n this.nodes[layer][node].weight = 0;\n }\n }\n this.biasNode.weight = 1;\n }", "function clearOutputs(notebook) {\n if (!notebook.model || !notebook.activeCell) {\n return;\n }\n const state = Private.getState(notebook);\n each(notebook.model.cells, (cell, index) => {\n const child = notebook.widgets[index];\n if (notebook.isSelectedOrActive(child) && cell.type === 'code') {\n cell.clearExecution();\n child.outputHidden = false;\n }\n });\n Private.handleState(notebook, state, true);\n }", "clearAllObject() {\r\n this.m_drawToolList.length = 0;\r\n this.clearTechToolMousePos();\r\n }", "dispatchSignalForward(){\n\n this.clearAllInputsOutputLayer();\n\n //console.log('Output layer inputs after clearing by hidden layer');\n // console.log(neuralNet.layers[2].neurons);\n // console.log(neuralNet.layers[2].neurons);\n\n for(var i = 0; i < this.neurons.length; i++){\n this.neurons[i].dispatchSignalForward();\n }\n }", "function resetAll () {\n resetOutput();\n resetRegisters();\n updateRegisterOutput();\n error = false;\n}", "clear() {\n this._targets.clear();\n this._proxies.clear();\n }", "clearAllFilters() {\n this.currentFilters = []\n\n each(this.filters, filter => {\n filter.value = ''\n })\n }", "function clearButton(){\n $('.large').on(\"click\", function(){\n inputArray = [];\n joinedArray = [];\n });\n }", "clear() {\n this.name = '';\n this.adj.clear();\n this.node.clear();\n clear(this.graph);\n }", "function clear() {\n resetStore();\n }", "function reset_form_input_reward_tensor(){\n document.getElementById(\"reward_tensor\").value=\"\"\n}", "function clearAll() {\n\t\t}", "clear()\n {\n this.clearVariables();\n this.clearTerminals();\n this.clearRules();\n this._startVariable = null;\n this._errors.length = 0;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
adds a new item to the items array in the state method is passed to the ShoppingListForm, which will be called with state from the form
addItem(item) { let newItem = { ...item, id: uuidv4() }; //taking the existing item with only name and id coming from the form and adding an id field this.setState(state => ({ items: [...state.items, newItem] //spread operator syntax, it sets items to be all the existing state items plus the new item })); }
[ "addNewItem() {\n\t\tconst newItem = {itemName: \"\", tag: \"None\", description:\"\", price:\"\", pic:\"\"};\n\t\tthis.setState((prevState, props) => ({\n\t\t\titems: prevState.items.concat(newItem)\n\t\t}))\n\t}", "function addItemShoppingList(newItem) {\n STORE.items.push({name: newItem, checked: false});\n}", "add(item) {\n this.items.add(item);\n }", "addNewItem() {\n // we remove whitespace from both sides of the string saved in newItem\n this.newItem = this.newItem.trim();\n if (this.isInputValid(this.newItem)) {\n // if the user input is valid, we add the user input to the todo-list\n this.todos.push(this.newItem);\n } else if (this.todos.includes(this.newItem)) {\n // if the user input already occurs in the todo-list, we notify the user about this fact\n alert('This item already occurs in the list');\n }\n // in any case, we reset the value of the input\n this.newItem = '';\n }", "addItemOnPress() {\n var receipt = this.state.receipt;\n receipt.addNewItem(\n this.state.quantityFieldValue,\n this.state.nameFieldValue,\n this.state.pricePerUnitFieldValue\n )\n\n this.setState({\n receipt: receipt\n })\n\n receipt.save()\n }", "addItem() {\n this.setState({ addItem: 'true' })\n }", "addItem() {\n this.setState({\n itemCount: this.state.itemCount + 1\n });\n }", "submit() {\n const { currentItem, addItem, inputMode, clearCurrentItem, setItemShowInput, editItem } = this.props\n if (inputMode === 'add') {\n addItem(currentItem);\n } else {\n editItem(currentItem)\n }\n clearCurrentItem();\n setItemShowInput(false);\n }", "addItem() {\n let newClothes = new Clothing(itemClothing.value, costClothing.value);\n this.clothes.push(newClothes); \n }", "function addItemToWishList(){\n\n\t\t\t\tconsole.log(wishlist);\n\t\t//increase the quantity of the item in case same item is added//\n\t\t\t\tfor (var i in wishlist){\n\t\t\t\t\tif (wishlist[i].name === name){\n\t\t\t\t\t\tif (wishlist[i].size === size){\n\t\t\t\t\t\t\tif (wishlist[i].flavors === flavors){\n\t\t\t\t\t\t\t\twishlist[i].quantity += quantity;\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tif (wishlist === null){\n\t\t\t\t\twishlist = [];\n\t\t\t\t}\n\t\t\t\t//push new item to wishlist//\n\t\t\t\tvar item = new Item ();\n\t\t\t\tconsole.log(wishlist);\n\t\t\t\tconsole.log(item);\n\t\t\t\twishlist.push(item);\n\t\t\t\tsaveWishList();\n\t\t\t}", "function addItem(item){\n basket.push(item);\n return true;\n}", "addValue() {\n const newItemName = document.querySelector('#item-name').value;\n const newItemPrice = document.querySelector('#item-price').value;\n const newOutStock = document.querySelector('#out-stock').value;\n const newItemType = document.querySelector('#item-type').value;\n const newItemDesc = document.querySelector('#item-desc').value;\n\n this.setState ({ newItemName, newItemPrice, newOutStock , newItemType, newItemDesc })\n }", "updateInput(input){\n this.setState({ newItem: input });\n }", "function addSelectedItemToCart(event) {\n // TODO: suss out the item picked from the select list\n console.log(event.target);\n console.log('QUANTITY VALUE', event.target.quantity.value);\n console.log('ITEM VALUE', event.target.items.value);\n var product = event.target.items.value;\n var quantity = event.target.quantity.value;\n\n // TODO: get the quantity\n // TODO: using those, add one item to the Cart\n cart.addItem(product, quantity);\n}", "function addSelectedItemToCart() {\n // TODO: suss out the item picked from the select list\n var product = document.getElementsById('items').value;\n // TODO: get the quantity\n var quantity = document.getElementById('quantity').value;\n // TODO: using those, add one item to the Cart\n cart.product = product;\n //cart.items.allProducts = product;\n //cart.product = value;\n //var numberOfProducts = cart.quantity++;\n //numberOfProducts = quantity;\n cart.quantity += quantity;\n}", "function createItem() {\n\t\tvar clInput = document.querySelector('#cl-item'),\n\t\t\tchecklistText = clInput.value,\n\t\t\tli = generateListitem(checklistText);\n\n\t\toptions.appendChild(li);\n\n\t\tchecklist.push(checklistText);\n\t\tupdateChecklist();\n\n\t\t//reset checklist input value to empty\n\t\tclInput.value = \"\";\n\t}", "function addItem(item) {\n item.order = this;\n var items = this.orderItems;\n if (items.indexOf(item) == -1) {\n items.push(item);\n }\n }", "onButtonClick(evt){\n evt.preventDefault();\n var form = ReactDOM.findDOMNode(this.refs.inputForm.textInput);\n var item = form.value;\n //create a new array instead of pushing to the old one!\n var updatedArr = this.state.itemArr.concat(item);\n this.setState({itemArr: updatedArr});\n console.log(this.state.itemArr, 'from onButtonClick');\n }", "function add_item_to_field(index, field_ident){\n //alert(\"field_ident: \" + field_ident + \", index: \" + index);\n\n if (data_hash[index]) {\n var id = data_hash[index].id;\n var display_text = data_hash[index].display_text;\n var from_userbox = 1;\n } else {\n var id = index;\n var display_text = index;\n var from_userbox = 0;\n }\n\n // create the new item\n var item = $('<li class=\"ub-item\"></li>').draggable(draggable_setup);\n item.data('index', index).data('in', field_ident);\n\n // call this if you want to remove it from the input box (and put it back in the userbox)\n item.data('removing', function(){\n item.data('moving')();\n if (from_userbox) $('#' + index).slideDown(); // put it back into the userbox\n });\n\n // call this if you're moving it from one input field to another\n item.data('moving', function(){\n remove_from_hidden(field_ident, id); // reset the hidden input\n slideLeft(item); // delete from this list\n });\n\n // remove it on a doubleclick\n item.dblclick( function(){\n item.data('removing')();\n });\n\n // create the close button, which removes the item\n var close = $('<a class=\"ub-close\">&times;</a>').click(function(){\n item.data('removing')();\n });\n\n // add the item (with the close button) to the appropriate input list\n li_inputs[field_ident].before( item.html(display_text).prepend(close) );\n\n // populate the hidden input field\n add_to_hidden(field_ident, id);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
funciton to render local searches on load
function renderLocalSearch () { //checks local storage for localScores item if(JSON.parse(localStorage.getItem("localCity")) === null) { return; } // if localScores is in local storage, parses string to highScoreStore array. storedSearches = JSON.parse(localStorage.getItem("localCity")); }
[ "function renderStoredSearch() {\n // console.log(\"Im in render stored search locations func\");\n //creating a variable to hold the items in local storage parsed into JSON\n var searchArray = JSON.parse(localStorage.getItem(\"searchLocations\"));\n //if there are items in local storage\n if (searchArray != null) {\n // console.log(\"searchArray\", searchArray);\n //do this for loop for the entire length of the new array\n for (var i = 0; i < searchArray.length; i++) {\n //run the add search function above add the previously searched items to the ul as lis\n addSearch(searchArray[i].searchLocation);\n }\n }\n }", "function load() {\n var artistsSearched = JSON.parse(localStorage.getItem(\"searches\"));\n // only run if a local storage object is found\n if (artistsSearched) {\n // empty the container before we append\n $(\"#search-items\").empty();\n\n $.each(artistsSearched, function (i) {\n var artist = artistsSearched[i];\n var newP = $(\"<p>\");\n newP.text(artist);\n $(\"#search-items\").append(newP);\n });\n }\n }", "function _drawResults() {\n\n let template = \"\";\n store.state.songs.forEach(song => {\n template += song.SearchTemplate;\n });\n document.getElementById(\"songs\").innerHTML = template;\n}", "function searchtoresults()\n{\n\tshowstuff('results');\n\thidestuff('interests');\t\n}", "function search()\n{\n\tvar searchText = searchInput.value;\n\n\t// if input's empty\n\t// displaying everything\n\tif (searchText == \"\")\n\t{\n\t\tshowAllFilteredWordEntries();\n\t\treturn;\n\t}\n\n\t// hiding everything except the matched words\n\tfor (let i = 0; i < loadedData.length; i++)\n\t{\n\t\tlet entry = getFilteredWordEntry(i);\n\t\tvar regx = new RegExp(searchText);\n\t\tif (regx.test(loadedData[i]))\n\t\t\tentry.hidden = false;\n\t\telse\n\t\t\tentry.hidden = true;\n\t}\n}", "function search() {\n\t\tvar searchVal = searchText.getValue();\n\n\t\tsources.genFood.searchBar({\n\t\t\targuments: [searchVal],\n\t\t\tonSuccess: function(event) {\n\t\t\t\tsources.genFood.setEntityCollection(event.result);\n\t\t\t},\n\t\t\tonError: WAKL.err.handler\n\t\t});\n\t}", "function searchSidebarResults ( term, baseurl, page, sort, search_count ) {\n var new_loc = $specified_loc.split(', ').join(',');\n var data = { what : term, where : new_loc, page_num : page, sortby : sort, count : search_count };\n $.ajax({\n type: \"POST\",\n url: baseurl + \"/api/search.php\",\n dataType: \"JSON\",\n data: data,\n success: function(data){\n if( data.success.results.locations.length > 0 ){\n if(!$.isEmptyObject(data.success.results.locations)){ \n renderSidebarResults(data.success.results.locations); \n }\n }\n }\n });\n }", "function searchFunc() {\n\t // get the value of the search input field\n\t var searchString = $('#search').val(); //.toLowerCase();\n\t markers.setFilter(showFamily);\n\n\t // here we're simply comparing the 'state' property of each marker\n\t // to the search string, seeing whether the former contains the latter.\n\t function showFamily(feature) {\n\t return (feature.properties.last_name === searchString || feature.properties[\"always-show\"] === true);\n\t }\n\t}", "function loadStoredResults() {\n //conditional statement to check if load is needed\n if (loadFromLocalStorage(\"reloadResults\") == true) {\n //initialize variable and store loaded results in it\n let searchResults = loadFromLocalStorage(\"latestSearchResults\");\n //display the results that have been loaded\n displaySearchResults(searchResults, loadFromLocalStorage(\"backToResultsPageToLoad\"));\n //clear data under backToResultsPageToLoad tag in local storage\n saveToLocalStorage(\"\", \"backToResultsPageToLoad\");\n //disable load results instruction to stop the results being loaded again if user navigates away and back to page\n disableLoadStoredResults();\n }\n}", "async displayRecentSearches(){\n try{\n // load the recent search from the device database cache\n let recentSearchData = await utopiasoftware[utopiasoftware_app_namespace].databaseOperations.\n loadData(\"recent-searches\", utopiasoftware[utopiasoftware_app_namespace].model.appDatabase);\n\n let displayContent = \"<ons-list-title>Recent Searches</ons-list-title>\"; // holds the content of the list to be created\n // create the Recent Searches list\n for(let index = 0; index < recentSearchData.products.length; index++){\n displayContent += `\n <ons-list-item modifier=\"longdivider\" tappable lock-on-drag=\"true\">\n <div class=\"center\">\n <div style=\"width: 100%;\" \n onclick=\"utopiasoftware[utopiasoftware_app_namespace].controller.searchPageViewModel.\n recentSearchesItemClicked(${index})\">\n <span class=\"list-item__subtitle\">${recentSearchData.products[index].name}</span>\n </div>\n </div>\n <div class=\"right\" prevent-tap \n onclick=\"utopiasoftware[utopiasoftware_app_namespace].controller.searchPageViewModel.\n removeRecentSearchItem(${index}, this);\">\n <ons-icon icon=\"md-close-circle\" style=\"color: lavender; font-size: 18px;\"></ons-icon>\n </div>\n </ons-list-item>`;\n }\n // attach the displayContent to the list\n $('#search-page #search-list').html(displayContent);\n }\n catch(err){\n\n }\n }", "function initLunr() {\n if (!endsWith(fsdocs_search_baseurl,\"/\")){\n fsdocs_search_baseurl = fsdocs_search_baseurl+'/'\n };\n\n // First retrieve the index file\n $.getJSON(fsdocs_search_baseurl +\"index.json\")\n .done(function(index) {\n pagesIndex = index;\n // Set up lunrjs by declaring the fields we use\n // Also provide their boost level for the ranking\n lunrIndex = lunr(function() {\n this.ref(\"uri\");\n this.field('title', {\n\t\t boost: 15\n });\n this.field('tags', {\n\t\t boost: 10\n });\n this.field(\"content\", {\n\t\t boost: 5\n });\n\t\t\t\t\n this.pipeline.remove(lunr.stemmer);\n this.searchPipeline.remove(lunr.stemmer);\n\t\t\t\t\n // Feed lunr with each file and let lunr actually index them\n pagesIndex.forEach(function(page) {\n\t\t this.add(page);\n }, this);\n })\n })\n .fail(function(jqxhr, textStatus, error) {\n var err = textStatus + \", \" + error;\n console.error(\"Error getting Hugo index file:\", err);\n });\n}", "function showSearchMovies(){\n query = moviesSearch.value;\n if (query != \"\"){\n resultsList.innerHTML = \"\";\n customQuery = query;\n resetPageNumbers();\n customPage = 1;\n tmdb.searchMovies(query, customPage).then(data => {\n resultsList.innerHTML = \"\";\n results = data.searchMovies.results;\n totalPages = data.searchMovies.total_pages;\n\n if (results != undefined){\n newMoviesList(results);\n removeMiniNavActive();\n }\n else{\n resetPageNumbers();\n }\n\n loadMore.style.display = (totalPages > 1) ? 'inline' : 'none';\n });\n }\n}", "function search() {\n searchingPerformers = false;\n\n var searchTerm = document.getElementById(\"searchBox\").value;\n // remove punctuation from search term\n searchTerm = searchTerm.replace(/[\\.,-\\/#!$%\\^\\*;:{}=\\-_`~()\"'¡]/gi, '').toLowerCase();\n\n var productionResults = [];\n for (production of Productions) {\n if (production) {\n var productionNoPunctuation = production.replace(/[\\.,-\\/#!$%\\^\\*;:{}=\\-_`~()\"'¡]/gi, '').toLowerCase();\n if (productionNoPunctuation.includes(searchTerm)) {\n productionResults.push(production);\n }\n }\n }\n\n if (productionResults.length <= 0) {\n document.getElementById(\"showResults\").innerHTML = \"No productions founds :(\";\n document.getElementById(\"resultsTitle\").innerHTML = \"\";\n return;\n }\n\n var productionsHtml = ejs.render(productionsTemplate, {\n productionResults: productionResults\n });\n\n document.getElementById(\"showResults\").innerHTML = productionsHtml;\n document.getElementById(\"resultsTitle\").innerHTML = \"\";\n}", "function handleSearch(){\n var term = element( RandME.ui.search_textfield ).value;\n if(term.length){\n requestRandomGif( term, true);\n }\n}", "buildSearchPage() {\n const myBooks = this.books.getMyBooks();\n if (this.searchedBooks === undefined) {\n return;\n }\n this.booksView.buildBookListing(this.searchedBooks, this.displayBook, myBooks);\n this.booksView.buildPagination(this.totalBooks, 100, this.currentPage, this.gotoPage, \"topPagination\");\n this.booksView.buildPagination(this.totalBooks, 100, this.currentPage, this.gotoPage, \"bottomPagination\");\n }", "function displaySearchResult(data) {\n\tconst pages = data.query.pages;\n\n\t//Create new li for each search item found.\n\tconst searchResultHtml = Object.keys(pages).map( function(key){\n\t\tconst { title, extract } = pages[key];\n\n\t\treturn html = `\n\t\t\t<li>\n\t\t\t\t<a href=\"https://en.wikipedia.org/wiki/${title}\">\n\t\t\t\t\t<div class=\"resultItem\">\t\t\t\t\t\t\n\t\t\t\t\t\t<h1> ${title} </h1> <br>\n\t\t\t\t\t\t${extract} \n\t\t\t\t\t\n\t\t\t\t\t</div>\n\t\t\t\t</a>\n\t\t\t</li>\n\t\t\t`;\n\t});\t\t\n\t//Put all li search result item in ul list.\n\tsearchResultList.innerHTML = searchResultHtml.join(\"\");\t\t\n}", "function populateSearchBox(searchterm) {\n\t\n\tvar newrow = '<tr ><td id=\"loading_dots_text\" style=\"text-align: right;\" width=\"60%\"></td><td id=\"loading_dots\" style=\"text-align:left;\"></td></tr>';\n\t$('#search-table').append(newrow);\t\n\t\n\tdots_id = setInterval(animateDots, 500);\n\n\t\n\t\n\t\n\t$.get(\"/search/\", {query: searchterm},\n\t\tfunction(data){\n\n\t\t\tclearInterval(dots_id);\n\t\t\tfillSearchBox(data);\n\t\t}\n );\t\n}", "function find() {\n isSearched = false;\n var storeLocatorForm = app.getForm('storelocator');\n storeLocatorForm.clear();\n\n var Content = app.getModel('Content');\n var storeLocatorAsset = Content.get('store-locator');\n\n var pageMeta = require('~/cartridge/scripts/meta');\n pageMeta.update(storeLocatorAsset);\n\n app.getView('StoreLocator', {isSearched: isSearched}).render('storelocator/storelocator');\n}", "function showSearch() {\n\t\ttm.fromTo($searchForm, .3, {'display': 'none', y: -220}, {'display': 'block', y: 0, ease: Power3.easeInOut})\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursively tries to push an item to the bottomright most tree possible. If there is no space left for the item, null will be returned.
function push_(item, a) { // Handle resursion stop at leaf level. if (a.height === 0) { if (a.table.length < M) { var newA = { ctor: '_Array', height: 0, table: a.table.slice() }; newA.table.push(item); return newA; } else { return null; } } // Recursively push var pushed = push_(item, botRight(a)); // There was space in the bottom right tree, so the slot will // be updated. if (pushed !== null) { var newA = nodeCopy(a); newA.table[newA.table.length - 1] = pushed; newA.lengths[newA.lengths.length - 1]++; return newA; } // When there was no space left, check if there is space left // for a new slot with a tree which contains only the item // at the bottom. if (a.table.length < M) { var newSlot = create(item, a.height - 1); var newA = nodeCopy(a); newA.table.push(newSlot); newA.lengths.push(newA.lengths[newA.lengths.length - 1] + length(newSlot)); return newA; } else { return null; } }
[ "_insertRecursively(node, data) {\n if (!node) {\n return new Node(data);\n }\n\n if (data <= node.data) {\n node.left = this._insertRecursively(node.left, data);\n } else {\n node.right = this._insertRecursively(node.right, data);\n }\n\n return node;\n }", "insert(val) {\n const newNode = new Node(val);\n // if BST is empty\n if (!this.root) {\n this.root = newNode;\n return this;\n }\n let curr = this.root;\n // traverse to find the right location for the new node;\n while (true) {\n // if the new val is eqal to curr val, return undefined;\n if (val === curr.val) return undefined;\n // if smaller traverse left\n if (val < curr.val) {\n // if no left\n if (!curr.left) {\n curr.left = newNode;\n return this;\n }\n // traverse\n curr = curr.left;\n } else {\n // if bigger move right\n // if no right\n if (!curr.right) {\n curr.right = newNode;\n return this;\n }\n // traverse\n curr = curr.right;\n }\n }\n }", "breadthFirstTraversal() {\n let queue = [];\n queue.push(this.root);\n while (queue.length){\n let node = queue.shift();\n console.log(node.val);\n if (node.left){queue.push(node.left);}\n if (node.right){queue.push(node.right)};\n }\n }", "levelByLevelOneQueueUsingDelimiter(root) {\n if (root == null) {\n return;\n }\n var q = [];\n q.push(root);\n q.push(null);\n while (q.length > 0) {\n root = q.shift();\n if (root != null) {\n console.log(root.val + \" \");\n if (root.leftChild != null) {\n q.push(root.leftChild);\n }\n if (root.rightChild != null) {\n q.push(root.rightChild);\n }\n } else {\n if (q.length > 0) {\n console.log(\" \");\n q.push(null);\n }\n }\n }\n }", "traverseLevelOrder() {\n const root = this._root;\n const queue = [];\n\n if (!root) {\n return;\n }\n queue.push(root);\n\n while (queue.length) {\n const temp = queue.shift();\n console.log(temp.value);\n if (temp.left) {\n queue.push(temp.left);\n }\n if (temp.right) {\n queue.push(temp.right);\n }\n }\n }", "enQueue(item) {\n // move all items from stack1 to stack2, which reverses order\n this.alternateStacks(this.stack1, this.stack2)\n\n // new item will be at the bottom of stack1 so it will be the last out / last in line\n this.stack1.push(item);\n\n // move items back to stack1, from stack2\n this.alternateStacks(this.stack2, this.stack1)\n }", "function create_right_sibling(node)\n{\n if (node === null) \n {\n return;\n }\n \n var numberOfChildren = node.children.length;\n \n var queue = [];\n for (var i=0; i < numberOfChildren ; i++)\n {\n if (node.children[i].right === null && node.children[i+1])\n {\n node.children[i].right = node.children[i+1];\n queue.push(node.children[i]);\n }\n }\n \n for (var j=0; j < queue.length; j++)\n {\n create_right_sibling(queue[j]); \n }\n}", "insert(value) {\n const search = (newNode) => {\n const newBinaryTree = new BinarySearchTree(value);\n if (value >= newNode.value) {\n if (!newNode.right) newNode.right = newBinaryTree;\n else search(newNode.right);\n } else {\n if (!newNode.left) {\n newNode.left = newBinaryTree;\n return;\n }\n search(newNode.left);\n }\n };\n search(this);\n }", "function fill_missing_child_nodes_right_sibling(node)\n{\n if (node === null) \n {\n return;\n }\n \n var numberOfChildren = node.children.length;\n var lastNodeIndex = numberOfChildren - 1;\n \n if (lastNodeIndex >= 0)\n {\n if (node.children[lastNodeIndex].right === null)\n {\n node.children[lastNodeIndex].right = find_right_sibling(node);\n }\n for (var i=0; i < numberOfChildren; i++)\n {\n fill_missing_child_nodes_right_sibling(node.children[i]); \n }\n }\n}", "insert(value) {\n let newNode = new TreeNode(value);\n let current;\n this.size++;\n\n if (this.root == null) {\n this.root = newNode;\n } else {\n current = this.root;\n\n while(current != newNode) {\n if (newNode.value >= current.value) {\n if (current.right != null) {\n current = current.right;\n } else {\n current.right = newNode;\n }\n } else {\n if (current.left != null) {\n current = current.left;\n } else {\n current.left = newNode;\n }\n }\n }\n }\n }", "TreePush(str_id=null)\n {\n let win = this.getCurrentWindow();\n this.Indent();\n win.DC.TreeDepth++;\n this.PushID(str_id ? str_id : \"#TreePush\");\n }", "push (value) {\n var node = new Node(value)\n var currentNode = this.head\n\n // 1st use-case: an empty list\n if (!currentNode) {\n this.head = node\n this.length++\n return node\n }\n\n // 2nd use-case: a non-empty list\n while (currentNode.next) {\n currentNode = currentNode.next\n }\n\n currentNode.next = node\n this.length++\n\n return node\n }", "pop() {\n if (this.currentNode.children.length > 0) return;\n\n let tmp = this.currentNode;\n this.previous();\n tmp.removeFromParent();\n }", "addLeft(data){\n\t\tlet copyRoot = this.root;\n\t\twhile (this.root.left){\n\t\t\tthis.root = this.root.left;\n\t\t}\n\n\t\tthis.root.left = new TreeNode(data, this.root);\n\t\tthis.root = copyRoot;\n\t}", "push(element) {\r\n //this.stack.push(element);\r\n this.stack.unshift(element);\r\n }", "heapUp(index) {\n\n if (index === 0) {\n return;\n }\n\n const childNode = this.store[index];\n let parentIndex;\n if (index % 2 === 0) {\n parentIndex = (index - 2) / 2;\n } else {\n parentIndex = (index - 1) / 2;\n }\n\n const parentNode = this.store[parentIndex];\n\n if (childNode.key >= parentNode.key) {\n return;\n } else {\n this.swap(index, parentIndex);\n this.heapUp(parentIndex);\n }\n \n }", "function push(tile) {\n \tvar id = tile.value == 1? tile.id1 : tile.id2;\n \tvar newState = { 'parent': currentState, tile: tile };\n \t// add the new state on top of the current\n \tcurrentState[id] = newState;\n \t// for this specific tile, count how many values have been tried\n \tif (currentState[tile.id])\n \t\tcurrentState[tile.id]++\n \telse\n \t\tcurrentState[tile.id] = 1;\n \tcurrentState = newState;\n }", "traverseBreadth(){\n let queue = new Queue();\n let arr = [];\n let current = this.root;\n\n queue.enqueue( current );\n\n while( queue.size > 0 ){\n\n current = queue.dequeue().val;\n arr.push( current.value );\n\n if( current.left !== null ) queue.enqueue( current.left );\n if( current.right !== null ) queue.enqueue( current.right );\n }\n\n return arr;\n }", "enqueue(item) {\n if (this.canEnqueue()) {\n this.queueControl.push(item);\n return this.queueControl;\n } \n throw new Error('QUEUE_OVERFLOW');\n }", "function MoveUpOneLevel()\r\n{\r\n var treeFrame = GetTreeFrame();\r\n var selectedNode = treeFrame.getSelectedTreeNode();\r\n if(selectedNode != null) //tree could be expanded but no node selected\r\n {\r\n var parentNode = selectedNode.getParent();\r\n if(parentNode != null) //check we are not at the top of the tree\r\n {\r\n var parentTag = parentNode.getTag();\r\n treeFrame.setSelectedTreeNode(parentTag);\r\n }\r\n }\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the serverVersion. Only override if you implement functionality specifically not available in the declared base serverVersion. This is used when writing out serverVersion and fullVersion in the various JSON and HTML outputs.
get serverVersion() { if (!this._devMode) console.log("Implement to override the default server version of 10.1"); return 10.1; }
[ "getServerVersion() {\n if(!_.isUndefined(this.nodeInfo) && !_.isUndefined(this.nodeInfo.server)\n && !_.isUndefined(this.nodeInfo.server.version)) {\n return this.nodeInfo.server.version;\n }\n }", "get nodeVersion() {\n return this._cliConfig.get('node-version', process.versions.node);\n }", "version() {\n console.log(\"HSA.version\");\n this._log.debug(\"HSA.version\");\n return this._version;\n }", "get pulumiVersion() {\n if (this._pulumiVersion === undefined) {\n throw new Error(`Failed to get Pulumi version`);\n }\n return this._pulumiVersion.toString();\n }", "parseVersion() {\n var version = this.map_['info']['version'];\n var parsed = '';\n if (goog.isString(version)) {\n parsed = parseInt(version, 10);\n if (isNaN(parsed)) parsed = version;\n else parsed = parsed.toString();\n this.version = parsed;\n }\n }", "get cliVersion() {\n return this._cliConfig.get('cli-version', null);\n }", "function getVersion() {\n var contents = grunt.file.read(\"formulate.meta/Constants.cs\");\n var versionRegex = new RegExp(\"Version = \\\"([0-9.]+)\\\";\", \"gim\");\n return versionRegex.exec(contents)[1];\n }", "eth_protocolVersion() {\n return this.request(\"eth_protocolVersion\", Array.from(arguments));\n }", "function getVersion(page) {\r\n\tif (dbug) console.log(\"wwvf-cs::Getting Version.\");\r\n\tvar rv = null;\r\n\tif (page) {\r\n\t\tvar xVer = /v((\\d+)\\.(\\d+)(?:\\.(\\d+(-?[a-z]\\d+)?))?)(-development|release)?/i;\r\n\t\tif (page != \"\" && page.match(/Web Experience Toolkit/i)) {\r\n\t\t\t/*var vNumRe = /\\* (.*?) v(\\d[\\d\\.a-z]+)/;\r\n\t\t\tvar wet3v = /\\* Version: v(\\d[\\d\\.a-zA-Z\\-]+)/;\r\n\t\t\tvar wet30 = /Web Experience Toolkit/;\r\n\t\t\tvar wet40 = /v((\\d+(\\.|-[a-z]\\d*))+(-development|release)?)/i;*/\r\n\t\t\tvar clf2Theme = /(CLF 2.0 theme|CSS presentation layer) v(\\d+.\\S+)/i;\r\n\t\r\n\t\t\tvar clf2ThemeVer = page.match(clf2Theme);\r\n\t\t\tif (clf2ThemeVer) {\r\n\t\t\t\trv = \"2.x\";\r\n\t\t\t} else {\r\n\t\t\t\t// Can't be WET 2.0.\r\n\t\t\t\tvar totVer = page.match(xVer);\r\n\t\t\t\tif (!totVer) {\r\n\t\t\t\t\tif (page.match(/Web Experience Toolkit|WET/i)) {\r\n\t\t\t\t\t\ttotVer = page.match(/\\* +((\\d+)\\.(\\d+)(?:\\.(\\d+(-?[a-z]\\d+)?))?)(-development|release)?/);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (totVer) {\r\n\t\t\t\t\trv = totVer[1];\r\n\t\t\t\t} else {\r\n\t\t\t\t\trv = \"?\";\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn rv;\r\n}", "baseVersion() {\n console.log(\"HSA.baseVersion\");\n this._log.debug(\"HSA.baseVersion\");\n throw {code: this.ErrorCodes.Version_ThisIsHSA, message: \"This is HSA interface.\"};\n }", "get version() { return this.name.replace('.js', ''); }", "get _versionCacheKey() {\n const oThis = this;\n\n return oThis.cacheBaseKey + '_v';\n }", "get configVersion() {\n return '0.0.0'\n }", "static get DB_VERSION() {\n return 1;\n }", "function getOStackModuleApiVersion (apiType)\n{\n var version = httpsOp.getHttpsOptionsByAPIType(apiType, 'apiVersion');\n if (null == version) {\n switch (apiType) {\n case global.label.IMAGE_SERVER:\n return glanceApi.imageListVerList;\n case global.label.COMPUTE_SERVER:\n return novaApi.novaAPIVerList;\n default:\n return null;\n }\n }\n return version;\n}", "function Version(major, minor, micro, special)\n{\n\tthis.major = major;\n\tthis.minor = minor;\n\tthis.micro = micro;\n\tthis.special = special;\t\t\n}", "function MM_FlashLatestPluginRevision(playerVersion)\r\n{\r\n var latestRevision;\r\n var platform;\r\n\r\n if (navigator.appVersion.indexOf(\"Win\") != -1)\r\n\tplatform = \"Windows\";\r\n else if (navigator.appVersion.indexOf(\"Macintosh\") != -1)\r\n\tplatform = \"Macintosh\";\r\n else if (navigator.appVersion.indexOf(\"X11\") != -1)\r\n\tplatform = \"Unix\";\r\n\r\n latestRevision = MM_latestPluginRevision[playerVersion][platform];\r\n\r\n return latestRevision;\r\n}", "function default_versionCode(version) {\n var nums = version.split('-')[0].split('.');\n var versionCode = 0;\n if (+nums[0]) {\n versionCode += +nums[0] * 10000;\n }\n if (+nums[1]) {\n versionCode += +nums[1] * 100;\n }\n if (+nums[2]) {\n versionCode += +nums[2];\n }\n\n events.emit('verbose', 'android-versionCode not found in config.xml. Generating a code based on version in config.xml (' + version + '): ' + versionCode);\n return versionCode;\n}", "function version(){\n var xmlReq = new XMLHttpRequest(); \n xmlReq.open(\"GET\", \"Info.plist\", false); \n xmlReq.send(null); \n \n var xml = xmlReq.responseXML; \n var keys = xml.getElementsByTagName(\"key\");\n var ver = \"0.0\";\n\n for (i=0; i<keys.length; ++i) {\n if (\"CFBundleVersion\" == keys[i].firstChild.data) {\n ver = keys[i].nextSibling.nextSibling.firstChild.data;\n break;\n }\n }\n\n return ver; \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
find sounds by character
static findSoundsByCharacter(character) { return CharacterToSounds[character]; }
[ "static findCharactersBySound(sound) {\n return SoundToCharacters[sound];\n }", "static findCharactersWithSingleSound(characters) {\n return _.select(characters, char => { \n return Canigma.findSoundsByCharacter(char).length == 1;\n });\n }", "static findOtherCharactersWithSameSound(originalCharacter, sound) {\n var characters = Canigma.findCharactersBySound(sound);\n return _.reject(characters, char => { return char === originalCharacter});\n }", "function findSoundAndPlay(message, channelID, userID){\n\tvar group_found = false,\n\tfound = false,\n\tsound_found = false,\n\tsound_path = sound_root, \n\tbase_group = sound_list, \n\tsounds_group, sounds_final,\n\tcur, names;\n\n\tvar requestMessage = message;\n\trequestMessage = requestMessage.split(\" \");\n\trequestMessage.shift();\n\n\t//request a group folder\n\tif(requestMessage.length > 0){\n\t\t//if the request is invalid\n\t\tif(isKeyPresent(base_group, requestMessage[0])){\n\t\t\t//requested key is present, go go\n\t\t\tgroup_found = true;\n\t\t\tsounds_group = base_group[requestMessage[0]];\n\n\t\t\t//check if the second param is here\n\t\t\t//if not we skip down and pick at random\n\t\t\tif(requestMessage.length > 1){\n\t\t\t//console.log(\"Trying \" + requestMessage[1]);\n\t\t\tvar keys = Object.keys(sounds_group);\n\t\t\tvar i, j;\n\t\t\t//loop through keys\n\t\t\tfor(i=0; i<keys.length && (!found); i+=1){\n\t\t\t\tcur = sounds_group[keys[i]];\n\t\t\t\tnames = cur.aliases;\n\t\t\t\t//loop through aliases\n\t\t\t\tfor(j=0; j<names.length && (!found); j+=1){\n\t\t\t\t\tif(requestMessage[1] === names[j]){\n\t\t\t\t\t\tsound_path = cur.path;\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\tsound_found = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n\n\t//If the lookup failed at the group level, or sound level, we catch and remediate here\n\n\t//if we failed to match the group get one at random\n\t//this will be fed to establishing the sound clip\n\tif(group_found == false){\n\t\t\t//pick a random group and random folder\n\t\t\t//get a random group from sounds\n\t\t\tsounds_group = base_group[pickRandomKey(base_group)];\n\t\t\tgroup_found = true;\n\t}\n\n\t//if we failed to match the sound we get one here at random...\n\t//sounds_group is guaranteed to be established by now either at random or by choice.\n\tif(sound_found == false){\n\t\t\t//get a random sounds from group\n\t\t\tsounds_final = sounds_group[pickRandomKey(sounds_group)];\n\t\t\t//append to the static sound_root\n\t\t\tsound_path = sounds_final.path;\n\t\t\tsound_found = true;\n\t}\n\n\tconsole.log(sound_path);\n\tplayAudioFromUserID(channelID, userID, sound_path);\n}", "function get_sounds(message){\r\n var files = fs.readdirSync('./sounds/');\r\n var names = \"```fix\\n\";\r\n files.forEach(file => {\r\n names = names.concat(file).concat('\\n');\r\n });\r\n names = names.concat(\"```\");\r\n message.channel.send(names);\r\n}", "function findFilePath (key) {\n let filePath = \"sounds/\"\n switch (key) {\n case \"w\":\n filePath += \"tom-1.mp3\"\n break;\n case \"a\":\n filePath += \"tom-2.mp3\"\n break;\n case \"s\":\n filePath += \"tom-3.mp3\"\n break\n case \"d\":\n filePath += \"tom-4.mp3\"\n break;\n case \"j\":\n filePath += \"snare.mp3\"\n break;\n case \"k\":\n filePath += \"crash.mp3\"\n break;\n case \"l\":\n filePath += \"kick-bass.mp3\"\n break;\n\n default: filePath = null;\n }\n return filePath;\n}", "function play_sound(sounds) {\n\tvar max = 4;\n\tfor (var i = 0; i < max; i++) {\n\t\tif (sounds[i] != '') {\n\t\t\tallSounds[allSoundNames.indexOf(sounds[i])].play();\n\t\t}\n\t}\n}", "function randomKeyboardSound(){\n let i=Math.floor(Math.random()*5)+1;\n let audiokeyboard=new Audio('assets/audio/sounds/keyb' + i + '.mp3');\n audiokeyboard.play();\n}", "function playSound(id) {\n sounds[id].play();\n}", "function getSoundByAlias(alias) {\n return sounds[soundsLookup[alias]];\n }", "function myLoop() {\n setTimeout(function() {\n let character = userInput.charAt(k).toLowerCase();\n //console.log('play sound: ' + character);\n newRipplePos = false;\n //switch statment decides which sound should be played\n switch (character) {\n case 'a':\n playNewSound(0);\n break;\n case 'b':\n playNewSound(1);\n break;\n case 'c':\n playNewSound(2);\n break;\n case 'd':\n playNewSound(3);\n break;\n case 'e':\n playNewSound(4);\n break;\n case 'f':\n playNewSound(5);\n break;\n case 'g':\n playNewSound(6);\n break;\n case 'h':\n playNewSound(7);\n break;\n case 'i':\n playNewSound(8);\n break;\n case 'j':\n playNewSound(9);\n break;\n case 'k':\n playNewSound(10);\n break;\n case 'l':\n playNewSound(11);\n break;\n case 'm':\n playNewSound(12);\n break;\n case 'n':\n playNewSound(13);\n break;\n case 'o':\n playNewSound(14);\n break;\n case 'p':\n playNewSound(15);\n break;\n case 'q':\n playNewSound(16);\n break;\n case 'r':\n playNewSound(17);\n break;\n case 's':\n playNewSound(18);\n break;\n case 't':\n playNewSound(19);\n break;\n case 'u':\n playNewSound(20);\n break;\n case 'v':\n playNewSound(21);\n break;\n case 'w':\n playNewSound(22);\n break;\n case 'x':\n playNewSound(23);\n break;\n case 'y':\n playNewSound(24);\n break;\n case 'z':\n playNewSound(25);\n break;\n case ' ':\n playNewSound(26);\n newRipplePos = true;\n break;\n //'$' represents the end of the user input\n case '$':\n playNewSound(27);\n newRipplePos = true;\n break;\n //the default will be called for non alphabetic characters\n default:\n playNewSound(26);\n }\n if(character !== ' ' && character !== '$' ){\n let newRipple = new ripple(xPosition, yPosition, red, green, blue, k);\n }else{\n\n let pickRandomColour = Math.floor(Math.random()*((redArray.length-1)-0+1)+0);\n red = redArray[pickRandomColour];\n green = greenArray[pickRandomColour];\n blue = blueArray[pickRandomColour];\n\n let tempXPos = (Math.floor(Math.random() * 800) - 400);\n let tempYPos = (Math.floor(Math.random() * 800) - 400);\n\n if(tempXPos <= 150 && tempXPos >= 0){\n tempXPos += 200;\n }else if(tempXPos >= -150 && tempXPos <= 0){\n tempXPos -= 200;\n }\n\n if(tempYPos <= 150 && tempYPos >= 0){\n tempYPos += 200;\n }else if(tempYPos >= -150 && tempYPos <= 0){\n tempYPos -= 200;\n }\n\n if((xPosition + tempXPos) >= window.innerWidth || (xPosition + tempXPos) < 0){\n tempXPos = tempXPos * -1;\n }\n\n if((yPosition + tempYPos) >= window.innerHeight || (yPosition + tempYPos) < 0){\n tempYPos = tempYPos * -1;\n }\n\n xPosition += tempXPos;\n yPosition += tempYPos;\n }\n \n if(red <= 200 && green <=200 && blue <=200){\n red += 20;\n green += 20;\n blue += 20;\n }\n //when the number of characters of an input becomes longer than a multiple of 7 characters\n if (k % 5 === 0 && k !== 0) {\n for (let i = 0; i < alphabet.length; ++i) {\n soundList[i].amp(0.2); //reduce the volume of the looping sounds\n }\n }\n if (k % 7 === 0 && k !== 0) {\n for (let i = 0; i < alphabet.length; ++i) {\n soundList[i].amp(0); //reduce the volume of the looping sounds\n }\n }\n k++;\n if (k < userInput.length) {\n myLoop();\n }\n } ,1500) // <- this value controls how many seconds dealy is inbetween each sound in ms\n }", "async inCategory(categoryName, path) {\n const categoryObj = await this.collection.findOne({sub: categoryName});\n if (categoryObj === null) return false;\n\n return categoryObj.sounds.includes(path)\n }", "function makeSound(key){\n //this switch statement takes in a single key character as input\n //then assigns the specific listener function to the diff event keys\n switch (key) {\n case 'w':\n var tom1 = new Audio(\"sounds/tom-1.mp3\");\n tom1.play();\n break;\n\n case 'a':\n var tom2 = new Audio(\"sounds/tom-2.mp3\");\n tom2.play();\n break;\n\n case 's':\n var tom3 = new Audio(\"sounds/tom-3.mp3\");\n tom3.play();\n break;\n\n case 'd':\n var tom4 = new Audio(\"sounds/tom-4.mp3\");\n tom4.play();\n break;\n\n case 'j':\n var snare = new Audio(\"sounds/snare.mp3\");\n snare.play();\n break;\n\n case 'k':\n var crash = new Audio(\"sounds/crash.mp3\");\n crash.play();\n break;\n\n case 'l':\n var kick = new Audio(\"sounds/kick-bass.mp3\");\n kick.play();\n break;\n\n default: console.log(buttonInnerHTML); //just showing which button triggered default case\n\n }\n}", "function correctSound() {\n for (var i = 0; i < box.length; i++) {\n this.addEventListener('click', playSound(sound2));\n }\n}", "function tellMe(joke){\n // got this code from tts api documentation \n VoiceRSS.speech({\n key: '233e1729322c4d28829ef0d633b14196',\n src: joke,\n hl: 'en-us',\n v: 'Harry',\n r: 0, \n c: 'mp3',\n f: '44khz_16bit_stereo',\n ssml: false\n})\n}", "function playSound(squareNum){\n var snd = new Audio(game.sounds[squareNum - 1]);\n snd.play();\n}", "function loadSounds() {\n confirmSound = new Howl({\n src: ['assets/sounds/confirm.ogg'],\n volume: 0.8\n });\n\n selectSound = new Howl({\n src: ['assets/sounds/select.ogg'],\n volume: 0.8\n });\n thudSound = new Howl({\n src: ['assets/sounds/thud.ogg'],\n volume: 0.8\n });\n moveSound = new Howl({\n src: ['assets/sounds/move.ogg'],\n volume: 0.6\n });\n turnSound = new Howl({\n src: ['assets/sounds/turn.ogg'],\n volume: 0.8\n });\n\n music1 = new Howl({\n src: ['assets/sounds/nesmusic1.mp3','assets/sounds/nesmusic1.ogg'],\n// buffer: true,\n loop:true,\n loaded: false,\n onplay: function() {\n },\n onload: function() {\n musicSelectionField.labels[0].alpha = 1;\n this.loaded = true;\n },\n onloaderror: function() {\n musicSelectionField.labels[0].alpha = 0.1;\n }\n\n });\n\n music2 = new Howl({\n src: ['assets/sounds/nesmusic2.mp3','assets/sounds/nesmusic2.ogg'],\n volume: 0.6,\n// buffer: true,\n loop:true,\n loaded: false,\n onplay: function() {\n },\n onload: function() {\n musicSelectionField.labels[1].alpha = 1;\n this.loaded = true;\n },\n onloaderror: function() {\n musicSelectionField.labels[1].alpha = 0.1;\n }\n\n\n });\n\n music3 = new Howl({\n src: ['assets/sounds/nesmusic3.mp3','assets/sounds/nesmusic3.ogg'],\n volume: 0.5,\n// buffer: true,\n loop: true,\n loaded: false,\n onplay: function() {\n },\n onload: function() {\n musicSelectionField.labels[2].alpha = 1;\n this.loaded = true;\n },\n onloaderror: function() {\n musicSelectionField.labels[2].alpha = 0.1;\n }\n\n });\n// music1Fast = music2Fast = music3Fast = music4Fast = music5Fast = music6Fast = undefined;\n // music1Fast = new Howl({\n // src: ['assets/sounds/g.ogg'],\n // volume: 0.8\n // });\n // music2Fast = new Howl({\n // src: ['assets/sounds/g.ogg'],\n // volume: 0.8\n // });\n // music3Fast = new Howl({\n // src: ['assets/sounds/g.ogg'],\n // volume: 0.8\n // });\n // music4Fast = new Howl({\n // src: ['assets/sounds/g.ogg'],\n // volume: 0.8\n // });\n // music5Fast = new Howl({\n // src: ['assets/sounds/g.ogg'],\n // volume: 0.8\n // });\n // music6Fast = new Howl({\n // src: ['assets/sounds/g.ogg'],\n // volume: 0.8\n // });\n deathSound = new Howl({\n src: ['assets/sounds/death.ogg'],\n volume: 0.8\n });\n levelUpSound = new Howl({\n src: ['assets/sounds/levelup.ogg'],\n volume: 0.8\n });\n\n lineSound = new Howl({\n src: ['assets/sounds/line.ogg'],\n volume: 0.8\n });\n fourLineSound = new Howl({\n src: ['assets/sounds/fourline.ogg'],\n volume: 0.8\n });\n\n\n musicSelections = [\n {normal:music1,fast:music1},\n {normal:music2,fast:music2},\n {normal:music3,fast:music3},\n ]\n\n\n}", "playSample(name)\n {\n if(name in this.bufferLookup)\n {\n let player = this.audio_context.createBufferSource();\n player.buffer = this.bufferLookup[name];\n player.loop = false;\n player.connect(this.masterVolume);\n player.start(this.audio_context.currentTime);\n }\n }", "function randomBackgroundSong(play){\n switch (play){\n case 'pause': backgroundSong[randomSongNum].backgroundSongAudio.pause(); break;\n case 'play': backgroundSong[randomSongNum].backgroundSongAudio.play(); break;\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
!onItemChanged To be called when the messageActive status changes, so that we can focus on the text control if appropriate.
function onMessageActive(newval, oldval) { if(!newval && !oldval) return; if(newval && !oldval) { $scope.focusTextInput(); } }
[ "ShowCurrentItems(){\n MyUtility.getInstance().sendTo('telegram.0', {\n chatId : MyUtility.getInstance().getState('telegram.0.communicate.requestChatId'/*Chat ID of last received request*/).val,\n text: 'Bitte Raum wählen:',\n reply_markup: {\n keyboard:\n this._telegramArray.getTelegramArray(this._currentIDX)\n ,\n resize_keyboard: true,\n one_time_keyboard: true\n }\n });\n\n this.emit(\"onItemChange\",this);\n }", "onMailViewChanged() {\n // only do this if we're currently active. no need to queue it because we\n // always update the mail view whenever we are made active.\n if (this.active) {\n // you cannot cancel a view change!\n window.dispatchEvent(\n new Event(\"MailViewChanged\", { bubbles: false, cancelable: false })\n );\n }\n }", "function checkIfActivePaginationItemChanged() {\r\n\t\t\tif ($activeItem[0]) {\r\n\t\t\t\t$paginationUnderline.css({\r\n\t\t\t\t\t\"width\": $activeItem.width(),\r\n\t\t\t\t\t\"left\": $activeItem.position().left\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t}", "_focusActiveOption() {\n var _a;\n if (!this.useActiveDescendant) {\n (_a = this.listKeyManager.activeItem) === null || _a === void 0 ? void 0 : _a.focus();\n }\n this.changeDetectorRef.markForCheck();\n }", "itemsChanged() {\n this._processItems();\n }", "selectMessageComingUp() {\n this._aboutToSelectMessage = true;\n }", "selectMessage(id) {\n // TODO: scroll into view.\n\n this.setState({ activeMessageId: id });\n }", "_handleFocusChange() {\n this.__focused = this.contains(document.activeElement);\n }", "function setPrevItemActive() {\n var items = getItems();\n\n var activeItem = document.getElementsByClassName(\"active\")[0];\n var prevElement = activeItem.previousElementSibling;\n\n if (!prevElement) {\n prevElement = items[items.length - 1];\n }\n\n changeActiveState(activeItem, prevElement);\n}", "_updateActiveOption() {\n if (!this._listKeyManager.activeItem) {\n return;\n }\n this._activeOption?.deactivate();\n this._activeOption = this._listKeyManager.activeItem;\n this._activeOption.activate();\n if (!this.useActiveDescendant) {\n this._activeOption.focus();\n }\n }", "focusFirstItem() {\n if (this.items.length === 0) {\n return;\n }\n\n this.items[0].focus();\n }", "function IsItemActivated() { return bind.IsItemActivated(); }", "function set_msg_focus() {\n\t$('#msg').focus();\n}", "function test_switch_to_message_a() {\n switch_tab(tabMessageA);\n assert_selected_and_displayed(messageA);\n assert_message_pane_focused();\n}", "_onSelectedChanged() {\n if (this._selected !== 'appsco-application-add-search') {\n this.$.addApplicationAction.style.display = 'block';\n this.playAnimation('entry');\n this._addAction = true;\n }\n else {\n this._addAction = false;\n this.playAnimation('exit');\n }\n }", "updateBody(event) {\r\n // If user is in the SMS Tab\r\n if(this.state.value){\r\n this.setState({smsBodyValue: event.target.value});\r\n } else{\r\n this.setState({emailBodyValue: event.target.value});\r\n }\r\n }", "componentDidUpdate(prevProps, prevState) {\n if (this.props.active) {\n this.focusInput();\n }\n }", "function showStatusMsg(msg) {\n\tExt.get('status-msg').update(msg);\n\t//Ext.get('status-msg').slideIn();\n}", "didFocus () {\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if a given browser's docshell should be active.
shouldActivateDocShell(aBrowser) { if (this._switcher) { return this._switcher.shouldActivateDocShell(aBrowser); } return (aBrowser == this.selectedBrowser && window.windowState != window.STATE_MINIMIZED && !window.isFullyOccluded) || this._printPreviewBrowsers.has(aBrowser); }
[ "function checkOpenDocument() {\r\n\tvar od = true;\r\n\tif (app.documents.length > 0) {\r\n\t\tvar docA = app.activeDocument;\r\n\t} else {\r\n\t\tvar msg = \"Annoyingly, Illustrator won't set the colour space of an SVG \";\r\n\t\tmsg += \"to CMYK unless there's already a file open! I'm going to open a new document, \";\r\n\t\tmsg += \"but you'll have to invoke the script again...\";\r\n\t\talert(msg);\r\n\t\tjdocA = app.documents.add();\r\n\t\tod = false;\r\n\t}\r\n\treturn od;\r\n}", "isWindowActive() {\n if (this.windowHandle === null) {\n this.windowHandle = Winhook.FindWindow(this.windowTitle);\n if (!this.windowHandle) {\n return false;\n }\n }\n return Winhook.GetForegroundWindow() === this.windowHandle;\n }", "function isGecko() {\n\t\tconst w = window\n\t\t// Based on research in September 2020\n\t\treturn (\n\t\t\tcountTruthy([\n\t\t\t\t'buildID' in navigator,\n\t\t\t\t'MozAppearance' in (document.documentElement?.style ?? {}),\n\t\t\t\t'onmozfullscreenchange' in w,\n\t\t\t\t'mozInnerScreenX' in w,\n\t\t\t\t'CSSMozDocumentRule' in w,\n\t\t\t\t'CanvasCaptureMediaStream' in w,\n\t\t\t]) >= 4\n\t\t)\n\t}", "function testBackgroundPage() {\n if (TARGET === \"firefox\" || TARGET === \"chrome\") {\n return backgroundPage.bg.test();\n } else {\n return false;\n }\n}", "async isCorrectPageOpened() {\n let currentURL = await PageUtils.getURL()\n return currentURL.indexOf(this.pageUrl)!== -1\n }", "function isSpecialTab(tab) {\r\n var url = tab.url;\r\n\r\n if (url.indexOf('chrome-extension:') === 0 ||\r\n url.indexOf('chrome:') === 0 ||\r\n url.indexOf('chrome-devtools:') === 0 ||\r\n url.indexOf('file:') === 0 ||\r\n url.indexOf('chrome.google.com/webstore') >= 0) {\r\n return true;\r\n }\r\n\r\n return false;\r\n}", "function isDesktopSafari() {\n\t\tconst w = window\n\t\treturn (\n\t\t\tcountTruthy([\n\t\t\t\t'safari' in w,\n\t\t\t\t!('DeviceMotionEvent' in w),\n\t\t\t\t!('ongestureend' in w),\n\t\t\t\t!('standalone' in navigator),\n\t\t\t]) >= 3\n\t\t)\n\t}", "function isDocumentNew(doc){\n\t// assumes doc is the activeDocument\n\tcTID = function(s) { return app.charIDToTypeID(s); }\n\tvar ref = new ActionReference();\n\tref.putEnumerated( cTID(\"Dcmn\"),\n\tcTID(\"Ordn\"),\n\tcTID(\"Trgt\") ); //activeDoc\n\tvar desc = executeActionGet(ref);\n\tvar rc = true;\n\t\tif (desc.hasKey(cTID(\"FilR\"))) { //FileReference\n\t\tvar path = desc.getPath(cTID(\"FilR\"));\n\t\t\n\t\tif (path) {\n\t\t\trc = (path.absoluteURI.length == 0);\n\t\t}\n\t}\n\treturn rc;\n}", "function crawlStarted() {\n return ($localStorage.currentCrawl !== undefined);\n }", "function isCookieLockEnabled() {\n return isChromium();\n}", "function IsWindowFocused(flags = 0) {\r\n return bind.IsWindowFocused(flags);\r\n }", "inDOM() {\n\t\t\treturn $(Utils.storyElement).find(this.dom).length > 0;\n\t\t}", "isOnServer() {\n return !(typeof window !== 'undefined' && window.document);\n }", "isVisible() {\n return this.toolbar.is(\":visible\");\n }", "function isCanvas() {\n return !isHome();\n}", "function isInCurrentSite(path) {\n\tvar siteRoot = dw.getSiteRoot();\n\tvar inCurSite = false;\n\t\n\tif (siteRoot) {\n\t\tvar siteRootForURL = dwscripts.filePathToLocalURL(site.getSiteRootForURL(path));\n\t\tinCurSite = (siteRoot == siteRootForURL);\n\t}\n\t\n\treturn inCurSite;\n}", "function isNeptunPage() {\n return document.title.toLowerCase().indexOf(\"neptun.net\") !== -1;\n}", "function checkBrowser(){\n\tvar browserInfo = navigator.userAgent;\n\tif(browserInfo.indexOf(\"Firefox\")!=-1)userBrowser=\"Firefox\";\n\tif(browserInfo.indexOf(\"Chrome\")!=-1)userBrowser=\"Chrome\";\n\tif(browserInfo.indexOf(\"Safari\")!=-1)userBrowser=\"Safari\";\n}", "function verificarBrowser(){\n // Verificando Browser\n if(Is.appID==\"IE\" && Is.appVersion<6 ){\n var msg = \"Este sistema possui recursos não suportados pelo seu Navegador atual.\\n\";\n msg += \"É necessário fazer uma atualização do browser atual para a versão 6 ou superior,\\n\";\n msg += \"ou poderá instalar o Navegador Firefox.\\n\";\n //msg += \"\\nDados do seu Navegador:\";\n //msg += \"\\n Browser:\"+Is.appName+\"\\n ID:\"+Is.appID+\"\\n Versão:\"+Is.appVersion;\n msg += \"\\n Baixar firefox agora?\";\n if(confirm(msg)){\n document.location.replace(\"http://br.mozdev.org/\");\n return false;\n }else{\n return false;\n }\n }else{\n return true;\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
recibe id favorito ,lleega por la url, recibe request y respuesta tipo get
function getFavorito(req,res){ var favoritoId= req.params.id; //para buscar ese favorito Favorito.findById(favoritoId,function(err,favorito){ if(err){ res.status(500).send({message:'error al devolver marcador'}) } else{ if (!favorito){ res.status(404).send({message:'No existe el marcador'}) } else{ res.status(200).send({ favorito}) } } }) }
[ "function getFavorites(success, error){\n let baseUrl = \"/favorites\";\n baseXHRGet(baseUrl, success, error);\n }", "function getElencoEsamiUltimoAnno(matId,anno){ \n return new Promise(function(resolve, reject) {\n var options = { \n method: 'GET',\n url: strUrlGetSingoloEsame + matId +'/righe/' + '?filter=esito.aaSupId%3D%3D' + anno,\n headers: \n { \n 'cache-control': 'no-cache',\n 'Content-Type': 'application/json',\n 'Authorization': 'Basic czI2OTA3MjpDR1ZZUDNURQ=='\n },\n json: true \n }\n request(options, function (error, response, body) {\n console.log('url di getElencoEsamiUltimoAnno '+ options.url);\n if (error) {\n reject(error);\n console.log('errore in getElencoEsamiUltimoAnno '+ error);\n } else {\n if (response.statusCode==200){\n \n resolve(body); \n } else {\n\n console.log('status code getElencoEsamiUltimoAnno = '+response.statusCode);\n resolve(response.statusCode);\n }\n }\n \n });\n \n }); \n}", "function findById(id) {\r\n $.ajax({\r\n type: 'GET',\r\n url: rootURL + '/pizza/' + id,\r\n dataType: \"json\",\r\n contentType: 'application/json',\r\n\r\n success: function (data) {\r\n setPizza(data);\r\n }\r\n });\r\n}", "function getFavoriteFact(number) {\n const resp = axios.get(`${BASE_URL}/${number}?json`);\n return resp;\n}", "static setDatabaseUrlOneFavorite(id, fav) {\r\n return `http://localhost:${DBHelper.PORT}/restaurants/${id}/?is_favorite=${fav}`;\r\n }", "function getFavorites(username){\n\t$.ajax({\n\t url: Url+'/getfavs?Username='+username,\n\t type: \"GET\",\n\t success: listFavorites,\n\t error: displayError,\n\t})\n}", "function getFavoriteMovies() {\n\t\tlet movieId = $('.movie-id').val();\n\n\t\t$.ajax({\n\t\t\turl: \"/favorites/all\",\n\t\t\tmethod: \"GET\",\n\t\t\tcontentType: \"application/json\",\n\t\t\tdataType: 'json',\n\n\t\t\tcomplete : function(data){ \t\n\t\t\t\tjQuery.each(data.responseJSON, function(index, item) {\n\t\t\t\t\t//favoriteMovies(item.movieId, item.user.id);\n\n\t\t\t\t\tif (item.movieId == movieId && item.user.id == myId) {\n\t\t\t\t\t\t$('.add-to-favorite').addClass(\"is-favorite\")\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t},fail : function(){\n\t\t\t\tconsole.log(\"Failed getting favorite movies\");\n\t\t\t}\n\t\t});\n\t}", "function searchProyecto() {\n\n getIdDirectivo();\n \n\t\n var get = getGET();\n var pagina = get.pagina;\n var dato = get.dato;\n var bq = '%' + dato + '%';\n\n switch (pagina) {\n case 'mapa_proyectos':\n //alert(\"pagina \" + pagina);\n Obras(bq);\n break;\n case 'lista_proyectos':\n //alert(\"pagina \" + pagina);\n Obras(bq);\n break;\n case 'detalle_proyectos':\n Obras(bq);\n break;\n case 'galeria':\n Obras(bq);\n break;\n default:\n Obras(bq);\n break;\n };\n}", "function getUsuario(id){\n return fetch('https://jsonplaceholder.typicode.com/users/'+id);\n }", "function checkIfFavourite() {\n const url = '/albumFavourite';\n // Since this is a GET request, simply call fetch on the URL\n fetch(url)\n .then((res) => {\n if (res.status === 200) {\n // return a promise that resolves with the JSON body\n return res.json()\n } else {\n }\n })\n .then((favouriteAlbum) => { // the resolved promise with the JSON body\n for( let i = 0; i < favouriteAlbum.length; i++ )\n {\n if(favouriteAlbum[i]._id == album._id )\n {\n isFavourite = true\n }\n }\n styleFavouriteButton();\n }).catch((error) => {\n })\n}", "function Requete_AJAX_GetMenusResaturants(url_request)\n{\n\t\tvar xhr = getXhr();\n\t\t// On dÈfini ce qu'on va faire quand on aura la rÈponse\n\t\txhr.onreadystatechange = function()\n\t\t{\n\t\t\t// On ne fait quelque chose que si on a tout reÁu et que le serveur est ok\n\t\t\tif(xhr.readyState == 4 && xhr.status == 200)\n\t\t\t{\n\t\t\t\treponse = xhr.responseText;\n\t\t\t\txmldom = (new DOMParser()).parseFromString(reponse, 'text/xml');\n\t\t\t\t\n\t\t\t\t//j\"ffiche le xml sur la console\n\t\t\t\tconsole.log(reponse);\n\t\t\t\t\n\t\t\t\t//J'efface les menus du précédent restaurant sélectionné qui sont contenus dans les balises<menu>\n\t\t\t\tclearHtml(\"menu\");\n\t\t\t\t\n\t\t\t\taddMenus(xmldom,\"menuList\");\n\t\t\t\t\n\t\t\t} \n\t\t}\n\n\t\tvar restaurantId=$( \"#restaurantList\" ).val();\n\t\tvar url=url_request+\"?restaurantId=\"+restaurantId;\n\t\tconsole.log(url);\n\t\txhr.open(\"GET\",url,true);\n\t\txhr.send(null);\n}", "function fetchSingleTweet(fetchOneId) {\n\n var fetchUrl = \"/api/tweet/\" + fetchOneId + \"/\";\n\n isSingleTweetDetailPage = true;\n\n console.log(fetchOneId);\n\n //var requestUrl;\n\n // if (!url){\n // requestUrl = initialUrl;\n // }else{\n // requestUrl = url;\n // }\n\n query = getParameterByName(\"q\");\n console.log(query);\n\n $.ajax({\n url: fetchUrl,\n data: {\n \"q\": query\n },\n\n method: \"GET\",\n\n success: function(data) {\n nextPage = data.next;\n\n if (nextPage == null){\n $(\".load-more\").css(\"display\", \"none\");\n }\n parseTweets(data.results)\n updateHashLinks();\n updateATTLinks();\n\n isSingleTweetDetailPage = false;\n\n if ($(\".media\").length == 1){\n $(\".media\").css(\"margin-left\", \"0px\");\n }\n },\n\n error: function (data) {\n console.log(\"ERROR\");\n console.log(data);\n\n isSingleTweetDetailPage = false;\n }\n });\n\n }", "function doGET(url) {\r\n\treturn llamadaAJAX(url, \"GET\", \"json\", false, null, null, null);\r\n}", "function get_trabajoActual() {\n fct_MyLearn_API_Client.get({ type: 'Proyectos', extension1: 'Curso', extension2: $routeParams.IdTrabajo.trim() }).$promise.then(function (data) {\n $scope.trabajoActual = data;\n });\n }", "function get_badgesObtenidos() {\n fct_MyLearn_API_Client.query({ type: 'Proyectos', extension1: 'Badges', extension2: $routeParams.IdTrabajo }).$promise.then(function (data) {\n $scope.ls_badgesObtenidos = data;\n });\n }", "function GetFreelancerById(id) {\n var URL = API_HOST + API_PROFILS_PATH +'/'+id\n Axios.get(URL)\n .then((response) => response.data);\n \n}", "static getFavoriteRestaurants() {\r\n return DBHelper.goGet(\r\n `${DBHelper.RESTAURANT_DB_URL}/?is_favorite=true`,\r\n \"❗💩 Error fetching favorite restaurants: \"\r\n );\r\n }", "function get_tray_info(rid) {\n var url = 'http://foodbot.ordr.in:8000/TextSearch?rid='+rid+'&target=pizza pie';\n request({\n url: url,\n json: true\n }, function (error, response, body) {\n if (!error && response.statusCode === 200) {\n for(var i=0; i<body.length; i++){\n if(body[i].tray){\n tray = body[i].tray;\n price = body[i].price;\n place_pizza_order(rid,tray,price);\n break;\n }\n }\n }\n else{\n console.log(error);\n }\n });\n\n}", "function castFilmSerie(idFilmSerie, tipo){\n var attori = []; //array dove verranno inseriti gli attori\n var isFilm = true; \n if (tipo === isFilm){ //se isFilm è true\n tipo = 'movie'; //valorizzo con movie\n }else{\n tipo = 'tv'; // valorizzo con tv\n }\n $.ajax({ \n url: 'https://api.themoviedb.org/3/'+ tipo + '/' + idFilmSerie + '/credits', //adeguo url\n method: \"GET\",\n data: {\n api_key: api_key,\n }, \n success: function(data){\n // ciclo ogni risultato della query\n var maxCast = 5; // massimo di attori\n var stringaAttori = \"\";\n for (var i = 0; i < data.cast.length; i++) {\n if(i == maxCast){ //se i arriva al maxCast\n i = data.cast.length; // cambia i al max dell'array\n }else{\n attori.push(data.cast[i].name); // aggiungo all'array\n stringaAttori += data.cast[i].name + \", \" //aggiungo alla stringa\n }\n }\n //ottengo stringa con tutti gli attori\n stringaAttori = stringaAttori.slice(0, stringaAttori.length - 2);\n //ottengo oggetto con id del film-serie e 5 attori \n objCastFiltrato.push(\n {\n 'id': idFilmSerie,\n 'actors': stringaAttori\n });\n },\n error: function(req, err){\n console.log(\"Errore nella funzione CastFilmSerie()\", err);\n } \n }) \n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check an object for unexpected properties. Accepts the object to check, and an array of allowed property names (strings). Returns an array of key names that were found on the object, but did not appear in the list of allowed properties. If no properties were found, the returned array will be of zero length.
function extraProperties(obj, allowed) { mod_assert.ok(typeof (obj) === 'object' && obj !== null, 'obj argument must be a non-null object'); mod_assert.ok(Array.isArray(allowed), 'allowed argument must be an array of strings'); for (var i = 0; i < allowed.length; i++) { mod_assert.ok(typeof (allowed[i]) === 'string', 'allowed argument must be an array of strings'); } return (Object.keys(obj).filter(function (key) { return (allowed.indexOf(key) === -1); })); }
[ "function defineObjectKeys(){\n Object.keys = (function() {\n 'use strict';\n var hasOwnProperty = Object.prototype.hasOwnProperty,\n hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),\n dontEnums = [\n 'toString',\n 'toLocaleString',\n 'valueOf',\n 'hasOwnProperty',\n 'isPrototypeOf',\n 'propertyIsEnumerable',\n 'constructor'\n ],\n dontEnumsLength = dontEnums.length;\n\n return function(obj) {\n if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {\n throw new TypeError('Object.keys called on non-object');\n }\n\n var result = [], prop, i;\n\n for (prop in obj) {\n if (hasOwnProperty.call(obj, prop)) {\n result.push(prop);\n }\n }\n\n if (hasDontEnumBug) {\n for (i = 0; i < dontEnumsLength; i++) {\n if (hasOwnProperty.call(obj, dontEnums[i])) {\n result.push(dontEnums[i]);\n }\n }\n }\n return result;\n };\n }());\n}", "function hasFieldsExcept( obj, arrFields )\n{\n\tvar field;\n\n\tfor ( field in obj )\n\t{\n\t\tif ( ! obj.hasOwnProperty( field ) )\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tif ( -1 === arrFields.indexOf( field ) )\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}", "function validateParamsPresent(expectedKeys, params) {\n params = params || {};\n var paramKeys = _.keys(params);\n return _.first(_.difference(expectedKeys, _.intersection(paramKeys, expectedKeys)));\n}", "function objectKeys(object) { Object.keys(object) }", "function showProperties(obj) {\n for(let key in obj) {\n if(typeof obj[key] === 'string') {\n console.log(key, obj[key]);\n }\n }\n}", "function keys(obj) {\n //return Object.keys(obj);\n var output = [];\n each(obj, function(elem, key) {\n output.push(key);\n });\n return output;\n}", "get missingIdentifierFields() {\n let results = [];\n for (let field in this.identifiers) {\n if (! this.identifiers[field]) {\n results.push(field);\n }\n }\n return results;\n }", "static _validateNoUndefinedMembers(jsonObject, keyPath) {\n if (!jsonObject) {\n return;\n }\n if (typeof jsonObject === 'object') {\n for (const key of Object.keys(jsonObject)) {\n keyPath.push(key);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const value = jsonObject[key];\n if (value === undefined) {\n const fullPath = JsonFile._formatKeyPath(keyPath);\n throw new Error(`The value for ${fullPath} is \"undefined\" and cannot be serialized as JSON`);\n }\n JsonFile._validateNoUndefinedMembers(value, keyPath);\n keyPath.pop();\n }\n }\n }", "getPropertyKeys() {\n let properties = this.getProperties();\n let propertyKeys = [];\n if (properties) {\n for (var key in properties) {\n if (Object.prototype.hasOwnProperty.call(properties, key)) {\n propertyKeys.push(key);\n }\n }\n }\n propertyKeys = propertyKeys.sort();\n return propertyKeys;\n }", "function validateObjectArgument(vObj){\n if(!(typeof vObj === 'object')) throw 'superSelect Requires an object argument';\n var keyCount = 0, objAryCount = 0, arys = [];\n for (keyCount; keyCount < Object.keys(vObj).length; keyCount++){\n if(Array.isArray(obj[Object.keys(vObj)[keyCount]])){\n arys.push(obj[Object.keys(vObj)[keyCount]]);\n objAryCount ++;\n }\n }\n if (objAryCount < 2) throw 'object argument requires two array properties';\n //Check arrays for object contents\n var arraysOfobjectOnlyCount = 0;\n arys.forEach(function(element, idx, ary){\n element.forEach(function(el, idx2, sary){\n\n }\n )\n });\n }", "function listAllProperties(o){ \n\tvar objectToInspect; \n\tvar result = [];\n\t\n\tfor(objectToInspect = o; objectToInspect !== null; objectToInspect = Object.getPrototypeOf(objectToInspect)){ \n\t\tresult = result.concat(Object.getOwnPropertyNames(objectToInspect)); \n\t}\n\t\n\treturn result; \n}", "check(validProps, layerName) {\n for (let propName of this.map.keys()) {\n let prop = validProps.get(propName);\n for (let other of prop.otherPropsRequired) {\n if (!this.has(other)) {\n throw new Error('Property \"' + propName + '\" also requires ' +\n 'property \"' + other + '\" but the second one was ' +\n 'not found. This happened in the layer \"' + layerName + '\".');\n }\n }\n }\n }", "objectKeys(obj) {\n if (obj instanceof Object) {\n return (function*() {\n for (let key in obj) {\n yield key;\n }\n })();\n } else {\n return [];\n }\n }", "function CfnBucket_S3KeyFilterPropertyValidator(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('rules', cdk.requiredValidator)(properties.rules));\n errors.collect(cdk.propertyValidator('rules', cdk.listValidator(CfnBucket_FilterRulePropertyValidator))(properties.rules));\n return errors.wrap('supplied properties not correct for \"S3KeyFilterProperty\"');\n}", "function hasProps(keys, x) {\n if(!isFoldable(keys)) {\n throw new TypeError(err)\n }\n\n if(isNil(x)) {\n return false\n }\n\n var result = keys.reduce(\n every(hasKey(x)),\n null\n )\n\n return result === null || result\n}", "function attributeKeys(record) {\n return Object.keys(record).filter(function(key) {\n return key !== 'id' || key !== 'type';\n })\n}", "function getAllKeys(obj) {\r\n for (let key in obj) {\r\n if (typeof obj[key] === \"object\") {\r\n keyArr.push(key);\r\n getAllKeys(obj[key]);\r\n } else {\r\n keyArr.push(key);\r\n }\r\n }\r\n return keyArr;\r\n}", "function omit(obj, arr){\n let newObj={};\n for (let key in obj){\n if (!arr.includes(key)) newObj[key] = obj[key];\n }\n \n return newObj;\n}", "function CfnBucket_NotificationFilterPropertyValidator(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('s3Key', cdk.requiredValidator)(properties.s3Key));\n errors.collect(cdk.propertyValidator('s3Key', CfnBucket_S3KeyFilterPropertyValidator)(properties.s3Key));\n return errors.wrap('supplied properties not correct for \"NotificationFilterProperty\"');\n}", "function pickAndValidateWheres(obj, publicToModel, allowedKeys) {\n // Pick all keys which are allowed in the query\n var whereObj = _.pickBy(obj, function(val, key) {\n var isAllowed = _.isArray(allowedKeys)\n ? _.includes(allowedKeys, key)\n : true;\n return isAllowed && !_.isUndefined(val);\n });\n\n // Validate all values used in the where query\n _.each(whereObj, function(val, whereKey) {\n var Model;\n var modelAttribute;\n if (!_.isPlainObject(publicToModel)) {\n Model = publicToModel\n modelAttribute = whereKey;\n } else {\n Model = publicToModel[whereKey].model;\n modelAttribute = publicToModel[whereKey].attribute;\n }\n\n var attributeSchema = Model.prototype.schema[modelAttribute];\n if (!attributeSchema) {\n attributeSchema = BASE_SCHEMA[modelAttribute];\n }\n\n var joiValidate = attributeSchema.optional();\n if (_.isArray(val)) {\n _.each(val, function(item) {\n validate(item, whereKey, joiValidate);\n });\n } else {\n validate(val, whereKey, joiValidate);\n }\n });\n\n return whereObj;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
rightResize: resize the rectangle by dragging the right handle
function rightResize(d) { if(isUser || in_progress) { // user page return; } // get event id var groupNum = d.groupNum; // get event object var ev = getEventFromId(groupNum); var newX = d3.event.x - (d3.event.x%(STEP_WIDTH)) - (DRAGBAR_WIDTH/2); if(newX > SVG_WIDTH){ newX = SVG_WIDTH; } var newWidth = newX - ev.x; if (newWidth < 30) return; ev.duration = durationForWidth(newWidth); drawEvent(ev, false); }
[ "function addRectHandle($canvas, parent, px, py) {\n\tvar handle, cursor;\n\n\t// Determine cursor to use depending on handle's placement\n\tif ((px === -1 && py === -1) || (px === 1 && py === 1)) {\n\t\tcursor = 'nwse-resize';\n\t} else if (px === 0 && (py === -1 || py === 1)) {\n\t\tcursor = 'ns-resize';\n\t} else if ((px === -1 || px === 1) && py === 0) {\n\t\tcursor = 'ew-resize';\n\t} else if ((px === 1 && py === -1) || (px === -1 && py === 1)) {\n\t\tcursor = 'nesw-resize';\n\t}\n\n\thandle = $.extend({\n\t\t// Set cursors for handle\n\t\tcursors: {\n\t\t\tmouseover: cursor\n\t\t}\n\t}, parent.handle, {\n\t\t// Define constant properties for handle\n\t\tlayer: true,\n\t\tdraggable: true,\n\t\tx: parent.x + ((px * parent.width / 2) + ((parent.fromCenter) ? 0 : parent.width / 2)),\n\t\ty: parent.y + ((py * parent.height / 2) + ((parent.fromCenter) ? 0 : parent.height / 2)),\n\t\t_parent: parent,\n\t\t_px: px,\n\t\t_py: py,\n\t\tfromCenter: true,\n\t\tdragstart: function (layer) {\n\t\t\t$(this).triggerLayerEvent(layer._parent, 'handlestart');\n\t\t},\n\t\t// Resize rectangle when dragging a handle\n\t\tdrag: function (layer) {\n\t\t\tvar parent = layer._parent;\n\n\t\t\tif (parent.width + (layer.dx * layer._px) < parent.minWidth) {\n\t\t\t\tparent.width = parent.minWidth;\n\t\t\t\tlayer.dx = 0;\n\t\t\t}\n\t\t\tif (parent.height + (layer.dy * layer._py) < parent.minHeight) {\n\t\t\t\tparent.height = parent.minHeight;\n\t\t\t\tlayer.dy = 0;\n\t\t\t}\n\n\t\t\tif (!parent.resizeFromCenter) {\n\t\t\t\t// Optionally constrain proportions\n\t\t\t\tif (parent.constrainProportions) {\n\t\t\t\t\tif (layer._py === 0) {\n\t\t\t\t\t\t// Manage handles whose y is at layer's center\n\t\t\t\t\t\tparent.height = parent.width / parent.aspectRatio;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Manage every other handle\n\t\t\t\t\t\tparent.width = parent.height * parent.aspectRatio;\n\t\t\t\t\t\tlayer.dx = layer.dy * parent.aspectRatio * layer._py * layer._px;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Optionally resize rectangle from corner\n\t\t\t\tif (parent.fromCenter) {\n\t\t\t\t\tparent.width += layer.dx * layer._px;\n\t\t\t\t\tparent.height += layer.dy * layer._py;\n\t\t\t\t} else {\n\t\t\t\t\t// This is simplified version based on math. Also you can write this using an if statement for each handle\n\t\t\t\t\tparent.width += layer.dx * layer._px;\n\t\t\t\t\tif (layer._px !== 0) {\n\t\t\t\t\t\tparent.x += layer.dx * ((1 - layer._px) && (1 - layer._px) / Math.abs((1 - layer._px)));\n\t\t\t\t\t}\n\t\t\t\t\tparent.height += layer.dy * layer._py;\n\t\t\t\t\tif (layer._py !== 0) {\n\t\t\t\t\t\tparent.y += layer.dy * ((1 - layer._py) && (1 - layer._py) / Math.abs((1 - layer._py)));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Ensure diagonal handle does not move\n\t\t\t\tif (parent.fromCenter) {\n\t\t\t\t\tif (layer._px !== 0) {\n\t\t\t\t\t\tparent.x += layer.dx / 2;\n\t\t\t\t\t}\n\t\t\t\t\tif (layer._py !== 0) {\n\t\t\t\t\t\tparent.y += layer.dy / 2;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Otherwise, resize rectangle from center\n\t\t\t\tparent.width += layer.dx * layer._px * 2;\n\t\t\t\tparent.height += layer.dy * layer._py * 2;\n\t\t\t\t// Optionally constrain proportions\n\t\t\t\tif (parent.constrainProportions) {\n\t\t\t\t\tif (layer._py === 0) {\n\t\t\t\t\t\t// Manage handles whose y is at layer's center\n\t\t\t\t\t\tparent.height = parent.width / parent.aspectRatio;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Manage every other handle\n\t\t\t\t\t\tparent.width = parent.height * parent.aspectRatio;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tupdateRectHandles(parent);\n\t\t\t$(this).triggerLayerEvent(parent, 'handlemove');\n\t\t},\n\t\tdragstop: function (layer) {\n\t\t\tvar parent = layer._parent;\n\t\t\t$(this).triggerLayerEvent(parent, 'handlestop');\n\t\t},\n\t\tdragcancel: function (layer) {\n\t\t\tvar parent = layer._parent;\n\t\t\t$(this).triggerLayerEvent(parent, 'handlecancel');\n\t\t}\n\t});\n\t$canvas.draw(handle);\n\t// Add handle to parent layer's list of handles\n\tparent._handles.push($canvas.getLayer(-1));\n}", "function i2uiResizeSlaveonmousedown(e)\r\n{\r\n var name;\r\n\r\n i2uiResizeSlaveOrigonmouseup = document.onmouseup;\r\n i2uiResizeSlaveOrigonmousemove = document.onmousemove;\r\n\r\n document.onmousemove = i2uiResizeSlaveonmousemove;\r\n document.onmouseup = i2uiResizeSlaveonmouseup;\r\n\r\n i2uiResizeSlavewhichEl = null;\r\n\r\n i2uiResizeSlavewhichEl = event.srcElement;\r\n\r\n name = i2uiResizeSlavewhichEl.id;\r\n\r\n //window.status = \"mousedown. target=\"+name;\r\n // determine if mousedown on a resize indicator\r\n while (i2uiResizeSlavewhichEl.id.indexOf(i2uiResizeKeyword) == -1)\r\n {\r\n //i2uiResizeSlavewhichEl = i2uiResizeSlavewhichEl.parentElement;\r\n i2uiResizeSlavewhichEl = i2uiResizeSlavewhichEl.parentNode;\r\n if (i2uiResizeSlavewhichEl == null)\r\n {\r\n return;\r\n }\r\n }\r\n\r\n if (i2uiResizeSlavewhichEl == null)\r\n {\r\n return;\r\n }\r\n\r\n //window.status = \"mousedown. name=\"+name;\r\n\r\n i2uiResizeSlavewhichEl.style.cursor = \"move\";\r\n\r\n // retain mousedown position\r\n i2uiResizeSlaveorigX = event.clientX + document.body.scrollLeft;\r\n}", "_handleResize(e) {\n this.resizeToolbar();\n }", "function makeResizable(id) {\n $(id).resizable({\n start: function(event, ui) {\n $(\".close-icon\").hide();\n $(id).css({\n 'outline': \"2px solid grey\"\n });\n },\n resize: function(event, ui) {\n jsPlumbInstance.revalidate(ui.helper);\n },\n stop: function(event, ui) {\n $(id).css({\n 'outline': \"none\"\n });\n },\n handles: \"all\"\n });\n }", "function handleMouseUp() {\n isResizing = false;\n}", "@throttle(1)\n _updateHoverRect(event) {\n const mouseOid = oak.event._mouseOid;\n const isInsideHandle = event && $(event.target).is(\".ResizeHandle\");\n let rect;\n if (mouseOid && !isInsideHandle && !oak.event.anyButtonDown) {\n rect = oak.getRectForOid(mouseOid);\n }\n this._moveRect(\"hover\", rect);\n }", "function moveRight() {\n removeShape();\n currentShape.x++;\n if (collides(grid, currentShape)) {\n currentShape.x--;\n }\n applyShape();\n }", "function updateRectHandles(parent) {\n\tvar handle, h;\n\tif (parent._handles) {\n\t\t// Move handles when dragging\n\t\tfor (h = 0; h < parent._handles.length; h += 1) {\n\t\t\thandle = parent._handles[h];\n\t\t\thandle.x = parent.x + ((parent.width / 2 * handle._px) + ((parent.fromCenter) ? 0 : parent.width / 2));\n\t\t\thandle.y = parent.y + ((parent.height / 2 * handle._py) + ((parent.fromCenter) ? 0 : parent.height / 2));\n\t\t}\n\t}\n\tupdateRectGuides(parent);\n}", "function resize () {\n width = slider.offsetWidth\n\n totalTravel = getTotalTravel()\n\n if (totalTravel <= 0 && active) {\n destroy()\n } else if (totalTravel > 0 && !active) {\n init()\n }\n\n if (active && !suspended) {\n reflow()\n selectByIndex(true) // skip focus, will jump page or slider otherwise\n }\n }", "handleResize() {\n // if we don't have a spreader, let it come around again\n if (!this.refs.spreader) { return; }\n\n const availableWidth = ReactDOM.findDOMNode(this.refs.spreader).offsetWidth;\n this._targetHeight = ReactDOM.findDOMNode(this.refs.sizer).offsetHeight;\n\n // set the max height right away, so that the resize throttle doesn't allow line break jumps\n this.setState({ fixHeight: this._targetHeight });\n\n // was there a width change?\n if (availableWidth !== this.state.lastCalculatedWidth) {\n // first render?\n if (this.state.children === '' || availableWidth < this.state.lastCalculatedWidth) {\n this._adjustDown();\n } else {\n this._adjustUp();\n }\n }\n }", "function resizedw(){\n loadSlider(slider);\n }", "function horizontalResize(e) {\n\t\t\tif (!horizResizing) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\te = e || window.event;\n\t\t\tdocument.documentElement.style.cursor = 'n-resize';\n\t\t\tvar nSplit = Math.floor(e.clientY / uiView.clientHeight * 100);\n\n\t\t\tif (nSplit >= options.minSplit && nSplit <= 100 - options.minSplit) {\n\t\t\t\toptions.split = nSplit;\n\t\t\t\trefreshUI();\n\t\t\t\tsaveOptions();\n\t\t\t}\n\t\t}", "function handleReposition(old_width, old_height) {\n $(\".handle\").each(function() {\n var x_pct = parseInt($(this).css(\"left\")) / old_width\n var y_pct = parseInt($(this).css(\"top\")) / old_height\n\n var new_x = x_pct * width + \"px\"\n var new_y = y_pct * height + \"px\"\n\n // Reposition each handle\n $(this).css({\n left: new_x,\n top: new_y\n })\n })\n}", "function onTrackEventResizedLeft( trackEvent, x, w, resizeEvent ) {\n if ( x <= min ) {\n resizeEvent.blockIteration( min );\n }\n }", "function resize()\r\n{\r\n var i;\r\n \r\n i = document.getElementById(\"vline\");\r\n if (i) i.height = (getInsideWindowHeight() - 100);\r\n\r\n i = document.getElementById(\"hline1\");\r\n if (i) i.width = getInsideWindowWidth();\r\n\r\n i = document.getElementById(\"hline2\");\r\n if (i) i.width = getInsideWindowWidth();\r\n}", "function i2uiResizeSlaveresize()\r\n{\r\n var distanceX = i2uiResizeSlavenewX - i2uiResizeSlaveorigX;\r\n //i2uitrace(1,\"resize dist=\"+distanceX);\r\n if (distanceX != 0)\r\n {\r\n //i2uitrace(1,\"resize variable=\"+i2uiResizeSlavewhichEl.id);\r\n\r\n // test that variable exists by this name\r\n if (i2uiIsVariableDefined(i2uiResizeSlavewhichEl.id.substring(i2uiResizeKeywordLength)))\r\n {\r\n var w = i2uiResizeSlavewhichEl.id.substring(i2uiResizeKeywordLength);\r\n var newwidth = eval(w) + distanceX;\r\n //i2uitrace(1,\"distance=\"+distanceX+\" old width=\"+eval(w)+\" new width=\"+newwidth);\r\n\r\n var len = i2uiResizeWidthVariable.length;\r\n //i2uitrace(1,\"array len=\"+len);\r\n for (var i=0; i<len; i++)\r\n {\r\n if (i2uiResizeWidthVariable[i] == i2uiResizeSlavewhichEl.id.substring(i2uiResizeKeywordLength))\r\n {\r\n //i2uitrace(1,\"resize slave2 table[\"+i2uiResizeSlave2Variable[i]+\"]\");\r\n //i2uitrace(1,\"resize master table[\"+i2uiResizeMasterVariable[i]+\"]\");\r\n\r\n // make newwidth the smaller of newwidth and scroll width\r\n var scrolleritem = document.getElementById(i2uiResizeSlave2Variable[i]+\"_scroller\");\r\n //i2uitrace(0,\"scrolleritem=\"+scrolleritem);\r\n if (scrolleritem != null)\r\n {\r\n //i2uitrace(1,\"scrolleritem=\"+scrolleritem);\r\n //i2uitrace(1,\"scroller: width=\"+scrolleritem.width+\" style.width=\"+scrolleritem.style.width+\" client=\"+scrolleritem.clientWidth+\" scroll=\"+scrolleritem.scrollWidth+\" offset=\"+scrolleritem.offsetWidth);\r\n newwidth = Math.min(newwidth,scrolleritem.scrollWidth);\r\n }\r\n\r\n // must know about row groupings !!\r\n i2uiResizeScrollableArea(i2uiResizeSlave2Variable[i],null,newwidth);\r\n i2uiResizeScrollableArea(i2uiResizeMasterVariable[i],null,20,i2uiResizeSlaveVariable[i],i2uiResizeFlagVariable[i],newwidth);\r\n eval(i2uiResizeSlavewhichEl.id.substring(i2uiResizeKeywordLength)+\"=\"+newwidth);\r\n break;\r\n }\r\n }\r\n }\r\n else\r\n {\r\n window.status = \"ERROR: variable [\"+i2uiResizeSlavewhichEl.id.substring(i2uiResizeKeywordLength)+\"] not valid\";\r\n }\r\n }\r\n}", "function i2uiResizeSlaveonmousemove(e)\r\n{\r\n if (i2uiResizeSlavewhichEl == null)\r\n {\r\n event.returnValue = true;\r\n }\r\n else\r\n {\r\n event.returnValue = false;\r\n }\r\n}", "static startImageResize(d) {\n //console.log('resize start');\n d3.event.sourceEvent.preventDefault();\n d3.event.sourceEvent.stopPropagation();\n d.newHeight = d.height;\n d.newWidth = d.width;\n //console.log(JSON.stringify(d));\n d3.select('#OVER-' + d.link)\n .append('rect')\n .attr('id', 'RESIZE_WINDOW')\n .attr('x', 0)\n .attr('y', 0)\n .attr('height', d.newHeight)\n .attr('width', d.newWidth)\n .style('stroke-width', 1)\n .style('stroke', 'rgb(0,0,0)')\n .style('fill', 'rgb(10,20,180)')\n .style('fill-opacity', '0.4');\n }", "function drawWindowRight() {\n //starts where it ended after it drew the left window, so moves to where the right window will be located on the house\n leftWindowToRightLocation();\n //leaves space so akward line is avoided, making it seem like it is not connected to the side of the house by a line\n penUp();\n moveForward(5);\n penDown();\n //draws small window (square)\n drawRightWindowSquare();\n //draws cross\n drawRightWindowCross();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function drawhookHighlights: called after plot 3 redraws, this handles making sure the right bars are highlighted
function drawhookHighlight(plot, canvas) { plot.unhighlight(); for (var i = 0; i < highlighted[3].length; i++) { plots[3].highlight(0,highlighted[3][i]); } plot.clearSelection(true); drawhook(plot, canvas); }
[ "function highlightBar(bar) {\n bar.fillColor = \"rgba(186,0,0,0.1)\";\n bar.strokeColor = \"rgba(186,0,0,0.5)\";\n bar.highlightStroke = \"rgba(208,0,0,0.5)\";\n bar.highlightFill = \"rgba(186,0,0,0.05)\";\n}", "onLayerHighlight() {}", "drawBarsRemoveOld(){\n }", "function resetDrawingHighlights() {\n abEamTcController.resetDrawingHighlights();\n}", "function removeOldHighlights() {\r\n var i, div;\r\n\r\n // Reset the colors\r\n for (i = 0; i < squaresWithHighlights.length; ++i) {\r\n div = document.getElementById(squaresWithHighlights[i].pos);\r\n div.style.backgroundColor = \r\n chess.board.isWhiteSquare(squaresWithHighlights[i].pos) ? \r\n 'white' : 'black';\r\n }\r\n\r\n // Clear the array\r\n squaresWithHighlights = [];\r\n\r\n // Re-add the currently selected square, if there is one\r\n if (chess.game.selectedPiece) {\r\n highlightSquare(chess.game.selectedPiece.pos, 'selected');\r\n }\r\n }", "drawIconHighlight(ctx) {}", "function highlight() {\n if (count === 0 && goesFirst === 2) {\n $('.x, .o').toggleClass('highlight');\n }\n }", "updateSelectable(data, svgGroup) {\n\t\tlet self = this;\n\t\tlet heightScale = d3.scaleLinear().domain([0, 100]).range([this.buttonMenuHeight, this.buttonMenuHeight + this.barGroupHeight]);\n\t\tlet widthScale = d3.scaleLinear().domain([0, 100]).range([0, this.barGroupWidth]);\n\t\tlet dataLenInv = 1 / data.length; \n \n /* Temporarily deselect the selected row, if selected. */\n d3.select(\".row-overlay.active\").classed(\"active\", false);\n\n svgGroup.append(\"rect\").classed(\".bar\", true);\n\t\tlet rects = svgGroup.selectAll(\".bar\").data(data);\n\t\trects.exit().remove();\n\t\tlet enterRects = rects.enter().append(\"rect\");\n\n\t\tenterRects\n\t\t\t.attr(\"x\", 0)\n\t\t\t.attr(\"width\", widthScale(100))\n\t\t\t.style(\"stroke-width\", 0);\n\n\t\tlet allRects = enterRects.merge(rects);\n\t\tallRects.attr(\"y\", (d, i) => {return heightScale((i * dataLenInv) * 100)})\n\t\t\t.attr(\"height\", dataLenInv * this.barGroupHeight)\n\t\t\t.classed(\"row-overlay\", true)\n\t\t\t.classed(\"active\", (d,i) => { return (d.x == self.selectedx && d.y == self.selectedy);})\n\t\t\t.on(\"mouseover\", function(d,i) {\n\t\t\t\td3.select(this).classed(\"hover\", true);\n\t\t\t\tif (self.imageview != null)\n \t\t\tself.imageview.hoverPixel(d.x, d.y);\n\t\t\t})\n \t.on(\"mouseout\", function(d,i) {\n \t\td3.select(this).classed(\"hover\", false);\n \t\tif (self.imageview != null)\n \t\t\tself.imageview.hoverPixel(-1000, -1000);\n \t})\n \t.on(\"click\", function(d,i) {\n \t\tself.selectedx = d.x;\n \t\tself.selectedy = d.y;\n \t\td3.select(\".row-overlay.active\").classed(\"active\", false);\n \t\td3.select(this).classed(\"active\", true);\n \t\tif (self.imageview != null)\n \t\t\tself.imageview.selectPixel(d.x, d.y);\n \t\tif (self.raytreeview != null)\n\t\t\t\t\tself.raytreeview.selectPixel(d.x, d.y);\n\n \t\t/* TODO: update tree view */\n \t});\n\n\t\treturn allRects;\n\t}", "highlightSelected() {\n\n this.highlighter.setPosition(this.xStart + this.selected * this.distance, this.yPosition + this.highlighterOffsetY);\n\n }", "function highlightSelectedDIVs() {\n if (Object.prototype.toString.call(selectedDIVs) === '[object Array]') {\n if (selectedDIVs.length < 1) return;\n selectedDIVs.forEach(function(_div) {\n var el = $(_div);\n el.css('border-top', '1px dashed #000');\n el.css('border-bottom', '1px dashed #000');\n el.css('background-color', 'lightblue');\n el.css('opacity', 0.35);\n });\n // Add left/right border to first and last DIV\n $(selectedDIVs[0]).css('border-left', '1px dashed #000');\n $(selectedDIVs[selectedDIVs.length - 1]).css('border-right', '1px dashed #000');\n }\n}", "appendHighlight( captured ) \n\t{\n\t\t\n\t\tfor (var key in captured) {\n\t\t if ( captured.hasOwnProperty(key) ) {\n\t\t let goodQueen = $(\"div#\" + key);\n\t\t let evilQueen = $(\"div#\" + captured[key]);\n\t\t goodQueen.addClass('highlight');\n\t\t evilQueen.addClass('highlight');\n\t\t } \n\t\t}\n\t}", "updateBars(data) {\n\t\t/* Pixel color */\n\t\tlet colorBar = this.updateBar(data, \"color\", d3.select(\".colorbar\"), this.totalBars);\n\t\tif (colorBar) colorBar.style(\"fill\", (d, i) => {return d3.rgb(d.color.red,d.color.blue,d.color.green);});\n\n\t\t/* Pixel render time */\n\t\tlet timeBar = this.updateBar(data, \"time\", d3.select(\".timebar\"), this.totalBars);\n\t\tvar timeColor = d3.scaleLinear()\n\t\t\t.domain([this.rawData.min_render_time, this.rawData.max_render_time])\n .range(['black','white']);\n\t\tif (timeBar) timeBar.style(\"fill\", (d) => {return timeColor(d.time);});\n\n\t\t/* Total secondary rays */\n\t\tlet secondaryRayBar = this.updateBar(data, \"branches\", d3.select(\".branchesbar\"), this.totalBars);\n\t\tvar srColor = d3.scaleLinear()\n\t\t\t.domain([this.rawData.min_secondary_rays, this.rawData.max_secondary_rays])\n .range(['black','white']);\n\t\tif (secondaryRayBar) secondaryRayBar.style(\"fill\", (d) => {return srColor(d.branches);});\n\n\t\t/* Total samples */\n\t\tlet samplesBar = this.updateBar(data, \"samples\", d3.select(\".samplesbar\"), this.totalBars);\n\t\tvar scColor = d3.scaleLinear()\n\t\t\t.domain([this.rawData.min_sample_count, this.rawData.max_sample_count])\n .range(['black','white']);\n\t\tif (samplesBar) samplesBar.style(\"fill\", (d) => {return scColor(d.samples);});\n\n\t\t/* Pixel depth */\n\t\tlet depthBar = this.updateBar(data, \"depth\", d3.select(\".depthbar\"), this.totalBars);\n\t\tvar dColor = d3.scaleLinear()\n\t\t\t.domain([this.rawData.min_depth, this.rawData.max_depth])\n .range(['black','white']);\n\t\tif (depthBar) depthBar.style(\"fill\", (d) => {return dColor(d.depth);});\n\n\t\t/* Pixel variance */\n\t\tlet varianceBar = this.updateBar(data, \"variances\", d3.select(\".variancebar\"), this.totalBars);\n\t\tvar vColor = d3.scaleLinear()\n\t\t\t.domain([this.rawData.min_variance, this.rawData.max_variance])\n .range(['black','white']);\n\t\tif (varianceBar) varianceBar.style(\"fill\", (d) => {return vColor(d.variance);});\n\n\t\t/* Ray Box interections */\n\t\tlet boxBar = this.updateBar(data, \"boxIntersections\", d3.select(\".boxIntersections\"), this.totalBars);\n\t\tvar vColor = d3.scaleLinear()\n\t\t\t.domain([this.rawData.min_box_intersections, this.rawData.max_box_intersections])\n .range(['black','white']);\n\t\tif (boxBar) boxBar.style(\"fill\", (d) => {return vColor(d.boxIntersections);});\n\n\t\t/* Ray Obj interections */\n\t\tlet objBar = this.updateBar(data, \"objIntersections\", d3.select(\".objIntersections\"), this.totalBars);\n\t\tvar vColor = d3.scaleLinear()\n\t\t\t.domain([this.rawData.min_primitive_intersections, this.rawData.max_primitive_intersections])\n .range(['black','white']);\n\t\tif (objBar) objBar.style(\"fill\", (d) => {return vColor(d.objIntersections);});\n\n\t\t/* Selectable bars */\n\t\tlet selectableBar = this.updateSelectable(data, d3.select(\".selectableBar\"))\n\t}", "function brushEvent() {\n var actives = dimensions.filter(function(p) { return !y[p].brush.empty(); });\n var extents = actives.map(function(p) { return y[p].brush.extent(); });\n \n foreground.style(\"display\", function(d) {\n return actives.every(function(p, i) {\n return extents[i][0] <= d[p] && d[p] <= extents[i][1];\n }) ? null : \"none\";\n });\n }", "function updateBars(code) {\n\n\t\t\t// get all the rows in graphic_data concerning current AREACD.\n\t\t\tvar data = graphic_data.filter(function(d) {return d.AREACD == code})\n\t\t\t// \"transpose\" this data into the right format for stacking\n\t\t\ttransposedData = []\n\t\t\tvarnames.forEach( function(d) {\n\t\t\t\tvar tmp_obj = {}\n\t\t\t\ttmp_obj.key = d\n\t\t\t\tdata.forEach( function(k) {\n\t\t\t\t\ttmp_obj[k[dvc.bar.stackVar]] = k[d]\n\t\t\t\t})\n\t\t\t\ttransposedData.push(tmp_obj)\n\t\t\t})\n\t\t\t// bind new data to bars\n\t\t\tbarg.data(stack(transposedData))\n\n\t\t\t// when data is very different for certain areas, it might be necessary to transition to a new x axis\n\t\t\t// get previous upper limit of x domain\n\t\t\tvar prevMax = x.domain()[1];\n\n\t\t\t// set new upper limit of x domain as newMax\n\t\t\t// by default it's the same as the old one\n\t\t\tvar newMax = x.domain()[1];\n\t\t\t// here's an example of some code to change the axis in specific parts of London\n\t\t\t// if (code == 'E09000001' || code == 'E09000030') {\n\t\t\t// \tvar newMax = 40;\n\t\t\t// } else if (code.slice(0,3) == 'E09') {\n\t\t\t// \tvar newMax = 16;\n\t\t\t// } else {\n\t\t\t// \tvar newMax = 5;\n\t\t\t// }\n\n\t\t\tif (prevMax == newMax) { // no change in domain so just move the bars\n\t\t\t\tbarg.selectAll('rect')\n\t\t\t\t\t.data(function(d) {return d})\n\t\t\t\tmoveBars(100)\n\t\t\t} else {\n\t\t\t\t// change in domain so change x.domain, move axis, contexual lines, data bars\n\t\t\t\tx.domain([0,newMax])\n\n\t\t\t\tvar transitionTime = 600;\n\n\t\t\t\td3.selectAll('.x.axis')\n\t\t\t\t\t.transition() // transition x axis\n\t\t\t\t\t.duration(transitionTime)\n\t\t\t\t\t.call(xAxis)\n\t\t\t\t\t.on(\"start\", function() {\n\t\t\t\t\t\td3.selectAll(\"line.line\") // transition contextual lines at same time as axis\n\t\t\t\t\t\t\t.transition()\n\t\t\t\t\t\t\t.duration(transitionTime)\n\t\t\t\t\t\t\t.attr(\"x1\", function(d) { return x(d.value)})\n\t\t\t\t\t\t\t.attr(\"x2\", function(d) { return x(d.value)})\n\t\t\t\t\t\t\t.on(\"start\", function() {\n\t\t\t\t\t\t\t\tmoveBars(transitionTime) // transition bars with axis\n\t\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t\t.on(\"end\", function() {\n\t\t\t\t\t\tbarg.selectAll('rect')\n\t\t\t\t\t\t\t.data(function(d) {return d})\n\t\t\t\t\t\tmoveBars(400)\n\t\t\t\t\t})\n\n\t\t\t} // end if else statement\n\n\t\t\tfunction moveBars(t) {\n\t\t\t\tbarg.selectAll('rect')\n\t\t\t\t\t.transition()\n\t\t\t\t\t.duration(t)\n\t\t\t\t\t.attr(\"width\", function(d) { return x(d[1]) - x(d[0]) })\n\t\t\t\t\t.attr(\"x\", function(d) { return x(d[0]) })\n\t\t\t}\n\t\t}", "_updateAutoHighlight(info) {\n const pickingModuleParameters = {\n pickingSelectedColor: info.picked ? info.color : null\n };\n const {\n highlightColor\n } = this.props;\n\n if (info.picked && typeof highlightColor === 'function') {\n pickingModuleParameters.pickingHighlightColor = highlightColor(info);\n }\n\n this.setModuleParameters(pickingModuleParameters); // setModuleParameters does not trigger redraw\n\n this.setNeedsRedraw();\n }", "function updateConditionsTrackChart2(){\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar temp = getDpsActive();\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar myData = \t[{\r\n\t\t\t\t\t\t\t\t\t\ttype: \"bar\",\r\n\t\t\t\t\t\t\t\t\t\tshowInLegend: true,\r\n\t\t\t\t\t\t\t\t\t\tcolor: \"blue\",\r\n\t\t\t\t\t\t\t\t\t\tname: \"Active\",\r\n\t\t\t\t\t\t\t\t\t\tdataPoints: dpsActive\r\n\t\t\t\t\t\t\t\t\t}, {\r\n\t\t\t\t\t\t\t\t\t\ttype: \"bar\",\r\n\t\t\t\t\t\t\t\t\t\tshowInLegend: true,\r\n\t\t\t\t\t\t\t\t\t\tcolor: \"green\",\r\n\t\t\t\t\t\t\t\t\t\tname: \"winCount\",\r\n\t\t\t\t\t\t\t\t\t\tdataPoints: [\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond1.winCount, label: \"cond1\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond2.winCount, label: \"cond2\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond3.winCount, label: \"cond3\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond4.winCount, label: \"cond4\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond5.winCount, label: \"cond5\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond6.winCount, label: \"cond6\"}\r\n\t\t\t\t\t\t\t\t\t\t]\r\n\t\t\t\t\t\t\t\t\t},{\r\n\t\t\t\t\t\t\t\t\t\ttype: \"bar\",\r\n\t\t\t\t\t\t\t\t\t\tshowInLegend: true,\r\n\t\t\t\t\t\t\t\t\t\tcolor: \"red\",\r\n\t\t\t\t\t\t\t\t\t\tname: \"lossCount\",\r\n\t\t\t\t\t\t\t\t\t\tdataPoints: [\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond1.lossCount, label: \"cond1\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond2.lossCount, label: \"cond2\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond3.lossCount, label: \"cond3\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond4.lossCount, label: \"cond4\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond5.lossCount, label: \"cond5\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond6.lossCount, label: \"cond6\"}\r\n\t\t\t\t\t\t\t\t\t\t]\r\n\t\t\t\t\t\t\t\t\t}];\r\n\t\t\t\r\n\t\t\t\t\t// Options to display value on top of bars\r\n\t\t\t\t\tvar myoption = {\r\n\t\t\t\t\t\ttooltips: {\r\n\t\t\t\t\t\t\tenabled: true\r\n\t\t\t\t\t\t},\r\n\t\t\t\t\t\thover: {\r\n\t\t\t\t\t\t\tanimationDuration: 1\r\n\t\t\t\t\t\t},\r\n\t\t\t\t\t\tanimation: {\r\n\t\t\t\t\t\tduration: 1,\r\n\t\t\t\t\t\tonComplete: function () {\r\n\t\t\t\t\t\t\tvar chartInstance = this.chart,\r\n\t\t\t\t\t\t\t\tctx = chartInstance.ctx;\r\n\t\t\t\t\t\t\t\tctx.textAlign = 'center';\r\n\t\t\t\t\t\t\t\tctx.fillStyle = \"rgba(0, 0, 0, 1)\";\r\n\t\t\t\t\t\t\t\tctx.textBaseline = 'bottom';\r\n\t\t\t\t\t\t\t\tthis.data.datasets.forEach(function (dataset, i) {\r\n\t\t\t\t\t\t\t\t\tvar meta = chartInstance.controller.getDatasetMeta(i);\r\n\t\t\t\t\t\t\t\t\tmeta.data.forEach(function (bar, index) {\r\n\t\t\t\t\t\t\t\t\t\tvar data = dataset.data[index];\r\n\t\t\t\t\t\t\t\t\t\tctx.fillText(data, bar._model.x, bar._model.y - 5);\r\n\t\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t};\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\tconditionsTrackChart = new CanvasJS.Chart(\"chartContainer5\", {\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\tbackgroundColor: \"black\",\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\ttitle: {\r\n\t\t\t\t\t\t\t\t\t\ttext: \"Conditions Success Rate\",\r\n\t\t\t\t\t\t\t\t\t\tfontColor: \"white\"\r\n\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\taxisX: {\r\n\t\t\t\t\t\t\t\t\t\t//title: \"Conditions\",\r\n\t\t\t\t\t\t\t\t\t\ttitleFontColor: \"green\",\r\n\t\t\t\t\t\t\t\t\t\tlabelFontColor: \"white\"\r\n\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\taxisY: {\r\n\t\t\t\t\t\t\t\t\t\ttitle: \"Count\",\r\n\t\t\t\t\t\t\t\t\t\ttitleFontColor: \"red\",\r\n\t\t\t\t\t\t\t\t\t\tlabelFontColor: \"white\"\r\n\t\t\t\t\t\t\t\t\t\t//interval: 10\r\n\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\tlegend: {\r\n\t\t\t\t\t\t\t\t\t\tcursor:\"pointer\",\r\n\t\t\t\t\t\t\t\t\t\titemclick : toggleDataSeries\r\n\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\ttoolTip: {\r\n\t\t\t\t\t\t\t\t\t\tshared: true,\r\n\t\t\t\t\t\t\t\t\t\tcontent: toolTipFormatter\r\n\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\tdata: myData, \t// Chart data\r\n\t\t\t\t\t\t\t\t\toptions: myoption \t// Chart Options [This is optional paramenter use to add some extra things in the chart].\r\n\t\t\t\t\t});\r\n\t\t\t\t\t\r\n\t\t\t\t\tconditionsTrackChart.render();\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t }", "function highlighter(selected){\n //return all circles to default\n d3.selectAll(\".market\")\n .attr(\"fill\", defaultColor)\n .attr(\"fill-opacity\", \"0.5\")\n\n //if there is anything selected, highlight it.\n if(selected.length != 0){\n //converted the selected list to a css selector string.\n var selector = \".\" + selected.join('.')\n d3.selectAll(selector)\n .attr(\"fill\", selectColor)\n // .attr(\"r\", 4)\n .attr(\"fill-opacity\", \"1\")\n .moveToFront()\n }\n\n}", "function highlight_heatmap(frames) {\r\n\r\n // Make highlighter_container visible\r\n document.querySelector('#highlighter_container').style.display = \"block\";\r\n\r\n // Find original node\r\n node = $('.highlighter')[0];\r\n\r\n for(i = 0; i<frames.length; i++) {\r\n\r\n // Duplicate highlighter node\r\n copy = node.cloneNode(true);\r\n node.parentNode.insertBefore(copy, node);\r\n\r\n // Make highlighter visible\r\n node.style.display = \"block\";\r\n\r\n start = frames[i][0];\r\n width = frames[i][1];\r\n\r\n node.style.marginLeft = (gridWidth * start) + \"px\";\r\n node.style.width = (gridWidth * width) + \"px\";\r\n\r\n node = copy;\r\n }\r\n}", "function drawUpdateBar(){\n\t\t\td3.select(\"#bar-cover #bar-chart\").selectAll(\"svg\").remove();\n\t\t\tdrawBar();\n\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns whether a platform id represents a web worker app platform.
function isPlatformWorkerApp(platformId) { return platformId === PLATFORM_WORKER_APP_ID; }
[ "function isRBMPlatform (currentPlatform) {\n return currentPlatform == HIGH_DIMENSIONAL_DATA[\"rbm\"].platform ? true : false;\n}", "function platform() {\n\tvar s = process.platform; // \"darwin\", \"freebsd\", \"linux\", \"sunos\" or \"win32\"\n\tif (s == \"darwin\") return \"mac\"; // Darwin contains win, irony\n\telse if (s.starts(\"win\")) return \"windows\"; // Works in case s is \"win64\"\n\telse return \"unix\";\n}", "function isChromeApp() {\n return (typeof chrome !== 'undefined' &&\n typeof chrome.storage !== 'undefined' &&\n typeof chrome.storage.local !== 'undefined');\n}", "function isStandaloneApp() {\n return navigator.standalone;\n }", "function detectPlatform () {\n var type = os.type();\n var arch = os.arch();\n\n if (type === 'Darwin') {\n return 'osx-64';\n }\n\n if (type === 'Windows_NT') {\n return arch == 'x64' ? 'windows-64' : 'windows-32';\n }\n\n if (type === 'Linux') {\n if (arch === 'arm' || arch === 'arm64') {\n return 'linux-armel';\n }\n return arch == 'x64' ? 'linux-64' : 'linux-32';\n }\n\n return null;\n}", "function getPlatformId(){\n return getURLParameter('platform');\n}", "function isUI16() {\n if (!window.top.angular) return false;\n var a = window.top.angular.element('overviewhelp').attr('page-name');\n return a == 'ui16' || a == 'helsinki';\n }", "isOnServer() {\n return !(typeof window !== 'undefined' && window.document);\n }", "function matchPlatform(names, info = getInfo()) {\n if (info.type === OSType.Unknown) {\n return false;\n }\n\n names = names.trim();\n\n if (names === '') {\n return true;\n }\n\n for (let name of names.split('|')) {\n name = name.trim();\n\n if (matchOnePlatform(name, info)) {\n return true;\n }\n }\n\n return false;\n}", "_isNativePlatform() {\n if ((this._isIOS() || this._isAndroid()) && this.config.enableNative) {\n return true;\n } else {\n return false;\n }\n }", "function is_predef_app(name) {\n var rule = get_predefined_rules(name);\n\n if(rule.length) {\n rule = rule.split(\"\\x02\");\n if(rule[_category] == CATEGORY_APP) {\n return true;\n }\n }\n return false;\n}", "function applePlatformName(targetOSList, platformType) {\n return applePlatformDirectoryName(targetOSList, platformType).toLowerCase();\n}", "function IsPC() {\n var userAgentInfo = navigator.userAgent\n var Agents = [\"Android\", \"iPhone\", \"SymbianOS\", \"Windows Phone\", \"iPad\", \"iPod\"]\n var devType = 'PC'\n for (var v = 0; v < Agents.length; v++) {\n if (userAgentInfo.indexOf(Agents[v]) > 0) {\n // Determine the system platform used by the mobile end of the user\n if (userAgentInfo.indexOf('Android') > -1 || userAgentInfo.indexOf('Linux') > -1) {\n //Android mobile phone\n devType = 'Android'\n } else if (userAgentInfo.indexOf('iPhone') > -1) {\n //Apple iPhone\n devType = 'iPhone'\n } else if (userAgentInfo.indexOf('Windows Phone') > -1) {\n //winphone\n devType = 'winphone'\n } else if (userAgentInfo.indexOf('iPad') > -1) {\n //Pad\n devType = 'iPad'\n }\n break;\n }\n }\n docEl.setAttribute('data-dev-type', devType)\n }", "function bouncer_getPlatformForMirror() {\n\tvar a = getArray();\n\tif ( navigator.platform != null ) {\n\t\tif ( navigator.platform.indexOf( \"Win32\" ) != -1 ) {\n\t\t\treturn ( a[3] == 'y' ) ? \"winwjre\" : \"win\";\n\t\t} else if ( navigator.platform.indexOf( \"Win64\" ) != -1 ) {\n\t\t\treturn ( a[3] == 'y' ) ? \"winwjre\" : \"win\";\n\t\t} else if ( navigator.platform.indexOf( \"Win\" ) != -1 ) {\n\t\t\treturn ( a[3] == 'y' ) ? \"winwjre\" : \"win\";\n\t\t} else if ( navigator.platform.indexOf( \"Linux\" ) != -1 ) {\n\t\t\tif ( navigator.userAgent != null ) {\n\t\t\t\tif ( navigator.userAgent.toLowerCase().indexOf( \"debian\" ) != -1 || navigator.userAgent.toLowerCase().indexOf( \"ubuntu\" ) != -1 ) {\n\t\t\t\t\treturn \"linuxinteldeb\";\n\t\t\t\t} else {\n\t\t\t\t\treturn ( a[3] == 'y' ) ? \"linuxintelwjre\" : \"linuxintel\";\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn ( a[3] == 'y' ) ? \"linuxintelwjre\" : \"linuxintel\";\n\t\t\t}\n\t\t} else if ( navigator.platform.indexOf( \"SunOS i86pc\" ) != -1 ) {\n\t\t\treturn ( a[3] == 'y' ) ? \"solarisx86wjre\" : \"solarisx86\";\n\t\t} else if ( navigator.platform.indexOf( \"SunOS sun4u\" ) != -1 ) {\n\t\t\treturn ( a[3] == 'y' ) ? \"solarissparcwjre\" : \"solarissparc\";\n\t\t} else if ( navigator.platform.indexOf( \"SunOS\" ) != -1 ) {\n\t\t\treturn ( a[3] == 'y' ) ? \"solarissparcwjre\" : \"solarissparc\";\n\t\t} else if ( navigator.platform.indexOf( \"Mac\" ) != -1 && navigator.platform.indexOf( \"Intel\" ) != -1 ) {\n\t\t\treturn \"macosxintel\";\n\t\t} else if ( navigator.platform.indexOf( \"Mac\" ) != -1 && navigator.platform.indexOf( \"PPC\" ) != -1 ) {\n\t\t\treturn \"macosxppc\";\n\t\t} else if ( navigator.platform.indexOf( \"Mac\" ) != -1 ) {\n\t\t\treturn \"macosxintel\";\n\t\t} else {\n\t\t\t// return ( a[3] == 'y' ) ? \"winwjre\" : \"win\";\n\t\t\treturn navigator.platform;\n\t\t}\n\t}\n\treturn ( a[3] == 'y' ) ? \"winwjre\" : \"win\";\n}", "function toDesktop(req){\n return req.cookies.desktop_interface == 'true';\n}", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === JavaAppLayer.__pulumiType;\n }", "function checkWebapiHasPermission(){\n if (!(\"Notification\" in window)) {\n return false\n }\n // Let's check whether notification permissions have already been granted\n else if (Notification.permission === \"granted\") {\n webapiHasPermission = true;\n } else if (Notification.permission === \"denied\") {\n webapiHasPermission = false;\n } else if (Notification.permission === \"default\") {\n // the user has not chosen anything, and the permission could be requested\n webapiHasPermission = \"default\";\n }\n\n return webapiHasPermission\n}", "function chkMobile() {\r\n\treturn /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);\r\n}", "async checkForAppUpdate () {\n this.checkForAppUpdateRunner = true\n let res = false\n if (process.env.MODE === 'pwa') {\n res = await this.__checkPWAUpdate()\n } else {\n console.error('appUpdate.js CheckForUpdate NotImplemented for this platfomr')\n }\n this.checkForAppUpdateRunner = false\n return res\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Host.__pulumiType;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if username meets the length requirement.
function validUsername(username) { return (username.trim().length) >= 3; }
[ "function passwordLongEnough(password){\n if(password.length>=15)return true \n return false\n}", "function strLength(x){\n if (typeof x === \"string\" && x.length >= 8){\n return true;\n }\n return false;\n }", "function validatePassword(input){\n if(input.length >= passwordLength){\n return true;\n }\n console.log(\"Password length must be 4 or more characters.\");\n return false;\n}", "function validName(input) {\n return input.length > 0\n }", "function usernameValidation(str) {\n const regex = /[^A-Za-z0-9\\_]/;\n return (\n str.length >= 4 &&\n str.length <= 25 &&\n str[0].match(/[A-z]/) &&\n !regex.test(str) &&\n str[str.length - 1] !== \"_\"\n );\n}", "validatePassword(password) {\n if (/^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{6,20}$/.test(password)) { return true }\n return false\n }", "function isStringOfLength( str, len )\n{\n\treturn ( typeof str === \"string\" && str.length === len );\n}", "function isCorrectLengthExtensions(s) {\n return isCorrectLength(s,50);\n}", "function sameLength(string1,string2){\n if(string1.length===string2.length)return true\n return false\n}", "function isPasswordValid() {\n return validLength(8, 100, $password, 'password').bool && regexCheck($password, 'password').bool;\n}", "function validate63(string) {\n return string != '' && string.length < 64;\n}", "function validUsername() {\n var userName = prompt(\"Enter username\");\n var len = userName.split(\"\");\n for(i = 0; i < len.length; i++) {\n if( (userName.slice(i,i+1) == \"@\") || (userName.slice(i,i+1) == \".\") || (userName.slice(i,i+1) == \"!\") ) {\n document.write(\"Invalid\");\n break;\n }\n }\n\n}", "isStringLengthValid (string) {\n // Check if string is undefined or not\n if (string) {\n // If length is bigger than 0 return true\n if (string.length > 0) {\n return true\n }\n }\n // If not, return false\n return false\n }", "function checkLength(len, ele) {\n var fieldLength = ele.value.length;\n if(fieldLength <= len){\n return true;\n }\n else\n {\n var str = ele.value;\n str = str.substring(0, str.length - 1);\n ele.value = str;\n }\n}", "function hasLength (data, value) {\n return assigned(data) && data.length === value;\n }", "function passwordLengthPrompt() {\n passwordLength = parseInt(prompt(\"How long would you like your password to be (Min: 8 Max: 128)\"));\n if (passwordLength === null || passwordLength === \"\" || passwordLength < 8 || 128 < passwordLength || !passwordLength) {\n passwordLengthPrompt();\n } \n lowerCaseLettersPrompt();\n}", "function customerHasValidLastName (cust) {\n return typeof cust === 'string' && cust !== '' && cust.length < 501;\n}", "function longWord (input) {\n return input.some(x => x.length > 10);\n}", "function VerificationPwd() {\n const pwd = document.getElementById(\"pwd\");\n const LMINI = 8; // DP LMINI = longueur minimale du mot de passe\n\n //DP si le mot de passe comporte moins de 8 lettres alors erreur\n if (pwd.value.length < LMINI) {\n console.log(\"longueur pwd NOK\", pwd.value.length);\n return false;\n } else {\n console.log(\"longueur pwd OK\", pwd.value.length);\n return true;\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a filtered array of all projects with a tag
projectsWithTag(tag) { return this.projects.filter((p) => p.tags.includes(tag)); }
[ "function relevantProjects(){\n let filteredProjects = [];\n projects.forEach(function (project){\n let include = false;\n if (Object.keys(filter).length === 0){\n include = true;\n }\n else{\n Object.keys(filter).forEach(function (f){\n\n })\n }\n if (include){\n filteredProjects.push(project);\n }\n })\n return filteredProjects;\n}", "async function getProjects(tags) {\n return knex('tags')\n .whereIn('tag', tags)\n .select('project_id')\n .then((results) => results.map((row) => row.project_id));\n }", "filterEventListByTags(filter_tags = []) {\n let filtered_events = [];\n let final_filtered_list = [];\n\n for(let event_cycler = 0; event_cycler < this.events.length; event_cycler++)\n {\n let tags_matched = 0;\n for(let tag_cycler = 0; tag_cycler < filter_tags.length; tag_cycler++)\n {\n if(this.events[event_cycler].tags.includes(filter_tags[tag_cycler])) {\n tags_matched += 1;\n }\n }\n\n if(tags_matched > 0) {\n filtered_events.push([tags_matched,this.events[event_cycler]]);\n }\n }\n\n //sorts by most relevant\n filtered_events.sort(function(first_ele, second_ele) {\n return second_ele[0] - first_ele[0];\n });\n\n //strips numbering\n for(let event_cycler = 0; event_cycler < filtered_events.length; event_cycler++)\n {\n filtered_events[event_cycler] = filtered_events[event_cycler][1];\n }\n\n return filtered_events;\n }", "function filterPosts(tag) {\n $('#posts-list .post').each(function() {\n var post = $(this);\n var tags = getTags(post);\n if(findOne(tagSearchFilters, tags)) {\n post.show();\n } else {\n post.hide();\n }\n });\n }", "function scopedProjects(user, projects) {\n if (user.role === ROLE.ADMIN) return projects;\n return projects.filter((project) => project.userId === user.id);\n}", "function filteredMoviesMock(tag){\n return moviesMock.filter(movie => movie.tags.includes(tag))\n}", "function getFiltered( visible, onlyNames ) {\n\t\tvar filteredTags;\n\t\t\n\t\t// Default to returning only visible tags.\n\t\tvisible = ( visible !== undefined ? visible : true );\n\t\t\n\t\t// Filter array of tags according to tag visibility.\n\t\tfilteredTags = tags.filter( function( tag ) {\n\t\t\treturn tag.isVisible() === visible;\n\t\t} );\n\t\t\n\t\t// Return only names if requested.\n\t\tif ( onlyNames === true ) {\n\t\t\t// Return array of only tags of tags array.\n\t\t\treturn filteredTags.map( function( tag ) {\n\t\t\t\treturn tag.tag();\n\t\t\t} );\n\t\t}\n\t\t\n\t\t// Return filtered array.\n\t\treturn filteredTags;\n\t}", "findByTagIndex(tag) {\n let tagNames;\n // A flag to control if a union of matched bindings should be created\n let union = false;\n if (tag instanceof RegExp) {\n // For wildcard/regexp, a union of matched bindings is desired\n union = true;\n // Find all matching tag names\n tagNames = [];\n for (const t of this.bindingsIndexedByTag.keys()) {\n if (tag.test(t)) {\n tagNames.push(t);\n }\n }\n }\n else if (typeof tag === 'string') {\n tagNames = [tag];\n }\n else {\n tagNames = Object.keys(tag);\n }\n let filter;\n let bindings;\n for (const t of tagNames) {\n const bindingsByTag = this.bindingsIndexedByTag.get(t);\n if (bindingsByTag == null)\n break; // One of the tags is not found\n filter = filter !== null && filter !== void 0 ? filter : (0, binding_filter_1.filterByTag)(tag);\n const matched = new Set(Array.from(bindingsByTag).filter(filter));\n if (!union && matched.size === 0)\n break; // One of the tag name/value is not found\n if (bindings == null) {\n // First set of bindings matching the tag\n bindings = matched;\n }\n else {\n if (union) {\n matched.forEach(b => bindings === null || bindings === void 0 ? void 0 : bindings.add(b));\n }\n else {\n // Now need to find intersected bindings against visited tags\n const intersection = new Set();\n bindings.forEach(b => {\n if (matched.has(b)) {\n intersection.add(b);\n }\n });\n bindings = intersection;\n }\n if (!union && bindings.size === 0)\n break;\n }\n }\n return bindings == null ? [] : Array.from(bindings);\n }", "function filterByColor(tags) {\n return tags == 'brown';\n }", "function getAllprojects(){\n\n}", "filterJobs(jobs, filters = {}) {\n const { tag, name } = filters;\n const nameRegex = name && new RegExp(`(^| )${name}( |$)`);\n return jobs.filter(job => {\n if (tag && (!job.tags.length || job.tags.indexOf(tag) === -1)) {\n return false;\n }\n if (nameRegex && (!job.name || !nameRegex.test(job.name || ''))) {\n return false;\n }\n return true;\n });\n }", "getSeriesForSelectedTag(selectedTag) {\n return this.data.filter(series => series.tags.indexOf(selectedTag) > -1)\n }", "function filterByDebut (year) {\n let arr = []\n for (const i of players)\n {\n if (i.debut == year)\n {\n arr.push(i)\n } \n }\n return arr\n}", "function filterJobsArray(arr) {\n let tempJobs = arr.filter(function(job) {\n let flag = true;\n \n if (jobFilter.role !== \"\" && jobFilter.role !== job.role) {\n flag = false;\n }\n\n if (jobFilter.level !== \"\" && jobFilter.level !== job.level) {\n flag = false;\n }\n\n jobFilter.languages.forEach(function(lang) {\n if (!job.languages.includes(lang)) {\n flag = false;\n }\n });\n\n jobFilter.tools.forEach(function(tool) {\n if (!job.tools.includes(tool)) {\n flag = false;\n }\n })\n\n if(flag === true) {\n return job;\n }\n });\n\n return tempJobs;\n}", "async function removeForProject(projectId) {\n await knex('tags').where({ project_id: projectId }).del();\n }", "function getTagsForDate(tags, date) {\n var time = date.getTime();\n var dateTags = [];\n for (var i = 0, len = tags.length; i < len; i++) {\n var tag = tags[i];\n if (sameDate(date, tag.start) || tag.end && sameDate(date, tag.end) ||\n tag.start.getTime() < time && tag.end === undefined ||\n tag.start.getTime() < time && time < tag.end.getTime()) {\n\n dateTags.push(tag);\n }\n }\n return dateTags;\n }", "function projectNames (array) {\n let nameArray = [];\n array.forEach( element => {\n nameArray.push(element.name)\n })\n return nameArray;\n}", "async function updateForProject(projectId, tags) {\n // We remove existent tags for that project\n removeForProject(projectId);\n\n if (!tags.length) return;\n\n // We add new ones\n const rows = tags.map((tag) => ({\n tag,\n project_id: projectId\n }));\n\n await knex('tags').insert(rows);\n }", "tagInSourceList(tag) {\n\n return this.props.sourceTags.find((source) => {\n\n return source.label === tag;\n\n }) ? true : false;\n\n }", "function TagFilter(tagName, excludeTag) {\n this.tagName = tagName;\n this.excludeTag = excludeTag === true;\n this.attrsMap = {};\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change task property, save settings and reload list Params: taskIndex index of array element property name of key to change value
changeTaskProperty(taskIndex, property, value = '') { if (taskIndex >= this.taskList.length) { throw Error(`Index ${taskIndex} doesn't exist!`); } this.taskList[taskIndex][property] = value; this.renderList(); this.saveStore(this.config.name, JSON.stringify(this.taskList)); }
[ "function updateTasksBackend() {\n let stringTasks = JSON.stringify(tasks);\n backend.setItem('test_tasks_board_jklaf', stringTasks);\n}", "function moveTask(index, task, value) {\n $scope.schedule[$scope.currentUserId].splice(index, 1);\n if (value == 1) {\n $scope.schedule[$scope.currentUserId].splice(index - 1, 0, task);\n } else {\n $scope.schedule[$scope.currentUserId].splice(index + 1, 0, task);\n }\n saveUserSchedule();\n }", "set task (value) {\n if (this._mem.work === undefined) {\n this._mem.work = {};\n }\n this._mem.work.task = value;\n }", "addAtIndex(task, index) {\n if(index === 0) {\n this.addToFront(task);\n } else if(index === this._taskArr.length) {\n this.addToBack(task);\n } else if(index < this._taskArr.length) {\n this._taskArr.splice(index,0, task);\n this.adjustTaskStartTime(index + 1);\n }\n }", "function changeImportance(i) {\n alert(\"Importance has been changed, task will be relocated!\");\n if (allTasks[i].importance == \"High\") {\n allTasks[i].importance = \"Low\";\n } else if (allTasks[i].importance == \"Low\") {\n allTasks[i].importance = \"High\";\n }\n reloadAllTasks();\n}", "function setStateProp(index, {key, value}) {\n\t\tlet state = Calc.getState();\n\t\tstate.expressions.list[index][key] = value;\n\t\tCalc.setState(state, {allowUndo: true});\n\t}", "function changeTodo(position, newValue){\n// todos[0] = 'some new value';\ntodos[position] = newValue;\ndisplayTodos();\n}", "function upDateTaskPhaseInLocalStorage(taskToUpdate, phase) {\r\n let LocalStorageTaskArray = getLocalStorage(\"task\");\r\n let taskTitle = document.getElementById(taskToUpdate).firstElementChild.innerHTML;\r\n let index = LocalStorageTaskArray.findIndex(obj => obj.name === taskTitle);\r\n LocalStorageTaskArray[index].phase = phase;\r\n setLocalStorage(\"task\", LocalStorageTaskArray);\r\n}", "function updateProjectTaskHours() {\n var error = checkControlValues();\n if (error != \"\") {\n Browser.msgBox(\"ERROR:Values in the Controls sheet have not been set. Please fix the following error:\\n \" + error);\n return;\n }\n\n var successCount = 0;\n\n var result = JSON.parse(getProjectTasks());\n\n var tasks = [];\n // Get the ID's for the tasks we're interested in.\n for (var i = 0; i < result.length; i++) {\n // Get tasks that do not have hours assigned.\n if (result[i].task_assignment.budget == null || result[i].task_assignment.budget == 0) {\n tasks.push([result[i].task_assignment.id, result[i].task_assignment.task_id]);\n }\n }\n\n var filteredTasks = [];\n // Get the names for the tasks we're interested in.\n for (var i = 0; i < tasks.length; i++) {\n var taskDetails = JSON.parse(getTaskDetails(tasks[i][1]));\n // Only look at non-default tasks.\n if (taskDetails.task.is_default == false) {\n filteredTasks.push([tasks[i][0], tasks[i][1], taskDetails.task.name]);\n }\n }\n\n var toUpload = [];\n var hours = scanSheet(false);\n // Loop through the sheet, get hours for the tasks we've filtered.\n for (var i = 0; i < hours.length; i++) {\n for (var j = 0; j < filteredTasks.length; j++) {\n // If the names match\n if (filteredTasks[j][2] == hours[i][0]) {\n toUpload.push([filteredTasks[j][0], hours[i][1]]);\n }\n }\n }\n\n // Upload new task budgets for tasks which do not already have budgets.\n for (i = 0; i < toUpload.length; i++) {\n var response = putProjectTaskHours(toUpload[i][0], toUpload[i][1]);\n successCount++;\n }\n\n Browser.msgBox(successCount + \" Harvest tasks had hours added. \");\n}", "updateTask(e) {\n const taskValue = e.target.value;\n const keyForTask = Math.round(Math.random() * Math.floor(999999));\n\n const updatedTask = {};\n \n updatedTask[keyForTask] = taskValue; \n\n this.setState({\n [e.target.name]: updatedTask\n });\n\n }", "_store (tasks) {\n this.onListChanged(tasks);\n localStorage.setItem('tasks', JSON.stringify(tasks));\n }", "get(index) {\n return this._taskArr[index];\n }", "function EditTaskProperties(){\n \n //Show values\n var arrDuration = GetTimeArrayFromMinutes(_curSelectedTask.duration);\n $(\"#txtTaskNameEdit\").html(_curSelectedTask.name);\n $(\"#txtTaskDescriptionEdit\").html(_curSelectedTask.description);\n\n $(\"#txtTaskDurationEditDays\").val(arrDuration[0]);\n $(\"#txtTaskDurationEditHours\").val(arrDuration[1]);\n $(\"#txtTaskDurationEditMinutes\").val(arrDuration[2]);\n\n //Show panel\n $(\"#taskPropertiesRead\").css(\"display\", \"none\");\n $(\"#taskPropertiesEdit\").css(\"display\", \"block\"); \n}", "function changeToDo(position, newVal) {\r\ntoDos[position] = newVal;\r\ndisplayToDos();\r\n}", "update(_task) {\n const { id, task, date, process } = _task\n let sql = `UPDATE tasks\n SET task = ?,\n date = ?,\n process = ?\n WHERE id = ?`;\n return this.dao.run(sql, [task, date, process, id])\n }", "copyTaskArr(taskList) {\n this._taskArr = [];\n for(let i = 0; i < taskList.length(); i++) {\n this._taskArr[i] = Task.copyTask(taskList.taskArr[i]);\n }\n }", "function task_update_todoist(task_name, project_id, todoist_api_token) {\n todoist_api_token = todoist_api_token || 'a14f98a6b546b044dbb84bcd8eee47fbe3788671'\n return todoist_add_tasks_ajax(todoist_api_token, {\n \"content\": task_name,\n \"project_id\": project_id\n }, 'item_update')\n}", "onTaskUpdated(task, updatedData) {\n const tasks = this.tasks.slice();\n const oldTask = tasks.splice(tasks.indexOf(task), 1, Object.assign({}, task, updatedData))[0];\n this.tasksUpdated.next(tasks);\n // Creating an activity log for the updated task\n this.activityService.logActivity(\n this.activitySubject.id,\n 'tasks',\n 'A task was updated',\n `The task \"${limitWithEllipsis(oldTask.title, 30)}\" was updated on #${this.activitySubject.document.data._id}.`\n );\n }", "adjustTaskStartTime(index) {\n if(index < this._taskArr.length && index > 0) {\n let curr = this._taskArr[index];\n let prev = this._taskArr[index - 1];\n if(prev.endTime.compareTo(curr.endTime) >= 0) {\n this.removeAtIndex(index);\n } else {\n curr.setStartTime(prev.endTime);\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Refreshes Highest Possible GPA
function refreshHighestGPA() { var maxSemester = $("#highest_GPA_semester > select").val(); $("#highest_gpa").html(formatGPA(user.highestGPA(maxSemester), 2)); }
[ "async updateBestSolutionAndFitness() {\n this.bestSolution = this.population[0];\n this.bestFitness = this.fitness_values[0];\n }", "function calcBasePop(useMaxFuel){\n //fuel and tauntimps\n var eff = game.generatorUpgrades[\"Efficiency\"].upgrades;\n var fuelCapacity = 3 + game.generatorUpgrades[\"Capacity\"].baseIncrease * game.generatorUpgrades[\"Capacity\"].upgrades;\n var supMax = 0.2 + 0.02 * game.generatorUpgrades[\"Supply\"].upgrades;\n var OCEff = 1 - game.generatorUpgrades[\"Overclocker\"].modifier;\n var magmaCells = game.talents.magmaFlow.purchased ? 18 : 16;\n var burn = game.permanentGeneratorUpgrades.Slowburn.owned ? 0.4 : 0.5;\n \n var popTick = Math.floor(Math.sqrt(fuelCapacity)* 500000000 * (1 + 0.1*eff) * OCEff);\n var endZone = (autoTrimpSettings.APValueBoxes.amalGoal > 0 ? autoTrimpSettings.APValueBoxes.amalZone : autoTrimpSettings.APValueBoxes.maxZone);\n \n var maxPopFound = 0;\n var maxPopFuelStart = 230;\n \n AutoPerks.fuelStartZone = 230;\n \n for(AutoPerks.fuelStartZone = 230; AutoPerks.fuelStartZone <= endZone - AutoPerks.fuelMaxZones + 1; AutoPerks.fuelStartZone++){\n AutoPerks.fuelEndZone = Math.min((autoTrimpSettings.APValueBoxes.amalGoal > 0 ? autoTrimpSettings.APValueBoxes.amalZone : autoTrimpSettings.APValueBoxes.maxZone), AutoPerks.fuelStartZone + AutoPerks.fuelMaxZones - 1);\n \n var pop = AutoPerks.startingPop;\n var currFuel = 0;\n for (var i = AutoPerks.fuelStartZone; i < endZone; i++){\n pop *= Math.pow(1.003, 2.97); //tauntimp average increase\n\n if(i <= AutoPerks.fuelEndZone){\n var fuelFromMagmaCell = Math.min(0.2 + (i-230) * 0.01, supMax);\n var fuelFromZone = magmaCells * fuelFromMagmaCell;\n currFuel += fuelFromZone;\n if(currFuel > 2*fuelCapacity){\n var ticks = Math.ceil((currFuel - 2*fuelCapacity) / burn);\n pop += ticks * popTick;\n currFuel -= burn * ticks;\n }\n }\n }\n if(maxPopFound < pop){\n maxPopFound = pop;\n maxPopFuelStart = AutoPerks.fuelStartZone;\n }\n }\n \n AutoPerks.totalMi = (game.talents.magmaFlow.purchased ? 18 : 16) * (autoTrimpSettings.APValueBoxes.maxZone - 230 - AutoPerks.fuelMaxZones);\n AutoPerks.startingFuelArr[AutoPerks.fuelMaxZones] = maxPopFuelStart;\n return Math.floor(maxPopFound * AutoPerks.DailyHousingMult);\n}", "function calcBasePopMaintain(){\n var eff = game.generatorUpgrades[\"Efficiency\"].upgrades;\n var fuelCapacity = 3 + game.generatorUpgrades[\"Capacity\"].baseIncrease * game.generatorUpgrades[\"Capacity\"].upgrades;\n var supMax = 0.2 + 0.02 * game.generatorUpgrades[\"Supply\"].upgrades;\n var OCEff = 1 - game.generatorUpgrades[\"Overclocker\"].modifier;\n var magmaCells = (game.talents.magmaFlow.purchased ? 18 : 16);\n var burn = game.permanentGeneratorUpgrades.Slowburn.owned ? 0.4 : 0.5;\n \n var currCarp1Bonus = Math.pow(1.1, game.portal[\"Carpentry\"].level);\n var currCarp2Bonus = 1 + 0.0025 * game.portal[\"Carpentry_II\"].level;\n var basePop = trimpsRealMax / currCarp1Bonus / currCarp2Bonus;\n var currFuel = game.global.magmaFuel;\n \n var popTick = Math.floor(Math.sqrt(fuelCapacity)* 500000000 * (1 + 0.1*eff) * OCEff);\n \n for (var i = game.global.world; i < autoTrimpSettings.APValueBoxes.maxZone; i++){\n basePop *= 1.009; //tauntimp average increase \n var fuelFromMagmaCell = Math.min(0.2 + (i-230) * 0.01, supMax);\n var fuelFromZone = magmaCells * fuelFromMagmaCell;\n currFuel += fuelFromZone;\n if(currFuel > 2*fuelCapacity){\n var ticks = Math.ceil((currFuel - 2*fuelCapacity) / burn);\n basePop += ticks * popTick;\n currFuel -= burn * ticks;\n }\n }\n \n return Math.floor(basePop);\n}", "function getGPA(score) {\n return Math.min(score / 3.0, 4.0);\n}", "evaluate(){\n let fastest = lifespan;\n for(let i = 0; i < this.popsize; i++){\n this.rockets[i].calcFitness();\n if(this.rockets[i].framesToFinish < fastest){\n fastest = this.rockets[i].framesToFinish\n }\n console.log(fastest)\n fastestRocketGen = fastest;\n if(fastestRocketGen < fastestRocketAll){\n fastestRocketAll = fastestRocketGen\n }\n }\n for(let i = 0; i < this.popsize;i++){\n for(let j = 0; j < this.popsize - 1;j++){\n if(this.rockets[j].fitness > this.rockets[j + 1].fitness){\n let temp = this.rockets[j];\n this.rockets[j] = this.rockets[j + 1];\n this.rockets[j + 1] = temp;\n }\n }\n }\n }", "gpaCalc() {\r\n let totalPoints = 0;\r\n let totalUnits = 0;\r\n const macPoints = {\"A+\": 12, \"A\": 11, \"A-\": 10,\r\n \"B+\": 9, \"B\": 8, \"B-\": 7,\r\n \"C+\": 6, \"C\": 5, \"C-\": 4,\r\n \"D+\": 3, \"D\": 2, \"D-\": 1,\r\n \"F\": 0};\r\n\r\n if (this.itemList.length > 0) {\r\n this.itemList.forEach(function(entry) {\r\n let thisCourseGrade;\r\n\r\n if (Object.keys(macPoints).includes(entry.grade)) {\r\n thisCourseGrade = macPoints[entry.grade];\r\n } else {\r\n thisCourseGrade = parseInt(entry.grade);\r\n }\r\n\r\n totalPoints += (thisCourseGrade * entry.units);\r\n totalUnits += entry.units;\r\n })\r\n }\r\n\r\n const totalGPA = totalPoints / totalUnits;\r\n return totalGPA.toFixed(1);\r\n }", "function mostFavorableGrid(){\r\n var bestGrid = 0;\r\n var index = 0;\r\n for(var i = 0; i < fitness.length; i++){\r\n if(fitness[i] > bestGrid){\r\n bestGrid = fitness[i];\r\n index = i;\r\n }\r\n }\r\n //console.log(\"Most favorable grid is grid:\" + index);\r\n\tdocument.getElementById(\"favGrid\").innerHTML = \"Grid #\" + index;\r\n return index;\r\n}", "fuelUp(gallons) {\n this.fuelLevel = this.fuelLevel + gallons\n\n //ensures no matter how much gas you add it can be more than the tank's capacity\n if(this.fuelLevel > this.gasTankCapacity) {\n this.fuelLevel = this.gasTankCapacity\n } else if(this.fuelLevel < 0) { // siphon off gas limit\n this.fuelLevel = 0\n }\n }", "function evaluateNextGenome() {\n //increment index in genome array\n currentGenome++;\n //If there is none, evolves the population.\n if (currentGenome == genomes.length) {\n evolve();\n }\n //load current gamestate\n loadState(roundState);\n //reset moves taken\n movesTaken = 0;\n //and make the next move\n makeNextMove();\n }", "async sortSolutionsDescending() {\n var sortedIndexes = Array.from(this.population.keys())\n .sort((a, b) => this.fitness_values[a] < this.fitness_values[b] ? -1 : (this.fitness_values[b] < this.fitness_values[a]) | 0)\n .reverse();\n\n var sortedPopulation = []\n for (let idx of sortedIndexes) {\n sortedPopulation.push(this.population[idx])\n }\n\n this.population = sortedPopulation;\n\n // sort fitness values descending\n this.fitness_values.sort((a, b) => b - a)\n }", "function popgear(gearList) {\n gearUI = new GearUI(document.getElementById('gear'), gearList);\n\n var importVal = location.hash.substr(1);\n\n if (importVal.length > 0) {\n importGear(importVal);\n } else {\n var glist = defaultGear;\n var gearCache = localStorage.getItem('cachedGear.v2');\n if (gearCache && gearCache.length > 0) {\n var parsedGear = JSON.parse(gearCache);\n if (parsedGear.length > 0) {\n glist = parsedGear;\n }\n }\n gearUI.updateEquipped(glist);\n }\n\n var currentGear = gearUI.currentGear;\n\n gearUI.addChangeListener((item, slot) => {\n updateGearStats(gearUI.currentGear);\n });\n updateGearStats(currentGear)\n\n var simlogrun = document.getElementById(\"simlogrun\");\n simlogrun.addEventListener(\"click\", (event) => {\n runSimWithLogs(toGearSpec(gearUI.currentGear));\n });\n\n var simrunbut = document.getElementById(\"simrunbut\");\n simrunbut.addEventListener(\"click\", (event) => {\n runSim(toGearSpec(gearUI.currentGear));\n });\n\n var rotationRunButton = document.getElementById(\"rotationRunButton\");\n rotationRunButton.addEventListener(\"click\", (event) => {\n runRotationSim(toGearSpec(gearUI.currentGear));\n });\n\n var caclweights = document.getElementById(\"calcstatweight\");\n caclweights.addEventListener(\"click\", (event) => {\n calcStatWeights(toGearSpec(gearUI.currentGear));\n });\n\n var inputs = document.querySelectorAll(\"#buffs input\");\n for (var i = 0; i < inputs.length; i++) {\n var inp = inputs[i];\n inp.addEventListener(\"input\", (e) => {\n updateGearStats(gearUI.currentGear);\n });\n }\n var selects = document.querySelectorAll(\"#buffs select\");\n for (var i = 0; i < selects.length; i++) {\n var sel = selects[i];\n sel.addEventListener(\"change\", (e) => {\n updateGearStats(gearUI.currentGear);\n })\n }\n\n updateGearSetList();\n\n loadSettings(); // load phase/quality settings\n\n // This will perform all the setup needed to use the stored settings from above.\n changePhaseFilter({ target: document.getElementById(\"phasesel\") });\n changeQualityFilter({ target: document.getElementById(\"qualsel\") })\n\n\n window.addEventListener('hashchange', () => {\n var importVal = location.hash;\n if (importVal.length > 0) {\n importVal = importVal.substr(1);\n if (importVal != currentHash) {\n currentHash = importVal;\n importGear(importVal);\n }\n }\n });\n}", "function increaseFinalVote(value)\n {\n setGame(\"final\");\n setVotes(true);\n }", "function compute_oBA_dis_mg(ibu, hopIdx, currVolume) {\n var oBA_addition = 0.0;\n var oBA_percent = 0.0;\n\n oBA_percent = 1.0 - ibu.add[hopIdx].freshnessFactor.value;\n oBA_addition = oBA_percent * SMPH.oBA_boilFactor *\n (ibu.add[hopIdx].BA.value / 100.0) *\n ibu.add[hopIdx].weight.value * 1000.0;\n\n // note: solubility limit of oBA is large enough that all is dissolved\n ibu.add[hopIdx].oBA_dis_mg = oBA_addition;\n if (SMPH.verbose > 4) {\n console.log(\" hop addition \" + hopIdx + \": [oBA] = \" +\n (ibu.add[hopIdx].oBA_dis_mg/currVolume).toFixed(4) +\n \" ppm from (\" + oBA_percent.toFixed(4) + \" * \" +\n SMPH.oBA_boilFactor +\n \" * \" + (ibu.add[hopIdx].BA.value/100.0).toFixed(4) + \" * \" +\n ibu.add[hopIdx].weight.value.toFixed(3) + \" * 1000.0 / \" +\n currVolume.toFixed(4));\n }\n\n return;\n}", "recharge(additional_mp){\n\t\tthis.stats.mp.current = Math.max(\n\t\t\tMath.min(\n\t\t\t\tthis.stats.mp.current + additional_mp,\n\t\t\t\tthis.stats.mp.max\n\t\t\t),\n\t\t\t0\n\t\t);\n\n\t\treturn this;\n\t}", "findMax() { \n if(this.isEmpty()) return Number.MIN_VALUE;\n return this.heap[0];\n }", "evaluatePopulationFitness() {\n\t\tfor (let i = 0; i < this.chromosomes.length; i++) {\n\t\t\tthis.updateFitness(this.chromosomes[i]);\n\t\t}\n\t}", "bestFirstSearch(){\n var heapOpen = new SortedList(comparer);\n var heapClosed = new SortedList(comparer);\n heapOpen.add(this.frontier);\n while(heapOpen.getCount() > 0){\n ITERATIONS++;\n var V = heapOpen.popFirst();\n MINPRIORITY = V.priority;\n V.generateStates();\n redraw();\n if(V.hash == 87654321){\n this.endPoint = V;\n break;\n }\n for(var i = 0 ; i < V.children.length; i++){\n V.children[i].priority = V.children[i].manhattanHeuristic() + V.children[i].outOfPlaceTilesHeuristic(); \n if(hasBetter(heapOpen,V.children[i].hash, V.children[i].priority)){\n continue;\n }\n if(hasBetter(heapClosed,V.children[i].hash, V.children[i].priority)){\n continue;\n }\n heapOpen.add(V.children[i]);\n }\n heapClosed.add(V);\n }\n heapOpen.clear();\n heapClosed.clear();\n return this.createSolution(this.endPoint);\n }", "function levelUpLeech(){\n if(protein >= upgradeLeechCost)\n {\n protein -= upgradeLeechCost;\n levelLeech += 1;\n\n performCalculations();\n updateLabels();\n }\n}", "function updateMaxQty(maxQty, upgradePurchased, cost, currency) {\r\n if(currency >= cost) {\r\n maxQty += upgradePurchased;\r\n currency -= cost;\r\n\r\n updatePbFill(beans, beansMax, 'pbBeansFill');\r\n document.getElementById('beans').innerHTML = \"Beans: \" + beans + \"/\" + beansMax;\r\n }\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds the current active list
_findActiveList() { return this._findList(l => this._isActiveList(l)); }
[ "function getCurrentListElement() {\n var main_list_id = document.getElementsByClassName('shopping_list')[0].id.substring(8);\n var overview_lists = document.getElementsByClassName('user_list_overview');\n var overview_lists_id;\n for(var i = 0; i < overview_lists.length; i++) {\n\toverview_lists_id = overview_lists[i].id.substring(8);\n\tif(overview_lists_id === main_list_id) {\n\t return overview_lists[i];\n\t}\n }\n}", "getCurrentList(){\n switch (this.getListSelector()) {\n case \"Blue\":\n return this.blueList;\n break;\n case \"Red\":\n return this.redList;\n break;\n case \"Purple\":\n return this.purpleList;\n break;\n\n }\n }", "getCurrentList(){\n return this.currentList;\n }", "_setActiveList(list)\n {\n this.activeList = list;\n }", "function getActivePlayListName() {\n vm.activated = true;\n videoService.getData('api', 'uservideoplaylist', vm.userInfo._id, '').\n then(function(response) {\n vm.activated = false;\n vm.playlist = response.data.data;\n if (angular.isDefined(vm.response) && vm.response != null) {\n commonService.showToast(response.data.message);\n }\n vm.getVideoListByName(vm.activeListDetail);\n // angular.forEach(vm.playlist, function(value, key) {\n // if (value.isactive) {\n // vm.getVideoListByName(value);\n // }\n // });\n })\n }", "_selectCurrentActiveItem() {\n const currentActive = this._getActiveListItemElement();\n const suggestionId =\n currentActive && currentActive.getAttribute('data-suggestion-id');\n const selection = this.state.list.filter(item => {\n return item.__suggestionId === suggestionId;\n })[0];\n\n if (selection) {\n this.options.onSelect(selection);\n this._filterAndToggleVisibility();\n this.setState({\n activeId: null,\n });\n }\n }", "function getActivePage() {\n\t\treturn document.querySelector('li[data-active-page=\"true\"]');\n\t}", "function searchMyActiveConversation() {\r\n\tconsole.info('Search my active conversation');\r\n\r\n\t// Keys in list\r\n let keys = Object.keys(conversationList);\r\n console.log('Keys in list object : ', keys );\r\n\t// Default conversation is empty\r\n\tlet thisConversation = {};\r\n\r\n\t// Iterate to find my 'connected' conversation\r\n\tkeys.some(function(key) {\r\n\t\tthisConversation = conversationList[key];\r\n\t\tconsole.log('Checking...: ', key, thisConversation);\r\n\t\t// Is my user connected?\r\n\t\tif( isMyUserConnected( thisConversation ) ) {\r\n \t\tconsole.log('My connected conversation...', thisConversation);\r\n\t\t\tconsole.log('Participants involved...', thisConversation.participants );\r\n\t\t\t// Is there a counterpart?\r\n\t\t\tlet ida = getAgentParticipantId(thisConversation);\r\n\t\t\tlet idc = getCustomerParticipantId(thisConversation);\r\n\t\t\tconsole.log('Id of customer and agent :', idc, ' - ', ida );\r\n\r\n\t\t if( idc !== 0 && ida !== 0) {\r\n \t\t\tconsole.log('Agent/User and Customer/External participants found!');\r\n\t\t\t \treturn (thisConversation);\r\n\t\t\t} else {\r\n\t\t\t\tconsole.log('...no counterpart');\r\n\t\t\t}\r\n }\r\n\t});\r\n\t// Return\r\n\treturn (thisConversation);\r\n}", "function getCurrentListName() {\n var element = document.getElementById('current_list');\n var list_name = element.innerText || element.textContent\n return list_name;\n}", "_clearActiveList()\n {\n this.activeList = getDefaultList();\n }", "function currentMenuItem() {\n\n\tvar cur_url = window.location.href;\n\tvar firstChar = cur_url.indexOf(\"/\", 7);\n\tvar lastChar = cur_url.indexOf(\"/\", firstChar + 1);\n\n\tif (lastChar > -1) {\n\t\tvar cur_word = cur_url.substring(firstChar + 1, lastChar);\n\t} else {\n\t\tvar cur_word = 'home';\n\t}\n\n\t$('.menu li').each(function(){\n\n\t\tif ( $(this).hasClass(cur_word) ) {\n\n\t\t\t$(this).addClass('active');\n\n\t\t} else if ( $(this).hasClass('active') ) {\n\n\t\t\t$(this).removeClass('active');\n\n\t\t}\n\t});\n}", "_getAriaActiveDescendant() {\n return this._useActiveDescendant ? this._listKeyManager?.activeItem?.id : null;\n }", "loadList(listId) {\n //finds list\n let listIndex = -1;\n for (let i = 0; (i < this.toDoLists.length) && (listIndex < 0); i++) {\n if (this.toDoLists[i].id === listId)\n listIndex = i;\n }\n //loads this list\n if (listIndex >= 0) {\n let listToLoad = this.toDoLists[listIndex];\n this.setCurrentList(listToLoad);\n //this.currentList = listToLoad;//change to set current list\n this.view.viewList(this.currentList);\n this.view.refreshLists(this.toDoLists);\n //set currentlist \n }\n this.tps.clearAllTransactions();\n this.buttonCheck();\n }", "function activeNavElement(targetText) {\n const navLi = document.getElementsByTagName('LI');\n for (element of [...navLi]) {\n if (element.innerHTML.includes(targetText)) {\n return element;\n }\n }\n}", "_activateNextList(list) {\n const nextIndex = list.index + 1;\n if (this.lists.length > nextIndex) {\n this._clearActiveList();\n this._cascadeReset(list);\n const nextList = this._findNextEditableListByIndex(list.index);\n this._setActiveList(nextList);\n this.enableList(nextList.element);\n this.requestData();\n } else {\n this.submit();\n }\n }", "function getListIndex()\n{\n\tvar prmstr = window.location.search.substr(1);\n\tvar prmarr = prmstr.split (\"&\");\n\tvar params = {};\n\n\tfor ( var i = 0; i < prmarr.length; i++) {\n\t var tmparr = prmarr[i].split(\"=\");\n\t params[tmparr[0]] = tmparr[1];\n\t}\n\tlistIndex = params.listindex;\n}", "function findActiveElement(carouselEl) {\n for (var I = carouselEl.length; I--;) {\n if (carouselEl[I].classList.contains(ACTIVE_CLASS))\n return I;\n }\n return -1;\n }", "function currentPlayerListIndex(gamestate){\n var out = undefined;\n gamestate.players.every(function(p,i) {\n if(p.id == gamestate.currentPlayerID) {\n out = i;\n return false;\n }\n return true;\n });\n return out;\n}", "_getCurrentBoard() {\n return _.find(this.props.boards, (b) => b.id === this.state.current_board)\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function will read files from supplied directory path. And it will call function to process on that files.
function readFiles(dirName, processOnFileContent, onError) { fs.readdir(dirName, function(err, fileNames) { if(err) { onError(err) return } //Now we have all fileNames.... fileNames.forEach(function(fileName) { var filePath = path.join(dirName, fileName) fs.readFile(filePath, function(err, content) { if(err) { onError(err) return } processOnFileContent(filePath, content) }) }) }) }
[ "function processRead(){\n\tvar platformPath;\n\t var operatingSystem = systemInfo.os;\n\tif(operatingSystem.indexOf('win32') > -1){\n\t\tplatformPath = 'C://';\n\t}\n\telse{\n\t\tplatformPath = '/proc';\n\t\t}\n\tvar subdir = platformPath;\n\tretrieveProcessInfo();\n\tfor(var i = 0; i < fileList.length-1; i++){\n\t\tvar newPath = subdir + fileList[i].name;\n\t\tif(accessGranted(newPath) == true){\n\t\t\tvar result = fs.lstatSync(newPath); //newPath\n\t\t\tvar subFileList = [];\n\t\t\tif(result.isDirectory() == true){\n\t\t\t\tvar myArray = [];\n\t\t\t\tmyArray = fs.readdirSync(newPath); \n\t\t\t\tmyArray.forEach(function(fileName){\n\t\t\t\t\t\t\t\t\t\tsubFileList.push(fileName);\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t });\n\t\t\t\tfileList[i].subFiles = subFileList;\n\t\t\t\t\t\t\t\t\t\t\t} //isDirectory\n\t\t\telse{\n\t\t\t\t\tsubFileList.push(newPath);\n\t\t\t\t\tfileList[i].subFiles = subFileList; \n\t\t\t\t}\n\t\t\t\t\t\t\t\t }//if accessGranted\n\t\t\t\t\t\t\t\t\t\t\t }//for\n} //function processRead", "function readFiles() {\n //alert(\"recommendor reading files\");\n //this.readFile(inheritancesFilename);\n this.createFiles();\n this.readFile(ratingsFilename);\n\t\tthis.updateLinks();\n\t\tthis.updatePredictions();\n\t\tmessage(\"recommendor done reading files\\r\\n\");\n\t\talert(\"recommendor done reading files\");\n }", "function forEachFile(pathToFind,callback){\r\n if(!fs.existsSync(pathToFind)){\r\n return;\r\n }\r\n\t\tdir = ///$/.test(dir) ? dir : dir + '/';\r\n (function dir(dirpath, fn) {\r\n if(!dirpath.endsWith(\"/\")){\r\n dirpath += \"/\";\r\n }\r\n var files = fs.readdirSync(dirpath);\r\n for (var i in files) {\r\n var item = files[i];\r\n var info = fs.statSync(dirpath + \"/\" + item);\r\n if (info.isDirectory()) {\r\n dir(dirpath + item + '/', callback);\r\n } else {\r\n if(dirpath[dirpath.length-1] == \"/\"){\r\n callback(dirpath + item);\r\n }\r\n else{\r\n callback(dirpath + \"/\" + item);\r\n }\r\n \r\n }\r\n\r\n }\r\n\r\n })(pathToFind);\r\n}", "directoryInjector(directoryPath) {\n return this.getFilesInDirectory(directoryPath)\n .then(files => Promise.all(files.map(file => this.fileInjector(path.join(directoryPath, file)))))\n .catch(err => Promise.reject(`Error injecting into files on '${directoryPath}': ${err}`));\n }", "function readHugeFiles(dirName, processOnFileLine, onError) {\n\tfs.readdir(dirName, function(err, fileNames) {\n\t\tif(err) {\n\t\t\tonError(err)\n\t\t\treturn\n\t\t}\n\n\t\t//Now we have all fileNames....\n\t\tfileNames.forEach(function(fileName) {\n\t\t\tvar filePath = path.join(dirName, fileName)\n\n\t\t\tvar lineReader = readline.createInterface({input: fs.createReadStream(filePath)})\n\n\t\t\tlineReader.on('line', function(line) {\n\t\t\t\tprocessOnFileLine(filePath, line)\n\t\t\t}) \t\n\n\t\t\tlineReader.on('close', function() {\n\t\t\t\tdebug(\"File \" + filePath + \" encounter file close operation\")\n\t\t\t})\n\t\t})\n\t})\t\n}", "function analyzingDir(startPath){\n\n \n \n try{ \n \n checkDirCount++;\n const files = fs.readdirSync(startPath); //reading the files in that directory.\n let filename = null;\n let fileStatus = null;\n\n files.forEach((file) => {\n filename=path.join(startPath,file); //joining the path + filename.\n fileStatus = fs.lstatSync(filename); //getting status of joined file.\n\n dirSize += fileStatus.size; //adding all files size\n \n if (fileStatus.isDirectory()){ //checking wheather it is a diretory? then incrementing the countDirectory\n //and passing the whole path again to the Analyzing method.\n dir++; //incrementing diretory count\n analyzingDir(filename); //recursive call\n }\n else{\n updateFileCounter(filename, fileStatus); //else if its a file, update file counter is called\n };\n });\n \n \n }\n catch(error){\n \n if(checkDirCount > 1){\n dir--;\n console.log(\"\\nPermission to this Directory Structure is denied : \"+error.path);\n }\n else{\n console.log(\"Note: Please give the Read Permission to this directory structure,\\nor try with the user who has Read Permission to this directory structure!\");\n process.exit();\n }\n}\n \n}", "function exploreDir (filePath) {\n fs.readdirSync(filePath).forEach(fileOrFolder => {\n const fileOrFolderPath = path.join(filePath, fileOrFolder)\n const stats = fs.statSync(fileOrFolderPath)\n if (stats.isDirectory()) {\n exploreDir(fileOrFolderPath)\n } else if (fileOrFolder.indexOf('.js') > -1) {\n analyzeFile(fileOrFolderPath)\n }\n })\n}", "readQueriesFromDir(dir) { \n var files = fs.readdirSync(dir, {withFileTypes:true})\n logger.info(`found ${files.length} files in directory ${dir}`)\n const ctx = this\n fs.readdir(dir, function (err, files) {\n files.forEach(function(f) {\n let q = ctx.readQueriesFromFile(path.join(dir,f))\n })\n })\n // for (var i = 0; i < files.length; i++) {\n // //console.log(`process file ${files[i].name}`)\n // //if (files[i].isDirectory()) continue\n // //if (!(path.basename(files[i]).endsWith('.yml'))) continue\n // //if (!files[i].name.endsWith(\".yml\")) continue\n // //var f = path.join(dir, files[i].name)\n // let q = this.readQueriesFromFile(files[i])\n // }\n //logger.info(`read ${Object.keys(this.sqls).length} queries`)\n }", "function readAll(startPath,filter){\n let jsonContent, contents;\n\n if (!fs.existsSync(startPath)){\n console.log(\"no dir \",startPath);\n return;\n }\n\n var files=fs.readdirSync(startPath);\n for(var i=0;i<files.length;i++){\n var filename=path.join(startPath,files[i]);\n var stat = fs.lstatSync(filename);\n if (stat.isDirectory()){\n readAll(filename,filter); //recurse\n }\n else if (filename.indexOf(filter)>=0) {\n contents = fs.readFileSync(filename);\n // Define to JSON type\n jsonContent = JSON.parse(contents);\n studentArray.push(sanitizeJSON(jsonContent));\n };\n };\n}", "findTemplateFiles ( dir_path ) {\n if (!dir_path) dir_path = this.path\n dir_path = path.resolve(this.base_path, this.base_name, 'files')\n return Walk.dir(dir_path).then( files => {\n return this.files = this.stripPrefixFromPaths(files, dir_path)\n })\n .catch({code: 'ENOENT'}, error => {\n error.original_message = error.message\n error.message = `Failed to read template set \"${this.base_name}\"\n No such file or directory \"${error.path}\"`\n throw error\n })\n }", "function runDuringWalkPlugins(filePath){\n\tvar contents;\n\t//Plugins will not process dot files\n\tif (util.getFileName(filePath).charAt(0) !== \".\") {\n\t\tif (p.extname(filePath) === '.json') {\n\t\t\t//Read the file contents so each plugin doesn't have to\n\t\t\tcontents = grunt.file.readJSON(filePath);\n\t\t} else {\n\t\t\tcontents = grunt.file.read(filePath);\n\t\t}\n\t\t//Process duringWalk plugins\n\t\taddContextFile(filePath, contents, siteContext);\n\t}\n}", "readDir(p) {\n let files = fs_1.readdirSync(p);\n for (let name of files) {\n let fileName = path.join(p, name);\n if (fs_1.statSync(fileName).isDirectory()) {\n this.readDir(fileName);\n continue;\n }\n let text = fs_1.readFileSync(fileName).toString();\n for (let part of text.split(/[\\n\\r]+\\-{3,}[\\n\\r]+/)) {\n let id;\n part = part.replace(/^\\#+\\s*([^\\n\\r]+)[\\n\\r]+/, (_s, t) => {\n id = t;\n return \"\";\n });\n if (id)\n this._content[id] = part;\n }\n }\n }", "function walk(dir, next) {\n var results = [];\n fs.readdir(dir, function(err, list) {\n if (err) return next(err);\n var pending = list.length;\n if (!pending) return next(null, results);\n list.forEach(function(file) {\n file = dir + '/' + file;\n fs.stat(file, function(err, stat) {\n if (stat && stat.isDirectory()) {\n walk(file, function(err, res) {\n results = results.concat(res);\n if (!--pending) next(null, results);\n });\n } else {\n results.push(file);\n if (!--pending) next(null, results);\n }\n });\n });\n });\n}", "function getShapeFiles(directory, callback){\n var shapeFiles = [];\n fs.readdir(directory, function(err, files){\n if (err) {\n console.log(\"Error: \", err);\n callback(err, null);\n }\n else{\n files.forEach(function(file, index){\n\n if(path.extname(file) == \".shp\") {\n shapeFiles.push(file);\n }\n });\n callback(null, shapeFiles);\n }\n });\n\n}", "walkSync(dir, rootPath, callback) {\n\t\tlet files = fs.readdirSync(dir);\n\n\t\tlet i;\n\t\tfor (i = 0; i < files.length; i++) {\n\t\t\tlet pathToFile = path.join(dir, files[i]);\n\t\t\tlet isDirectory = fs.statSync(pathToFile).isDirectory();\n\t\t\tif (isDirectory) {\n\t\t\t\tthis.walkSync(pathToFile, rootPath, callback);\n\t\t\t} else {\n\t\t\t\tcallback(pathToFile);\n\t\t\t}\n\t\t}\n\t}", "function wikiReadDir(path)\n{\n return eval( FILE.scandir(path) ); \n}", "static findFiles (dir) {\n return Walk.dir(dir)\n .catch({code: 'ENOENT'}, error => {\n error.message = `No such file or directory \"${error.path}\"`\n error.simple = `Failed to read templates for \"${this.base_name}\"`\n throw error\n })\n }", "function visit(dir: string): void {\n for (const file of readdirSync(dir)) {\n const path = join(dir, file);\n if (statSync(path).isDirectory()) {\n if (file !== 'node_modules' && file !== 'jsii-calc') {\n visit(path);\n }\n continue;\n }\n if (file === 'go.mod') {\n const args = process.argv.slice(2);\n console.error(`$ go ${args.join(' ')} # ${path}`);\n try {\n runCommand('go', args, { cwd: dir, stdio: 'inherit' });\n } catch (e) {\n console.error(e.message);\n process.exit(-1);\n }\n }\n }\n}", "function visitDirectories(dir, fcn){\n\tgetDirectories(dir).forEach(function (v) {\n\t\tvisitDirectories(v, fcn);\n\t\tfcn(v);\n\t})\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a rating to a chord and +1 to the total number of raters
function rateChord(chordKey, newRating) { return new Promise(function (resolve, reject) { if (newRating < 1 || newRating > 5) { reject('Rating value should be between 1 - 5'); } var localRef = PlyFirebase.getRef("chords/" + chordKey); localRef.once('value') .then(function (snapshot) { var countRating = snapshot.val().countRating || 1; var rating = snapshot.val().rating || 1; //New weighted average rating = ((rating * countRating) + (newRating * 1)) / (countRating + 1); rating = Math.round(rating); rating = Math.min(rating, 5); localRef.child('countRating').set(countRating + 1); localRef.child('rating').set(rating); return resolve(); }) .catch(function (error) { return reject(error); }); //TODO - add the rating to the user as well }); }
[ "function increaseMoveCounter( )\n {\n moves.textContent = ++moveCounter;\n starRating( );\n }", "function adjustRating() {\n if(newRestroom.rating === 1) {\n newRestroom.rating += 1;\n } else if(newRestroom.rating === -1){\n newRestroom.rating -= 1;\n }// end if\n console.log('current rating: ', newRestroom.rating);\n }//end adjustRating", "function updateRating(rscName, rating, rerate, old_rating) {\n var newRating;\n Resource.findOne({ className: rscName }, function(err, resource) {\n if (err) console.log(err);\n else {\n if (rerate) {\n newRating = (resource.rating * resource.numRatings - old_rating + rating)/ resource.numRatings;\n Resource.update({ className: rscName }, { $set: { rating: newRating }}, function(err, raw) {\n if (err) console.log(err);\n else console.log('Rerate successful');\n });\n } else {\n newRating = (resource.rating * resource.numRatings + rating)/(resource.numRatings + 1);\n Resource.update({ className: rscName }, { $set: { rating: newRating }, $inc: {numRatings : 1}}, function(err, raw) {\n if (err) console.log(err);\n else console.log('Rating updated and numRatings incremented');\n });\n }\n }\n });\n}", "function incMoves() {\n mvs = mvs + 1;\n counter.textContent = 'moves ' + mvs;\n starRating();\n}", "function score(answer) {\n if (answer == \"gr\") {\n dog.data[0].count++;\n } else if (answer == \"is\") {\n dog.data[1].count++;\n } else if (answer == \"ch\") {\n dog.data[2].count++;\n } else {\n dog.data[3].count++;\n }\n }", "setCommunityRating(rating){\n this.game.communityRating = \"\" + Math.round(rating) + \"/100\";\n }", "updateMoodNum (num) {\n this.props.updateMood({...this.props.mood, rating: num})\n }", "skierIncreaseSpeed() {\n if (vars.score == 500) {\n vars.skierSpeed++;\n } else if (vars.score == 1000) {\n vars.skierSpeed += 2;\n } else if (vars.score == 2000) {\n vars.skierSpeed += 4;\n }\n }", "calculateNewScore() {\n this.score = 0;\n let numberOfAces = 0;\n for (const card of this.hand) {\n if (card.value === 'A') {\n this.score += card.weight()[1];\n numberOfAces++;\n } else {\n this.score += card.weight();\n }\n }\n if (this.score > 21 && numberOfAces !== 0) {\n for (let i = 0; i < numberOfAces; i++) {\n this.score -= 10; // Count the ace as 1 instead, removing 10.\n if (this.score <= 21) {\n break;\n }\n }\n }\n }", "changeRating(newRating){\n this.rating = newRating;\n return(`The updated rating is ${this.rating}`);\n }", "static async rateTrip(id, username, rating) {\n const result = await db.query(\n `UPDATE user_trips\n SET trip_rating = $1\n WHERE trip_id = $2\n AND username = $3\n RETURNING trip_id AS \"tripId\", \n username, \n trip_rating AS \"tripRating\"`,\n [rating, id, username]\n );\n return result.rows[0];\n }", "calculateRating(stars) {\n \n // Array that will store the classes of the five stars\n let totalStars = []\n // Number of full stars (rating rounded down)\n const fullStars = Math.floor(stars)\n // If the rating is bigger than itself rounded down, then there is a half star\n const halfStar = stars > fullStars ? 1 : 0\n // Calculate the number of blank stars\n const blankStars = 5 - fullStars - halfStar\n\n // Place all the full stars on the array\n for(let i=0; i<fullStars; i++){\n totalStars.push('full')\n }\n\n // Place one half star if needed\n if(halfStar)\n totalStars.push('half')\n\n // Place all the blank stars on the array\n for(let j=0; j<blankStars; j++){\n totalStars.push('')\n }\n\n return totalStars\n }", "function ApplyRating() \n{\n $(\"div[id^='movieratingdiv']\").each(function () \n {\n var avgRating = $(this).attr('avgrating');\n if(avgRating == null)\n {\n $(this).text(\"No Rating\")\n }\n else\n {\n $(this).raty(\n {\n start: avgRating,\n readOnly: true,\n half: true\n }\n );\n }\n });\n\n $('div .moviesDiv').each(function () { $(this).corners() });\n}", "function repsButtonCounter(exercise) {\n if (!this.value){\n this.value = exercise.maxReps;\n } else if(this.value == 1) {\n this.value = null;\n } else {\n this.value --;\n }\n //save the counter inside the object..so you can save it afterwards\n exercise.reps = this.value;\n}", "function addBeerCounter(val){\n \t\t\tvar qty = beer;\n \t\t\tvar new_qty = parseInt(qty, 10) + val;\n \t\t\tif (new_qty < 0) {\n \t\t\t\tnew_qty = 0;\n \t\t\t\t\t }\n \t\t\t\t\t beer = new_qty;\n \t\t\t\treturn new_qty;\n \t\t}", "incrementWins() {\n this.wins += 1; \n }", "function increaseYakuzaVote(value)\n {\n setGame(\"yakuza\");\n setVotes(true);\n }", "function showRating(ratings) {\n let oneStars = +ratings.one \n let twoStars = +ratings.two *2\n let threeStars = +ratings.three*3\n let fourStars = +ratings.four*4\n let fiveStars = +ratings.five*5\n\n let totalRatings = +ratings.one + +ratings.two + +ratings.three + +ratings.four + +ratings.five\n\n let averageRating = ((oneStars + twoStars + threeStars + fourStars + fiveStars)/totalRatings)\n let averageRatingFormatted = averageRating.toFixed(2)\n return averageRatingFormatted\n}", "function questionIndexIncrease() {\n questionIndex++;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Memory game router, handles registering a user for a new game & sending over information about a specific card in the game
function memoryRouter(parsedUrl, req, res) { var data = ''; var route = parsedUrl.pathname; var query = parsedUrl.query; if (req.method === 'POST' && route === '/memory/intro') { // Request to register a user with a new game readRequestBody(req, function(err, data){ userList[data.id] = makeBoard(4); // Setting content type to plain text res.writeHead(200, {'content-type': 'text/plain'}); res.end(); }); } else if (req.method === 'GET' && route === '/memory/card') { // Request to get information about a specific card if (query.id && query.rowIdx && query.cardIdx) { // Three parameters need to be sent in the query // We'll look into our internal game board for this user at the requested // row and column (card) index and send that card value to them data = userList[query.id][query.rowIdx][query.cardIdx]; } // Setting content type to plain text res.writeHead(200, {'content-type': 'text/plain'}); // Sending response res.end('' + data); } else { // Setting content type to plain text res.writeHead(200, {'content-type': 'text/plain'}); // Sending response res.end(data); } }
[ "function makeNewGame() {\n // //http://localhost:5000/\n //https://lit-retreat-32140.herokuapp.com/games/new\n\n postData('https://lit-retreat-32140.herokuapp.com/games/new', {\n username1: 'O',\n username2: 'x',\n }).then((data) => {\n if (data.game) {\n gameId = data.game._id;\n\n drawBoard();\n }\n });\n}", "function createGame() {\n console.log('Creating game...');\n socket.emit('create', {size: 'normal', teams: 2, dictionary: 'Simple'});\n}", "function startGame() {\n removeWelcomePage();\n createGamePage();\n createCards();\n}", "pass() {\n // in progress: getting the canPass functionality to work.\n // send info to server --> fact that player did not play cards\n //if (this.canPass) {\n //}\n //;else (document.getElementById(\"error_message_game\").innerHTML = \"you cannot pass on the first turn\");\n\n\t document.getElementById(\"error_message_game\").innerHTML = \"\";\n play_cards();\n }", "function joinGame(gameId){\n\n canRequestGameList = false;\n tempGameId = gameId;\n\n changePage(\"pass-page\");\n\n}", "function startGame() {\n createButtons();\n createCards();\n displayCards();\n}", "async function connectToGame(req, res, game_id) {\n let game_data = await getGameData(game_id)\n .catch((err) => console.log(err));\n console.log(game_data);\n \n // Determine where to place current user\n let target;\n let uid_1 = game_data.uid_1;\n let uid_2 = game_data.uid_2;\n\n // TODO: Update game is_active flag\n // If user already in the game, else if creating a new game, \n // else if joining an existing game, else game is full\n if (uid_1 == req.user.uid || uid_2 == req.user.uid) {\n console.log(\"User already in this game. Redirecting...\");\n res.redirect('/game/' + game_id);\n } else if (uid_1 == null) {\n console.log(\"New room created. Adding user \" + req.user.username);\n target = \"uid_1\";\n let update = await updateGamePlayer(req, game_id, target)\n .catch((err) => console.log(err))\n res.redirect('/game/' + game_id);\n } else if (uid_2 == null) {\n console.log(\"Joining an existing room. Adding user \" + req.user.username);\n target = \"uid_2\";\n let update = await updateGamePlayer(req, game_id, target)\n .catch((err) => console.log(err))\n res.redirect('/game/' + game_id);\n } else {\n console.log(\"Room is full. Returning to lobby.\");\n res.redirect('/lobby');\n }\n}", "register(steamID, username, action){\n const sid = new SteamID(steamID);\n }", "function newgameOK(response) {\n if (response.indexOf(\"<!doctype html>\") !== -1) { // User has timed out.\n window.location = \"access-denied.html\";\n } else if (response === \"nobox\") {\n $(\"#bi_error\").text('Invalid Game Box ID.').show(); \n $(\"#boxid\") .trigger('focus');\n } else if (response === \"dupname\") {\n $(\"#sn_error\").text('Duplicate Game Name is not allowed.').show(); \n $(\"#sessionname\") .trigger('focus');\n } else if (response.indexOf(\"noplayer\") !== -1) { \n // Response contains \"noplayer\".\n var plerr = 'Player #' + response.substr(9) + ' does not exist';\n $(\"#pc_error\").text(plerr).show(); \n $(\"#player1\") .trigger('focus');\n } else if (response === \"success\") {\n $('#newgame .error').hide();\n $('#newgame :text').val('');\n // Send an email notification to each player in the game.\n var cString;\n BD18.mailError = false;\n for (var i = 0; i < BD18.playerCount; i++) {\n cString = 'game=' + BD18.name + '&login=' + BD18.player[i];\n $.post(\"php/emailPlayerAdd.php\", cString, emailPlayerResult);\n }\n delayGoToMain();\n } else if (response === \"fail\") {\n var ferrmsg ='New game was not created due to an error.\\n';\n ferrmsg += 'Please contact the BOARD18 webmaster.';\n alert(ferrmsg);\n } else { // Something is definitly wrong in the code.\n var nerrmsg ='Invalid return code from createGame.php.\\n';\n nerrmsg += response + '\\nPlease contact the BOARD18 webmaster.';\n alert(nerrmsg);\n }\n}", "function SessionHandler() {\n\n var self = this;\n function send(message, color) {\n if (typeof message !== \"string\") {\n message = JSON.stringify(message);\n }\n message = Util.processHighlights(message);\n if (color !== undefined) {\n message = Util.colorize(message, color);\n }\n self.send(message);\n }\n\n var signUpData = {};\n\n this.states = {\n \"AskingUserName\": {\n \"enter\": function() {\n send(\" == District 21 ==\\n\\n\");\n },\n \"prompt\": function() {\n send(\"Unidentified Clone, enter your ID: \");\n },\n \"processInput\": function(input) {\n if (input.substr(0, 1) === \"c\" || input.substr(0, 1) === \"C\") {\n input = input.substr(1);\n }\n\n var cloneId = parseInt(input, 10);\n if (input.length < 2 || input.length > 5 || isNaN(cloneId) || cloneId < 14) {\n send(\"Not a valid Clone ID number. A valid Clone ID a number ranging from 14 \" +\n \"through 99999\\n\");\n return;\n }\n\n var player;\n if (cloneId >= 14) {\n player = Realm.getPlayer(\"C\" + cloneId);\n }\n\n if (player) {\n this.setPlayer(player);\n this.setState(\"AskingPassword\");\n } else {\n signUpData.userName = \"C\" + cloneId;\n this.setState(\"AskingUserNameConfirmation\");\n }\n }\n },\n\n \"AskingPassword\": {\n \"enter\": function() {\n send({ \"inputType\": \"password\" });\n },\n \"exit\": function() {\n send({ \"inputType\": \"text\" });\n },\n \"prompt\": function() {\n send(this.player.name + \", enter your passphrase: \");\n },\n \"processInput\": function(input) {\n if (this.player.matchesPassword(input)) {\n LogUtil.logSessionEvent(this._session.source, \"Authentication success for \" +\n \"player \" + this.player.name);\n\n if (this.player.isOnline()) {\n send(\"Rejected. Clone is already active from another terminal.\\n\");\n this.setState(\"SessionClosed\");\n return;\n }\n\n send((\"%1 Authenticated. Type *help* for instructions.\\n\" +\n \"\\n\" +\n \"You open your eyes.\\n\")\n .arg(this.player.name));\n this.setState(\"SignedIn\");\n } else {\n LogUtil.logSessionEvent(this._session.source, \"Authentication failed for \" +\n \"player \" + this.player.name);\n\n send(\"Authentication Failure.\\n\\n\", Color.Red);\n }\n }\n },\n\n \"AskingUserNameConfirmation\": {\n \"prompt\": function() {\n send(\"\\n%1 Not Registered. Register? \".arg(signUpData.userName));\n },\n \"processInput\": function(input) {\n var answer = input.toLower();\n if (answer === \"yes\" || answer === \"y\") {\n this.setState(\"AskingSignUpPassword\");\n } else if (answer === \"no\" || answer === \"n\") {\n this.setState(\"SignInAborted\");\n } else {\n send(\"Enter *yes* or *no*.\\n\");\n }\n }\n },\n\n \"AskingSignUpPassword\": {\n \"enter\": function() {\n send({ \"inputType\": \"password\" });\n },\n \"prompt\": function() {\n send(\"\\nChoose a passphrase: \");\n },\n \"processInput\": function(input) {\n if (input.length < 6) {\n send(\"Passphrase should be at least 6 characters.\\n\", Color.Red);\n return;\n }\n if (input.toLower() === signUpData.userName.toLower()) {\n send(\"Passphrase may not equal Clone ID.\\n\", Color.Red);\n return;\n }\n if (input === \"123456\" || input === \"654321\") {\n send(\"Passphrase too simple.\\n\", Color.Red);\n return;\n }\n signUpData.password = input;\n this.setState(\"AskingSignUpPasswordConfirmation\");\n }\n },\n\n \"AskingSignUpPasswordConfirmation\": {\n \"exit\": function() {\n send({ \"inputType\": \"text\" });\n },\n \"prompt\": function() {\n send(\"Confirm passphrase: \");\n },\n \"processInput\": function(input) {\n if (signUpData.password === input) {\n send(\"Passphrase confirmed.\\n\", Color.Green);\n this.setState(\"AskingGender\");\n } else {\n send(\"Passphrases don't match.\\n\", Color.Red);\n this.setState(\"AskingSignUpPassword\");\n }\n }\n },\n\n \"AskingGender\": {\n \"enter\": function() {\n send(\"\\n\" +\n \"Choose a gender for your clone:\");\n },\n \"processInput\": function(input) {\n var answer = input.toLower();\n if (answer === \"male\" || answer === \"m\") {\n send(\"Male clone selected.\\n\", Color.Green);\n signUpData.gender = \"male\";\n this.setState(\"AskingSignUpConfirmation\");\n } else if (answer === \"female\" || answer === \"f\") {\n send(\"Female clone selected.\\n\", Color.Green);\n signUpData.gender = \"female\";\n this.setState(\"AskingSignUpConfirmation\");\n } else {\n send(\"\\n\" +\n \"Choose *male* or *female*.\\n\");\n }\n }\n },\n\n \"AskingSignUpConfirmation\": {\n \"enter\": function() {\n send(\"\\n\" +\n \"Clone is ready for production.\\n\");\n },\n \"prompt\": function() {\n send(\"\\n\" +\n \"Continue?\\n\");\n },\n \"processInput\": function(input) {\n var answer = input.toLower();\n if (answer === \"yes\" || answer === \"y\") {\n var humanRace = Realm.getObject(\"Race\", 2);\n var soldierClass = Realm.getObject(\"Class\", 3);\n\n var stats = humanRace.stats.plus(soldierClass.stats);\n\n var height = humanRace.height;\n var weight = humanRace.weight;\n if (signUpData.gender === \"male\") {\n stats[STRENGTH]++;\n height += 10;\n weight += 15;\n } else {\n stats[DEXTERITY]++;\n weight -= 5;\n }\n\n for (var i = 0; i < 9; i++) {\n var attr = randomInt(0, 6);\n stats[attr]++;\n if (attr === STRENGTH) {\n weight++;\n } else if (attr === DEXTERITY) {\n if (byChance(1, 2)) {\n height--;\n }\n } else if (attr === INTELLIGENCE) {\n height++;\n }\n }\n\n var player = Realm.getPlayer(signUpData.userName);\n if (player) {\n send(\"Clone ID already taken. Please re-register.\\n\");\n this.setState(\"SessionClosed\");\n return;\n }\n\n player = Realm.createObject(\"Player\");\n player.admin = Realm.players().isEmpty();\n player.name = signUpData.userName;\n player.race = humanRace;\n player.characterClass = soldierClass;\n player.gender = signUpData.gender;\n player.stats = stats;\n player.height = height;\n player.weight = weight;\n player.currentRoom = humanRace.startingRoom;\n\n player.hp = player.maxHp;\n player.mp = player.maxMp;\n\n player.setPassword(signUpData.password);\n\n signUpData = {};\n\n LogUtil.logSessionEvent(this._session.source, \"Character created for player \" +\n player.name);\n\n send((\"%1 Created. Type *help* for instructions.\\n\").arg(this.player.name) +\n \"\\n\" +\n \"You open your eyes.\\n\");\n\n this.setPlayer(player);\n this.setState(\"SignedIn\");\n } else if (answer === \"no\" || answer === \"n\" ||\n answer === \"back\" || answer === \"b\") {\n this.setState(\"AskingGender\");\n } else {\n send(\"Please answer with yes or no.\\n\");\n }\n }\n },\n\n \"SignedIn\": {\n \"enter\": function() {\n this.setSessionState(SessionState.SignedIn);\n }\n },\n\n \"SignInAborted\": {\n \"enter\": function() {\n this.setState(\"SessionClosed\");\n }\n },\n\n \"SessionClosed\": {\n \"enter\": function() {\n this.setSessionState(SessionState.SessionClosed);\n }\n }\n };\n\n this.state = null;\n\n this.player = null;\n\n this._session = null;\n}", "switchUser() {\n this.currentPlayer = this.currentPlayer == 1 ? 0 : 1;\n this.io.to(this.id).emit('g-startTurn', this.players[this.currentPlayer]);\n }", "checkNextGame (){\n\n }", "function matchPlayers(userId) {\n var temp = [];\n for(var i=0; i < Users.length; i++) {\n if(Users[i].inGame === false) {\n temp.push({\n playerID: Users[i].id\n });\n\n if(temp.length === 2) {\n var gameId = uniqid();\n var player_1 = findUser(temp[0].playerID);\n var player_2 = findUser(temp[1].playerID);\n Games.push({\n id: gameId,\n player_1: player_1,\n player_2: player_2\n });\n startGame(gameId,userId); // ################## sTART gAME tO eARLY (1 pLAER).. \n }\n }\n }\n}", "deployRPSGame(selectionHash, opponentAddress, stakedEther) {\n rpsGameContract.new(\n web3.toBigNumber(selectionHash),\n web3.toBigNumber(opponentAddress.toLowerCase()),\n {\n from: web3.eth.accounts[0],\n data: CONTRACT_BYTECODE,\n gas: GAS_LIMIT,\n value: web3.toWei(stakedEther, 'ether'),\n },\n function (e, contract){\n if (e) {\n // TODO error handling\n console.log(e);\n }\n if (contract && typeof contract.address !== 'undefined') {\n console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);\n // navigate to game page\n browserHistory.push('/' + contract.address);\n } else {\n this.setState({\n pendingTxHash: contract.transactionHash\n });\n }\n }.bind(this)\n );\n }", "function sendTurnData(){\n let emitKey = (phase === PHASES.GUESSING || phase === PHASES.START) ? 'nextGuess' : 'nextImage';\n for(let name in players){\n let player = players[name];\n let playerIdx = passOrder.indexOf(name);\n let targetIdx = (playerIdx + turnCount) % passOrder.length;\n let targetPlayer = players[passOrder[targetIdx]];\n let data = player.entryData[player.entryData.length - 1].data;\n targetPlayer.socket.emit(emitKey, data);\n targetPlayer.targetPlayer = player;\n }\n }", "startGame() {\r\n this.generateInitialBoard();\r\n this.printBoard();\r\n this.getMoveInput();\r\n }", "function gameManager() {\n switch (game.gameMode) {\n case \"Classic\":\n {\n classic();\n break;\n }\n case \"Survival\":\n {\n survival();\n break;\n }\n case \"TimeAttack\":\n {\n ui.showUI(\"TimeAttackUI\");\n timeAttack();\n break;\n }\n }\n}", "function addGame() {\n console.log(\"in addGame...\");\n\n //only make new game if current game is empty\n // if ((vm.currentGame === null) || (vm.currentGame.gameInProgress || vm.currentGame.postGame)) {\n \n vm.games.$add(blankBoard)\n .then(function(ref) {\n setCurrentGame(ref.key());\n // vm.currentGame.time = Firebase.ServerValue.TIMESTAMP;\n vm.currentGame.time = new Date().getTime();\n saveCurrentGame();\n }, catchError);\n }", "function create(ids,names,gameid){\r\n var ng = new Game(gameid);\r\n if (ids.length < 12){\r\n var roles=[\"WW\",\"WW\",\"Seer\",\"Witch\",\"Hunter\",\"Cupid\"];\r\n for (i = 0; i < (ids.length - 6); i++) {\r\n roles.push(\"Villager\");\r\n }\r\n }else if((ids.length > 11 && ids.length < 18)){\r\n var roles=[\"WW\",\"WW\",\"WW\",\"Seer\",\"Witch\",\"Hunter\",\"Cupid\"];\r\n for (i = 0; i < (ids.length - 7); i++) {\r\n roles.push(\"Villager\");\r\n }\r\n }else if((ids.length > 17 )){\r\n var roles=[\"WW\",\"WW\",\"WW\", \"WW\",\"Seer\",\"Witch\",\"Hunter\",\"Cupid\"];\r\n for (i = 0; i < (ids.length - 8); i++) {\r\n roles.push(\"Villager\");\r\n }\r\n }\r\n shuffled=shuffle(roles);\r\n for (i = 0; i < (ids.length); i++){\r\n var np = new GamePlayer(ids[i], names[i], shuffled[i]);\r\n np.checkwitch();\r\n final_players.push(np)\r\n console.log(\"np.id display role \");\r\n ng.addplayer(np);\r\n ng.Roles.push(np.role);\r\n ////////\r\n }\r\n return ng;\r\n\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
let viewMat = new Mat4().setLookAt(x, y, z, 0, 0, 0, 0, 1, 0) // let viewMat2 = new Mat4()._setLookAt(x, y, z, 0, 0, 0, 0, 1, 0) // let viewMat = new Mat4().setLookAt(0, 0, 0.25, 0, 0, 0, 0, 1, 0) gl.uniformMatrix4fv(u_ViewMat, false, viewMat.getArray()) gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT) gl.drawArrays(gl.TRIANGLE_FAN, 0, 4)
function draw() { requestAnimationFrame(draw) x += 0.00001 y += 0.00001 // z += 0.001 let viewMat = new Mat4().setLookAt(x, y, z, 0, 0, 0, 0, 1, 0) // let viewMat = new Mat4().setLookAt(0, 0, 0.25, 0, 0, 0, 0, 1, 0) gl.uniformMatrix4fv(u_ViewMat, false, viewMat.getArray()) gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT) gl.drawArrays(gl.TRIANGLE_FAN, 0, 4) }
[ "function draw() { \r\n var translateVec = vec3.create();\r\n var scaleVec = vec3.create();\r\n \r\n gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);\r\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\r\n uploadViewDirToShader();\r\n\r\n // We'll use perspective \r\n mat4.perspective(pMatrix,degToRad(75), gl.viewportWidth / gl.viewportHeight, 0.1, 200.0);\r\n \r\n //Draw \r\n // Setup the scene and camera\r\n \r\n var rotateMat = mat4.create();\r\n // Rotatation for orbitting around the teapot\r\n mat4.rotateY(rotateMat, rotateMat, 0);\r\n mvPushMatrix();\r\n mat4.rotateY(rotateMat, rotateMat, modelYRotationRadians);\r\n mat4.rotateX(rotateMat, rotateMat, modelXRotationRadians);\r\n mat4.rotateZ(rotateMat, rotateMat, modelZRotationRadians);\r\n uploadRotateMatrixToShader(rotateMat);\r\n vec3.set(translateVec,0.0,0.0,-10.0);\r\n mat4.translate(mvMatrix, mvMatrix,translateVec);\r\n setMatrixUniforms();\r\n // Calculate view point from eye point and view direction\r\n vec3.add(viewPt, eyePt, viewDir);\r\n // Generate the lookat matrix and initialize the model-view matrix\r\n mat4.lookAt(mvMatrix,eyePt,viewPt,up);\r\n \r\n if(document.getElementById(\"reflectyes\").checked){\r\n switchreflect(false);\r\n    }\r\n if(document.getElementById(\"reflectno\").checked){\r\n switchreflect(true);\r\n    } \r\n // Setup lights\r\n //in other words, the color that teapot will show out\r\n uploadLightsToShader([88,88,88],[0.0,0.0,0.0],[0.6,0.6,0.6],[0.08,0.08,0.08]);\r\n \r\n // render the skybox\r\n drawSkybox();\r\n\r\n // if the teapot file has been successfully loaded, render the teapot\r\n if (ready_to_draw){\r\n mat4.rotateY(mvMatrix,mvMatrix,modelYRotationRadians);\r\n mat4.rotateX(mvMatrix,mvMatrix,modelXRotationRadians);\r\n mat4.rotateZ(mvMatrix,mvMatrix,modelZRotationRadians);\r\n drawTeapot();\r\n\r\n \r\n }\r\n mvPopMatrix();\r\n \r\n}", "function setMV() {\r\n gl.uniformMatrix4fv(modelViewMatrixLoc, false, flatten(modelViewMatrix) );\r\n normalMatrix = inverseTranspose(modelViewMatrix) ;\r\n gl.uniformMatrix4fv(normalMatrixLoc, false, flatten(normalMatrix) );\r\n}", "function configureProjectiveMat() {\n var projectionMat = mat4.create();\n var screenRatio = gl.drawingBufferWidth / gl.drawingBufferHeight;\n mat4.perspective(projectionMat, glMatrix.toRadian(45), screenRatio, 1, 100);\n gl.uniformMatrix4fv(ctx.uProjectionMatId , false , projectionMat);\n}", "function camera_perspective_view() {\n camera.rotation.y += Math.PI/4;\n camera.position.x = 2.0;\n camera.position.z = 2.8;\n camera.position.y = 0.6; \n}", "function display() {\r\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\r\n\r\n var eye = vec3(a * Math.sin(theta) * Math.cos(phi), //used for mouse rotation\r\n b * Math.sin(theta) * Math.sin(phi),\r\n c * Math.cos(theta));\r\n\r\n\tviewMatrixLoc = gl.getUniformLocation( programId, \"viewMatrix\" );\r\n\tviewMatrix = mult(transCamera, lookAt(eye, at, up));\r\n\tgl.uniformMatrix4fv( viewMatrixLoc, false, flatten(viewMatrix) );\r\n\t\r\n\t/////////////////////////////////////////////\r\n // TODO: Draw the superquadric, implement perspective projection\r\n /////////////////////////////////////////////\r\n\r\n\tgl.uniform4fv(color, flatten(getWireframeColor()));\r\n\t\r\n\tgl.drawArrays( gl.LINE_STRIP, 0, points.length);\r\n}", "function uploadModelViewMatrixToShader() \n{\n gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);\n}", "function draw() {\n ndraw++;\t\t// not really needed but illustrates a discussion point\n x -= deltax;\t// to get position we are \"integrating\" velocity\n y += deltay;\n z += deltaz;\n if(z > 0) {\t// reinitialize position+rotation when object passes\n\tx = -2;\n\ty = -1.5;\n\tz = -60.0;\n\trotDeg = 0;\n }\n rotDeg += 20;\t// .5 deg additional rotation per time step\n if(rotDeg >= 360)\t// often convenient to reset large rotations to 0\n\trotDeg -= 360;\n mat4.perspective(\n\tpMatrix,45*Math.PI/180, gl.viewportWidth / gl.viewportHeight, 1, 100);\n mat4.identity(mvMatrix);\n mat4.translate(mvMatrix,mvMatrix,[x,y,z]);\n mat4.rotate(mvMatrix,mvMatrix,rotDeg*Math.PI/180, [rotX,rotY,rotZ]);\n gl.bindBuffer(gl.ARRAY_BUFFER, verticeBufferObject);\n gl.vertexAttribPointer(program.vertPos, vertSize, gl.FLOAT, false,0,0);\n gl.bindBuffer(gl.ARRAY_BUFFER, verticeColorBufferObject);\n gl.vertexAttribPointer(program.vertexColorAttrib, 4, gl.FLOAT, false, 0, 0);\n gl.uniformMatrix4fv(program.pMatrixUniform, false, pMatrix);\n gl.uniformMatrix4fv(program.mvMatrixUniform, false, mvMatrix);\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n gl.drawArrays(gl.TRIANGLE_FAN, 0, numVertices);\n setTimeout(\"draw()\", 50); // redraw after 50ms delay\n}", "setSideView() {\n\t\t'use strict';\n\t\tvar ratio = 6;\n\t\tvar camera = new THREE.OrthographicCamera(window.innerWidth / - ratio, window.innerWidth / ratio, window.innerHeight / ratio, window.innerHeight / - ratio);\n\n\t\tcamera.position.set(0, 45, window.innerHeight / 6); //Camera is set to y = 45 and z = 100\n\t\tcamera.updateProjectionMatrix();\n\t\tthis.camera = camera;\n\n\t}", "function render(){\n gl.clear( gl.COLOR_BUFFER_BIT );\n gl.drawArrays( gl.TRIANGLES, 0, points.length );\n}", "setFrontView() {\n\t\t'use strict';\n\t\tvar ratio = 6;\n\t\tvar camera = new THREE.OrthographicCamera(window.innerWidth / - ratio, window.innerWidth / ratio, window.innerHeight / ratio, window.innerHeight / - ratio);\n\n\t\tcamera.position.set(window.innerWidth / - 6, 45, 0); //Camera is set on the position x = -200, y = 45\n\t\tcamera.rotation.y = - (Math.PI / 2); //Camera is rotated 90 degrees (default is xy, we want it looking to yz)\n\t\tcamera.updateProjectionMatrix();\n\t\tthis.camera = camera;\n\t}", "function switchToView(view0)\n{\n\t\n\tview = view0;\n\tvar mode = objController.controlCube.getMode();\n\tif (view == 'perspective') {\n\t\tcontrolHandler.orthographic = false;\n\t\tcontrolsPerspective.enabled = true;\n\t\tcontrolsOrth.enabled = false;\n\t\tobjController.controlCube.enabled = true;\n\n\t\tif (INTERSECTED) {\n\t\t\tshaderMaterial.uniforms.threshold_min.value = INTERSECTED.name.level_min;\n\t\t\tshaderMaterial.uniforms.threshold_max.value = INTERSECTED.name.level_max;\n\t\t}\n\t\telse {\n\t\t\tshaderMaterial.uniforms.threshold_min.value = GROUND_POS.initial.perspective;\n\t\t\tshaderMaterial.uniforms.threshold_max.value = SKY_POS.initial.perspective;\n\t\t}\t\n\n\t\tparas.level_min = shaderMaterial.uniforms.threshold_min.value;\n\t\tparas.level_max = shaderMaterial.uniforms.threshold_max.value;\n\t}\n\n\telse if (view == 'orth') {\n\n\t\t// first find the closest camera\n\t\tvar center = new THREE.Vector3(controlsPerspective.marker3D.matrixWorld.elements[12], \n\t\t\t\t\t\t\t controlsPerspective.marker3D.matrixWorld.elements[13],\n\t\t\t\t\t\t\t controlsPerspective.marker3D.matrixWorld.elements[14]);\n\t\t\n\t\tcontrolHandler.orthographic = true;\n\t\tcontrolsPerspective.enabled = false;\n\t\tcontrolsOrth.enabled = true;\n\t\tobjController.controlCube.enabled = false;\n\n\t\tif (INTERSECTED) {\n\t\t\tshaderMaterial.uniforms.threshold_min.value = INTERSECTED.name.level_min;\n\t\t\tshaderMaterial.uniforms.threshold_max.value = INTERSECTED.name.level_max;\n\t\t}\n\t\telse {\n\t\t\tshaderMaterial.uniforms.threshold_min.value = GROUND_POS.min; //currentPos.height - VERTICAL_HEIGHT_MIN;\n\t\t\tshaderMaterial.uniforms.threshold_max.value = GROUND_POS.max; //currentPos.height + VERTICAL_HEIGHT_MIN;\n\t\t}\n\n\t\tparas.level_min = shaderMaterial.uniforms.threshold_min.value;\n\t\tparas.level_max = shaderMaterial.uniforms.threshold_max.value;\n\t}\n\n\tviewOld = view;\n}", "lookAtModel() {\n const box = new THREE.Box3().setFromObject(this.model);\n const size = box.getSize().length();\n const center = box.getCenter();\n\n this.model.position.x += (this.model.position.x - center.x);\n this.model.position.y += (this.model.position.y - center.y);\n this.model.position.z += (this.model.position.z - center.z);\n \n this.camera.near = size / 100;\n this.camera.far = size * 100;\n this.camera.updateProjectionMatrix();\n \n this.camera.position.x = 176270.75252929013;\n this.camera.position.y = -26073.99366690377;\n this.camera.position.z = 39148.29418709834;\n }", "makeCube(cx, cy, cz, sx, sy, sz) {\n let v0 = [ cx - sx / 2, cy - sy / 2, cz - sz / 2 ];\n let v1 = [ cx - sx / 2, cy - sy / 2, cz + sz / 2 ];\n let v2 = [ cx - sx / 2, cy + sy / 2, cz - sz / 2 ];\n let v3 = [ cx - sx / 2, cy + sy / 2, cz + sz / 2 ];\n let v4 = [ cx + sx / 2, cy - sy / 2, cz - sz / 2 ];\n let v5 = [ cx + sx / 2, cy - sy / 2, cz + sz / 2 ];\n let v6 = [ cx + sx / 2, cy + sy / 2, cz - sz / 2 ];\n let v7 = [ cx + sx / 2, cy + sy / 2, cz + sz / 2 ];\n\n let vertices = [];\n\n let insert = (x) => {\n vertices.push(x[0]);\n vertices.push(x[1]);\n vertices.push(x[2]);\n };\n\n insert(v0); insert(v3); insert(v1); insert(v0); insert(v2); insert(v3);\n insert(v3); insert(v5); insert(v1); insert(v3); insert(v7); insert(v5);\n insert(v3); insert(v6); insert(v7); insert(v3); insert(v2); insert(v6);\n insert(v1); insert(v4); insert(v0); insert(v1); insert(v5); insert(v4);\n insert(v5); insert(v6); insert(v4); insert(v5); insert(v7); insert(v6);\n insert(v0); insert(v6); insert(v2); insert(v0); insert(v4); insert(v6);\n\n let buffer = new Float32Array(vertices);\n\n let vertex_buffer = new GL.Buffer();\n let vertex_array = new GL.VertexArray();\n GL.bindBuffer(GL.ARRAY_BUFFER, vertex_buffer);\n GL.bufferData(GL.ARRAY_BUFFER, buffer.length * 4, buffer, GL.STATIC_DRAW);\n GL.bindVertexArray(vertex_array);\n GL.enableVertexAttribArray(0);\n GL.bindBuffer(GL.ARRAY_BUFFER, vertex_buffer);\n GL.vertexAttribPointer(0, 3, GL.FLOAT, GL.FALSE, 12, 0);\n GL.bindVertexArray(0);\n let m = { };\n m.vertex_buffer = vertex_buffer;\n m.vertex_array = vertex_array;\n m.vertex_count = vertices.length / 3;\n return m;\n }", "setTopView() {\n\t\t'use strict';\n\t\tvar ratio = 6;\n\t\tvar camera = new THREE.OrthographicCamera(window.innerWidth / - ratio, window.innerWidth / ratio, window.innerHeight / ratio, window.innerHeight / - ratio);\n\n\t\tcamera.position.set(0, window.innerWidth / 6, 0); //Camera is set on position y = 200\n\t\tcamera.lookAt(this.scene.position); //Camera looks at the center of the scene (0, 0, 0)\n\t\tcamera.updateProjectionMatrix();\n\t\tthis.camera = camera;\n\t}", "function camera_top_view() {\n camera.rotation.x += Math.PI/2;\n camera.position.y = 3.4;\n}", "function setMaterial(mat)\n{\n gl.uniform3fv(material.diffuseLoc, mat.diffuse);\n gl.uniform3fv(material.specularLoc, mat.specular);\n gl.uniform3fv(material.ambientLoc, mat.diffuse);\n gl.uniform1f(material.shininessLoc, mat.shininess);\n}", "beginHUD(renderer, w, h) {\n var cam = this.cam;\n renderer = renderer || cam.renderer;\n\n if(!renderer) return;\n this.pushed_rendererState = renderer.push();\n\n var gl = renderer.drawingContext;\n var w = (w !== undefined) ? w : renderer.width;\n var h = (h !== undefined) ? h : renderer.height;\n var d = Number.MAX_VALUE;\n\n gl.flush();\n // gl.finish();\n\n // 1) disable DEPTH_TEST\n gl.disable(gl.DEPTH_TEST);\n // 2) push modelview/projection\n // p5 is not creating a push/pop stack\n this.pushed_uMVMatrix = renderer.uMVMatrix.copy();\n this.pushed_uPMatrix = renderer.uPMatrix .copy();\n\n // 3) set new modelview (identity)\n //renderer.resetMatrix(); //behavior changed in p5 v1.6\n renderer.uMVMatrix = p5.Matrix.identity();\n \n // 4) set new projection (ortho)\n renderer._curCamera.ortho(0, w, -h, 0, -d, +d);\n // renderer.ortho();\n // renderer.translate(-w/2, -h/2);\n\n }", "function setProjection(mesh) {\n let bounds = mesh.extent;\n\n let fov_x = X_FIELD_OF_VIEW * Math.PI / 180,\n fov_y = fov_x / ASPECT_RATIO,\n // Distance required to view entire width/height\n width_distance = bounds.width / (2 * Math.tan(fov_x / 2)),\n height_distance = bounds.height / (2 * Math.tan(fov_y / 2)),\n // Distance camera must be to view full mesh\n camera_z = bounds.near + Math.max(width_distance, height_distance) * 1.1;\n\n let projectionMatrix = MV.perspectiveRad(\n fov_y, ASPECT_RATIO, PERSPECTIVE_NEAR_PLANE, PERSPECTIVE_FAR_PLANE);\n\n\tlet eye = vec3(bounds.midpoint[0],\n bounds.midpoint[1],\n camera_z),\n\t at = bounds.midpoint,\n\t up = vec3(0, 1, 0);\n\n\tvar viewMatrix = MV.lookAt(eye, at, up);\n\n // Add margins around the mesh\n var margins = MV.scalem(0.9, 0.9, 0.9);\n projectionMatrix = MV.mult(margins, projectionMatrix);\n\n gl.uniformMatrix4fv(shader.projectionMatrix,\n false,\n MV.flatten(projectionMatrix));\n\n gl.uniformMatrix4fv(shader.viewMatrix,\n false,\n MV.flatten(viewMatrix));\n}", "function gPush() {\r\n MVS.push(modelViewMatrix) ;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a BigInt to a byte array of length l in MSB first order.
function bigint2bytes(m,l) { let r = []; m = BigInt(m); // just in case for(let i = 1 ; i <= l ; i++) { r[l - i] = Number(m & 0xFFn); m >>= 8n; } if (m != 0n) console.log("m too big for l", m, l, r); return r; }
[ "function longToByteArray(long){\n var byteArray = new Uint8Array(8);\n\n for (var index = 0; index < byteArray.length; index++){\n var byte = long & 0xff;\n byteArray [index] = byte;\n long = (long - byte) / 256 ;\n }\n return byteArray;\n}", "function array2bigint(bytes)\n{\n\tlet hex;\n\n\tif (typeof(bytes) == \"string\")\n\t{\n\t\thex = bytes\n\t\t.split('')\n\t\t.map( c => ('00' + c.charCodeAt(0).toString(16)).slice(-2) )\n\t\t.join('');\n\t} else\n\tif (typeof(bytes) == \"object\")\n\t{\n\t\thex = Array.from(bytes)\n\t\t.map( c => ('00' + c.toString(16)).slice(-2) )\n\t\t.join('');\n\t} else\n\t{\n\t\tconsole.log('ERROR', bytes);\n\t}\n\n\tif (hex.length == 0)\n\t{\n\t\tconsole.log(\"ERROR: empty hex string?\", typeof(bytes), bytes);\n\t\thex = \"00\";\n\t}\n\n\tlet bi = BigInt(\"0x\" + hex);\n\t//console.log(bytes, bi);\n\treturn bi;\n}", "function bigint2hex(m,l)\n{\n\tlet r = bigint2bytes(m, l);\n\treturn \"0x\" + r.map(c => ('00' + c.toString(16)).slice(-2) ).join('');\n}", "function bigIntToBuffer(bigint) {\n return hexToBuffer(bigint.toString(16))\n}", "function sha256bigint(m,l)\n{\n\tlet a = bigint2bytes(m,l);\n\tlet hash = sha256.sha256(a);\n\treturn array2bigint(new Uint8Array(hash));\n}", "function arrayPacking(a) {\n return a.reduceRight((aByte, bByte) => (aByte << 8) + bByte);\n}", "function encode_int(v) {\n if (!(v instanceof BigInteger) ||\n v.compareTo(BigInteger.ZERO) < 0 ||\n v.compareTo(LARGEST_NUM_PLUS_ONE) >= 0) {\n throw new Error(\"BigInteger invalid or out of range\");\n }\n return intToBigEndian(v);\n }", "static bytes1(v) { return b(v, 1); }", "bigIntToUint8Array(bigInt) {\n const arr = new Uint8Array(NONCE_LEN)\n let n\n for (let idx = NONCE_LEN - 1; idx >= 0; idx -= 1) {\n n = NONCE_LEN - (idx + 1)\n // 256 ** n is the value of one bit in arr[idx], modulus to carry over\n // (bigInt / 256**n) % 256;\n const denominator = JSBI.exponentiate(JSBI.BigInt('256'), JSBI.BigInt(n))\n const fraction = JSBI.divide(bigInt, denominator)\n const uint8Val = JSBI.remainder(fraction, JSBI.BigInt(256))\n arr[idx] = JSBI.toNumber(uint8Val)\n }\n return arr\n }", "function hs_wordToWord64(low) {\n return [0, low];\n}", "function createBigInt(num){if(typeof BigInteger==='undefined'){BigInteger=getBigIntConstructor();}if(BigInteger===null){throw new Error('BigInt is not supported!');}return BigInteger(num);}", "function binary(dataset) {\n if(dataset.length > 1) {\n var bits =[];\n var msb = conv(dataset[0]);\n var remander = binary(dataset.slice(1,dataset.length));\n bits = bits.concat(msb, remander);\n return bits;\n } else {\n return [conv(dataset)];\n }\n}", "function intToBuffer(integer){var hex=intToHex(integer);return Buffer.from(hex,'hex');}", "function encodeUint8(num) {\n if (num > 255) {\n throw new Error(\"overflow\");\n }\n var encoded = new Uint8Array(8);\n encoded[0] = num;\n return encoded;\n}", "static bytes8(v) { return b(v, 8); }", "function bufferToBigInt(buf) {\n return BigInt('0x' + bufferToHex(buf))\n}", "function toBigendianUint64BytesUnsigned(i, bufferResponse = false) {\n let input = i\n if (!Number.isInteger(input)) {\n input = parseInt(input, 10)\n }\n\n const byteArray = [0, 0, 0, 0, 0, 0, 0, 0]\n\n for (let index = 0; index < byteArray.length; index += 1) {\n const byte = input & 0xFF // eslint-disable-line no-bitwise\n byteArray[index] = byte\n input = (input - byte) / 256\n }\n\n byteArray.reverse()\n\n if (bufferResponse === true) {\n const result = Buffer.from(byteArray)\n return result\n }\n const result = new Uint8Array(byteArray)\n return result\n}", "function dec2bin_array(array,no_of_variables)\n{\n\tvar bin_array = [];\n\tfor (var i = 0; i < array.length; i++)\n\t{\n\t\tbin_array.push(dec2bin(array[i]));\n\t}\n\tfix_size(bin_array,no_of_variables);\n\treturn bin_array;\n}", "function append_byte_array(so, val, bytes) {\n if (\"number\" !== typeof val) {\n throw new Error(\"Integer is not a number\");\n }\n if (val < 0 || val >= (Math.pow(256, bytes))) {\n throw new Error(\"Integer out of bounds\");\n }\n var newBytes = [];\n for (var i=0; i<bytes; i++) {\n newBytes.unshift(val >>> (i*8) & 0xff);\n }\n so.append(newBytes);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the surround mode to game.
setSurroundModeToGame() { this._setSurroundMode("s_game"); }
[ "setSurroundModeToAuto() {\n this._setSurroundMode(\"s_auto\");\n }", "setSurroundModeToStandard() {\n this._setSurroundMode(\"s_standard\");\n }", "setSurroundModeToStereo() {\n this._setSurroundMode(\"s_stereo\");\n }", "setSurroundModeToRight() {\n this._setSurroundMode(\"s_right\");\n }", "function setGameArea(gameArea) {\n if (g_gamearea) g_gamearea = gameArea;\n}", "setSurroundModeToDolby() {\n this._setSurroundMode(\"s_dolby\");\n }", "setSurroundModeToMusic() {\n this._setSurroundMode(\"s_music\");\n }", "function setGame() {\n console.log(\"game being set\");\n gameStart = false;\n resetRods();\n resetBall();\n}", "changePlayerMode() {\n this._inPlayerMode = !this._inPlayerMode\n this.reset()\n }", "setSurroundModeToVirtual() {\n this._setSurroundMode(\"s_virtual\");\n }", "setSurroundModeToMatrix() {\n this._setSurroundMode(\"s_matrix\");\n }", "setSurroundModeToLeft() {\n this._setSurroundMode(\"s_left\");\n }", "function changeBattlePlan() {\n switch (battleSettings.currentBattleMode) {\n case 'defence':\n battleSettings.currentBattleMode = 'machineGunAttack';\n break;\n\n case 'sideDefence':\n battleSettings.currentBattleMode = 'defence';\n break;\n\n case 'massiveAttack':\n battleSettings.currentBattleMode = 'sideDefence';\n break;\n\n case 'ultraAttack':\n\n break;\n\n case 'machineGunAttack':\n if (battleSettings.massiveCannonsCounter >= 2) { //number of machineGun sets\n battleSettings.currentBattleMode = 'massiveAttack';\n battleSettings.massiveCannonsCounter = 0;\n } else {\n battleSettings.currentBattleMode = 'defence';\n }\n break;\n\n default:\n\n }\n }", "setSurroundModeToNeural() {\n this._setSurroundMode(\"s_neural\");\n }", "startGame() {\n let self = this\n this.props.changeSetupConfigClass(\"setupconfig__holder setupconfig__holder__deactive\")\n setTimeout(()=>{\n self.props.changeResetCoords(true)\n self.props.changeMarkerCoords([0,0])\n self.props.changeResetCoords(false)\n self.props.changeActiveHandler(this.props.game.id, false, true)\n self.props.changeActiveState(this.props.game.id, true)\n }, 1600)\n }", "function displayModePatch() {\n\tif (PLAYER.type!=PLAYERTYPE) {\n\t\tPLAYERTYPE=PLAYER.type;\n\t\tif ($_modesel.val()==\"chMode\" || $_modesel.val()==\"rMode\") {\n\t\t\t$videowidth.removeClass().addClass('span1');\n\t\t\t$(\"#ytapiplayer\").attr(\"width\", '1').attr(\"height\", '1');\n\t\t}\n\n\t}\n}", "setSurroundModeToDirect() {\n this._setSurroundMode(\"s_direct\");\n }", "changeTurn() {\n this.setupFog(false);\n super.changeTurn();\n }", "set resolutionMode(value) {}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove user from group See: ``` api.removeUserFromGroup( id, userId ) ``` TODO: check what this returns
removeUserFromGroup (id, userId) { assert.equal(typeof id, 'number', 'id must be number') assert.equal(typeof userId, 'number', 'userId must be number') return this._apiRequest(`/group/${id}/user/${userId}`, 'DELETE') }
[ "removeUserFromGroup(hub, group, userId, options) {\n const operationOptions = coreHttp.operationOptionsToRequestOptionsBase(options || {});\n return this.client.sendOperationRequest({ hub, group, userId, options: operationOptions }, removeUserFromGroupOperationSpec);\n }", "static async removeUser(userId, groupId) {\n const size = Group.decrement_group_size(groupId);\n if (size === 0) {\n Group.remove(groupId);\n }\n else {\n const result = await db.query(\n `DELETE FROM user_groups \n WHERE user_id = $1 \n AND group_id = $2\n RETURNING id`,\n [userId, groupId]\n );\n return result.rows[0];\n }\n }", "removeUser(userId) {\n for (let user of this.getUsers()) {\n if (user._id === userId) {\n this.users.splice(this.users.indexOf(user), 1);\n }\n }\n }", "function removeGroup(name){\n var grp = getGroupByName(name);\n var index = 0;\n for (var i = 0; i < this.groups.length; i++) {\n grp = this.groups[i];\n if(grp.name == name){\n index = i;\n }\n }\n io.emit('kickfromgroup', name);\n this.groups.splice(index, 1);\n dbDelete({name : name}, \"groups\");\n}", "admin_remove_user(user_id) {\n if (Roles.userIsInRole(Meteor.userId(), ['admin'])) {\n Meteor.users.remove(user_id);\n return \"OK\";\n }else { return -1; }\n }", "async function deleteGroup(user, group) {\n const userId = ObjectId(user);\n const groupId = ObjectId(group);\n\n // Try to delete a group that has no users other than the user\n const query = {\n _id: groupId,\n $and: [\n { grpUsers: { $size: 1 } },\n { \"grpUsers.user\": userId },\n ],\n };\n const result = await db.collection(\"Groups\")\n .findOneAndDelete(query, { projection: { _id: 0, modules: 1 } });\n\n // Check if the deletion was successful\n if (!result.value) {\n return false;\n }\n\n // Remove the group from the user\n await db.collection(\"Users\")\n .updateOne({ _id: userId }, { $pull: { groups: groupId } });\n\n // Remove direct invites and invite links\n await db.collection(\"Invites\").deleteMany({ group: groupId });\n await db.collection(\"GroupLinks\").deleteMany({ group: groupId });\n\n // Remove all modules and items\n const inModules = { $in: result.value.modules };\n await db.collection(\"Modules\").deleteMany({ _id: inModules });\n await db.collection(\"Messages\").deleteMany({ modId: inModules });\n await db.collection(\"Tasks\").deleteMany({ modId: inModules });\n await db.collection(\"Events\").deleteMany({ modId: inModules });\n\n return true;\n}", "async function deleteUser(userId) {\n await fetch(`/api/users/${userId}`, {\n method: 'DELETE'\n });\n\n // Re-fetch users after deleting\n fetchUsers()\n }", "static deleteAction(userId, groupId){\n\t\tlet kparams = {};\n\t\tkparams.userId = userId;\n\t\tkparams.groupId = groupId;\n\t\treturn new kaltura.RequestBuilder('groupuser', 'delete', kparams);\n\t}", "addUserToGroup (id, userId, roleId) {\n assert.equal(typeof id, 'number', 'id must be number')\n assert.equal(typeof userId, 'number', 'userId must be number')\n assert.equal(typeof roleId, 'string', 'roleId must be string')\n return this._apiRequest(`/group/${id}/user/${userId}`, 'POST', {\n user_role_id: roleId\n })\n }", "deleteGroup (id) {\n assert.equal(typeof id, 'number', 'id must be number')\n return this._apiRequest(`/group/${id}`, 'DELETE')\n }", "async destroy({ params, request, response }) {\n const group = await Group.find(params.group_id)\n if (!group) return response.notFound({ message: 'group not found!' })\n\n const user = await User.find(params.id)\n if (!user) return response.notFound({ message: 'user does not exist!' })\n\n if (!await group.isMember(params.id)) {\n return response.forbidden({ message: `${user.name} is not member of ${group.title}` })\n }\n\n if (group.admin_id !== params.id) {\n return response.forbidden({ message: `Only admin of the ${group.title} can delete members` })\n }\n\n const res = await group.users()\n .detach([params.id])\n\n return {\n message: res,\n }\n }", "async function kick(user, group, targetUser) {\n await permissionCheck(user, group, targetUser, 'kick');\n await removeFromGroup(targetUser, group);\n}", "removeUserFromChannel(username, channel){\n var index = -1;\n var ch = this.getChannelByName(channel);\n if(ch != null){\n for (var i = 0; i < ch.users.length; i++) {\n var u = ch.users[i];\n if(u.name == username){\n index = i;\n }\n }\n }\n if(index > -1 && ch != null){\n ch.users.splice(index, 1);\n }\n io.emit('refreshchannels', [this.name, username]);\n dbDelete({groupname: this.name, channelname: channel, username: username}, \"channel_users\");\n }", "deleteDisplayTemplateGroup (groupId) {\n console.log('deleteDisplayTemplateGroup:', groupId);\n let user = Auth.requireAuthentication();\n \n // Validate the data is complete\n check(groupId, String);\n \n // Validate that the current user is an administrator\n if (user.isAdmin()) {\n DisplayTemplateGroups.remove(groupId);\n \n // Remove this groupId from everything using it, so they go back to the parentless group\n DisplayTemplates.update({ parentGroup: groupId }, { $unset: { parentGroup: true } });\n DisplayTemplateGroups.update({ parentGroup: groupId }, { $unset: { parentGroup: true } });\n } else {\n console.error('Non-admin user tried to delete an integration display template group:', user.username, groupId);\n throw new Meteor.Error(403);\n }\n }", "function deleteUser(req, res) {\n User.remove({_id : req.params.id}, (err, result) => {\n res.json({ message: \"Bucket successfully deleted!\", result });\n });\n}", "addUserToGroup(hub, group, userId, options) {\n const operationOptions = coreHttp.operationOptionsToRequestOptionsBase(options || {});\n return this.client.sendOperationRequest({ hub, group, userId, options: operationOptions }, addUserToGroupOperationSpec);\n }", "deleteUser( id ) {\n fluxUserManagementActions.deleteUser( id );\n }", "function deleteUser(event) {\n let id = getUserId(event.target);\n fetch(url+\"/api/users/\"+id, {\n method: \"DELETE\",\n headers: {\n \"authorization\": jwt\n }\n }).\n then((response) => {\n if (response.ok) {\n updateStateAndRefresh(\"User \" + id + \" has been deleted.\", true);\n }\n else {\n updateStateAndRefresh(\"User \" + id + \" not deleted!\", false);\n }\n });\n}", "function userDelete(id, cb){\n User.findByIdAndDelete(id, function (err, user) {\n if (err) {\n if (cb) cb(err, null)\n return\n }\n console.log('Deleted User: ' + user);\n if (cb) cb(null, user)\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
searchCrit is a mongoDb search criteria. TODO: SECURITY!!!!!!!!!!!!!!!!!!!!!11 callback(err, campaignArray)
function findCampaigns(searchCrit, callback) { $.ajax({ type: 'POST', url: '/api/search', data: JSON.stringify(searchCrit), success: function(data) {if (callback) {callback(null, data);}}, error:function(jqXHR ) {if (callback) {callback(jqXHR.responseText);}}, contentType: "application/json", dataType: 'json' }); }
[ "function findCampaignsMetadata(searchCrit, callback) {\r\n $.ajax({\r\n type: 'POST',\r\n url: '/api/search',\r\n data: JSON.stringify(searchCrit),\r\n success: function(data) {if (callback) {callback(null, data);}},\r\n error:function(jqXHR ) {if (callback) {callback(jqXHR.responseText);}},\r\n contentType: \"application/json\",\r\n dataType: 'json'\r\n });\r\n}", "function concertSearch() {\n let search = process.argv.splice(3).join(\"%20\");\n\n let queryURL = \"https://rest.bandsintown.com/artists/\" + search + \"/events?app_id=\" + concerts.id;\n // actual request for the concerts\n axios.get(\n queryURL\n ).then(function (response) {\n\n let concert = response.data;\n // for every concert returned, console log the requested information\n for (i = 0; i < concert.length; i++) {\n console.log(\"\\n\" + concert[i].datetime // couldn't figure out how to use moment to make the time easier to read\n + \"\\n\" + concert[i].venue.name + \" in \" + concert[i].venue.city + \", \" + concert[i].venue.region\n + \"\\n\" + concert[i].lineup.join(\", \"));\n };\n\n }).catch(function (err) {\n console.log(err);\n });\n}", "function findCollectionByX(collection, criteria, callback) {\n connectToDb(function onConnect(err, db) {\n if (err) {\n callback(err);\n } else {\n db.collection(collection).find(criteria).toArray(function onResult(err2, data) {\n db.close();\n callback(err2, data);\n });\n }\n });\n}", "function searchCongressMembers(searchQuery, members) {\n\tlet searchedCongressMembers = members.filter(member => {\n\t\tlet memberName;\n\t\tif (member.middle_name) {\n\t\t\tmemberName = `${member.first_name} ${member.middle_name} ${member.last_name}`;\n\t\t} else {\n\t\t\tmemberName = `${member.first_name} ${member.last_name}`;\n\t\t}\n\t\treturn memberName.toLowerCase().includes(searchQuery.toLowerCase());\n\t});\n\treturn searchedCongressMembers;\n}", "function search(err, client, done, req, res) {\n if(err) {\n return console.error('error fetching client from pool', err);\n }\n var reqArr = [req.body.lifetime, req.body.type, req.body.netFood, req.body.posFood, req.body.negFood, req.body.members];\n var jsonQuery = \"\";\n var i;\n jsonQuery += \"array[\";\n for (i=0; i<req.body.members.length; i++) {\n jsonQuery += JSON.stringify(req.body.members[i]) + \"::json\";\n if (i < (req.body.members.length-1)) {\n jsonQuery += \",\";\n }\n }\n jsonQuery += \"]\";\n reqArr[5] = jsonQuery;\n client\n //INSERT INTO \"ACSchema\".\"Search\"( \"Lifetime\", \"Type\", \"Net_Food\", \"Pos_Food\", \"Neg_Food\", \"Members\") VALUES (5, 4, 3, 2, 1, array_to_json('{{1,5},{99,100}}'::int[]));\n .query('INSERT INTO \"ACSchema\".\"Search\"(\"Lifetime\", \"Type\", \"Net_Food\", \"Pos_Food\", \"Neg_Food\", \"Members\") VALUES ($1, $2, $3, $4, $5, $6)',\n //.query('INSERT INTO \"ACSchema\".\"Search\"(\"Lifetime\", \"Type\", \"Net_Food\", \"Pos_Food\", \"Neg_Food\", \"Members\") VALUES (1, 1, 1, 1, 1, array[\\'{\"key\\\":\"value\"}\\'::json,\\'{\"key\":\"value\"}\\'::json])',\n reqArr,\n function(err) {\n done();\n if(err) {\n res.json({reqArr: reqArr[5]});\n return console.error('error running query', err);\n }\n res.send(req.query);\n });\n}", "function search() {\n\n const search_value = document.querySelector('#name').value.toLowerCase();\n var word = search_value.toString()\n console.log(word);\n var search_arr = [];\n\n for(i = 0; i < monst_arr.length; i++){\n const monster_name = monst_arr[i];\n if(monster_name.includes(word)){\n console.log(\"found it\", monst_arr[i]);\n search_arr.push(monster_name);\n }\n };\n \n console.log(search_arr)\n //function that loads the search results with the new array as the argument\n load_search_results(search_arr)\n\n }", "async function matchJobTitle(userIdIn, preferenceIn) {\n\n var db = await MongoClient.connect(process.env.PROD_MONGODB);\n var searchPreferences = await db.collection('preferences').find({userId: new ObjectID(userIdIn)}).toArray();\n //console.log(searchPreferences);\n var locationPrefs = [];\n for (var i = 0; i < searchPreferences.length; i++) {\n if (searchPreferences[i].type == 'location') {\n //var commaIndex = searchPreferences[i].preference.indexOf(',');\n locationPrefs.push(searchPreferences[i].preference); //.slice(0, commaIndex));\n }\n }\n var {preference} = preferenceIn;\n\n var locationsOR = [];\n for (var i = 0; i < locationPrefs.length; i++) {\n var commaIndex = locationPrefs[i].indexOf(',');\n var citySegment = locationPrefs[i].slice(0, commaIndex);\n var stateSegment = locationPrefs[i].slice(commaIndex + 2);\n locationsOR.push({city: citySegment, state: stateSegment});\n }\n\n if (locationsOR.length > 0) {\n var matches = await db.collection('jobs').find(\n {crawled: true, jobTitle: { $regex: preference, $options: 'i' }, $or: locationsOR }\n ).project({_id: 1}).toArray();\n\n await db.close();\n return matches.map(function(a) {return a._id;});\n }\n else {\n await db.close();\n return [];\n }\n}", "function mongoFindAll(collection, field, value, extra, callback){\n\t\tvar searchobj = {};\n\t\tsearchobj[field] = value;\n\t\t\n\t\tdbo.collection(collection).find(searchobj).toArray(function(err, result){\n\t\t\tif (err) throw err;\n\t\t\tcallback(result, extra);\n\t\t});\n\t}", "function autocomplete (index, query) {\n var reg, matches = [];\n\n query = query.trim();\n var queryItems = query.split(' ');\n\n // kindof hacky but supports input like 198:111\n if (query.indexOf(':') != -1) {\n var nums = query.split(':');\n if (tryNumber(nums[0])) {\n queryItems = [nums[0], nums[1]];\n }\n }\n\n // If the last token looks like a number and is the right length, don't use it\n // when looking for subjects because its probably a courseno\n\n // Also, if queryItems.length is 1 then this is a subjno, not a courseno\n\n var courseno = queryItems[queryItems.length - 1];\n if (tryNumber(courseno) && queryItems.length > 1) {\n queryItems.pop();\n query = queryItems.join(' ');\n } else courseno = null;\n\n var subjno = queryItems[0];\n if (tryNumber(subjno)) {\n if (index.ids[subjno]) matches.push({subj: subjno});\n }\n\n // fuzzy search of subject names\n if (query.length > 2) {\n var temp = fuzzy(index.names, query);\n\n matches = matches.concat(_.map(temp, function (item) {\n return {subj: item};\n }));\n } \n\n // Search subject abbreviations\n if (index.abbrevs[query.toUpperCase()]) {\n matches = matches.concat(_.map(index.abbrevs[query.toUpperCase()], function (id) {\n return {subj: id};\n }));\n }\n\n // if we have a courseno try to locate it in the subjects we found\n if (courseno) {\n if (matches.length > 0) {\n matches = _.reduce(matches, function (memo, item) {\n var idx;\n if (index.ids[item.subj].courses[courseno]) {\n memo.push({subj: item.subj, course: courseno});\n }\n return memo;\n }, []);\n }\n }\n\n // search all courses.. only do this if we couldn't find anything else\n if (matches.length === 0 && query.length > 2) {\n matches = fuzzy(index.courses, query);\n }\n\n return matches;\n}", "function getData(route, item, from, to, callback){\r\n\t\tvar collection;\r\n\t\tif(whitelist[route].indexOf(item) >= -1){\r\n\t\t\tcollection = db.collection(route+\"\"+item);\r\n\t\t\tcollection.find({\"created_at\" : {\"$gt\":from, \"$lt\": to}}).limit(500).toArray(function(err,docs){\r\n\t\t\t\tif(err){\r\n\t\t\t\t\tconsole.error(\"error : \", err);\r\n\t\t\t\t\treturn callback(\"Error in db query\", null);\r\n\t\t\t\t}\r\n\t\t\t\treturn callback(null, docs);\r\n\t\t\t});\r\n\t\t}else{\r\n\t\t\treturn callback(\"Item or category not found\", null);\r\n\t\t}\r\n\t}", "LoadCriteres() {\n\t\t//window.console.log('rso load crit : offer Id'+this.selectedOffer);\n\t\tgetCriteres({RecordId: this.selectedOffer})\n\t\t.then(result => {\n\t\t\t\n\t\t\n\t\t\t//window.console.log('rso log crit All 2 '+JSON.stringify(result));\n\t\t\tthis.Sectioncriteres=result;\n\t\t\tthis.criteres=result;\n\t\t\t//indow.console.log('rso log crit All 2');\n\n\t\t\t\n\n\t\t\n\t\t\t/*if(result) {\n\t\t\t\tfor(let key in result) {\n\t\t\t\t\t// Preventing unexcepted data\n\t\t\t\t\tif (result.hasOwnProperty(key)) { // Filtering the data in the loop\n\t\t\t\t\t\tthis.mapData.push({value:result[key], key:key});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\t*/\n\t\t\t\n\t\t\t\n\t\t})\n\t\t.catch(error => {\n\t\t\tthis.error = error;\n\t\t});\n\t}", "isSomeActionDoneOnThisDocumentAndFilterWho(userArray, activitynum) {\n var Documentarr = [];\n userArray.forEach((element) => {\n if (element.objectId == this.objectId && element.owner.email.replace(/.*@/, \"\") != this.domain) {\n Documentarr.push(element);\n }\n ;\n });\n if (Documentarr.length == 0) {\n return { text: 'no' };\n }\n else {\n var emailsWhoPrinted = [];\n Documentarr.forEach((element) => {\n if (element.type == activitynum) {\n emailsWhoPrinted.push(element.owner.email);\n }\n });\n if (emailsWhoPrinted.length == 0) {\n return { text: 'no' };\n }\n else {\n return { text: 'yes', name: emailsWhoPrinted };\n }\n }\n }", "searchDocuments() {\n\n let searchObj = {}\n if (this.searchType === 'query') {\n searchObj.query = this.query;\n } else if (this.searchType === 'field') {\n searchObj.fieldCode = this.queryField;\n searchObj.fieldValue = this.queryFieldValue;\n }\n this.etrieveViewer.Etrieve.searchDocuments(searchObj)\n .catch(err => {\n console.error(err);\n });\n }", "static searchContacts(searchStr) {\n const searchStrLowerCase = searchStr.toLowerCase();\n const searchContacts = ContactsStorage.getContacts().then((contacts) => {\n const matches = [];\n contacts.forEach((contact) => {\n const firstNameLower = contact.first_name.toLowerCase();\n const lastNameLower = contact.last_name.toLowerCase();\n const emailLower = contact.email.toLowerCase();\n if (\n firstNameLower.startsWith(searchStrLowerCase) ||\n lastNameLower.startsWith(searchStrLowerCase) ||\n contact.email.startsWith(searchStrLowerCase)\n ) {\n matches.push(contact);\n }\n });\n const contactsRow = document.querySelector(\"#contacts-row\");\n contactsRow.innerHTML = \"\";\n if (matches.length === 0) UserInterface.errorMessage(\"No contacts found\");\n matches.forEach((match) => UserInterface.addContactsToDisplay(match));\n });\n }", "function search1(searchTerm) {\n let docsWithTerm = []\n let reportsWithTerm = []\n let selectedReports = []\n docToRep = {}\n\n Object.keys(store.page).forEach(page => {\n if (page.body.includes(searchTerm) || page.footnote.includes(searchTerm)) {\n docsWithTerm.push(page.document_id)\n }\n })\n Object.keys(store.document).forEach(doc => {\n if (docsWithTerm.includes(doc.id) || doc.name.includes(searchTerm)) {\n reportsWithTerm.push(doc.report_id)\n }\n })\n Object.keys(store.report).forEach(rep => {\n if (reportsWithTerm.includes(rep.id) || rep.title.includes(searchTerm)) {\n selectedReports.push(rep.title)\n }\n })\n return selectedReports\n}", "function searchChannels(query, channels) {\n const queryLowerCased = query.toLowerCase();\n return channels.filter(\n (ch) =>\n ch.name.toLowerCase().includes(queryLowerCased) ||\n ch.description.toLowerCase().includes(queryLowerCased)\n );\n}", "function handle_bp_biller_corp_search(req, startTime, apiName) {\n this.req = req; this.startTime = startTime; this.apiName = apiName;\n}", "search(config, options) {\n let documents = [];\n const selector = {\n $distinct: { vpath: 1 }\n };\n if (options.pathmatch) {\n if (typeof options.pathmatch === 'string') {\n selector.vpath = new RegExp(options.pathmatch);\n } else if (options.pathmatch instanceof RegExp) {\n selector.vpath = options.pathmatch;\n } else {\n throw new Error(`Incorrect PATH check ${options.pathmatch}`);\n }\n }\n if (options.renderpathmatch) {\n if (typeof options.renderpathmatch === 'string') {\n selector.renderPath = new RegExp(options.renderpathmatch);\n } else if (options.renderpathmatch instanceof RegExp) {\n selector.renderPath = options.renderpathmatch;\n } else {\n throw new Error(`Incorrect PATH check ${options.renderpathmatch}`);\n }\n }\n if (options.mime) {\n if (typeof options.mime === 'string') {\n selector.mime = { $eeq: options.mime };\n } else if (Array.isArray(options.mime)) {\n selector.mime = { $in: options.mime };\n } else {\n throw new Error(`Incorrect MIME check ${options.mime}`);\n }\n }\n if (options.layouts) {\n if (typeof options.layouts === 'string') {\n selector.docMetadata = {\n layout: { $eeq: options.layouts }\n }\n } else if (Array.isArray(options.layouts)) {\n selector.docMetadata = {\n layout: { $in: options.layouts }\n }\n } else {\n throw new Error(`Incorrect LAYOUT check ${options.layouts}`);\n }\n }\n let coll = this.getCollection(this.collection);\n let paths = coll.find(selector, {\n vpath: 1,\n $orderBy: { renderPath: 1 }\n });\n for (let p of paths) {\n let info = this.find(p.vpath);\n documents.push(info);\n }\n\n if (options.tag) {\n documents = documents.filter(doc => {\n if (!doc.metadata) return false;\n return (doc.metadata.tags.includes(options.tag))\n ? true : false;\n });\n }\n\n if (options.rootPath) {\n documents = documents.filter(doc => {\n return (doc.renderPath.startsWith(options.rootPath))\n ? true : false;\n });\n }\n\n if (options.glob) {\n documents = documents.filter(doc => {\n return minimatch(doc.vpath, options.glob);\n });\n }\n\n if (options.renderglob) {\n documents = documents.filter(doc => {\n return minimatch(doc.renderPath, options.renderglob);\n });\n }\n\n if (options.renderers) {\n documents = documents.filter(doc => {\n if (!options.renderers) return true;\n let renderer = config.findRendererPath(doc.vpath);\n for (let renderer of options.renderers) {\n if (renderer instanceof renderer) {\n return true;\n }\n }\n return false;\n });\n }\n\n if (options.filterfunc) {\n documents = documents.filter(doc => {\n return options.filterfunc(config, options, doc);\n });\n }\n\n return documents;\n }", "function searchAndAddMatchesToDivide(resultsDivide, arrayToSearch, inputString){\n\n for (index = 0; index < arrayToSearch.length; index++) {\n \n if (arrayToSearch[index].title.substr(0, inputString.length).toUpperCase() == inputString.toUpperCase()) {\n addResultElementTo(resultsDivide, arrayToSearch[index]); \n \n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update specific classname to fixed element
styleFixedElement(element, computedStyle = null) { const { hasFixedPosition, leftPx, rightPx } = this.getFixedPosition(element, computedStyle); if (!hasFixedPosition) { if (element.classList.contains(StyleClass.FixedElement)) { element.classList.remove(StyleClass.FixedElement, ...this.classes); } } else if (!element.classList.contains(StyleClass.FixedElement)) { if (leftPx !== null) { if(rightPx >= leftPx) { const leftClass = this.getLeftClass(leftPx); element.classList.add(StyleClass.FixedElement, leftClass); } if(rightPx < 0 && rightPx >= - 50) { element.classList.add(StyleClass.FixedElement); } } else { const hasMaxWidth = this.getMaxWidth(element, computedStyle); if(!hasMaxWidth) { element.classList.add(StyleClass.FixedElement); } } } }
[ "function updateElement(elementClass,replaceContent){\n\n document.querySelector(elementClass).innerHTML = replaceContent;\n\n\n}", "function mark(elem, marker) {\n\tif (elem && !hasClass(elem, marker)) {\n\t\tvar names = getClassNames(elem) || [];\n\t\tnames.push(marker);\n\t\telem.className = names.join(' ');\n\t}\n}", "function updateContentClass(content, desiredState) {\n // If no desiredState, remove all classes\n if (!desiredState) content.classList.remove(\"left\", \"center\", \"right\")\n // Else update to desiredState by replacing or adding\n else {\n if (content.classList.contains(\"left\")) content.classList.replace(\"left\", desiredState)\n else if (content.classList.contains(\"center\")) content.classList.replace(\"center\", desiredState)\n else if (content.classList.contains(\"right\")) content.classList.replace(\"right\", desiredState)\n else content.classList.add(desiredState)\n }\n}", "function changeClass(elementId, className){\r\n // Get a reference to the element\r\n element = document.getElementById(elementId);\r\n // Make sure the element was on the page\r\n if (element) {\r\n\t\t\t// Update the element's className property\r\n\t\t\telement.className = className;\r\n }\r\n }", "function setNavPosition(){\n let fixed = nav.classList.contains(\"fixed\")\n\n if(yOffset >= about.offsetTop && !fixed)\n {\n nav.classList.add(\"fixed\")\n }\n else if(yOffset < about.offsetTop && fixed)\n {\n nav.classList.remove(\"fixed\")\n }\n}", "function placeMarker(cell, currentClass) {\n cell.classList.add(currentClass);\n}", "function _on__classChange()\n {\n var newAbsalignClass = _fetch__absalignClassFromClass(),\n is__absalignClassDifferent = (_absalignClass !== newAbsalignClass);\n\n if (is__absalignClassDifferent)\n {\n _absalignClass = newAbsalignClass;\n\n _populate__axesFromAbsalignClass(_absalignClass);\n _place();\n }\n\n setTimeout(_on__classChange, 100);\n }", "function replaceClass(element, search, replace) {\n\t\t\tif(element.className) {\n\n\t\t\t\tif(replace && new RegExp(\"(^|\\\\s)\" + replace + \"(\\\\s|$)\").test(element.className)) {\n\t\t\t\t\treplace = ''\n\t\t\t\t}\n\n\t\t\t\tvar subject = element.className,\n\t\t\t\t searchRE = new RegExp(\"(^|\\\\s+)\" + search + \"(\\\\s+|$)\", \"g\"),\n\t\t\t\t m = searchRE.exec(subject);\n\n\t\t\t\tif(m) {\n\t\t\t\t\t// swallow unneeded/extra spaces\n\t\t\t\t\tif(replace)\n\t\t\t\t\t\treplace = (m[1] ? \" \" : \"\") + replace + (m[2] ? \" \" : \"\")\n\t\t\t\t\telse\n\t\t\t\t\t\treplace = m[1] && m[2] ? \" \" : \"\"\n\n\t\t\t\t\telement.className = subject.replace(searchRE, replace)\n\t\t\t\t}\n\t\t\t}\n\t\t}", "function changeBackgroundColorForClass(className) {\n var elements = document.getElementsByClassName(className);\n changeBG(elements);\n}", "function switchToFixedLayout() {\n layout = \"fixed\";\n var sidebarFull = $(\".left-sidebar-toplevel\").detach();\n $(\".sidebar-target-fixed\").prepend(sidebarFull);\n $(\".left-sidebar-toplevel\").removeClass(\"left-sidebar-collapsible\");\n $(\".left-sidebar-toplevel\").addClass(\"left-sidebar-fixed col-4 col-lg-4 col-xl-3 \");\n $(\".left-sidebar-togglebutton\").addClass(\"hide\");\n $(\".center-content\").addClass(\"col-8\");\n\t\t$(\".main-container-fixed\").css(\"margin-left\",\"auto\");\n\t\t$(\".center-content\").removeClass(\"col-12\");\n\t}", "addClass (className, addClass, callbacks) {\n let t = this\n let elements = t.element.getElementsByClassName(className)\n for (let i = 0; i < elements.length; ++i) {\n TextMark.addClassToElement(elements[i], addClass)\n }\n if (callbacks !== undefined) {\n if (elements.length > 0 && callbacks.add !== undefined) {\n callbacks.add(elements[0])\n }\n }\n }", "function changeNavClass(nav_element) {\n document.getElementById(\"nav-about\").className = \"nav-icons\";\n document.getElementById(\"nav-research\").className = \"nav-icons\";\n document.getElementById(\"nav-publication\").className = \"nav-icons\";\n document.getElementById(\"nav-conference\").className = \"nav-icons\";\n document.getElementById(\"nav-teaching\").className = \"nav-icons\";\n\n document.getElementById(nav_element).className += \" active\";\n\n document.getElementById(\"location_icon\").className = \"fas fa-map-marker-alt\";\n document.getElementById(\"research_icon\").className = \"fa fa-flask fa-fw\";\n document.getElementById('book_icon').src=\"assets/images/icons/book-1.png\"\n document.getElementById(\"gear1\").style.display = \"none\";\n document.getElementById(\"gear2\").style.display = \"none\";\n\n }", "function addCssClasses(){\n $('.blur-container').addClass(\"blur-filter\");\n $('.shelter-contact').addClass('shelter-legibility');\n}", "function myFunction() {\n\tif (window.pageYOffset >= sticky) {\n\t\ttoolbar.classList.add(\"toolbar-fixed\")\n\t} else {\n\t\ttoolbar.classList.remove(\"toolbar-fixed\");\n\t}\n}", "function flightHandlerFunction() {\ndocument.getElementById(\"flight\").classList.replace(\"powerDisabled\", \"powerEnabled\");\n}", "function limitBarColor(status, amount, chara){\n\n//Use the string to locate the correct id whom class name will be replaced and then removes it.\ndocument.querySelector(\"[id=\"+`${chara}LimitBar`+\"]\").classList.remove(document.querySelector(\"[id=\"+`${chara}LimitBar`+\"]\").className);\n//Use the status and amount to determine the new class, if the amount is 180 (maximum) the class will be \"Break\" else will be determined by status.\nlet newClass; \n\nif (amount == \"180px\"){\n newClass = \"limitBarBreak\";\n }\nelse {\n switch(status){\n\n case \"Fury\":\n newClass = \"limitBarFury\";\n break;\n\n case \"Sadness\":\n newClass = \"limitBarSadness\";\n break;\n\n default:\n newClass = \"limitBar\"; \n }\n} \nreturn newClass;\n}", "function addClassesToElmnt (elmnt, classesToAdd) {\n elmnt.className = ''; // removes all classes from element\n let classesToAddVar = \"\" ; // blank string\n // Now loops through the strings in array classesToAdd\n // and concatenate them with blank string in var\n // classesToAddVar: \n for (let i = 0; i < classesToAdd.length; i++) {\n classesToAddVar += classesToAdd[i] ;\n } // end for\n // Now add all the classes to the element in question: \n elmnt.classList.add (classesToAddVar);\n }", "function updateStyle(phase) {\n d3.select('span#phase')\n .attr('class', phase);\n d3.select('body')\n .attr('class', phase);\n d3.selectAll('.panel')\n .attr('class', 'panel ' + phase);\n }", "applyFixedHeader() {\n if ( $('body').hasClass('allow-fixed-header') ) {\n if ($(window).scrollTop() > 0) {\n $('body').addClass('fixed-header');\n } else {\n $('body').removeClass('fixed-header');\n $('.has-submenu.active').removeClass('show-submenu');\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the thrust of the rocket
updateThrust() { this._thrust = this.fuel * 0.04; }
[ "set thrust(thrust) {\n if(typeof(thrust) != 'number') { throw new Error('INVALID_THRUST')}\n\n this._thrust = thrust;\n }", "SetTurtle(num) {\n if (num == 1) { this.turtleToughness = -1; this.turtleCapacity = 1; this.capacity += this.turtleCapacity; }\n if (num == 2) { this.turtleToughness = -1; this.turtleCapacity = 2; this.capacity += -1 + this.turtleCapacity; }\n if (num == 3) { this.turtleToughness = -2; this.turtleCapacity = 4; this.capacity += -2 + this.turtleCapacity; }\n }", "function SetTorque(t : float) {\n\t\tthis.torque = t * utilScript.signedSqrt(Speed());\n\t}", "changeSpeed() {\r\n this.speed = Math.random() * 3 + 1.5;\r\n }", "hunt() {\n this.food += 2\n }", "set speedVariation(value) {}", "set treadleLevel(newLevel) {\n if (newLevel < 0 || newLevel > 127)\n throw new Error('The treadle level must lie between 0 and 127');\n\n this._treadleLevel = newLevel;\n // Send a CC11 value change\n this._send('cc', { controller: 11, value: newLevel });\n }", "skierIncreaseSpeed() {\n if (vars.score == 500) {\n vars.skierSpeed++;\n } else if (vars.score == 1000) {\n vars.skierSpeed += 2;\n } else if (vars.score == 2000) {\n vars.skierSpeed += 4;\n }\n }", "function setSpeed(s)\r\n{\r\n \r\n ballSpeed = s;\r\n}", "setHightSpeed_() {\r\n this.gameSpeed_ = CONSTANTS.requestAnimationHighSpeed;\r\n\r\n this.board_.setBoardSpeed(this.gameSpeed_);\r\n }", "burnFuel(){\n this.fuel -=1;\n }", "increaseSpeed(value){\r\n this.speed += value;\r\n }", "function adjustCrit (luckySign, luckModifier) {\n var adjust = luckModifier * 1;\n if (luckySign.luckySign != undefined && luckySign.luckySign === \"Warrior's arm\"){\n adjust = luckModifier * 2;\n }\n\treturn adjust;\n}", "function changeDirectionObstacle(rover) {\r\n if (myRover.direction == 'N') {\r\n myRover.direction = 'E';\r\n } else if (myRover.direction == 'E') {\r\n myRover.direction = 'S';\r\n } else if (myRover.direction == 'W') {\r\n myRover.direction = 'N';\r\n } else {\r\n myRover.direction = 'W';\r\n }\r\n}", "sailAway() {\n // making the boat sail to the right \n this.x ++\n // if the boat sails off the screen\n // bring it back from the left\n if (this.x > 400) {\n this.x = - this.w;\n }\n }", "function Tower(spec) {\n spec.selected = false;\n spec.center = {\n x: spec.gridPosition.x * graphics.cellWidth + graphics.cellWidth/2,\n y: spec.gridPosition.y * graphics.cellWidth + graphics.cellWidth/2\n };\n spec.target = {\n x: spec.center.x + 50,\n y: spec.center.y\n };\n var that = {},\n baseSprite = graphics.Sprite({\n sprite: spec.baseSprite,\n center: spec.center,\n rotation: 0\n }),\n weaponSprite = graphics.Sprite({\n sprite: spec.weaponSprite,\n center: spec.center,\n rotation: 0\n });\n\n spec.rotation = 0;\n\n //------------------------------------------------------------------\n //\n // Here we check to see if the tower should still rotate towards the target.\n //\n //------------------------------------------------------------------\n that.update = function (elapsedTime) {\n //\n // Check to see if the tower is pointing at the target or not\n var result = computeAngle(spec.rotation, spec.center, spec.target);\n if (testTolerance(result.angle, 0, .01) === false) {\n if (result.crossProduct > 0) {\n weaponSprite.rotateRight(spec.rotateRate);\n spec.rotation += spec.rotateRate;\n } else {\n weaponSprite.rotateLeft(spec.rotateRate);\n spec.rotation -= spec.rotateRate;\n }\n }\n };\n\n //------------------------------------------------------------------\n //\n // Two parts to the tower, a base and the weapon.\n //\n //------------------------------------------------------------------\n that.render = function () {\n baseSprite.draw();\n weaponSprite.draw();\n\n if (spec.selected || showWeaponCoverage) {\n weaponSprite.drawArc(spec.radius);\n }\n if (spec.selected) {\n graphics.drawGridSquare(spec.gridPosition, 'rgba(0,255,0,0.5)');\n }\n };\n\n that.displayStats = (showSellValue = true) => {\n specName.innerHTML = spec.towerName;\n specTargetType.innerHTML = spec.creepType;\n specLevel.innerHTML = spec.level;\n specRange.innerHTML = spec.radius;\n specDamage.innerHTML = spec.damage;\n specFireRate.innerHTML = spec.fireRate;\n specCost.innerHTML = spec.cost;\n if (showSellValue) {\n specSellVal.innerHTML = spec.sellValue;\n specCostTitle.innerHTML = 'Upgrade Cost';\n document.getElementById('sell-row').classList.remove('hide');\n } else {\n specCostTitle.innerHTML = 'Cost';\n document.getElementById('sell-row').classList.toggle('hide', true);\n }\n document.getElementById('tower-specs').classList.remove('hide');\n };\n\n that.upgradable = () => {\n return (spec.level < 3);\n };\n\n that.upgradeTower = (upgradeData) => {\n weaponSprite.updateImage(upgradeData.weaponSprite);\n spec.radius = upgradeData.radius;\n spec.damage = upgradeData.damage;\n spec.level = upgradeData.level;\n };\n\n that.getCost = () => {\n return spec.cost;\n };\n\n that.getSellVal = () => {\n return spec.sellValue;\n };\n\n that.animateSell = () => {\n graphics.sold(spec.center.x, spec.center.y);\n graphics.smoke(spec.center.x, spec.center.y);\n };\n\n //------------------------------------------------------------------\n //\n // Point we want our weapon to point at.\n //\n //------------------------------------------------------------------\n that.setTarget = function (x, y) {\n spec.target = {\n x: x,\n y: y\n };\n };\n\n that.setSelected = (bool) => {\n spec.selected = bool;\n };\n\n that.positionSame = (gridPosition) => {\n return (gridPosition.x == spec.gridPosition.x && gridPosition.y == spec.gridPosition.y);\n };\n\n return that;\n }", "set metallic(value) {}", "move() {\n this.change = this.mouthGap == 0 ? -this.change : this.change;\n this.mouthGap = (this.mouthGap + this.change) % (Math.PI / 4) + Math.PI / 64;\n this.x += this.horizontalVelocity;\n this.y += this.verticalVelocity;\n }", "function turnWheelTo(angle) {\n\tglobal.target = angle;\n\tvar difference = (global.currentAngle - global.target);\n\t// NOTE, js treats '+' as string concatination by default, + in front of globa.target forces int typing\n\t\n\tif (Math.abs(difference) < global.SLOW_TOLORANCE) {\n\t\tvar forceCoefficient = global.PROPORTIONAL_CONSTANT * difference / (2 * global.SLOW_TOLORANCE); // max value = 0.5\n\t\t// console.log(forceCoefficient);\n\t\tif (difference > global.TOLORANCE) {\n\t\t\t// g.forceConstant(0.3);\n\t\t\tg.forceConstant(0.5 - forceCoefficient);\n\t\t\tglobal.turning = 0;\n\t\t}\n\t\telse if(difference < (-global.TOLORANCE)) {\n\t\t\t// g.forceConstant(0.7);\n\t\t\tg.forceConstant(0.5 - forceCoefficient);\n\t\t\tglobal.turning = 1;\n\t\t} else {\n\t\t\tg.forceConstant(.5);\n\t\t}\n\t}\n\telse if (global.currentAngle > (+ global.target + global.TOLORANCE)) {\n\t\t// console.log('turned wheel left to ' + angle);\n\t\tg.forceConstant(.1);\n\t\tglobal.turning = 0; // turning left\n\t}\n\telse if (global.currentAngle < (+ global.target - global.TOLORANCE)) {\n\t\t// console.log('turned wheel right to' + angle);\n\t\tg.forceConstant(.9);\n\t\tglobal.turning = 1; // turning right\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generates the markdown for the version tag line
_generateTagLine(newVersion, currentVersion) { if (this.repoUrl && Str.weaklyHas(this.repoUrl, 'github.com')) { return (`## [${newVersion}](${this.repoUrl}/compare/v${currentVersion}...v${newVersion}) - ` + `(${Moment().format('YYYY-MM-DD')})`) } else { return (`## ${newVersion} - (${Moment().format('YYYY-MM-D')}) `) } }
[ "function generateMarkdown(readmeData) {\n return `\n # ${readmeData.projectName}\n ${selectBadge(readmeData.license)}\n ## Description\n ${readmeData.description}\n ## Table of Contents\n * [Installation](#installation)\n * [Usage](#usage)\n * [License](#license)\n * [Contributing](#contributors)\n * [Tests](#tests)\n * [Questions](#questions)\n ## Installation\n To install the necessary dependencies, run the following command in your command line: \n ${readmeData.installation}\n ## Usage\n ${readmeData.usage}\n ## License \n This project is covered by ${readmeData.license}.\n ## Contributing\n ${readmeData.userInfo}\n ## Tests\n To run tests, run the following command: \n ${readmeData.test}\n ## Questions\n If you have questions about the project or run into issues, contact me at ${readmeData.email}. You can access more of my work at [${readmeData.github}](https://github.com/${readmeData.github})\n `;\n }", "toString() {\n return `${changelogTitle}\n${changelogDescription}\n\n${stringifyReleases(this._releases, this._changes)}\n\n${stringifyLinkReferenceDefinitions(this._repoUrl, this._releases)}`;\n }", "function tag_version(){\n\treturn new Promise((resolve, reject)=>{\n\t\tconst pkg = reload('../../package.json');\n const tag = `v${pkg.version}`;\n gutil.log('Tagging as: '+gutil.colors.cyan(tag));\n git.tag(tag, `Tagging as ${tag}`, (err)=>{\n\t\t\tcheckError(err);\n\t\t\tresolve(tag);\n })\n\t})\n}", "function logoArt() {\n console.log(\n logo({\n name: \"Employee DB\",\n font: \"Speed\",\n lineChars: 10,\n padding: 2,\n margin: 3,\n borderColor: \"grey\",\n logoColor: \"bold-green\",\n textColor: \"green\",\n })\n .emptyLine()\n .right(\"version 1.0.0\")\n .emptyLine()\n .center(longText)\n .render()\n );\n}", "function generateMD(answer) {\n return `\n# ${answer.title}\n\n## Description \n${answer.description}\n \n## Table of Contents\n* [Installation](#installation)\n* [Usage](#usage)\n* [Credits](#credits)\n* [License](#license)\n \n## Installation\n${answer.installation}\n \n## Usage \n${answer.usage}\n \n## License\n${answer.license}\n \n## Credits\nGitHub usernames:\n${answer.contribution}\n `\n}", "function generateGitContent(data) {\n return (\n `\n## Github details\n${data.name} <br>\n[GitHub URL](${data.url}) <br>\n[Image URL](${data.image}) <br>\nEmail: ameliajanegoodson@gmail.com <br>\n\n`)\n}", "function outputFullVersion(charInfo, version, excludeVersion)\r\n{\r\n debugger;\r\n var output = \"\";\r\n var node = charInfo.head;\r\n\r\n if (excludeVersion === undefined)\r\n {\r\n excludeVersion = [];\r\n }\r\n else if (Array.isArray(excludeVersion) === false)\r\n {\r\n excludeVersion = [excludeVersion];\r\n }\r\n\r\n while (node)\r\n {\r\n if (Array.isArray(version))\r\n {\r\n var include = true;\r\n for (var i = 0; i < version.length; i++)\r\n {\r\n if (node.data.versions.includes(version[i]) === false)\r\n {\r\n include = false;\r\n break;\r\n }\r\n }\r\n if (include === true)\r\n {\r\n for (var i = 0; i < excludeVersion.length; i++)\r\n {\r\n if (node.data.versions.includes(excludeVersion[i]))\r\n {\r\n include = false;\r\n break;\r\n }\r\n }\r\n }\r\n if (include === true) output += node.data.char;\r\n }\r\n else if (version === undefined || node.data.versions.includes(version)) //todo: implement binary search of versions\r\n {\r\n var include = true;\r\n for (var i = 0; i < excludeVersion.length; i++)\r\n {\r\n if (node.data.versions.includes(excludeVersion[i]))\r\n {\r\n include = false;\r\n break;\r\n }\r\n }\r\n if (include === true)\r\n {\r\n output += node.data.char;\r\n }\r\n }\r\n node = node.next;\r\n }\r\n return output;\r\n}", "async function update_changelog() {\n let options = {\n remote: \"origin\",\n commitLimit: 10000,\n backfillLimit: 10000,\n tagPrefix: \"\",\n sortCommits: \"relevance\",\n appendGitLog: \"\",\n appendGitTag: \"\",\n latestVersion: NEW_VERSION,\n };\n const remote = await fetchRemote(options);\n options = {\n ...options,\n ...remote,\n };\n console.log(\"Fetching tags…\");\n const tags = await fetchTags(options);\n console.log(`${tags.length} version tags found…`);\n const onParsed = ({ title }) => console.log(`Fetched ${title}…`);\n const json = await parseReleases(tags, options, onParsed);\n const changelog = await template(json);\n fs.writeFileSync(\"./CHANGELOG.md\", changelog);\n sh`git add CHANGELOG.md`.runSync();\n}", "function getVersion() {\n var contents = grunt.file.read(\"formulate.meta/Constants.cs\");\n var versionRegex = new RegExp(\"Version = \\\"([0-9.]+)\\\";\", \"gim\");\n return versionRegex.exec(contents)[1];\n }", "function logVersion() {\n logger.info(`skyux-cli: ${getVersion()}`);\n}", "async renderHtml () {\n let html = marked(this.markdown, {\n highlight (code, lang) {\n // Language may be undefined (GH#591)\n if (!lang) {\n return code\n }\n\n if (DIAGRAM_TYPE.includes(lang)) {\n return code\n }\n\n const grammar = Prism.languages[lang]\n if (!grammar) {\n console.warn(`Unable to find grammar for \"${lang}\".`)\n return code\n }\n return Prism.highlight(code, grammar, lang)\n },\n emojiRenderer (emoji) {\n const validate = validEmoji(emoji)\n if (validate) {\n return validate.emoji\n } else {\n return `:${emoji}:`\n }\n },\n mathRenderer (math, displayMode) {\n return katex.renderToString(math, {\n displayMode\n })\n }\n })\n html = sanitize(html, EXPORT_DOMPURIFY_CONFIG)\n const exportContainer = this.exportContainer = document.createElement('div')\n exportContainer.classList.add('ag-render-container')\n exportContainer.innerHTML = html\n document.body.appendChild(exportContainer)\n // render only render the light theme of mermaid and diragram...\n this.renderMermaid()\n await this.renderDiagram()\n let result = exportContainer.innerHTML\n exportContainer.remove()\n // hack to add arrow marker to output html\n const pathes = document.querySelectorAll('path[id^=raphael-marker-]')\n const def = '<defs style=\"-webkit-tap-highlight-color: rgba(0, 0, 0, 0);\">'\n result = result.replace(def, () => {\n let str = ''\n for (const path of pathes) {\n str += path.outerHTML\n }\n return `${def}${str}`\n })\n this.exportContainer = null\n return result\n }", "function insertProjectVersionInDOM() {\n var oldvalue = \"<b><u>Version :</u></b> \";\n document.getElementById(\"projectVersion\").innerHTML = oldvalue + getSelectedVersionsName();\n}", "function update_package_file_version() {\r\n\tconst package_file_path = library_base_directory + 'package.json';\r\n\tlet package_file_content = CeL.read_file(package_file_path).toString()\r\n\t\t// version stamp\r\n\t\t.replace(/(\"version\"[\\s\\n]*:[\\s\\n]*\")[^\"]*(\")/, function (all, header, footer) {\r\n\t\t\treturn header + CeL.version + footer;\r\n\t\t});\r\n\tCeL.write_file(package_file_path, package_file_content, { changed_only: true });\r\n}", "compile() {\n // Retrieves the DOM elements of the links we will change\n const dlLink = document.getElementById(\"link-download-vdt\")\n const vwLink = document.getElementById(\"link-view-vdt\")\n const rlLink = document.getElementById(\"link-real-vdt\")\n\n // Converts the tree structure of our page to a Videotex stream\n const actions = MiEdit.mieditActions(this.mitree.serialize())\n const bytes = Minitel.actionsToStream(actions, 0, 0).toArray()\n const vdt = String.fromCharCode.apply(null, bytes)\n\n // Compress the Videotex stream to Base64 format but modifies it so that\n // the generated can be included in a URL\n const compressed = LZString.compressToBase64(vdt)\n .replace(new RegExp('\\\\+', 'g'), '.')\n .replace(new RegExp('/', 'g'), '_')\n .replace(new RegExp('=', 'g'), '-')\n\n // Create the Download VDT link\n dlLink.href = \"data:text/plain;charset=ascii,\"\n + encodeURIComponent(vdt)\n dlLink.setAttribute(\"download\", this.pageName + \".vdt\")\n dlLink.innerHTML = \"Download Videotex stream\"\n\n // Create the View VDT link\n vwLink.href = \"minitel-viewer.html?cstream=\" + compressed\n vwLink.innerHTML = \"View Videotex in fullscreen emulator\"\n\n // Create the View VDT link\n rlLink.href = \"minitel-real-viewer.html?cstream=\" + compressed\n rlLink.innerHTML = \"View Videotex on a Minitel screen\"\n }", "formatDescription(desc) {\n let tag = \"What does this PR do?\";\n let start = desc.indexOf(tag);\n if (start >= 0) {\n let end = desc.indexOf(\"\\r\\n\", start + tag.length + 2);\n return desc.substring(start + tag.length + 1, end);\n } else {\n let end = desc.indexOf(\"\\r\\n\");\n return end >= 0 ? desc.substring(0, end) : desc;\n }\n }", "function notebookStructure(){\n return '<section><div class=\"container\"><div class=\"timeline\"><div class=\"timeline-hline\"></div>'+notebook_content+'</div></div></section>'\n}", "function verbatim( contents )\n{\n //global config;\n verbat = config.INTERNAL.VERBATIM;\n index = verbat.length;\n verbat[index] = contents;\n return \"\\\"+getVerbatim(\"+index+\")+\\\"\";\n}", "function buildNametagHTML (nametag) {\n // TODO: Your code goes here.\n return `\n <div class=\"d-flex align-items-center text-center mt-5\">\n <div style=\"\n width: 200px;\n height: 100px;\n background-color: #FF00FF;\n \">\n <p>${nametag}</p>\n </div>\n </div>\n `\n }", "function generate_flag_html(index)\n{\n var topic_words = reverse_topic_indices[index].replace(/_/g, \"<br>\");\n var text = \"\";\n text += \"<span class='flag_title'>Topic \" + index + \": \";\n text += \"<br></span>\";\n text += topic_words;\n return text;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enter a parse tree produced by Java9ParsersingleElementAnnotation.
enterSingleElementAnnotation(ctx) { }
[ "enterAnnotationTypeElementModifier(ctx) {\n\t}", "enterUnescapedAnnotation(ctx) {\n\t}", "lesx_parseElement() {\n var startPos = this.start,\n startLoc = this.startLoc;\n\n this.next();\n\n return this.lesx_parseElementAt(startPos, startLoc);\n }", "enterAnnotationTypeMemberDeclaration(ctx) {\n\t}", "_generate(ast) {}", "function add(node, parent) {\n var children = parent ? parent.children : tokens;\n var prev = children[children.length - 1];\n\n if (\n prev &&\n node.type === prev.type &&\n node.type in MERGEABLE_NODES &&\n mergeable(prev) &&\n mergeable(node)\n ) {\n node = MERGEABLE_NODES[node.type].call(self, prev, node);\n }\n\n if (node !== prev) {\n children.push(node);\n }\n\n if (self.atStart && tokens.length !== 0) {\n self.exitStart();\n }\n\n return node;\n }", "fillElements() {\n this.replaceTokens(this.tags, CD.params());\n }", "function BAElement() { }", "buildTree() {\n if (!this.drawnAnnotations.length && !this.annosToBeDrawnAsInsets.size) {\n // Remove all exlisting clusters\n this.areaClusterer.cleanUp(new KeySet());\n return;\n }\n\n // if (this.newAnno) this.tree.load(this.drawnAnnotations);\n\n this.createInsets();\n }", "function newAnnotation(type) {\n \n updateAutori();\n //ricavo il testo selezionato\n selezione = selection();\n \n //differenza tra selezione e fragmentselection: per operare sui nodi serve il primo, poichè è sostanzialmente\n //un riferimento all'interno del documento; il secondo invece estrapola dallo stesso il contenuto selezionato ogni\n //volta che viene rilasciato il tasto sinistro del mouse. dal secondo non si può risalire ai nodi, o almeno non si\n //può con il metodo utilizzato sotto. tuttavia, usando selezione è impossibile detectare se \"esiste\" la selezione\n //stessa o se è vuota, poichè jQuery per qualche motivo non riesce a confrontare l'oggetto con \"\", '', null o \n //undefined; allo stesso tempo, è molto più difficile visualizzare selezione nel modale di inserimento annotazioni.\n //per questo motivo, viene più comodo e semplice usare due variabili separate che prelevano la stessa cosa e che \n //la gestiscono in modo diverso e in momenti diversi.\n if (fragmentselection === '') {\n avviso(\"Attenzione! Nessun frammento selezionato.\");\n } \n else {\n registerAnnotation(type);\n }\n}", "function addAnnotation(){\n var selection = window.getSelection();\n var n = selection.rangeCount;\n\n if (n == 0) {\n window.alert(\"Nie zaznaczono żadnego obszaru\");\n return false;\n }\n\n // for now allow only 1 range\n if (n > 1) {\n window.alert(\"Zaznacz jeden obszar\");\n return false;\n }\n\n // remember the selected range\n var range = selection.getRangeAt(0);\n\n if (!verifyTagInsertPoint(range.endContainer)) {\n window.alert(\"Nie można wstawić w to miejsce przypisu.\");\n return false;\n }\n\n // BUG #273 - selected text can contain themes, which should be omitted from\n // defining term\n var text = html2plainText(range.cloneContents());\n var tag = $('<span></span>');\n range.collapse(false);\n range.insertNode(tag[0]);\n\n xml2html({\n xml: '<pe><slowo_obce>' + text + '</slowo_obce> --- </pe>',\n success: function(text){\n var t = $(text);\n tag.replaceWith(t);\n openForEdit(t);\n },\n error: function(){\n tag.remove();\n alert('Błąd przy dodawaniu przypisu:' + errors);\n }\n })\n }", "build() {\n\t\tconst self = this;\n\n\t\tself.buildTags();\n\t\tself.buildTree();\n\t}", "iterate(enter, leave) {\n for (let depth = 0; ; ) {\n let mustLeave = false\n if (this.type.isAnonymous || enter(this) !== false) {\n if (this.firstChild()) {\n depth++\n continue\n }\n if (!this.type.isAnonymous) mustLeave = true\n }\n for (;;) {\n if (mustLeave && leave) leave(this)\n mustLeave = this.type.isAnonymous\n if (this.nextSibling()) break\n if (!depth) return\n this.parent()\n depth--\n mustLeave = true\n }\n }\n }", "function anno_highlight(xpath) {\n //if element is already highlighted\n if (anno_getElementByXpath(xpath).id != \"mark\" || !(anno_getElementByXpath(xpath).id)) {\n // hightlight selected element, calling function\n $j(anno_getElementByXpath(xpath)).wrapInner(\"<span id='mark' style='background:yellow;'></span>\");\n annolet_pushToStack(xpath);\n } else {\n console.log('highlighted already');\n }\n}", "_add_integer_expression_subtree_to_ast(integer_expression_node, parent_var_type) {\n this.verbose[this.verbose.length - 1].push(new NightingaleCompiler.OutputConsoleMessage(SEMANTIC_ANALYSIS, INFO, `Adding ${integer_expression_node.name} subtree to abstract syntax tree.`) // OutputConsoleMessage\n ); // this.verbose[this.verbose.length - 1].push\n // Integer expression is DIGIT--INTOP--EXPRESSION\n let digit_value_node = integer_expression_node.children_nodes[0].children_nodes[0];\n // If, no parent type was given to enforce type matching...\n let valid_type = false;\n if (parent_var_type === UNDEFINED) {\n // Enforce type matching using the current type from now on.\n parent_var_type = INT;\n } // if\n // Else, there is a parent type to enforce type matching with.\n else {\n valid_type = !this.check_type(parent_var_type, digit_value_node, INT);\n } // else\n if (integer_expression_node.children_nodes.length > 1) {\n let integer_operation_lexeme_node = integer_expression_node.children_nodes[1].children_nodes[0];\n let expression_node = integer_expression_node.children_nodes[2];\n this._current_ast.add_node(integer_operation_lexeme_node.name, NODE_TYPE_BRANCH, valid_type, false, integer_operation_lexeme_node.getToken());\n this._current_ast.add_node(digit_value_node.name, NODE_TYPE_LEAF, valid_type, false, digit_value_node.getToken());\n // Add expression subtree to the assignment statement subtree\n this._add_expression_subtree(expression_node, parent_var_type);\n } // if\n else if (integer_expression_node.children_nodes.length === 1) {\n this._current_ast.add_node(digit_value_node.name, NODE_TYPE_LEAF, valid_type, false, digit_value_node.getToken());\n } // else if \n else {\n // This should never happen based on our language\n throw (\"AST failed to find children for CST Integer Expression Node!\");\n } // else\n }", "function ExpressionParser() {\n \t\tthis.parse = function() {\n\t \t\treturn Statement(); \n\t \t}\n \t\t\n//\t\tStatement := Assignment | Expr\t\n\t\tthis.Statement=function() {return Statement();}\n\t \tfunction Statement() {\n\t \t\tdebugMsg(\"ExpressionParser : Statement\");\n\t\n \t var ast;\n \t // Expressin or Assignment ??\n \t if (lexer.skipLookAhead().type==\"assignmentOperator\") {\n \t \tast = Assignment(); \n \t } else {\n \t \tast = Expr();\n \t }\n \t return ast;\n\t \t}\n\t \t\n//\t\tAssignment := IdentSequence \"=\" Expr \n//\t\tAST: \"=\": l:target, r:source\n \t\tthis.Assignment = function() {return Assignment();}\n \t\tfunction Assignment() {\n \t\t\tdebugMsg(\"ExpressionParser : Assignment\");\n \t\t\n \t\t\tvar ident=IdentSequence();\n \t\t\tif (!ident) return false;\n \t\t\n \t\t\tcheck(\"=\"); // Return if it's not an Assignment\n \t\t\n \t\t\tvar expr=Expr();\n \t\t\t\n \t\t\treturn new ASTBinaryNode(\"=\",ident,expr);\n\t \t}\n \t\t\n\n//\t\tExpr := And {\"|\" And} \t\n//\t\tAST: \"|\": \"left\":And \"right\":And\n \t\tthis.Expr = function () {return Expr();}\t\n \t\tfunction Expr() {\n \t\t\tdebugMsg(\"ExpressionParser : Expr\");\n \t\t\t\n \t\t\tvar ast=And();\n \t\t\tif (!ast) return false;\n \t\t\t\t\t\n \t\t\n \t\t\twhile (test(\"|\") && !eof()) {\n \t\t\t\tdebugMsg(\"ExpressionParser : Expr\");\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(\"|\",ast,And());\n \t\t\t}\n \t\t\treturn ast;\n \t\t}\n \t\n//\t\tAnd := Comparison {\"&\" Comparison}\n//\t\tAST: \"&\": \"left\":Comparasion \"right\":Comparasion\t\n\t\tfunction And() {\n \t\t\tdebugMsg(\"ExpressionParser : And\");\n \t\t\tvar ast=Comparasion();\n \t\t\tif (!ast) return false;\n \t\t\t\t\n \t\t\twhile (test(\"&\") && !eof()) {\n\t \t\t\tdebugMsg(\"ExpressionParser : And\");\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(\"&\",ast,Comparasion());\n\t \t\t}\n\t \t\treturn ast;\n\t \t}\n\t \t \t\n// \t\tComparison := Sum {(\"==\" | \"!=\" | \"<=\" | \">=\" | \"<\" | \">\" | \"in\") Sum}\n//\t\tAST: \"==\" | \"!=\" | \"<=\" | \">=\" | \"<\" | \">\" : \"left\":Sum \"right\":Sum\n\t\tfunction Comparasion() {\n \t\t\tdebugMsg(\"ExpressionParser : Comparasion\");\n\t\t\tvar ast=Sum();\n\t\t\tif (!ast) return false;\n\t\t\n\t\t\twhile ((test(\"==\") ||\n\t\t\t\t\ttest(\"!=\") ||\n\t\t\t\t\ttest(\"<=\") ||\n\t\t\t\t\ttest(\">=\") ||\n\t\t\t\t\ttest(\"<\") ||\n\t\t\t\t\ttest(\">\")) ||\n\t\t\t\t\ttest(\"in\") &&\n\t\t\t\t\t!eof())\n\t\t\t{\n \t\t\t\tdebugMsg(\"ExpressionParser : Comparasion\");\n\t\t\t\tvar symbol=lexer.current.content;\n\t\t\t\tlexer.next();\n\t \t\t\tast=new ASTBinaryNode(symbol,ast,Sum());\n\t\t\t} \t\n\t\t\treturn ast;\t\n\t \t}\n\t \t\n//\t\tSum := [\"+\" | \"-\"] Product {(\"+\" | \"-\") Product}\n//\t\tAST: \"+1\" | \"-1\" : l:Product\n//\t\tAST: \"+\" | \"-\" : l:Product | r:Product \n \t\tfunction Sum() {\n \t\t\tdebugMsg(\"ExpressionParser : Sum\");\n\t\t\n\t\t\tvar ast;\n\t\t\t// Handle Leading Sign\n\t\t\tif (test(\"+\") || test(\"-\")) {\n\t\t\t\tvar sign=lexer.current.content+\"1\";\n\t\t\t\tlexer.next();\n\t\t\t\tast=new ASTUnaryNode(sign,Product());\t\n\t \t\t} else {\n\t \t\t\tast=Product();\n\t \t\t} \n \t\t\t\n \t\t\twhile ((test(\"+\") || test(\"-\")) && !eof()) {\n \t\t\t\tdebugMsg(\"ExpressionParser : Sum\");\n \t\t\t\tvar symbol=lexer.current.content;\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(symbol,ast,Product());\t\t\n \t\t\t} \t\n \t\t\treturn ast;\n \t\t}\n\n//\t\tProduct := Factor {(\"*\" | \"/\" | \"%\") Factor} \t\n\t \tfunction Product() {\n\t \t\tdebugMsg(\"ExpressionParser : Product\");\n\n \t\t\tvar ast=Factor();\n \t\t\n\t \t\twhile ((test(\"*\") || test(\"/\") || test(\"%\")) && !eof()) {\n\t \t\t\tdebugMsg(\"ExpressionParser : Product\");\n\n\t \t\t\tvar symbol=lexer.current.content;\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(symbol,ast,Factor());\n \t\t\t} \n\t \t\treturn ast;\n \t\t}\n \t\t\n// \t Factor := \t\t[(\"this\" | \"super\") \".\"]IdentSequence [\"(\" [Expr {\",\" Expr}] \")\"]\n//\t\t\t\t\t | \"!\" Expr \n//\t\t\t\t\t | \"(\" Expr \")\" \n//\t\t\t\t\t | Array \n//\t\t\t\t\t | Boolean\n//\t\t\t\t\t | Integer\n//\t\t\t\t\t | Number\n//\t\t\t\t\t | Character\n//\t\t\t\t\t | String \n \t\tfunction Factor() {\n \t\t\tdebugMsg(\"ExpressionParser : Factor\"+lexer.current.type);\n\n\t \t\tvar ast;\n \t\t\n\t \t\tswitch (lexer.current.type) {\n\t \t\t\t\n\t \t\t\tcase \"token\"\t:\n\t\t\t\t//\tAST: \"functionCall\": l:Ident(Name) r: [0..x]{Params}\n\t\t\t\t\tswitch (lexer.current.content) {\n\t\t\t\t\t\tcase \"new\": \n\t\t\t\t\t\t\tlexer.next();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tvar ident=Ident(true);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcheck(\"(\");\n\t\t\t\t\t\t\n \t\t\t\t\t\t\tvar param=[];\n \t\t\t\t\t\t\tif(!test(\")\")){\n \t\t\t\t\t\t\t\tparam[0]=Expr();\n\t\t\t\t\t\t\t\tfor (var i=1;test(\",\") && !eof();i++) {\n\t\t\t\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\t\t\t\tparam[i]=Expr();\n \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\t\t\t\t\t\t\t\n \t\t\t\t\t\t\tcheck(\")\");\n \t\t\t\t\t\n \t\t\t\t\t\t\tast=new ASTBinaryNode(\"new\",ident,param);\n \t\t\t\t\t\tbreak;\n \t\t\t\t\t\tcase \"this\":\n \t\t\t\t\t\tcase \"super\":\n\t\t\t\t\t\tcase \"constructor\": return IdentSequence();\n \t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\terror.expressionExpected();\n \t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\n//\t\t\t\tFactor :=\tIdentSequence \t\t\t\t\n \t\t\t\tcase \"ident\":\n \t\t\t\t return IdentSequence();\n \t\t\t\tbreak;\n \t\t\t\t\n// \t\t\tFactor:= \"!\" Expr\t\t\t\n \t\t\t\tcase \"operator\": \n\t \t\t\t\tif (!test(\"!\")) {\n\t \t\t\t\t\terror.expressionExpected();\n\t \t\t\t\t\treturn false;\n \t\t\t\t\t}\n \t\t\t\t\tlexer.next();\n \t\t\t\t\n\t \t\t\t\tvar expr=Expr();\n \t\t\t\t\tast=new ASTUnaryNode(\"!\",expr);\n\t \t\t\tbreak;\n \t\t\t\t\n//\t\t\t\tFactor:= \"(\" Expr \")\" | Array \t\t\t\n \t\t\t\tcase \"brace\"\t:\n \t\t\t\t\tswitch (lexer.current.content) {\n \t\t\t\t\t\t\n// \t\t\t\t\t \"(\" Expr \")\"\n \t\t\t\t\t\tcase \"(\":\n \t\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\t\tast=Expr();\t\t\t\t\t\n \t\t\t\t\t\t\tcheck(\")\");\n \t\t\t\t\t\tbreak;\n \t\n \t\t\t\t\t\n \t\t\t\t\t\tdefault:\n \t\t\t\t\t\t\terror.expressionExpected();\n \t\t\t\t\t\t \treturn false;\n\t \t\t\t\t\tbreak;\n\t \t\t\t\t}\n\t \t\t\tbreak;\n \t\t\t\n//\t\t\t\tFactor:= Boolean | Integer | Number | Character | String\n//\t\t\t\tAST: \"literal\": l: \"bool\" | \"int\" | \"float\" | \"string\" | \"char\": content: Value \n\t \t\t\tcase \"_$boolean\" \t\t:\t\t\t\n\t \t\t\tcase \"_$integer\" \t\t:\n\t \t\t\tcase \"_$number\" \t\t:\n\t \t\t\tcase \"_$string\"\t\t\t:\t\t\n\t\t\t\tcase \"_$character\"\t\t:\n\t\t\t\tcase \"null\"\t\t\t\t:\n\t\t\t\t\t\t\t\t\t\t\tast=new ASTUnaryNode(\"literal\",lexer.current);\n \t\t\t\t\t\t\t\t\t\t\tlexer.next();\n \t\t\t\tbreak;\n\t\t\t\t\n//\t\t\t\tNot A Factor \t\t\t\t \t\t\t\t\n \t\t\t\tdefault: \terror.expressionExpected();\n \t\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\t\treturn false;\n\t \t\t\t\t\t\tbreak;\n \t\t\t}\n \t\t\treturn ast;\n \t\t}\n\n \n//\t\tIdentSequence := (\"this\" | \"super\") | [(\"this\" | \"super\") \".\"] (\"constructor\" \"(\" [Expr {\",\" Expr}] \")\" | Ident {{ArrayIndex} | \".\" Ident } [\"(\" [Expr {\",\" Expr}] \")\"]);\n//\t\tAST: \"identSequence\": l: [0..x][\"_$this\"|\"_$super\"](\"constructor\" | Ident{Ident | ArrayIndex})\n// \t\tor AST: \"functionCall\": l:AST IdentSequence(Name), r: [0..x]{Params}\n\t\tthis.IdentSequence=function () {return IdentSequence();};\n \t\tfunction IdentSequence() {\n \t\t\tdebugMsg(\"ExpressionParser:IdentSequence()\");\n \t\t\t\n \t\t\tvar ast=new ASTListNode(\"identSequence\");\n \t\t\tif (test(\"this\") || test(\"super\")) {\n \t\t\t\tast.add({\"type\":\"ident\",\"content\":\"_$\"+lexer.current.content,\"line\":lexer.current.line,\"column\":lexer.current.column});\n \t\t\t\tlexer.next();\n \t\t\t\tif (!(test(\".\"))) return ast;\n \t\t\t\tlexer.next();\n \t\t\t}\n\n\t\t\tvar functionCall=false;\n\t\t\tif (test(\"constructor\")) {\n\t\t\t\tast.add({\"type\":\"ident\",\"content\":\"construct\",\"line\":lexer.current.line,\"column\":lexer.current.column});\n\t\t\t\tlexer.next();\n\t\t\t\tcheck(\"(\");\n\t\t\t\tfunctionCall=true;\n\t\t\t} else {\n \t\t\t\tvar ident=Ident(true);\n \t\t\t\n \t\t\t\tast.add(ident);\n \t\t\t\n \t\t\t\tvar index;\n \t\t\t\twhile((test(\".\") || test(\"[\")) && !eof()) {\n \t\t\t\t\t if (test(\".\")) {\n \t\t\t\t\t \tlexer.next();\n \t\t\t\t\t\tast.add(Ident(true));\n \t\t\t\t\t} else ast.add(ArrayIndex());\n \t\t\t\t}\n \t\t\t\tif (test(\"(\")) {\n \t\t\t\t\tfunctionCall=true;\n \t\t\t\t\tlexer.next();\n \t\t\t\t}\n \t\t\t}\n \t\n \t\t\tif (functionCall) {\t\n\t\t\t\tvar param=[];\n\t\t\t\tif(!test(\")\")){\n \t\t\t\t\tparam[0]=Expr();\n\t\t\t\t\tfor (var i=1;test(\",\") && !eof();i++) {\n\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\tparam[i]=Expr();\t\t\t\t\t\t\t\n \t\t\t\t\t}\n \t\t\t\t}\t \t\t\t\t\t\t\t\t\t\n \t\t\t\tcheck(\")\");\n \t\t\t\tast=new ASTBinaryNode(\"functionCall\",ast,param);\n \t\t\t} \n \t\t\treturn ast;\n \t\t}\n \t\t\n //\t\tArrayIndex:=\"[\" Expr \"]\"\n //\t\tAST: \"arrayIndex\": l: Expr\n \t\tfunction ArrayIndex(){\n \t\t\tdebugMsg(\"ExpressionParser : ArrayIndex\");\n \t\t\tcheck(\"[\");\n \t\t\t \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\n \t\t\tcheck(\"]\");\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"arrayIndex\",expr);\n \t\t}\n\n//\t\tIdent := Letter {Letter | Digit | \"_\"}\n//\t\tAST: \"ident\", \"content\":Ident\n\t \tthis.Ident=function(forced) {return Ident(forced);}\n \t\tfunction Ident(forced) {\n \t\t\tdebugMsg(\"ExpressionParser:Ident(\"+forced+\")\");\n \t\t\tif (testType(\"ident\")) {\n \t\t\t\tvar ast=lexer.current;\n \t\t\t\tlexer.next();\n \t\t\t\treturn ast;\n \t\t\t} else {\n \t\t\t\tif (!forced) return false; \n \t\t\t\telse { \n \t\t\t\t\terror.identifierExpected();\n\t\t\t\t\treturn SystemIdentifier();\n\t\t\t\t}\n\t\t\t} \t\n \t\t}\n \t}", "_add_boolean_expression_subtree_to_ast(boolean_expression_node, parent_var_type) {\n this.verbose[this.verbose.length - 1].push(new NightingaleCompiler.OutputConsoleMessage(SEMANTIC_ANALYSIS, INFO, `Adding ${boolean_expression_node.name} subtree to abstract syntax tree.`) // OutputConsoleMessage\n ); // this.verbose[this.verbose.length - 1].push\n let open_parenthesis_or_boolean_value_node = boolean_expression_node.children_nodes[0];\n // Enforce type matching in boolean expressions\n let valid_type = false;\n // If, no parent type was given to enforce type matching...\n if (parent_var_type === UNDEFINED) {\n // Enforce type matching using the current type from now on.\n parent_var_type = BOOLEAN;\n } // if\n // Else, there is a parent type to enforce type matching with.\n else {\n valid_type = !this.check_type(parent_var_type, open_parenthesis_or_boolean_value_node, BOOLEAN);\n } // else\n // Boolean expression ::== ( Expr BoolOp Expr )\n if (boolean_expression_node.children_nodes.length > 1) {\n // Ignore Symbol Open Argument [(] and Symbol Close Argument [)]\n // let open_parenthisis_node = boolean_expression_node.children_nodes[0];\n // let open_parenthisis_node = boolean_expression_node.children_nodes[4];\n let boolean_operator_value_node = boolean_expression_node.children_nodes[2].children_nodes[0];\n let left_expression_node = boolean_expression_node.children_nodes[1];\n let right_expression_node = boolean_expression_node.children_nodes[3];\n // FIRST Add the Boolean Operator\n this._current_ast.add_node(boolean_operator_value_node.name, NODE_TYPE_BRANCH, valid_type, false, boolean_operator_value_node.getToken()); // this._current_ast.add_node\n // Start by recursively evaluating the left side...\n // Note the type as it will be used to enforce type matching with the right side.\n let left_expression_type = this._add_expression_subtree(left_expression_node, UNDEFINED);\n // If it was an integer expression climb back up to the parent boolean expression node\n if (left_expression_node.children_nodes[0].name === NODE_NAME_INT_EXPRESSION) {\n while ((this._current_ast.current_node !== undefined || this._current_ast.current_node !== null)\n && this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_EQUALS\n && this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_NOT_EQUALS) {\n if (this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_EQUALS\n || this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_NOT_EQUALS) {\n this._current_ast.climb_one_level();\n } // if\n } // while\n } // if\n // Ensures the correct order of nested operators in the ast.\n //\n // Look ahead in the tree on the left side of the \n // boolean expression and climb if it's an expression and not some value.\n if (left_expression_node.children_nodes[0].children_nodes[0].name == \"(\") {\n this._climb_ast_one_level();\n } // if\n // Then recursively deal with the right side...\n // To enforce type matching, use the left sides type as the parent type.\n let right_expression_type = this._add_expression_subtree(right_expression_node, left_expression_type);\n // If it was an integer expression climb back up to the parent boolean expression node\n if (right_expression_node.children_nodes[0].name === NODE_NAME_INT_EXPRESSION) {\n while ((this._current_ast.current_node !== undefined || this._current_ast.current_node !== null)\n && this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_EQUALS\n && this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_NOT_EQUALS) {\n if (this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_EQUALS\n || this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_NOT_EQUALS) {\n this._current_ast.climb_one_level();\n } // if\n } // while\n } // if\n // Ensures the correct order of nested operators in the ast.\n //\n // Look ahead in the tree on the right side of the \n // boolean expression and climb if it's an expression and not some value.\n if (right_expression_node.children_nodes[0].children_nodes[0].name == \"(\") {\n this._climb_ast_one_level();\n } // if\n } // if\n // Boolean expression is: boolval\n else if (boolean_expression_node.children_nodes.length === 1) {\n this._current_ast.add_node(open_parenthesis_or_boolean_value_node.children_nodes[0].name, NODE_TYPE_LEAF, valid_type, false);\n } // else if\n // Boolean expression is neither: ( Expr BoolOp Expr ) NOR boolval...\n else {\n // Given a valid parse tree, this should never happen...\n throw Error(\"You messed up Parse: Boolean expression has no children, or negative children.\");\n } // else \n }", "function parseElem() {\n var tableIndex = t.indexLiteral(0);\n var offset = [];\n var funcs = [];\n\n if (token.type === _tokenizer.tokens.identifier) {\n tableIndex = identifierFromToken(token);\n eatToken();\n }\n\n if (token.type === _tokenizer.tokens.number) {\n tableIndex = t.indexLiteral(token.value);\n eatToken();\n }\n\n while (token.type !== _tokenizer.tokens.closeParen) {\n if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.offset)) {\n eatToken(); // (\n\n eatToken(); // offset\n\n while (token.type !== _tokenizer.tokens.closeParen) {\n eatTokenOfType(_tokenizer.tokens.openParen);\n offset.push(parseFuncInstr());\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n\n eatTokenOfType(_tokenizer.tokens.closeParen);\n } else if (token.type === _tokenizer.tokens.identifier) {\n funcs.push(t.identifier(token.value));\n eatToken();\n } else if (token.type === _tokenizer.tokens.number) {\n funcs.push(t.indexLiteral(token.value));\n eatToken();\n } else if (token.type === _tokenizer.tokens.openParen) {\n eatToken(); // (\n\n offset.push(parseFuncInstr());\n eatTokenOfType(_tokenizer.tokens.closeParen);\n } else {\n throw function () {\n return new Error(\"\\n\" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + \"\\n\" + \"Unsupported token in elem\" + \", given \" + tokenToString(token));\n }();\n }\n }\n\n return t.elem(tableIndex, offset, funcs);\n }", "visitIn_elements(ctx) {\n\t return this.visitChildren(ctx);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shows the given trials, up to _trialsPerPage, from the given start position.
function _showTrials(trials, start) { var trial_list = $('#trial_list'); if (!start || 0 == start) { trial_list.empty(); } $('#show_more_trials').remove(); $('#g_map_toggle').show(); // no trials to show if (!trials || 0 == trials.length || start >= trials.length) { if (trials.length > 0 && start >= trials.length) { console.warn('Cannot show trials starting at: ', start, 'trials: ', trials); } if (!trials || 0 == trials.length) { $('#g_map_toggle > span').text(''); showNoTrialsHint(); } return; } // get active keywords var active_keywords = []; $('#selector_keywords').children('span').each(function(idx, item) { active_keywords.push($(item).data('normalized')); }); // calculate range var show_max = start + _trialsPerPage; if (trials.length > show_max && trials.length < start + _trialsPerPage + (_trialsPerPage / 10)) { // if it's less than 10% more, show them all show_max = trials.length + start; } var has_more = false; var map = $('#g_map'); if (!_trial_locations) { _trial_locations = []; } for (var i = start; i < trials.length; i++) { var trial = new Trial(trials[i]); _trial_locations.push.apply(_trial_locations, trial.locationPins()); // add the trial element to the list if (i < show_max) { var li = $('<li/>').append(can.view('templates/trial_item.ejs', {'trial': trial, 'active_keywords': active_keywords})); trial_list.append(li); trial.showClosestLocations(g_patient_location, li, 0, 3); } else { has_more = true; } } $('#g_map_toggle > span').text(_trial_locations.length > 1000 ? ' (' + _trial_locations.length + ' trial locations)' : ''); if ($('#g_map').is(':visible')) { updateTrialLocations(); } hideNoTrialsHint(); // are there more? if (has_more) { var more = trials.length - show_max; var li = $('<li/>', {'id': 'show_more_trials'}).append('<h1>There are ' + more + ' more trials</h1>'); var link = $('<a/>', {'href': 'javascript:void(0);'}).text('Show ' + ((_trialsPerPage < more) ? _trialsPerPage + ' more' : 'all')) .click(function(e) { _showTrials(trials, start + _trialsPerPage); }); li.append($('<h1/>').append(link)); trial_list.append(li); } }
[ "function displayPetals() {\n const start = (currentPage - 1)\n}", "get start_results(){\n return this.page_number * this.size + 1;\n }", "function walkAverage(trials){\n var sum = 0,\n count = 0;\n\n function step(){\n var next = Math.random();\n sum += next;\n count += 1;\n\n //display on UI\n show((sum/count), true);\n\n if(count < trials){\n setTimeout(step,0);\n }\n }\n setTimeout(step,0);\n}", "function display_roll(diceRoll, iter, end) {\n\t\n\ttimeouts.push(setTimeout(function(){ \n\t\t$('#roll_amount').hide().html(\"<i><u>Roll #\" + iter + \"</u></i><br>\" + diceRoll).fadeIn();\n\n\t}, (iter * 2000)));\n\n\tif (end == true) {\n\t\ttimeouts.push(setTimeout(function(){\n\t\t\t$('#loading').remove();\n\t\t\t$(\"#rollResults\").show();\n\t\t}, ((1+iter) * 2000)));\n\t\t\n\t}\n\t\n}", "function setUpStartPage(){\n $('.start-page').show();\n $('.nav-items').hide();\n $('.question-page').hide();\n $('.question-result').hide();\n $('.results-page').hide();\n // show inital values\n $('.score').html('Score: '+score+'/0');\n $('.progress').html('Progress: '+progress+'%');\n}", "function trkDisplayPagesNeeded() {\n for(i = 0; i < (trkPagination.length); i++) {\n var loopCurrentPageValue = trkPagination[i].attributes.value.value;\n if(loopCurrentPageValue <= trkNumberOfPagesNeeded) {\n trkPagination[i].style.display = \"flex\";\n } else {\n trkPagination[i].style.display = \"none\";\n }\n }\n}", "function trkDisplayAmount() {\n for(i = 0; i < trkFilteredProducts.length; i++) {\n trkFilteredProducts[i].style.display = \"none\";\n }\n if(trkSelectedPageValue == 1) {\n trkShowPageOne();\n } else if(trkSelectedPageValue == 2) {\n trkShowPageTwo();\n } else if(trkSelectedPageValue == 3) {\n trkShowPageThree();\n } else if(trkSelectedPageValue == 4) {\n trkShowPageFour();\n } else if(trkSelectedPageValue == 5) {\n trkShowPageFive();\n } else if(trkSelectedPageValue == 6) {\n trkShowPageSix();\n } else {\n console.log(\"Unknown page selection.\");\n }\n}", "function showPage(list, page)\n{\n const startIndex = MAX_ITEMS_PER_PAGE * (page - 1); // index of first element.\n const endIndex = MAX_ITEMS_PER_PAGE * page - 1; // index of last element.\n\n for(let i=0; i<list.length; i++)\n {\n if (i>=startIndex && i<=endIndex) // item belongs to the page --> show it .\n list[i].style.display = ''; \n else // item doesn't belong to the page --> hide it.\n list[i].style.display = 'none'; \n } \n}", "function makePagination(taskLists) {\n var numberPages = Math.ceil(taskLists.length / numberRecord);\n $(\".pagination\").html(\"\");\n if(numberPages <= 1){\n $(\".pagination\").append('');\n }else{\n for (var i = 1; i <= numberPages; i++) {\n $(\".pagination\").append('<li class=\"page-item\"><a class=\"page-link\" href=\"#\">' + i + '</a></li>');\n }\n }\n}", "function changeNav(total,startpage) {\r\n\tif (total > noi) {//results does not fit into one page\r\n\t\tvar html = \"\";\r\n\t\tvar startNum = cachePageNum-Math.floor(nop/2);\r\n\t\tvar totalPage = Math.ceil(total/noi);\r\n var displayTargetPage=\"\";\r\n if(document.getElementById('live_updateArea'))\r\n displayTargetPage=\"result-cached.html\";\r\n else\r\n displayTargetPage=\"result-offline.html\";\r\n\r\n\t\tif (startNum < 1)\r\n\t\t\tstartNum = 1;\r\n\t\tfor (var i = startNum; i < Math.min(nop+startNum,totalPage+1); i++) {\r\n\t\t\tif (i != cachePageNum)\r\n\t\t\t\thtml += ' <a href=\"'+displayTargetPage+'?cp='+i+'&lp='+livePageNum+'&s='+searchString+'\">'+i+'</a> ';\r\n\t\t\telse\r\n\t\t\t\thtml += ' '+i+' ';\r\n\t\t}\r\n\t\tif (cachePageNum != 1)\r\n\t\t\thtml='<a href=\"'+displayTargetPage+'?cp='+(cachePageNum-1)+'&lp='+livePageNum+'&s='+searchString+'\">Previous</a> &nbsp; &nbsp; &nbsp; &nbsp; '+html;\r\n\t\tif (cachePageNum != totalPage)\r\n\t\t\thtml += '&nbsp; &nbsp; &nbsp; &nbsp; <a href=\"'+displayTargetPage+'?cp='+(cachePageNum+1)+'&lp='+livePageNum+'&s='+searchString+'\">Next</a>';\r\n\t\tdocument.getElementById('nav').innerHTML=html;\r\n\t}\r\n}", "function displayTrips()\n{\n let scheduleIndex = localStorage.getItem(CURRENT_USER_KEY); // Getting the user index\n let output = \"\"; // Setting output as a blank string\n let tripNumber = 0;\n \n // For every trip stored under the current user, the following code will run\n for (let j = 0; j < listOfUsers.users[scheduleIndex].trips.length; j++) \n {\n let currentDate = new Date(); // Getting the current date\n let tripDate = new Date(listOfUsers.users[scheduleIndex].trips[j].timeBooked); // Changing the trip date to a date object\n\n \n // If the current date is earlier than the trip date, the following code will run\n if (currentDate <= tripDate)\n {\n // Defining the country, airport, date and trip number of the trip\n let country = listOfUsers.users[scheduleIndex].trips[j].country;\n let airport;\n\n if (listOfUsers.users[scheduleIndex].trips[j].flights[0] == undefined){ // If the airport is undefined\n airport = \"Airport Name: Not Found\"; // Set the airport variable to 'Airport Name: Not Found'\n }\n else { // If the airport is found \n airport = listOfUsers.users[scheduleIndex].trips[j].flights[0].departureCity; // Setting it to the airport variable \n }\n \n // Retrieving the date of the trip and setting it to the right format\n let startDate = new Date(listOfUsers.users[scheduleIndex].trips[j].timeBooked);\n let startDateFormatted = startDate.getDate() +\"-\"+(startDate.getMonth()+1)+\"-\"+startDate.getFullYear();\n tripNumber++ // Incrementing the trip number\n\n // The output that will be sent to the HTML file scheduledTrips.html\n output += `<tr> \n <td class=\"mdl-data-table__cell--non-numeric\">${tripNumber}</td> \n <td class=\"mdl-data-table__cell--non-numeric\">${country}</td>\n <td class=\"mdl-data-table__cell--non-numeric\">${airport}</td>\n <td class=\"mdl-data-table__cell--non-numeric\">${startDateFormatted}</td>\n </tr>`;\n }\n }\n // Sending the output HTML code to the ID 'tripsDisplay'\n let tripDisplayRef = document.getElementById(\"tripsDisplay\");\n tripDisplayRef.innerHTML = output;\n}", "function showEndSLTrials() {\n hideElements();\n ind = 0; onPC = false; onPR = false; onSL = false; onSLtest = false; onPFtaskA = true;\n $('#instructions').show();\n $('#instructions').load('html/pfinstructions.html'); \n $('#next').show();\n $('#next').click(showPFInstructionChecks);\n}", "nextTrial() {\n\t\t// determine staircase\n\t\tthis.determineStairCase();\n\t\t\n\t\t// if all done, finished\n\t\tif (this.isFinished()) {\n\t\t\treturn null; // signifiy that it's finished\n\t\t}\n\n\t\t// get the params for this trial\n\t\tvar stairparams = this.staircases[this.stairIndex];\n\t\t// calculate the diff value from the stair \n\t\tvar stairValue = this.getCurrentStaircase().stairLevel2Value();\n\t\t// make a trial from the this staircase\n\t\tvar trial = new Trial(\n\t\t\tstairparams.count1, \n\t\t\tstairparams.count2,\n\t\t\tstairValue,\n\t\t\tstairparams.style);\n\t\ttrial.stairLevel = this.getCurrentStaircase().level;\n\t\t// set trial indices\n\t\ttrial.index = this.trials.length;\n\t\ttrial.indexStair = this.getCurrentStaircase().trials.length;\n\t\t// whether to show feedback after response\n\t\ttrial.feedback = trial.indexStair < ROUNDS_OF_FEEDBACK || alwaysFeedback;\n\t\tif (trial.indexStair < ROUNDS_OF_FEEDBACK) {\n\t\t\ttrial.presentationTime = 60 * 60 * 1000;\n\t\t\ttrial.maxValueRequested = 1 - trial.maxMean;\n\t\t\ttrial.minValueRequested = trial.maxMean;\n\t\t\ttrial.makeSets();\n\t\t}\n\t\t// add trial to staircase and experiment history\n\t\tthis.trials.push(trial);\n\t\tthis.getCurrentStaircase().trials.push(trial);\n\t\t// set it as the current trial\n\t\tthis.currentTrial = trial;\n\t\treturn trial;\n\t}", "function showPage(list,page) {\r\n\tconst startIndex = (page-1)*itemsPerPage;\r\n\tconst endIndex = Math.min(page*itemsPerPage,list.length);\r\n\t// get the correct <ul> element\r\n\tconst ul = document.querySelector('ul.student-list');\r\n\t// clear the elements already in the list\r\n\tul.innerHTML = \"\"\r\n\tif (list.length === 0) {\r\n\t\t// list is empty, unhide the noResults message\r\n\t\tnoResults.hidden = false;\r\n\t} else {\r\n\t\tnoResults.hidden = true;\r\n\t}\r\n\t// Create the new <li> elements\r\n\tfor (let i = startIndex; i < endIndex; i++) {\r\n\t\tconst datum = list[i];\r\n\t\tconst li = document.createElement('li');\r\n\t\tli.className = \"student-item cf\";\r\n\t\tli.innerHTML = `\r\n\t\t\t<div class=\"student-details\">\r\n\t\t\t\t<img class=\"avatar\" src=\"${datum.picture.large}\" alt=\"Profile Picture\">\r\n\t\t\t\t<h3>${datum.name.first} ${datum.name.last}</h3>\r\n\t\t\t\t<span class=\"email\">${datum.email}</span>\r\n\t\t\t</div>\r\n\t\t\t<div class=\"joined-details\">\r\n\t\t\t\t<span class=\"date\">Joined ${datum.registered.date}</span>\r\n\t\t\t</div>`\r\n\t\tul.appendChild(li)\r\n\t}\r\n\treturn ;\r\n}", "function displayPage(pageNumber) {\n //First and last profiles on each page\n const startIndex = (pageNumber - 1) * profilesPerPage;\n const endIndex = startIndex + profilesPerPage;\n //Looping through array of all profiles to display suitable profiles\n for (let i = 0; i < totalProfiles.length; i++) {\n if (i >= startIndex && i < endIndex) {\n totalProfiles[i].style.display = '';\n } else {\n totalProfiles[i].style.display = 'none';\n }\n }\n}", "function displayTrainers(trainers) {\n // the argument that we're passing in when we call this function above //\n // in the REQUEST function //\n // are the trainers we're getting back from the API //\n let trainerHTML = trainers.map(trainer => renderTrainer(trainer))\n // for each trainer, pass in the info to the renderTrainer function below //\n // and save it to the variable trainerHTML\n // console.log(trainerHTML);\n trainerContainer.innerHTML = trainerHTML.join('')\n // set the innerHTML of the trainerContainer to be equivalent to the trainerHTML //\n // HTML that we just created above //\n // and join every string together //\n // the browser is smart enough to create HTML based on the string //\n }", "_addPages (startNumber, upToNumbers) {\n var upTo = Math.min(...upToNumbers)\n\n for (var i = startNumber; i <= upTo; i++) {\n if (!this._pageNumberIncluded(i)) {\n this._addPageNumber(i)\n }\n }\n }", "function displayTotal(stepTotal) {\n console.log(`${stepTotal} Steps`);\n}", "function logBetweenStepper (min, max, step) {\n for (let i = min; i <= max; i+=step) {\n console.log(i)\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the property existsInKG to true if the Node has triples in the DC KG.
async setExistsInKG() { if (!this.dcid || this.existsInKG) { return; } this.existsInKG = await doesExistsInKG(this.dcid); }
[ "static checkPathForAllNodes(stationMap, path) {\n const pathSet = new Set(path);\n if (pathSet.size === stationMap.size) {\n console.log('All stations are included in the path');\n } else {\n console.log('There are only ' + pathSet.size + ' stations in the path.');\n }\n }", "updateIsOnGraphStatus(id) {\n var docNode = this.getDocNodeShortText(id);\n if (!docNode) {\n return false\n }\n\n if (docNode && !this.getEditor().value.document.hasNode(docNode.key)) {\n // tell the graph node that there is no doc node any more, for whatever reason\n this.removeDocNode(id)\n return false\n }\n\n return true\n }", "async exists() {\n return $(this.rootElement).isExisting();\n }", "isConnected(node1, node2) {\r\n for (let index = 0; index < this.edgeList.length; index++) {\r\n if ((this.edgeList[index].startNode === node1 &&\r\n this.edgeList[index].endNode === node2) ||\r\n (this.edgeList[index].endNode === node1 &&\r\n this.edgeList[index].startNode === node2)) {\r\n return true;\r\n }\r\n\r\n }\r\n return false;\r\n }", "function ollHasSelected(oll)\r\n{\r\n var ollMap = zbllMap[oll];\r\n for (var coll in ollMap) if (ollMap.hasOwnProperty(coll)) {\r\n collMap = ollMap[coll];\r\n for (var zbll in collMap) if (collMap.hasOwnProperty(zbll))\r\n if (collMap[zbll][\"c\"])\r\n return true;\r\n }\r\n return false;\r\n}", "function isValidSolution(costMap, node) {\n const reachedLocation = {};\n ancestry(node).forEach(n => reachedLocation[n.location] = true);\n return Object.keys(costMap)\n .filter(l => !(l in reachedLocation))\n .length === 0;\n}", "function isFree(aLocation) {\n //for (var liste in locations) {\n // for (var i in liste) {\n // if (i.x == aLocation.x && i.y == aLocation.y) {\n // return false;\n // }\n // }\n //}\n return true;\n}", "function existsSet() {\n\tvar cardList = ourmodel.getRoot().get('cardList');\n\tfor(var i = 0; i < cardList.length; i++){\n\t\tfor(var j = 0; j < cardList.length; j++){\n\t\t\tfor(var k = 0; k < cardList.length; k++){\n\t\t\t\tif(isSet(i, j, k)){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}", "hasTriples(subject, predicate, object) {\n throw new Error('hasTriples has not been implemented');\n }", "function isVisited(visited, node) {\n return visited.includes(node);\n }", "check_node_compatibility(node, neighborhood = false){\n\n var node_id = node._private.data.id;\n\n //first make all transparent\n this.activate_nodes(null,false, true);\n //activate selected node\n this.activate_nodes(\"node[id='\"+node_id+\"']\", true, true);\n //get the nodes i must check\n var nodes_to_check = {\n 'all_nodes': this.cy.nodes('[type = \"data\"]').union(this.cy.nodes('[type = \"tool\"]')).difference(this.cy.nodes(\"node[id='\"+node_id+\"']\")),\n 'target_nodes': this.cy.edges('[source = \"'+node_id+'\"]').target(),\n 'source_nodes': this.cy.edges('[target = \"'+node_id+'\"]').source()\n };\n\n //in case we want to check only the neighborhood nodes (the connected nodes)\n if (neighborhood) {\n nodes_to_check.all_nodes = [];\n } else {\n nodes_to_check.target_nodes = [];\n nodes_to_check.source_nodes = [];\n }\n\n for (var k_nodes in nodes_to_check) {\n if (nodes_to_check[k_nodes] != undefined) {\n for (var i = 0; i < nodes_to_check[k_nodes].length; i++) {\n var node_to_check_obj = nodes_to_check[k_nodes][i];\n var node_to_check_obj_id = node_to_check_obj._private.data.id;\n var flag_compatible = false;\n if (k_nodes == 'target_nodes') {\n flag_compatible = this.is_compatible(node, node_to_check_obj);\n if (!(flag_compatible)){\n this.cy.remove(this.cy.edges('edge[source=\"'+node_id+'\"]').edges('edge[target=\"'+node_to_check_obj_id+'\"]') );\n }\n }\n else if (k_nodes == 'source_nodes') {\n flag_compatible = this.is_compatible(node_to_check_obj, node);\n if (!(flag_compatible)){\n this.cy.remove(this.cy.edges('edge[source=\"'+node_to_check_obj_id+'\"]').edges('edge[target=\"'+node_id+'\"]') );\n }\n }\n else if (k_nodes == 'all_nodes') {\n flag_compatible = this.is_compatible(node, node_to_check_obj);\n }\n this.activate_nodes(\"node[id='\"+node_to_check_obj_id+\"']\",flag_compatible, flag_compatible);\n }\n }\n }\n\n return nodes_to_check;\n }", "exists(objectHash) {\n return objectHash !== undefined\n && fs.existsSync(nodePath.join(Files.gitletPath(), 'objects', objectHash));\n }", "function hasLayerMask() {\n var hasLayerMask = false;\n try {\n var ref = new ActionReference();\n var keyUserMaskEnabled = app.charIDToTypeID('UsrM');\n ref.putProperty(app.charIDToTypeID('Prpr'), keyUserMaskEnabled);\n ref.putEnumerated(app.charIDToTypeID('Lyr '), app.charIDToTypeID('Ordn'), app.charIDToTypeID('Trgt'));\n var desc = executeActionGet(ref);\n if (desc.hasKey(keyUserMaskEnabled)) {\n hasLayerMask = true;\n }\n } catch (e) {\n hasLayerMask = false;\n }\n return hasLayerMask;\n}", "function hasPathTo(v) {\n return this.visitedBfs[v];\n }", "isAdjacent(node) {\n console.log(this.adjacents.indexOf(node) > -1);\n return this.adjacents.indexOf(node) > -1;\n }", "exists() {\n return null !== this._document;\n }", "function add_stations(){\n for (var i = 0; i < features.length; i++) {\n counter = 0\n for (var j = 0; j < stations.length; j++){\n poly = get_polygon(features[i])\n if(inside(stations[j], poly)){\n counter++\n }\n }\n features[i].properties.stations = counter\n }\n}", "_computeGraph() {\n // Compute K-Means of the endpoints\n const clusteredData = turf.clustersKmeans(\n this.getEndpointsCollection()\n );\n\n // Instantiate local graph\n this._tripGraph = new Graph;\n\n // Build nodes for centroids\n const centroids = clusteredData.features\n .forEach(feature => {\n if (!this._tripGraph.hasNode(feature.properties.cluster)) {\n this._tripGraph.addNode(feature.properties.cluster, {\n coords : feature.properties.centroid\n });\n }\n });\n\n // Add edges (each adjacent pair came from a trip)\n _\n .chunk(clusteredData.features, 2)\n .map(([start, stop]) => [start.properties.cluster, stop.properties.cluster])\n .forEach(([startCluster, stopCluster], tripNo) => {\n if (!this._tripGraph.hasEdge(startCluster, stopCluster)) {\n // Trip does not exist yet, create it as an edge\n this._tripGraph.addEdge(startCluster, stopCluster, {\n trips : [ tripNo ]\n });\n } else {\n // Trip exists, add trip number to array\n this._tripGraph.getEdge(startCluster, stopCluster)\n .getData()\n .trips\n .push(tripNo);\n }\n });\n }", "hasMultipleConnections() {\n let result = false;\n this.getConnections().forEach(connection => {\n this.getConnections().forEach(_connection => {\n if (_connection.id !== connection.id) {\n if (_connection.source.node === connection.source.node) {\n if (_connection.target.node === connection.target.node) {\n result = true;\n }\n }\n }\n })\n });\n return result;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A function to find the index of a swatch in a specified palette. If the color is found, otherwise it will return 1
function findSwatchIndex(paletteResolver, swatch) { return (designSystem) => { if (!(0,_common__WEBPACK_IMPORTED_MODULE_1__.isValidColor)(swatch)) { return -1; } const colorPalette = (0,_fast_design_system__WEBPACK_IMPORTED_MODULE_0__.evaluateDesignSystemResolver)(paletteResolver, designSystem); const index = colorPalette.indexOf(swatch); // If we don't find the string exactly, it might be because of color formatting differences return index !== -1 ? index : colorPalette.findIndex((paletteSwatch) => { return ((0,_common__WEBPACK_IMPORTED_MODULE_1__.isValidColor)(paletteSwatch) && (0,_common__WEBPACK_IMPORTED_MODULE_1__.colorMatches)(swatch, paletteSwatch)); }); }; }
[ "function findClosestSwatchIndex(paletteResolver, swatch) {\n return (designSystem) => {\n const resolvedPalette = (0,_fast_design_system__WEBPACK_IMPORTED_MODULE_0__.evaluateDesignSystemResolver)(paletteResolver, designSystem);\n const resolvedSwatch = (0,_fast_design_system__WEBPACK_IMPORTED_MODULE_0__.evaluateDesignSystemResolver)(swatch, designSystem);\n const index = findSwatchIndex(resolvedPalette, resolvedSwatch)(designSystem);\n let swatchLuminance;\n if (index !== -1) {\n return index;\n }\n try {\n swatchLuminance = (0,_common__WEBPACK_IMPORTED_MODULE_1__.luminance)(resolvedSwatch);\n }\n catch (e) {\n swatchLuminance = -1;\n }\n if (swatchLuminance === -1) {\n return 0;\n }\n return resolvedPalette\n .map((mappedSwatch, mappedIndex) => {\n return {\n luminance: (0,_common__WEBPACK_IMPORTED_MODULE_1__.luminance)(mappedSwatch),\n index: mappedIndex,\n };\n })\n .reduce((previousValue, currentValue) => {\n return Math.abs(currentValue.luminance - swatchLuminance) <\n Math.abs(previousValue.luminance - swatchLuminance)\n ? currentValue\n : previousValue;\n }).index;\n };\n}", "function get_color_index(selector, elem) {\n var result = null;\n $root.find(selector + \" .color_sample\").each(function(i, e) {\n if(e == elem) result = i;\n });\n return result;\n }", "FindIndexOfFace(color){\n let faceIndex = -1;\n this.faces.forEach((face, index) => {\n if (face.color == color){\n faceIndex = index;\n }\n })\n return faceIndex;\n }", "function findKing(squares, color) {\n for (let j=0; j < 64; j++) {\n if (squares[j].piece === \"King\" && squares[j].color === color) {\n return (j);\n }\n }\n}", "function swatchByContrast(referenceColor) {\n /**\n * A function that expects a function that resolves a palette\n */\n return (paletteResolver) => {\n /**\n * A function that expects a function that resolves the index\n * of the palette that the algorithm should begin looking for a swatch at\n */\n return (indexResolver) => {\n /**\n * A function that expects a function that determines which direction in the\n * palette we should look for a swatch relative to the initial index\n */\n return (directionResolver) => {\n /**\n * A function that expects a function that determines if the contrast\n * between the reference color and color from the palette are acceptable\n */\n return (contrastCondition) => {\n /**\n * A function that accepts a design-system. It resolves all of the curried arguments\n * and loops over the palette until we reach the bounds of the palette or the condition\n * is satisfied. Once either the condition is satisfied or we reach the end of the palette,\n * we return the color\n */\n return (designSystem) => {\n const color = (0,_fast_design_system__WEBPACK_IMPORTED_MODULE_0__.evaluateDesignSystemResolver)(referenceColor, designSystem);\n const sourcePalette = (0,_fast_design_system__WEBPACK_IMPORTED_MODULE_0__.evaluateDesignSystemResolver)(paletteResolver, designSystem);\n const length = sourcePalette.length;\n const initialSearchIndex = (0,_common__WEBPACK_IMPORTED_MODULE_1__.clamp)(indexResolver(color, sourcePalette, designSystem), 0, length - 1);\n const direction = directionResolver(initialSearchIndex, sourcePalette, designSystem);\n function contrastSearchCondition(valueToCheckAgainst) {\n return contrastCondition((0,_common__WEBPACK_IMPORTED_MODULE_1__.contrast)(color, valueToCheckAgainst));\n }\n const constrainedSourcePalette = [].concat(sourcePalette);\n const endSearchIndex = length - 1;\n let startSearchIndex = initialSearchIndex;\n if (direction === -1) {\n // reverse the palette array when the direction that\n // the contrast resolves for is reversed\n constrainedSourcePalette.reverse();\n startSearchIndex = endSearchIndex - startSearchIndex;\n }\n return binarySearch(constrainedSourcePalette, contrastSearchCondition, startSearchIndex, endSearchIndex);\n };\n };\n };\n };\n };\n}", "function flag_color(flag_index, i){\n return colors[flag_index][i % colors[flag_index].length]\n}", "function getColorCode(name) \n{\n\tfor (var i=0; i<=COLORS.length; i++) {\n\t\tif (COLORS[i].name == name) {\n\t\t\treturn COLORS[i].code;\n\t\t}\n\t}\n\treturn \"#FFFFFF\";\n\tcb.log('Error: Could not find the code for this color: ' + name);\n}", "function referenceColorInitialIndexResolver(referenceColor, sourcePalette, designSystem) {\n return findClosestSwatchIndex(sourcePalette, referenceColor)(designSystem);\n}", "function getPaletteIntensity(palette) {\n return palette\n .map(color => {\n return rgbToHsv(color).v\n })\n .reduce((sum, val) => {\n return sum + val\n })\n /palette.length;\n}", "getNbBlockOfColor(researchedColor) {\n var nbBlocksFound = 0;\n // for each row on the map\n this._map.forEach((row) => {\n // For each block on the row\n row.forEach((block) => {\n if (block == researchedColor)\n nbBlocksFound++;\n });\n });\n return (nbBlocksFound);\n }", "function findIndexInDidArrayMatchingSelection() {\t\n\t\tvar i=0;\n\t\twhile(i<detailIdJson.did_array.length) {\n\t\t\tif(detailIdJson.did_array[i].color==self.color() &&\n\t\t\t detailIdJson.did_array[i].size ==self.size() &&\n\t\t\t detailIdJson.did_array[i].sex ==self.sex() )\n\t\t\t\tbreak;\n\t\t\ti++;\n\t\t}\n\t\tif(i==detailIdJson.did_array.length)\n\t\t{\n\t\t\treturn -1;\n\t\t} else {\n\t\t\treturn i;\n\t\t}\t\n\t}", "function getMatchingIndex(arr, key, value) {\n for (let i = 0; i < arr.length; i++) {\n if (arr[i][key] === value)\n return i;\n }\n return null;\n}", "function nextColor() {\n c = colors[ count % color.length]\n count = count + 1\n return c\n}", "function chooseAvailableColor() {\n // Count how many times each color is used\n var colorUsage = {};\n colorNames.forEach(function(color) {colorUsage[color] = 0; })\n dataLayers.forEach(function(layer) {\n var color = layer.color;\n if (color in colorUsage)\n colorUsage[color] = colorUsage[color] + 1;\n else\n colorUsage[color] = 1;\n });\n // Convert to array and sort by usage\n colorUsage = Object.entries(colorUsage).sort(function(a,b) {return a[1] - b[1]});\n // Return the first color (the one with the least usage)\n return colorUsage[0][0];\n}", "function get_color_value(selector, i) {\n return self.get_css_color($root.find(selector + \" .color_sample\")[i]);\n }", "function mapcolor(c) {\n if (c === '#eb565c') {\n return 'retail';\n }\n else if (c === '#e7cd77') {\n return 'residential';\n }\n else if (c === '#98eaa6') {\n return 'office';\n }\n else if (c === 'black') {\n return 'void';\n }\n}", "function get_pixel(piece, x, y)\n{\n\tvar index = x + y * piece.width;\n\tpixel = piece.map[index];\n\tif(pixel == undefined)\n\t{\n\t\treturn false;\n\t}\n\telse\n\t{\n\t\treturn pixel;\n\t}\n}", "function getStartingPoint() {\n let firstVisitX = Math.floor(random(0, width));\n let firstVisitY = Math.floor(random(0, height));\n let mapIndex = 0;\n let randomIndex = Math.floor(random(0, imgColors.size));\n let firstColor;\n for(let value of imgColors.values()) {\n if(mapIndex === randomIndex) {\n\n //gets random color from markov chain\n let valueIndex = Math.floor(random(0, value.length-1));\n firstColor = value[valueIndex];\n\n //marks pixel as visited and pushes pixelRecord onto pixelStack\n pixelVisit[firstVisitX][firstVisitY] = true;\n let pixelRecord = {\n pos: [firstVisitX, firstVisitY],\n col: firstColor\n };\n pixelStack.push(pixelRecord);\n\n break;\n }\n mapIndex++;\n }\n}", "function winningColorGenerator(){\r\n\tfor (var i = 0; i < colors.length; i++){\r\n\t\tvar randNum = Math.floor(Math.random() * numSquare);\r\n\t}\r\n\treturn colors[randNum];\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Controller function to get all lists
getAllLists(req, res, next) { listsHelper.getAllLists(req.reqId).then((lists) => { res.json({ success: 1, message: responseMessages.listsFetched.success, data: lists, }); }).catch((error) => { next(error); }); }
[ "static listAllOfMyNews() {\n\t\treturn RestService.get('api/news');\n\t}", "static async listStations(req, res) {\n const stations = await Station.retrieve();\n return res.json(stations);\n }", "function listAll() {\n $scope.voters = VoterService.listAllVoters();\n }", "list(_, res) {\n return pacientes\n .findAll({\n })\n .then(pacientes => res.status(200).send(pacientes))\n .catch(error => res.status(400).send(error))\n }", "function buildList() {\n $log.debug(\"Building list...\");\n vm.list = Object.keys(queryFields); //get the keys\n vm.definitions = queryFields;\n $log.debug(vm.definitions);\n }", "list(req, res) {\n const userId = req.param('userId');\n\n if(req.token.id !== userId) {\n return res.fail('You don\\'t have permission to do this.');\n }\n\n ApplianceService.fetchAllForUser(userId)\n .then(res.success)\n .catch(res.fail);\n }", "async listAll() {\n\t\tlet searchParams = this.type ? { type: this.type } : {};\n\t\tlet records = await StockModel\n\t\t\t.find(searchParams)\n\t\t\t.select({ 'name': 1, 'latest': 1, '_id': 0, 'type': 1 })\n\t\t\t.sort({ 'type': 'asc', 'latest': 'desc' });\n\t\treturn { 'status': 200, records };\n\t}", "function showAll(request){\n\tnamesDB.getAll(gotNames);\n\tfunction gotNames(names){\n\t\tnamesText = \"\";\n\t\tif (names.length > 0){\n\t\t\tfor (i =0; i < names.length; i++) {\n\t\t\t\t// create a link like: <a href=\"/view/1DlDQu55m85dqNQJ\">Joe</a><br/>\n\t\t\t namesText += '<a href=\"/view/' + names[i]._id + '\">' + names[i].name + \"</a><br/>\";\n\t\t\t}\n\t\t} else {\n\t\t\tnamesText = \"No people in the database yet.\";\n\t\t}\n\t\t\n\t\t//console.log(namesText);\n\t\tvar footerText = '<hr/><p><a href=\"/search\">Search</a>';\n\t\trequest.respond( namesText + footerText);\n\t}\t\n}", "static async list(ctx) {\n // build sql query including any query-string filters; eg ?field1=val1&field2=val2 becomes\n // \"Where field1 = :field1 And field2 = :field2\"\n let sql = 'Select * From Team';\n if (ctx.request.querystring) {\n const filter = Object.keys(ctx.request.query).map(q => `${q} = :${q}`).join(' and ');\n sql += ' Where '+filter;\n }\n sql += ' Order By Name';\n\n try {\n\n const [ teams ] = await Db.query(sql, ctx.request.query);\n\n await ctx.render('teams-list', { teams });\n\n } catch (e) {\n switch (e.code) {\n case 'ER_BAD_FIELD_ERROR': ctx.throw(403, 'Unrecognised Team field'); break;\n default: throw e;\n }\n }\n }", "function list(req, res) {\n res.json({ data: dishes });\n}", "getAll(req, res, next) {\n\n var\n request = new Request(req),\n response = new Response(request, this.expandsURLMap),\n criteria = this._buildCriteria(request);\n\n this.Model.paginate(criteria, request.options, function(err, paginatedResults, pageCount, itemCount) {\n /* istanbul ignore next */\n if (err) { return next(err); }\n\n response\n .setPaginationParams(pageCount, itemCount)\n .formatOutput(paginatedResults, function(err, output) {\n /* istanbul ignore next */\n if (err) { return next(err); }\n\n res.json(output);\n });\n\n });\n }", "function getAllItems(){\n\n}", "listAllGroups () {\n return this._apiRequest('/groups/all')\n }", "static list(collection, filter={}) {\n return db.db.allDocs({include_docs: true});\n }", "indexAction(req, res) {\n Robot.find((err, robots) => {\n if (err)\n this.jsonResponse(res, 400, { 'error': err });\n\n this.jsonResponse(res, 200, { 'robots': robots });\n });\n }", "function listarUsuarios() {\r\n\t\t\tconsole.log('refrescando.......');\r\n\t\t\thttpservice.get('semestresAnteriores/listaUsuarios', null,\r\n\t\t\t\t\tsuccess = function(data, status, headers, config) {\r\n\t\t\t\t\t\tconsole.log('success.......');\r\n\t\t\t\t\t\t$scope.usuarios = data.obj;\r\n\t\t\t\t\t}, null);\r\n\t\t}", "function apiShowAll(req, res) {\n //console.log('GET /api/breed/all');\n // return JSON object of specified breed\n db.Breed.find({}, function(err, allBreeds) {\n if (err) {\n res.send('ERROR::' + err);\n } else {\n res.json({breeds: allBreeds});\n }\n });\n}", "async function list(req, res, next) {\n try {\n const data = await moviesService.list();\n const { is_showing } = req.query;\n const byResult = is_showing\n ? (movie) => movie.is_showing == true\n : () => true; // if given query parameter is_showing, return only movies with is_showing == true\n res.json({ data: data.filter(byResult) });\n } catch (error) {\n next(error);\n }\n}", "function getListItems() {\n let isLoggedIn = localStorage.getItem(\"isLoggedIn\")\n let username = localStorage.getItem(\"username\")\n\n if (isLoggedIn && username) {\n console.log(\"getting list of items\")\n axios\n .get(`/api/pantry?cmd=getList&username=${username}`)\n .then(response => {\n let items = response.data.items\n console.log(\"Response: \" + response)\n listOfItems.push(...items) // push each item separately into the list listOfItems\n allItems.push(...items) // push each item separately into the list listOfItems\n showListItems()\n })\n .catch(error => {\n console.error(error)\n })\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draws debug data in foreground
drawDebugForeground() { if (this.showDebug) { var x = 15; var y = 15; this.ctx.fillStyle = Color.Style(Color.White50); this.ctx.font = "12px monospace"; this.ctx.textBaseline = "top"; this.ctx.textAlign = "right"; this.ctx.fillText(Math.round(this.loop.getFPS()) + " FPS", this.viewportSize.x - 15, 15); var text = this.camera.toString(); text += "\n" + "Entities count: " + this.entityManager.count(); this.ctx.fillStyle = Color.Style(Color.White50); this.ctx.font = "12px monospace"; this.ctx.textBaseline = "top"; this.ctx.textAlign = "left"; var lines = text.split("\n"); for (var i = 0; i < lines.length; i++) { this.ctx.fillText(lines[i], x, y); y += 15; } } }
[ "function debug(text){\n stats.setContent(stats.getContent()+\"<br>\"+text);\n}", "debugDrawObject(obj, time) {\n obj.debugDraw(time, this, this.drawContext);\n }", "display() {\n //set the color\n stroke(this.element*255) ;\n //draw the point\n point(this.identity.x,this.identity.y)\n }", "function setupDebug(){\n debug = new DEBUGTOOL(false,null,[8,8,16]);\n}", "function _initDebugBackground() {\n if (!this.options.debug) return;\n\n this.containers.forEach(function(containerObj, i) {\n\n var background = new Surface({\n properties: {\n background: 'black',\n border: '1px dashed green',\n zIndex: '-9999999'\n }\n });\n\n containerObj.container.add(background);\n });\n}", "draw() {\n this.context.clear();\n this.stave = this.drawStave();\n this.stave.draw();\n const notes = this.drawNotes(this.noteData);\n\n // eslint-disable-next-line new-cap\n this.VF.Formatter.FormatAndDraw(this.context, this.stave, notes);\n }", "function DOMDisplay(parent, level) {\n\tthis.wrap = parent.appendChild(elMaker(\"div\", \"game\"));\n\tthis.level = level;\n\n\tthis.wrap.appendChild(this.drawBackground());\n\tthis.activeLayer = null;\n\tthis.drawFrame();\n}", "display() {\n this.draw(this.points.length);\n }", "function fDbg(v)\n{\n\tconsole.log(\"|~|\" + v);\n}", "draw() {\n\t\tconst output = this.buffer.join(\",\");\n\t\tthis.style.applyCSS(output);\n\t}", "function dbg(prs, id, w, h, mode, fr){\n\t//save instance of visualizer\n\tthis._vis = viz.getVisualizer(\n\t\tVIS_TYPE.DBG_VIEW,\t\t\t\t//debugging viewport\n\t\tprs,\t\t\t\t\t\t\t//parser instance\n\t\tid,\t\t\t\t\t\t\t\t//HTML element id\n\t\tw,\t\t\t\t\t\t\t\t//width\n\t\th,\t\t\t\t\t\t\t\t//height\n\t\tfunction(cellView, evt, x, y){\t//mouse-click event handler\n\t\t\t//ES 2017-12-09 (b_01): is visualizer use canvas framework\n\t\t\tvar tmpDoCanvasDraw = viz.__visPlatformType == VIZ_PLATFORM.VIZ__CANVAS;\n\t\t\t//ES 2017-12-09 (b_01): is visualizer use jointjs framework\n\t\t\tvar tmpDoJointJSDraw = viz.__visPlatformType == VIZ_PLATFORM.VIZ__JOINTJS;\n\t\t\t//if clicked command (we can put breakpoint only on command)\n\t\t\t//ES 2017-12-09 (b_01): refactor condition to adopt for Canvas framework\n\t\t\tif( (tmpDoCanvasDraw && cellView._type == RES_ENT_TYPE.COMMAND ) || \n\t\t\t\t(tmpDoJointJSDraw && cellView.model.attributes.type == \"command\") \n\t\t\t){\n\t\t\t\t//get debugger (do not need to pass any values, since\n\t\t\t\t//\tdebugger should exist by now, and thus we should\n\t\t\t\t//\tnot try to create new debugger instance)\n\t\t\t\tvar tmpDbg = dbg.getDebugger();\n\t\t\t\t//ES 2017-12-09 (b_01): declare var for command id\n\t\t\t\tvar tmpCmdId = null;\n\t\t\t\t//ES 2017-12-09 (b_01): if drawing using Canvas framework\n\t\t\t\tif( tmpDoCanvasDraw ) {\n\t\t\t\t\t//get command id in string representation\n\t\t\t\t\ttmpCmdId = cellView.obj._id.toString();\n\t\t\t\t//ES 2017-12-09 (b_01): else, drawing with JointJS framework\n\t\t\t\t} else {\n\t\t\t\t\t//get command id for this jointJS entity\n\t\t\t\t\t//ES 2017-12-09 (b_01): move var declaration outside of IF\n\t\t\t\t\ttmpCmdId = cellView.model.attributes.attrs['.i_CmdId'].text;\n\t\t\t\t\t//right now command id contains ':' -- filter it out\n\t\t\t\t\ttmpCmdId = tmpCmdId.substring(0, tmpCmdId.indexOf(':'));\n\t\t\t\t}\t//ES 2017-12-09 (b_01): end if drawing using Canvas framework\n\t\t\t\t//check if this breakpoint already has been added for this command\n\t\t\t\tif( tmpCmdId in tmpDbg._breakPoints ){\n\t\t\t\t\t//ES 2017-12-09 (b_01): if drawing using Canvas framework\n\t\t\t\t\tif( tmpDoCanvasDraw ) {\n\t\t\t\t\t\t//remove breakpoint DIV\n\t\t\t\t\t\t$(tmpDbg._breakPoints[tmpCmdId]).remove();\n\t\t\t\t\t//ES 2017-12-09 (b_01): else, drawing using JointJS framework\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//diconnect breakpoint from this command\n\t\t\t\t\t\tcellView.model.unembed(tmpDbg._breakPoints[tmpCmdId]);\n\t\t\t\t\t\t//remove circle that represents a breakpoint\n\t\t\t\t\t\ttmpDbg._breakPoints[tmpCmdId].remove();\n\t\t\t\t\t}\t//ES 2017-12-09 (b_01): end if drawing using Canvas framework\n\t\t\t\t\t//delete breakpoint entry in our collection\n\t\t\t\t\tdelete tmpDbg._breakPoints[tmpCmdId];\n\t\t\t\t} else {\t//else, create a breakpoint\n\t\t\t\t\t//ES 2017-12-09 (b_01): declare color constants for breakpoint to be used\n\t\t\t\t\t//\tby all visualizer frameworks\n\t\t\t\t\tvar tmpBrkStroke = \"#00E000\";\t\t//border color\n\t\t\t\t\tvar tmpBrkFill = \"#E00000\";\t\t\t//filling color\n\t\t\t\t\t//ES 2017-12-09 (b_01): declare vars for breakpoint dimensions\n\t\t\t\t\tvar tmpBrkWidth = 15;\n\t\t\t\t\tvar tmpBrkHeight = 15;\n\t\t\t\t\t//ES 2017-12-09 (b_01): x-offset between breakpoint and left side of command\n\t\t\t\t\tvar tmpBrkOffX = 20;\n\t\t\t\t\t//ES 2017-12-09 (b_01): if drawing using Canvas framework\n\t\t\t\t\tif( tmpDoCanvasDraw ) {\n\t\t\t\t\t\t//compose html elem ID where to insert breakpoint\n\t\t\t\t\t\tvar tmpCnvMapId = \"#\" + viz.getVisualizer(VIS_TYPE.DBG_VIEW).getCanvasElemInfo(VIS_TYPE.DBG_VIEW)[1];\n\t\t\t\t\t\t//create circle shape DIV and save it inside set of breakpoints\n\t\t\t\t\t\t//\tsee: https://stackoverflow.com/a/25257964\n\t\t\t\t\t\ttmpDbg._breakPoints[tmpCmdId] = $(\"<div>\").css({\n\t\t\t\t\t\t\t\"border-radius\": \"50%\",\n\t\t\t\t\t\t\t\"width\": tmpBrkWidth.toString() + \"px\",\n\t\t\t\t\t\t\t\"height\": tmpBrkHeight.toString() + \"px\",\n\t\t\t\t\t\t\t\"background\": tmpBrkFill,\n\t\t\t\t\t\t\t\"border\": \"1px solid \" + tmpBrkStroke,\n\t\t\t\t\t\t\t\"top\": cellView.y.toString() + \"px\",\n\t\t\t\t\t\t\t\"left\": (cellView.x - tmpBrkOffX).toString() + \"px\",\n\t\t\t\t\t\t\t\"position\": \"absolute\"\n\t\t\t\t\t\t});\n\t\t\t\t\t\t//add breakpoint to canvas map\n\t\t\t\t\t\t$(tmpCnvMapId).append(tmpDbg._breakPoints[tmpCmdId]);\n\t\t\t\t\t//ES 2017-12-09 (b_01): else, drawing using JointJS framework\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//create visual attributes for breakpoint\n\t\t\t\t\t\tvar brkPtAttrs = {\n\t\t\t\t\t\t\tposition : {\t//place breakpoint to the left of command id\n\t\t\t\t\t\t\t\t//ES 2017-12-09 (b_01): replace x-offset with var\n\t\t\t\t\t\t\t\tx : cellView.model.attributes.position.x - tmpBrkOffX,\n\t\t\t\t\t\t\t\ty : cellView.model.attributes.position.y\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tsize : {\t//show small circle\n\t\t\t\t\t\t\t\t//ES 2017-12-09 (b_01): replace dimension consts with vars\n\t\t\t\t\t\t\t\twidth : tmpBrkWidth,\n\t\t\t\t\t\t\t\theight : tmpBrkHeight\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tattrs : {\n\t\t\t\t\t\t\t\tcircle : {\n\t\t\t\t\t\t\t\t\t//ES 2017-12-09 (b_01): replace color constants with vars\n\t\t\t\t\t\t\t\t\tstroke: tmpBrkStroke,\t//border with green color\n\t\t\t\t\t\t\t\t\tfill : tmpBrkFill\t\t//fill with red color\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\t\t\t\t\t\t//create breakpoint circle\n\t\t\t\t\t\tvar tmpCircle = new joint.shapes.basic.Circle(brkPtAttrs);\n\t\t\t\t\t\t//show it in viewport\n\t\t\t\t\t\tviz.getVisualizer(VIS_TYPE.DBG_VIEW)._graph.addCells([tmpCircle]);\n\t\t\t\t\t\t//add this command to collection that maps command id to breakpoint\n\t\t\t\t\t\ttmpDbg._breakPoints[tmpCmdId] = tmpCircle;\n\t\t\t\t\t\t//connect breakpoint with this command (so if command moves, so does breakpoint)\n\t\t\t\t\t\tcellView.model.embed(tmpCircle);\n\t\t\t\t\t}\t//ES 2017-12-09 (b_01): end if drawing using Canvas framework\n\t\t\t\t}\t//end if breakpoint for this command already exists\n\t\t\t}\t//end if clicked command\n\t\t}\t//end mouse-click event handler\n\t);\t//end retrieve/create visualizer\n\t//draw CFG, starting from global scope\n\tthis._vis.drawCFG(prs._gScp);\n\t//if mode is not set\n\tif( typeof mode == \"undefined\" || mode == null ){\n\t\t//set it to be NON_STOP\n\t\tmode = DBG_MODE.NON_STOP;\n\t}\n\t//reference to the cursor framework object\n\tthis._cursorEnt = null;\n\t//array of framework objects for current command arguments\n\tthis._cmdArgArrEnt = [];\n\t//collection of breakpoints\n\t//\tkey: command_id\n\t//\tvalue: framework entity (visual representation of breakpoint)\n\tthis._breakPoints = {};\n\t//collection that maps command id to framework objects for resulting command value\n\t//\tkey: command id\n\t//\tvalue: framework object for resulting value\n\tthis._cmdToResValEnt = {};\n\t//call stack -- collects DFS (debugging function state(s))\n\tthis._callStack = [];\n\t//create current debugging function state\n\tthis._callStack.push(\n\t\tnew dfs(mode, fr, null, null)\n\t);\n\t//create key stroke handler\n\t$(document).keypress(\t//when key is pressed, fire this event\n\t\tfunction(e){\t\t\t//handler for key press event\n\t\t\t//get debugger (do not need to pass any values)\n\t\t\tvar tmpDbg = dbg.getDebugger();\n\t\t\t//depending on the character pressed by the user\n\t\t\tswitch(e.which){\n\t\t\t\tcase 97:\t\t\t//'a' - again run program\n\t\t\t\t\t//reset static and non-static fields, set current frame, and load vars\n\t\t\t\t\tentity.__interp.restart();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 110:\t\t\t//'n' - next command (step thru)\n\t\t\t\t\ttmpDbg.getDFS()._mode = DBG_MODE.STEP_OVER;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 115:\t\t\t//'s' - step in\n\t\t\t\t\ttmpDbg.getDFS()._mode = DBG_MODE.STEP_IN;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 114:\t\t\t//'r' - run non stop\n\t\t\t\t\ttmpDbg.getDFS()._mode = DBG_MODE.NON_STOP;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 118:\t\t\t//'v' - variables\n\t\t\t\t\t//Comment: do not reset mode, we just want to show/hide lookup box\n\t\t\t\t\t//show lookup box with all accessible variables\n\t\t\t\t\ttmpDbg.showEntityLookUpBox();\n\t\t\t\t\t//quit to prevent running next command\n\t\t\t\t\treturn;\n\t\t\t\tcase 113:\t\t\t//'q' - quit\n\t\t\t\t\t//quit debugger\n\t\t\t\t\ttmpDbg.quitDebugger();\n\t\t\t\t\t//quit to prevent running next command\n\t\t\t\t\treturn;\n\t\t\t\tcase 99:\t\t\t//'c' center on cursor\n\t\t\t\t\ttmpDbg.scrollTo(tmpDbg.getDFS()._pos._cmd._id);\n\t\t\t\t\tbreak;\n\t\t\t}\t//end switch -- depending on the key pressed by the user\n\t\t\t//declare var for returned value from RUN function\n\t\t\tvar tmpRunVal;\n\t\t\t//if returning function value from stepped in function\n\t\t\tif( tmpDbg.getDFS()._val != 0 ){\n\t\t\t\t//invoke run and pass in return value\n\t\t\t\tentity.__interp.run(tmpDbg.getDFS()._frame, tmpDbg.getDFS()._val);\n\t\t\t\t//reset return value to 0\n\t\t\t\ttmpDbg.getDFS()._val = 0;\n\t\t\t} else {\t//regular execution\n\t\t\t\t//invoke interpreter's run function\n\t\t\t\ttmpRunVal = entity.__interp.run(tmpDbg.getDFS()._frame);\n\t\t\t}\n\t\t\t//if return value from RUN function is defined and NULL\n\t\t\tif( typeof tmpRunVal != \"undefined\" &&\t//make sure that RUN returned smth \n\t\t\t\ttmpRunVal == null && \t\t\t\t//make sure RUN function quit\n\t\t\t\ttmpDbg._callStack.length > 0 &&\t\t//call stack is not empty\n\n\t\t\t\t//make sure it is not EXIT command\n\t\t\t\ttmpDbg._callStack[tmpDbg._callStack.length - 1]._funcCall != null ){\n\t\t\t\t//pop last entry from call stack\n\t\t\t\tvar tmpLstCallStk = tmpDbg._callStack.pop();\n\t\t\t\t//get functinoid id for the completed function call\n\t\t\t\tvar tmpFuncId = tmpLstCallStk._funcCall._funcRef._id;\n\t\t\t\t//get function call object\n\t\t\t\tvar tmpFuncCallObj = tmpLstCallStk._frame._funcsToFuncCalls[tmpFuncId];\n\t\t\t\t//get return value from completed function call\n\t\t\t\ttmpDbg.getDFS()._val = tmpFuncCallObj._returnVal;\n\t\t\t\t//re-draw cursor\n\t\t\t\ttmpDbg.showCursor();\n\t\t\t}\n\t\t}\t//end handler function\n\t);\n\t//reference to box that stores set of entities currently accessible in the code\n\tthis._entLookupBox = null;\n}", "function drawDebugHitbox(entity) {\n let canvas = document.getElementById('gameWorld');\n let ctx = canvas.getContext('2d');\n ctx.beginPath();\n ctx.strokeStyle = entity.isRecoiling ? 'orange' : 'green';\n ctx.lineWidth = 2;\n ctx.rect(entity.hitbox.x, entity.hitbox.y, entity.hitbox.width, entity.hitbox.height);\n ctx.stroke();\n ctx.closePath();\n}", "function printWin() {\n $('#hint').text(userString.winMessage).css(\"color\", \"#000000\");\n}", "function clearConsole() {\n // reset drawing title\n abEamTcController.setDrawingPanelTitle(getMessage('noFlSelected'));\n // clear drawing content\n abEamTcController.clearDrawing();\n // clear asset details\n abEamTcController.clearAssetDetailRestriction(true);\n}", "function extendedDraw() {\r\n this._drawBackground()\r\n this._drawHeader()\r\n originalDraw()\r\n }", "function draw_display(video, context, width, height)\n {\n context.drawImage(video, 0, 0, width, height);\n context.drawImage(active_filter, 0, 0, width, height);\n display_timeout = setTimeout(draw_display, 10, video, context, width, height);\n }", "function drawFeedback() {\n 'use strict';\n let ctx = document.getElementById('canvas').getContext('2d');\n let dat = jsPsych.data.get().last(1).values()[0];\n ctx.font = prms.fbFont;\n ctx.textAlign = 'center';\n ctx.textBaseline = 'middle';\n ctx.fillStyle = 'black';\n ctx.fillText(prms.fbTxt[dat.corrCode], dat.end_x, dat.end_y);\n}", "function frame(){\n\t//FRAME DEBUG\n\t\t// noFill();\n\t\t// stroke(0)\n\t\t// strokeWeight(1);\n\t\n\t//Frame Appearance\n\tnoStroke();\n\tfill(0);\n\t\n\t//Frame Render\n\trect(0, 0, canvasWidth, frameThickness);\n\trect(0, canvasWidth-frameThickness, canvasWidth, frameThickness);\n\trect(0, 0, frameThickness, canvasWidth);\n\trect(canvasWidth-frameThickness, 0, frameThickness, canvasWidth);\n}", "printBuffers() {\n for (var i = 0; i < this.numVertices; i++) {\n console.log(\"v \", this.positionData[i*3], \" \",\n this.positionData[i*3 + 1], \" \",\n this.positionData[i*3 + 2], \" \");\n }\n for (var i = 0; i < this.numVertices; i++) {\n console.log(\"n \", this.normalData[i*3], \" \",\n this.normalData[i*3 + 1], \" \",\n this.normalData[i*3 + 2], \" \");\n }\n for (var i = 0; i < this.numFaces; i++) {\n console.log(\"f \", this.faceData[i*3], \" \",\n this.faceData[i*3 + 1], \" \",\n this.faceData[i*3 + 2], \" \");\n }\n }", "function DebugLayer(scene){var _this=this;this.BJSINSPECTOR=typeof INSPECTOR!=='undefined'?INSPECTOR:undefined;/**\n * Observable triggered when a property is changed through the inspector.\n */this.onPropertyChangedObservable=new BABYLON.Observable();this._scene=scene;this._scene.onDisposeObservable.add(function(){// Debug layer\nif(_this._scene._debugLayer){_this._scene._debugLayer.hide();}});}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function that maps subscript to full feature name
function subToFeature(sub){ if(sub === "absmag") return "Absolute Magnitude"; else if(sub === "mag") return "Apparent Magnitude"; else if(sub === "ci") return "Color Index"; else return "Luminance"; }
[ "function nameOf(fun) {\n var ret = fun.toString();\n ret = ret.substr('function '.length);\n ret = ret.substr(0, ret.indexOf('('));\n return ret;\n }", "function abbreviatedFun(fullname) {\n let array = fullname.split(' ');\n let result = array[0];\n for (i = 1; i < array.length; i++) {\n result += ' ' + (array[i])[0];\n }\n result += '.';\n return result;\n \n}", "function getFeatureIdNameCategory(featureId) {\n var splitId = featureId.split('/');\n return {\n category: splitId[0],\n name: splitId[1]\n };\n}", "function nameString(featureSet) {\n return featureSet.map(function (feature) {\n return feature.name;\n }).sort().join(\":::;\");\n }", "getShortName() {\n let shortName = this.firstName + ' ' + this._getInitial(this.lastName) + '.';\n return shortName;\n }", "function FunctionName(FunctionF){\n\tvar name=FunctionF.toString().replace(/\\(.*/,\"\").replace(\"function \",\"\");\n\tname=name.replace(/\\s.*/gm,\"\");\n\tif(name!==\"function\")\n\t\treturn name;\n\telse{\n\t\tvar body=FunctionF.toString().replace(/[^\\)]*\\)/,\"\");\n\t\treturn body.replace(/[^ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890]/gi,\"\").replace(/^[1234567890]*/,\"\");\n\t}\n}", "function updateFuncName(obj) {\r\n\r\n var sO = CurStepObj;\r\n //\r\n if (!sO.isSpaceActive) {\r\n var pos = sO.activeChildPos;\r\n var fname = obj.innerHTML;\r\n\r\n if (isExistingName(CurModObj, CurFuncObj, CurStepObj, fname)) {\r\n\r\n alert(\"Function name \" + fname + \" already exists!\");\r\n\r\n } else {\r\n\r\n sO.activeParentExpr.exprArr[pos].str = obj.innerHTML;\r\n }\r\n\r\n // Redraw program structure heading to indicate new function name\r\n //\r\n drawProgStructHead(); // update program structre heading\r\n drawCodeWindow(sO);\r\n }\r\n}", "function makeStandardJSName(s){\n return s.replace(/_([a-z])/g, function (g) { return g[1].toUpperCase(); });\n }", "nameFormat(name) {\n return name;\n }", "visitString_function_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function addFeature() {\n\n}", "function idOf(word) {\n return \".word_\" + word;\n}", "function subscript(str) {\n str = str.replace(/0/g, \"₀\");\n str = str.replace(/1/g, \"₁\");\n str = str.replace(/2/g, \"₂\");\n str = str.replace(/3/g, \"₃\");\n str = str.replace(/4/g, \"₄\");\n str = str.replace(/5/g, \"₅\");\n str = str.replace(/6/g, \"₆\");\n str = str.replace(/7/g, \"₇\");\n str = str.replace(/8/g, \"₈\");\n str = str.replace(/9/g, \"₉\");\n return str;\n }", "visitDotted_as_name(ctx) {\r\n console.log(\"visitDotted_as_name\");\r\n if (ctx.NAME() !== null) {\r\n return {\r\n type: \"Imported\",\r\n name: this.visit(ctx.dotted_name()),\r\n alias: ctx.NAME().getText(),\r\n };\r\n } else {\r\n return {\r\n type: \"Imported\",\r\n name: this.visit(ctx.dotted_name()),\r\n alias: null,\r\n };\r\n }\r\n }", "function fvFunctionCode(f) {\n\tf = f.toString();\n\treturn f.substring(f.indexOf('{') + 1, f.lastIndexOf(';') + 1);\n}", "function fnExoticToStringTag() {}", "function getPlainName(oper) {\n if (oper.indexOf('$') === -1) return oper;\n else return oper.substr(0, oper.indexOf('$'));\n}", "function getStateLabel(feature) {\n return feature.properties.state;\n}", "function getFuzzificationMethodLabel(x)\n{\n\tswitch(x)\n\t{\n\t\tcase TRIANGULAR_PERCENT:\n\t\treturn TRIANGULAR_PERCENT_ID;\n\t\tbreak;\n\t\t\n\t\tcase TRIANGULAR_ABSOLUTE:\n\t\treturn TRIANGULAR_ABSOLUTE_ID;\n\t\tbreak;\n\t\t\n\t\tcase TRAPEZOIDAL_PERCENT:\n\t\treturn TRAPEZOIDAL_PERCENT_ID;\n\t\tbreak;\n\t\t\n\t\tcase TRAPEZOIDAL_ABSOLUTE:\n\t\treturn TRAPEZOIDAL_ABSOLUTE_ID;\n\t\tbreak;\n\t\t\n\t\tcase SINGLETON:\n\t\treturn SINGLETON_ID;\n\t\tbreak;\n\t}\n}", "function printCool(name) {\n return `${name} is cool.`\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the usage flags for a given track across every frame
getSoundEffectFlagsForTrack(trackId) { return this.getSoundEffectFlags().map(flags => flags[trackId]); }
[ "getSoundEffectFlags() {\r\n return this.decodeSoundFlags().map(frameFlags => ({\r\n [exports.FlipnoteSoundEffectTrack.SE1]: frameFlags[0],\r\n [exports.FlipnoteSoundEffectTrack.SE2]: frameFlags[1],\r\n [exports.FlipnoteSoundEffectTrack.SE3]: frameFlags[2]\r\n }));\r\n }", "dumpTrack() {\n const strs = [];\n const perSize = Math.floor(TRACK_MAX_SIZE / 2);\n const tracks = (this._tracks.length > TRACK_MAX_SIZE) ?\n this._tracks.slice(0, perSize).concat([' ... ']).concat(this._tracks.slice(-perSize)) :\n this._tracks;\n let ud = '';\n for (const el of tracks) {\n if (el === TRACK_CHAR_UPLOAD || el === TRACK_CHAR_DOWNLOAD) {\n if (ud === el) {\n continue;\n }\n ud = el;\n }\n strs.push(el);\n }\n const samples = this._tracks.filter(Number.isInteger).length;\n logger.info(`[socket] [${this._id}] summary(${samples} sampled): ${strs.join(' ')}`);\n }", "getFrameCameraFlags(frameIndex) {\r\n this.seek(this.frameMetaOffsets[frameIndex] + 0x1A);\r\n const cameraFlags = this.readUint8();\r\n return [\r\n (cameraFlags & 0x1) !== 0,\r\n (cameraFlags & 0x2) !== 0,\r\n (cameraFlags & 0x4) !== 0,\r\n ];\r\n }", "getFrameCameraFlags(frameIndex) {\r\n return [false, false];\r\n }", "function allFlagsPercentDataProvider(fid) {\n // Decimal number\n var decimalInput = '[{id: ' + fid + ', value: ' + numberDecimalOnly + '}]';\n var expectedDecimalRecord = '{id: ' + fid + ', value: ' + numberDecimalOnly + ', display: \"0,75%\"}';\n\n // Double number\n var doubleInput = '[{id: ' + fid + ', value: ' + numberDouble + '}]';\n var expectedDoubleRecord = '{id: ' + fid + ', value: ' + numberDouble + ', display: \"98.76.54.32.100,75%\"}';\n\n // Int number\n var intInput = '[{id: ' + fid + ', value: ' + numberInt + '}]';\n var expectedIntRecord = '{id: ' + fid + ', value: ' + numberInt + ', display: \"99,00%\"}';\n\n // Null number\n var nullInput = '[{id: ' + fid + ', value: null}]';\n var expectedNullRecord = '{id: ' + fid + ', value: null, display: \"\"}';\n\n return [\n {\n message : 'display decimal number with all format flags',\n record : decimalInput,\n format : 'display',\n expectedFieldValue: expectedDecimalRecord\n },\n {\n message : 'raw decimal number with all format flags',\n record : decimalInput,\n format : 'raw',\n expectedFieldValue: decimalInput\n },\n {\n message : 'display double number with all format flags',\n record : doubleInput,\n format : 'display',\n expectedFieldValue: expectedDoubleRecord\n },\n {\n message : 'raw double number with all format flags',\n record : doubleInput,\n format : 'raw',\n expectedFieldValue: doubleInput\n },\n {\n message : 'display int number with all format flags',\n record : intInput,\n format : 'display',\n expectedFieldValue: expectedIntRecord\n },\n {\n message : 'raw int number with all format flags',\n record : intInput,\n format : 'raw',\n expectedFieldValue: intInput\n },\n {\n message : 'display null number with all format flags',\n record : nullInput,\n format : 'display',\n expectedFieldValue: expectedNullRecord\n },\n {\n message : 'raw null number with all format flags',\n record : nullInput,\n format : 'raw',\n expectedFieldValue: nullInput\n }\n ];\n }", "getFlags() {\n this.context.store.dispatch(getFlags());\n }", "parseTrack() {\n\t\tlet done = false;\n\t\tif (this.fetchString(4) !== 'MTrk') {\n\t\t\tconsole.log('ERROR: No MTrk');\n\t\t\tthis.error = { code: 4, pos: ppos, msg: 'Failed to find MIDI track.' };\n\t\t\treturn;\n\t\t}\n\t\t// this.trks.push(new MIDItrack());\n\t\tlet len = this.fetchBytes(4);\n\t\t// console.log('len = '+len);\n\t\twhile (!done) {\n\t\t\tdone = this.parseEvent();\n\t\t}\n\t\tthis.labelCurrentTrack();\n\t\t// console.log('Track '+tpos);\n\t\t// console.log(this.trks[tpos].events);\n\t\t// console.log(trackDuration);\n\t\tif (trackDuration > this.duration) {\n\t\t\tthis.duration = trackDuration;\n\t\t}\n\t\ttrackDuration = 0;\n\t\tnoteDelta.fill(0);\n\t}", "async getAudioFeatures(tracks) {\n let features = {};\n for (let track of tracks) {\n const id = 'id' in track ? track.id : track.track_id;\n await this.spotify.getAudioFeaturesForTrack(id)\n .then(function (data) {\n features[id] = data.body;\n features[id].name = track.name;\n });\n }\n return features;\n }", "function getTimePlayed(track) {\n /* YOUR CODE HERE */\n}", "function diagnostic() {\n return Object.keys(tape)\n .map(key => tape[key] === 1 ? 1 : 0)\n .reduce((acc, v) => acc + v, 0);\n}", "getFrameLayerDepths(frameIndex) {\r\n assertRange(frameIndex, 0, this.frameCount - 1, 'Frame index');\r\n this.seek(this.frameMetaOffsets[frameIndex] + 0x14);\r\n return [\r\n this.readUint8(),\r\n this.readUint8(),\r\n this.readUint8()\r\n ];\r\n }", "function buildTrackCounts() {\n interactionEvents.sort(function (a, b) {\n return (+a[config.timePointColumn]) - (+b[config.timePointColumn]);\n });\n for (let i = 0, eventCount = interactionEvents.length; i < eventCount; i++) {\n let event = interactionEvents[i];\n let proteinA = event[config.proteinAColumn];\n let proteinB = event[config.proteinBColumn];\n let timePoint = +event[config.timePointColumn];\n addTrackCount(proteinA, proteinB, timePoint);\n addTrackCount(proteinB, proteinA, timePoint);\n }\n\n if (config.removeDuplicateInteractions === \"true\") {\n removeDuplicateInteractions();\n }\n for (let protein in trackCounts) {\n removeSmallerTrackCounts(protein);\n }\n }", "getFrameLayerDepths(frameIndex) {\r\n return [0, 0];\r\n }", "function noFlagsPercentDataProvider(fid) {\n // Decimal number\n var decimalInput = '[{id: ' + fid + ', value: ' + numberDecimalOnly + '}]';\n var expectedDecimalRecord = '{id: ' + fid + ', value: ' + numberDecimalOnly + ', display: \"0.74765432000000%\"}';\n\n // Double number\n var doubleInput = '[{id: ' + fid + ', value: ' + numberDouble + '}]';\n var expectedDoubleRecord = '{id: ' + fid + ', value: ' + numberDouble + ', display: \"98765432100.74765000000000%\"}';\n\n // Int number\n var intInput = '[{id: ' + fid + ', value: ' + numberInt + '}]';\n var expectedIntRecord = '{id: ' + fid + ', value: ' + numberInt + ', display: \"99.00000000000000%\"}';\n\n // Null number\n var nullInput = '[{id: ' + fid + ', value: null}]';\n var expectedNullRecord = '{id: ' + fid + ', value: null, display: \"\"}';\n\n return [\n {\n message : 'display decimal number with no format flags',\n record : decimalInput,\n format : 'display',\n expectedFieldValue: expectedDecimalRecord\n },\n {\n message : 'raw decimal number with no format flags',\n record : decimalInput,\n format : 'raw',\n expectedFieldValue: decimalInput\n },\n {\n message : 'display double number with no format flags',\n record : doubleInput,\n format : 'display',\n expectedFieldValue: expectedDoubleRecord\n },\n {\n message : 'raw double number with no format flags',\n record : doubleInput,\n format : 'raw',\n expectedFieldValue: doubleInput\n },\n {\n message : 'display int number with no format flags',\n record : intInput,\n format : 'display',\n expectedFieldValue: expectedIntRecord\n },\n {\n message : 'raw int number with no format flags',\n record : intInput,\n format : 'raw',\n expectedFieldValue: intInput\n },\n {\n message : 'display null number with no format flags',\n record : nullInput,\n format : 'display',\n expectedFieldValue: expectedNullRecord\n },\n {\n message : 'raw null number with no format flags',\n record : nullInput,\n format : 'raw',\n expectedFieldValue: nullInput\n }\n ];\n }", "decodeAudioTrack(trackId) {\r\n // note this doesn't resample\r\n // decode a 4 bit IMA adpcm audio track\r\n // https://github.com/Flipnote-Collective/flipnote-studio-docs/wiki/PPM-format#sound-data\r\n const src = this.getAudioTrackRaw(trackId);\r\n const srcSize = src.length;\r\n const dst = new Int16Array(srcSize * 2);\r\n let srcPtr = 0;\r\n let dstPtr = 0;\r\n let sample = 0;\r\n let stepIndex = 0;\r\n let predictor = 0;\r\n let lowNibble = true;\r\n while (srcPtr < srcSize) {\r\n // switch between high and low nibble each loop iteration\r\n // increments srcPtr after every high nibble\r\n if (lowNibble)\r\n sample = src[srcPtr] & 0xF;\r\n else\r\n sample = src[srcPtr++] >> 4;\r\n lowNibble = !lowNibble;\r\n const step = ADPCM_STEP_TABLE[stepIndex];\r\n let diff = step >> 3;\r\n if (sample & 1)\r\n diff += step >> 2;\r\n if (sample & 2)\r\n diff += step >> 1;\r\n if (sample & 4)\r\n diff += step;\r\n if (sample & 8)\r\n diff = -diff;\r\n predictor += diff;\r\n predictor = clamp(predictor, -32768, 32767);\r\n stepIndex += ADPCM_INDEX_TABLE_4BIT[sample];\r\n stepIndex = clamp(stepIndex, 0, 88);\r\n dst[dstPtr++] = predictor;\r\n }\r\n return dst;\r\n }", "function analyze() {\n raf = requestAnimationFrame(analyze);\n var stream = audioAnalyzer.getFrequencyAnalysis();\n\n if(false === stream) {\n onEnd();\n return;\n }\n\n var a = utils.average(stream),\n id;\n // Glitch on clap\n if (a > 100.5 && a < 102.5) {\n if(Date.now() - lastGlitch < 500) {\n // Don't replay glitch before 0.5s\n return;\n }\n // Play glitch scene\n SM.play(0);\n lastSwitch = lastGlitch = Date.now();\n\n return;\n }\n // Change scene on specific frequency\n if(a > 78 && a < 88) {\n if(Date.now() - lastSwitch < 300) {\n // Don't change scene before 0.3s\n return;\n }\n\n playRandomScene();\n if (false === rendering) {\n SM.render();\n TweenMax.set(render, {autoAlpha: 1, display: 'block'});\n rendering = true;\n }\n lastSwitch = Date.now();\n }\n}", "labelCurrentTrack() {\n\t\tlet labl = 'empty';\n\t\tif (this.trks[tpos].usedInstruments.length === 1) {\n\t\t\tif (this.trks[tpos].hasPercussion) {\n\t\t\t\tlabl = 'Percussion';\n\t\t\t} else {\n\t\t\t\tlabl = getInstrumentLabel(this.trks[tpos].usedInstruments[0]);\n\t\t\t}\n\t\t} else if (this.trks[tpos].usedInstruments.length > 1) {\n\t\t\tlabl = 'Mixed Track';\n\t\t}\n\t\tthis.trks[tpos].label = `${labl} ${this.getLabelNumber(labl)}`;\n\t}", "function ProbeTrack(gsvg, data, trackClass, label, additionalOptions) {\n var that = Track(gsvg, data, trackClass, label);\n\n //console.log(\"creating probe track options:\"+additionalOptions);\n var opts = new String(additionalOptions).split(\",\");\n if (opts.length > 0) {\n that.density = opts[0];\n if (typeof that.density === 'string') {\n that.density = parseInt(that.density);\n }\n if (opts.length > 1) {\n that.colorSelect = opts[1];\n } else {\n that.colorSelect = \"annot\";\n }\n if (opts.length > 2) {\n that.tissues = opts[2].split(\":\");\n\n } else {\n that.tissues = [\"Brain\"];\n if (organism == \"Rn\") {\n that.tissues = [\"Brain\", \"BrownAdipose\", \"Heart\", \"Liver\"];\n }\n }\n } else {\n that.density = 3;\n that.colorSelect = \"annot\";\n that.tissues = [\"Brain\"];\n if (organism == \"Rn\") {\n that.tissues = [\"Brain\", \"BrownAdipose\", \"Heart\", \"Liver\"];\n }\n }\n if (that.gsvg.xScale.domain()[1] - that.gsvg.xScale.domain()[0] > 1000000) {\n that.density = 1;\n }\n\n that.tissuesAll = [\"Brain\"];\n if (organism == \"Rn\") {\n that.tissuesAll = [\"Brain\", \"BrownAdipose\", \"Heart\", \"Liver\"];\n }\n that.xPadding = 1;\n /*if(that.gsvg.xScale.domain()[1]-that.gsvg.xScale.domain()[0]>2000000){\n that.xPadding=0.5;\n }*/\n\n that.scanBackYLines = 75;\n that.curColor = that.colorSelect;\n //console.log(\"start Probes\");\n //console.log(\"density:\"+that.density);\n //console.log(\"colorSelect:\"+that.colorSelect);\n //console.log(\"curColor:\"+that.curColor);\n //console.log(that.tissues);\n\n that.ttTrackList = new Array();\n that.ttTrackList.push(\"ensemblcoding\");\n that.ttTrackList.push(\"braincoding\");\n that.ttTrackList.push(\"liverTotal\");\n that.ttTrackList.push(\"heartTotal\");\n that.ttTrackList.push(\"mergedTotal\");\n that.ttTrackList.push(\"ensemblnoncoding\");\n that.ttTrackList.push(\"brainnoncoding\");\n that.ttTrackList.push(\"repeatMask\");\n //that.ttTrackList.push(\"ensemblsmallnc\");\n //that.ttTrackList.push(\"brainsmallnc\");\n\n that.color = function (d, tissue) {\n var color = d3.rgb(\"#000000\");\n if (that.colorSelect == \"annot\") {\n color = that.colorAnnotation(d);\n } else if (that.colorSelect == \"herit\") {\n var value = getFirstChildByName(d, \"herit\").getAttribute(tissue);\n var cval = Math.floor(value * 255);\n color = d3.rgb(cval, 0, 0);\n } else if (that.colorSelect == \"dabg\") {\n var value = getFirstChildByName(d, \"dabg\").getAttribute(tissue);\n var cval = Math.floor(value * 2.55);\n color = d3.rgb(0, cval, 0);\n }\n return color;\n };\n\n that.colorAnnotation = function (d) {\n var color = d3.rgb(\"#000000\");\n if (d.getAttribute(\"type\") == \"core\") {\n color = d3.rgb(255, 0, 0);\n } else if (d.getAttribute(\"type\") == \"extended\") {\n color = d3.rgb(0, 0, 255);\n } else if (d.getAttribute(\"type\") == \"full\") {\n color = d3.rgb(0, 100, 0);\n } else if (d.getAttribute(\"type\") == \"ambiguous\") {\n color = d3.rgb(0, 0, 0);\n }\n return color;\n };\n\n that.pieColor = function (d, i) {\n var color = d3.rgb(\"#000000\");\n var tmpName = new String(d.data.names);\n if (tmpName == \"Core\") {\n color = d3.rgb(255, 0, 0);\n } else if (tmpName == \"Extended\") {\n color = d3.rgb(0, 0, 255);\n } else if (tmpName == \"Full\") {\n color = d3.rgb(0, 100, 0);\n } else if (tmpName == \"Ambiguous\") {\n color = d3.rgb(0, 0, 0);\n }\n return color;\n };\n\n that.createToolTip = function (d) {\n var strand = \".\";\n if (d.getAttribute(\"strand\") == 1) {\n strand = \"+\";\n } else if (d.getAttribute(\"strand\") == -1) {\n strand = \"-\";\n }\n var len = parseInt(d.getAttribute(\"stop\"), 10) - parseInt(d.getAttribute(\"start\"), 10);\n var tooltiptext = \"<BR><div id=\\\"ttSVG\\\" style=\\\"background:#FFFFFF;\\\"></div><BR>Affy Probe Set ID: \" + d.getAttribute(\"ID\") + \"<BR>Strand: \" + strand + \"<BR>Location: \" + d.getAttribute(\"chromosome\") + \":\" + numberWithCommas(d.getAttribute(\"start\")) + \"-\" + numberWithCommas(d.getAttribute(\"stop\")) + \" (\" + len + \"bp)<BR>\";\n tooltiptext = tooltiptext + \"Type: \" + d.getAttribute(\"type\") + \"<BR><BR>\";\n //var tissues=$(\".settingsLevel\"+that.gsvg.levelNumber+\" input[name=\\\"tissuecbx\\\"]:checked\");\n var herit = getFirstChildByName(d, \"herit\");\n var dabg = getFirstChildByName(d, \"dabg\");\n tooltiptext = tooltiptext + \"<table class=\\\"tooltipTable\\\" width=\\\"100%\\\" colSpace=\\\"0\\\"><tr><TH>Tissue</TH><TH>Heritability</TH><TH>DABG</TH></TR>\";\n if (that.tissues.length < that.tissuesAll.length) {\n tooltiptext = tooltiptext + \"<TR><TD colspan=\\\"3\\\">Displayed Tissues:</TD></TR>\";\n }\n var displayed = {};\n for (var t = 0; t < that.tissues.length; t++) {\n var tissue = new String(that.tissues[t]);\n if (tissue.indexOf(\"Affy\") > -1) {\n tissue = tissue.substr(0, tissue.indexOf(\"Affy\"));\n }\n displayed[tissue] = 1;\n var hval = Math.floor(herit.getAttribute(tissue) * 255);\n var hcol = d3.rgb(hval, 0, 0);\n var dval = Math.floor(dabg.getAttribute(tissue) * 2.55);\n var dcol = d3.rgb(0, dval, 0);\n tooltiptext = tooltiptext + \"<TR><TD>\" + tissue + \"</TD><TD style=\\\"background:\" + hcol + \";color:white;\\\">\" + herit.getAttribute(tissue) + \"</TD><TD style=\\\"background:\" + dcol + \";color:white;\\\">\" + dabg.getAttribute(tissue) + \"%</TD></TR>\";\n }\n if (that.tissues.length < that.tissuesAll.length) {\n tooltiptext = tooltiptext + \"<TR><TD colspan=\\\"3\\\">Other Tissues:</TD></TR>\";\n for (var t = 0; t < that.tissuesAll.length; t++) {\n var tissue = new String(that.tissuesAll[t]);\n if (tissue.indexOf(\"Affy\") > -1) {\n tissue = tissue.substr(0, tissue.indexOf(\"Affy\"));\n }\n if (displayed[tissue] != 1) {\n var hval = Math.floor(herit.getAttribute(tissue) * 255);\n var hcol = d3.rgb(hval, 0, 0);\n var dval = Math.floor(dabg.getAttribute(tissue) * 2.55);\n var dcol = d3.rgb(0, dval, 0);\n tooltiptext = tooltiptext + \"<TR><TD>\" + tissue + \"</TD><TD style=\\\"background:\" + hcol + \";color:white;\\\">\" + herit.getAttribute(tissue) + \"</TD><TD style=\\\"background:\" + dcol + \";color:white;\\\">\" + dabg.getAttribute(tissue) + \"%</TD></TR>\";\n }\n }\n }\n tooltiptext = tooltiptext + \"</table>\";\n return tooltiptext;\n };\n\n that.updateSettingsFromUI = function () {\n if ($(\"#\" + that.trackClass + \"Dense\" + that.level + \"Select\").length > 0) {\n that.density = $(\"#\" + that.trackClass + \"Dense\" + that.level + \"Select\").val();\n } else if (!that.density) {\n that.density = 1;\n }\n that.curColor = that.colorSelect;\n if ($(\"#\" + that.trackClass + that.level + \"colorSelect\").length > 0) {\n that.curColor = $(\"#\" + that.trackClass + that.level + \"colorSelect\").val();\n } else if (!that.curColor) {\n that.curColor = \"annot\";\n }\n var count = 0;\n if ($(\"#affyTissues\" + that.level + \" input[name=\\\"tissuecbx\\\"]\").length > 0) {\n that.tissues = [];\n var tis = $(\"#affyTissues\" + that.level + \" input[name=\\\"tissuecbx\\\"]:checked\");\n for (var t = 0; t < tis.length; t++) {\n var tissue = new String(tis[t].id);\n tissue = tissue.substr(0, tissue.indexOf(\"Affy\"));\n that.tissues[count] = tissue;\n count++;\n }\n }\n };\n\n that.savePrevious = function () {\n that.prevSetting = {};\n that.prevSetting.density = that.density;\n that.prevSetting.curColor = that.curColor;\n that.prevSetting.tissues = that.tissues;\n };\n\n that.revertPrevious = function () {\n that.density = that.prevSetting.density;\n that.curColor = that.prevSetting.curColor;\n that.tissues = that.prevSetting.tissues;\n };\n\n //Pack method does perform additional packing above the default method in track.\n //May be slightly slower but avoids the waterfall like non optimal packing that occurs with the sorted features.\n that.calcY = function (start, end, i, idLen) {\n var tmpY = 0;\n var idPix = idLen * 8 + 5;\n if (that.density === 3 || that.density === '3') {\n if ((start >= that.xScale.domain()[0] && start <= that.xScale.domain()[1]) ||\n (end >= that.xScale.domain()[0] && end <= that.xScale.domain()[1]) ||\n (start <= that.xScale.domain()[0] && end >= that.xScale.domain()[1])) {\n var pStart = Math.round(that.xScale(start));\n if (pStart < 0) {\n pStart = 0;\n }\n var pEnd = Math.round(that.xScale(end));\n if (pEnd >= that.gsvg.width) {\n pEnd = that.gsvg.width - 1;\n }\n var pixStart = pStart - that.xPadding;\n if (pixStart < 0) {\n pixStart = 0;\n }\n var pixEnd = pEnd + that.xPadding;\n if (pixEnd >= that.gsvg.width) {\n pixEnd = that.gsvg.width - 1;\n }\n\n //add space for ID\n if ((pixEnd + idPix) < that.gsvg.width) {\n pixEnd = pixEnd + idPix;\n pEnd = pEnd + idPix;\n } else if ((pixStart - idPix) > 0) {\n pixStart = pixStart - idPix;\n pStart = pStart - idPix;\n }\n\n //find yMax that is clear this is highest line that is clear\n var yMax = 0;\n for (var pix = pixStart; pix <= pixEnd; pix++) {\n if (that.yMaxArr[pix] > yMax) {\n yMax = that.yMaxArr[pix];\n }\n }\n yMax++;\n //may need to extend yArr for a new line\n var addLine = yMax;\n if (that.yArr.length <= yMax) {\n that.yArr[addLine] = new Array();\n for (var j = 0; j < that.gsvg.width; j++) {\n that.yArr[addLine][j] = 0;\n }\n }\n //check a couple lines back to see if it can be squeezed in\n var startLine = yMax - that.scanBackYLines;\n if (startLine < 1) {\n startLine = 1;\n }\n var prevLine = -1;\n var stop = 0;\n for (var scanLine = startLine; scanLine < yMax && stop == 0; scanLine++) {\n var available = 0;\n for (var pix = pixStart; pix <= pixEnd && available == 0; pix++) {\n if (that.yArr[scanLine][pix] > available) {\n available = 1;\n }\n }\n if (available == 0) {\n yMax = scanLine;\n stop = 1;\n }\n }\n if (yMax > that.trackYMax) {\n that.trackYMax = yMax;\n }\n for (var pix = pStart; pix <= pEnd; pix++) {\n if (that.yMaxArr[pix] < yMax) {\n that.yMaxArr[pix] = yMax;\n }\n that.yArr[yMax][pix] = 1;\n }\n tmpY = yMax * 15;\n } else {\n tmpY = 15;\n }\n } else if (that.density === 2 || that.density === '2') {\n tmpY = (i + 1) * 15;\n } else {\n tmpY = 15;\n }\n if (that.trackYMax < (tmpY / 15)) {\n that.trackYMax = (tmpY / 15);\n }\n return tmpY;\n };\n\n that.redraw = function () {\n var tissueLen = that.tissues.length;\n if (that.curColor != that.colorSelect || ((that.colorSelect === \"herit\" || that.colorSelect === \"dabg\") && tissueLen != that.tissueLen)) {\n that.tissueLen = tissueLen;\n that.draw(that.data);\n } else {\n that.trackYMax = 0;\n that.yMaxArr = new Array();\n that.yArr = new Array();\n that.yArr[0] = new Array();\n for (var j = 0; j < that.gsvg.width; j++) {\n that.yMaxArr[j] = 0;\n that.yArr[0][j] = 0;\n }\n that.colorSelect = that.curColor;\n that.tissueLen = tissueLen;\n if (that.colorSelect == \"dabg\" || that.colorSelect == \"herit\") {\n if (that.colorSelect == \"dabg\") {\n that.drawScaleLegend(\"0%\", \"100%\", \"of Samples DABG\", \"#000000\", \"#00FF00\", 0);\n } else if (that.colorSelect == \"herit\") {\n that.drawScaleLegend(\"0\", \"1.0\", \"Probeset Heritability\", \"#000000\", \"#FF0000\", 0);\n }\n var totalYMax = 1;\n for (var t = 0; t < that.tissues.length; t++) {\n var tissue = new String(that.tissues[t]);\n //tissue=tissue.substr(0,tissue.indexOf(\"Affy\"));\n that.trackYMax = 0;\n that.yMaxArr = new Array();\n that.yArr = new Array();\n that.yArr[0] = new Array();\n for (var j = 0; j < that.gsvg.width; j++) {\n that.yMaxArr[j] = 0;\n that.yArr[0][j] = 0;\n }\n totalYMax++;\n that.svg.select(\"text.\" + tissue).attr(\"y\", totalYMax * 15);\n that.svg.selectAll(\"g.probe.\" + tissue)\n .attr(\"transform\", function (d, i) {\n var st = that.gsvg.xScale(d.getAttribute(\"start\"));\n var y = that.calcY(parseInt(d.getAttribute(\"start\"), 10), parseInt(d.getAttribute(\"stop\"), 10), i, d.getAttribute(\"ID\").length) + totalYMax * 15 - 10;\n return \"translate(\" + st + \",\" + y + \")\";\n })\n .each(function (d) {\n var tmpD = d;\n var d3This = d3.select(this);\n var wX = 1;\n if (that.gsvg.xScale(tmpD.getAttribute(\"stop\")) - that.gsvg.xScale(tmpD.getAttribute(\"start\")) > 1) {\n wX = that.gsvg.xScale(tmpD.getAttribute(\"stop\")) - that.gsvg.xScale(tmpD.getAttribute(\"start\"));\n }\n //Set probe rect width,etc\n d3This.selectAll(\"rect\")\n .attr(\"width\", wX)\n .attr(\"fill\", that.color(tmpD, tissue));\n //change text to indicate strandedness\n var strChar = \">\";\n if (d.getAttribute(\"strand\") == \"-1\") {\n strChar = \"<\";\n }\n var fullChar = \"\";\n var rectW = wX;\n if (rectW >= 7.5 && rectW <= 15) {\n fullChar = strChar;\n } else if (rectW > 15) {\n rectW = rectW - 7.5;\n while (rectW > 7.5) {\n fullChar = fullChar + strChar;\n rectW = rectW - 7.5;\n }\n }\n d3This.select(\"text#strand\").text(fullChar);\n //update position and add labels if needed\n if (that.density == 2 || that.density == 3) {\n var curLbl = d.getAttribute(\"ID\");\n if (d3This.select(\"text#lblTxt\").size() === 0) {\n d3This.append(\"svg:text\").attr(\"dx\", function () {\n var xpos = that.xScale(d.getAttribute(\"stop\")) + curLbl.length * 8 + 5;\n var finalXpos = that.xScale(d.getAttribute(\"stop\")) - that.xScale(d.getAttribute(\"start\")) + 5;\n if (xpos > that.gsvg.width) {\n finalXpos = -1 * curLbl.length * 8;\n }\n return finalXpos;\n })\n .attr(\"dy\", 10)\n .attr(\"id\", \"lblTxt\")\n //.attr(\"fill\",that.colorAnnotation(d))\n .text(curLbl);\n } else {\n\n d3This.select(\"text#lblTxt\").attr(\"dx\", function () {\n var xpos = that.xScale(d.getAttribute(\"stop\")) + curLbl.length * 8 + 5;\n var finalXpos = that.xScale(d.getAttribute(\"stop\")) - that.xScale(d.getAttribute(\"start\")) + 5;\n if (xpos > that.gsvg.width) {\n finalXpos = -1 * curLbl.length * 8;\n }\n return finalXpos;\n });\n }\n } else {\n d3This.selectAll(\"text#lblTxt\").remove();\n }\n });\n totalYMax = totalYMax + that.trackYMax;\n }\n that.trackYMax = totalYMax * 15;\n that.svg.attr(\"height\", that.trackYMax);\n } else if (that.colorSelect === \"annot\") {\n var legend = [{color: \"#FF0000\", label: \"Core\"}, {color: \"#0000FF\", label: \"Extended\"}, {color: \"#006400\", label: \"Full\"}, {\n color: \"#000000\",\n label: \"Ambiguous\"\n }];\n that.drawLegend(legend);\n that.trackYMax = 0;\n that.yMaxArr = new Array();\n that.yArr = new Array();\n that.yArr[0] = new Array();\n for (var j = 0; j < that.gsvg.width; j++) {\n that.yMaxArr[j] = 0;\n that.yArr[0][j] = 0;\n }\n\n that.svg.selectAll(\"g.probe\")\n .attr(\"transform\", function (d, i) {\n var st = that.xScale(d.getAttribute(\"start\"));\n return \"translate(\" + st + \",\" + that.calcY(parseInt(d.getAttribute(\"start\"), 10), parseInt(d.getAttribute(\"stop\"), 10), i, d.getAttribute(\"ID\").length) + \")\";\n //return \"translate(\"+st+\",\"+that.calcY(d.getAttribute(\"start\"),d.getAttribute(\"stop\"),that.density,i,2)+\")\";\n });\n that.svg.selectAll(\"g.probe rect\")\n .attr(\"width\", function (d) {\n var wX = 1;\n if (that.xScale(d.getAttribute(\"stop\")) - that.xScale(d.getAttribute(\"start\")) > 1) {\n wX = that.xScale(d.getAttribute(\"stop\")) - that.xScale(d.getAttribute(\"start\"));\n }\n return wX;\n })\n .attr(\"fill\", function (d) {\n return that.color(d, \"\");\n });\n that.svg.selectAll(\"g.probe\").each(function (d) {\n var d3This = d3.select(this);\n var strChar = \">\";\n if (d.getAttribute(\"strand\") == \"-1\") {\n strChar = \"<\";\n }\n var fullChar = \"\";\n var rectW = d3This.select(\"rect\").attr(\"width\");\n if (rectW >= 7.5 && rectW <= 15) {\n fullChar = strChar;\n } else if (rectW > 15) {\n rectW = rectW - 7.5;\n while (rectW > 7.5) {\n fullChar = fullChar + strChar;\n rectW = rectW - 7.5;\n }\n }\n d3This.select(\"text\").text(fullChar);\n if (that.density == 2 || that.density == 3) {\n var curLbl = d.getAttribute(\"ID\");\n if (d3This.select(\"text#lblTxt\").size() === 0) {\n d3This.append(\"svg:text\").attr(\"dx\", function () {\n var xpos = that.xScale(d.getAttribute(\"stop\")) + curLbl.length * 8 + 5;\n var finalXpos = that.xScale(d.getAttribute(\"stop\")) - that.xScale(d.getAttribute(\"start\")) + 5;\n if (xpos > that.gsvg.width) {\n finalXpos = -1 * curLbl.length * 8;\n }\n return finalXpos;\n })\n .attr(\"dy\", 10)\n .attr(\"id\", \"lblTxt\")\n //.attr(\"fill\",that.colorAnnotation(d))\n .text(curLbl);\n } else {\n d3This.select(\"text#lblTxt\").attr(\"dx\", function () {\n var xpos = that.xScale(d.getAttribute(\"stop\")) + curLbl.length * 8 + 5;\n var finalXpos = that.xScale(d.getAttribute(\"stop\")) - that.xScale(d.getAttribute(\"start\")) + 5;\n if (xpos > that.gsvg.width) {\n finalXpos = -1 * curLbl.length * 8;\n }\n return finalXpos;\n });\n }\n } else {\n d3This.selectAll(\"text#lblTxt\").remove();\n }\n });\n if (that.density == 1) {\n that.svg.attr(\"height\", 30);\n } else if (that.density == 2) {\n that.svg.attr(\"height\", (that.trackYMax + 1) * 15);\n } else if (that.density == 3) {\n that.svg.attr(\"height\", (that.trackYMax + 1) * 15);\n }\n }\n }\n that.redrawSelectedArea();\n };\n\n that.update = function (d) {\n that.redraw();\n };\n\n that.updateData = function (retry) {\n var tag = \"probe\";\n var path = dataPrefix + \"tmpData/browserCache/\" + genomeVer + \"/regionData/\" + that.gsvg.folderName + \"/probe.xml\";\n d3.xml(path, function (error, d) {\n if (error) {\n if (retry < 3) {//wait before trying again\n var time = 5000;\n if (retry == 1) {\n time = 10000;\n }\n setTimeout(function () {\n that.updateData(retry + 1);\n }, time);\n } else if (retry >= 3) {\n d3.select(\"#Level\" + that.levelNumber + that.trackClass).select(\"#trkLbl\").text(\"An errror occurred loading Track:\" + that.trackClass);\n d3.select(\"#Level\" + that.levelNumber + that.trackClass).attr(\"height\", 15);\n that.gsvg.addTrackErrorRemove(that.svg, \"#Level\" + that.gsvg.levelNumber + that.trackClass);\n }\n } else if (d) {\n var probe = d.documentElement.getElementsByTagName(tag);\n var mergeddata = new Array();\n var checkName = new Array();\n var curInd = 0;\n for (var l = 0; l < that.data.length; l++) {\n if (typeof that.data[l] !== 'undefined') {\n mergeddata[curInd] = that.data[l];\n checkName[that.data[l].getAttribute(\"ID\")] = 1;\n curInd++;\n }\n }\n for (var l = 0; l < probe.length; l++) {\n if (typeof probe[l] !== 'undefined' && typeof checkName[probe[l].getAttribute(\"ID\")] === 'undefined') {\n mergeddata[curInd] = probe[l];\n curInd++;\n }\n }\n\n that.draw(mergeddata);\n that.hideLoading();\n } else {\n //shouldn't need this\n //that.draw(that.data);\n that.hideLoading();\n }\n });\n };\n\n that.draw = function (data) {\n that.data = data;\n\n that.colorSelect = that.curColor;\n that.trackYMax = 0;\n that.yMaxArr = new Array();\n that.yArr = new Array();\n that.yArr[0] = new Array();\n for (var j = 0; j < that.gsvg.width; j++) {\n that.yMaxArr[j] = 0;\n that.yArr[0][j] = 0;\n }\n if (that.colorSelect == \"dabg\" || that.colorSelect == \"herit\") {\n if (that.colorSelect == \"dabg\") {\n that.drawScaleLegend(\"0%\", \"100%\", \"of Samples DABG\", \"#000000\", \"#00FF00\", 0);\n } else if (that.colorSelect == \"herit\") {\n that.drawScaleLegend(\"0\", \"1.0\", \"Probeset Heritability\", \"#000000\", \"#FF0000\", 0);\n }\n that.svg.selectAll(\".probe\").remove();\n that.svg.selectAll(\".tissueLbl\").remove();\n that.tissueLen = that.tissues.length;\n var totalYMax = 1;\n for (var t = 0; t < that.tissues.length; t++) {\n var tissue = new String(that.tissues[t]);\n if (tissue.indexOf(\";\") > 0) {\n tissue = tissue.substr(0, tissue.indexOf(\";\"));\n }\n if (tissue.indexOf(\":\") > 0) {\n tissue = tissue.substr(0, tissue.indexOf(\":\"));\n }\n //tissue=tissue.substr(0,tissue.indexOf(\"Affy\"));\n that.trackYMax = 0;\n that.yMaxArr = new Array();\n that.yArr = new Array();\n that.yArr[0] = new Array();\n for (var j = 0; j < that.gsvg.width; j++) {\n that.yMaxArr[j] = 0;\n that.yArr[0][j] = 0;\n }\n var dispTissue = tissue;\n if (dispTissue == \"BrownAdipose\") {\n dispTissue = \"Brown Adipose\";\n } else if (dispTissue == \"Brain\") {\n dispTissue = \"Whole Brain\";\n }\n var tisLbl = new String(\"Tissue: \" + dispTissue);\n totalYMax++;\n that.svg.append(\"text\").attr(\"class\", \"tissueLbl \" + tissue).attr(\"x\", that.gsvg.width / 2 - (tisLbl.length / 2) * 7.5).attr(\"y\", totalYMax * 15).text(tisLbl);\n\n //console.log(\";.probe.\"+tissue+\";\");\n //update\n if (data.length > 0) {\n var probes = that.svg.selectAll(\".probe.\" + tissue)\n .data(data, function (d) {\n return keyTissue(d, tissue);\n })\n .attr(\"transform\", function (d, i) {\n return \"translate(\" + that.xScale(d.getAttribute(\"start\")) + \",\" + (that.calcY(parseInt(d.getAttribute(\"start\"), 10), parseInt(d.getAttribute(\"stop\"), 10), i, d.getAttribute(\"ID\").length) + totalYMax * 15 - 10) + \")\";\n });\n //add new\n probes.enter().append(\"g\")\n .attr(\"class\", \"probe \" + tissue)\n .attr(\"transform\", function (d, i) {\n return \"translate(\" + that.xScale(d.getAttribute(\"start\")) + \",\" + (that.calcY(parseInt(d.getAttribute(\"start\"), 10), parseInt(d.getAttribute(\"stop\"), 10), i, d.getAttribute(\"ID\").length) + totalYMax * 15 - 10) + \")\";\n })\n .append(\"rect\")\n //.attr(\"class\",tissue)\n .attr(\"height\", 10)\n .attr(\"rx\", 1)\n .attr(\"ry\", 1)\n .attr(\"width\", function (d) {\n var wX = 1;\n if (that.xScale(d.getAttribute(\"stop\")) - that.xScale(d.getAttribute(\"start\")) > 1) {\n wX = that.xScale(d.getAttribute(\"stop\")) - that.xScale(d.getAttribute(\"start\"));\n }\n return wX;\n })\n .attr(\"id\", function (d) {\n return d.getAttribute(\"ID\") + tissue;\n })\n .style(\"fill\", function (d) {\n return that.color(d, tissue);\n })\n .style(\"cursor\", \"pointer\")\n .on(\"dblclick\", that.zoomToFeature)\n .on(\"mouseover\", function (d) {\n if (that.gsvg.isToolTip == 0) {\n overSelectable = 1;\n $(\"#mouseHelp\").html(\"<B>Double Click</B> to zoom in on this feature.\");\n var thisD3 = d3.select(this);\n that.curTTColor = thisD3.style(\"fill\");\n if (thisD3.style(\"opacity\") > 0) {\n thisD3.style(\"fill\", \"green\");\n tt.transition()\n .duration(200)\n .style(\"opacity\", 1);\n tt.html(that.createToolTip(d))\n .style(\"left\", function () {\n return that.positionTTLeft(d3.event.pageX);\n })\n .style(\"top\", function () {\n return that.positionTTTop(d3.event.pageY);\n });\n //Setup Tooltip SVG\n that.setupToolTipSVG(d, 0.2);\n }\n }\n })\n .on(\"mouseout\", function (d) {\n overSelectable = 0;\n $(\"#mouseHelp\").html(\"Navigation Hints: Hold mouse over areas of the image for available actions.\");\n var thisD3 = d3.select(this);\n if (thisD3.style(\"opacity\") > 0) {\n thisD3.style(\"fill\", that.curTTColor);\n tt.transition()\n .delay(500)\n .duration(200)\n .style(\"opacity\", 0);\n }\n });\n that.svg.selectAll(\"g.probe.\" + tissue).each(function (d) {\n var d3This = d3.select(this);\n var strChar = \">\";\n if (d.getAttribute(\"strand\") == \"-1\") {\n strChar = \"<\";\n }\n var fullChar = strChar;\n var rectW = d3This.select(\"rect\").attr(\"width\");\n if (rectW < 7.5) {\n fullChar = \"\";\n } else {\n rectW = rectW - 7.5;\n while (rectW > 8.5) {\n fullChar = fullChar + strChar;\n rectW = rectW - 7.5;\n }\n }\n d3This.append(\"svg:text\").attr(\"dx\", \"1\").attr(\"id\", \"strand\").attr(\"dy\", \"10\").style(\"pointer-events\", \"none\").style(\"fill\", \"white\").text(fullChar);\n if (that.density == 2 || that.density == 3) {\n var curLbl = d.getAttribute(\"ID\");\n d3This.append(\"svg:text\").attr(\"dx\", function () {\n var xpos = that.xScale(d.getAttribute(\"stop\")) + curLbl.length * 8 + 5;\n var finalXpos = that.xScale(d.getAttribute(\"stop\")) - that.xScale(d.getAttribute(\"start\")) + 5;\n if (xpos > that.gsvg.width) {\n finalXpos = -1 * curLbl.length * 8;\n }\n return finalXpos;\n })\n .attr(\"dy\", 10)\n .attr(\"id\", \"lblTxt\")\n //.attr(\"fill\",that.colorAnnotation(d))\n .text(curLbl);\n\n } else {\n d3This.selectAll(\"text#lblTxt\").remove();\n }\n });\n totalYMax = totalYMax + that.trackYMax + 1;\n }\n }\n //probes.exit().remove();\n that.trackYMax = totalYMax;\n that.svg.attr(\"height\", totalYMax * 15 + 45);\n } else if (that.colorSelect == \"annot\") {\n var legend = [{color: \"#FF0000\", label: \"Core\"}, {color: \"#0000FF\", label: \"Extended\"}, {color: \"#006400\", label: \"Full\"}, {\n color: \"#000000\",\n label: \"Ambiguous\"\n }];\n that.drawLegend(legend);\n that.trackYMax = 0;\n that.yMaxArr = new Array();\n that.yArr = new Array();\n that.yArr[0] = new Array();\n for (var j = 0; j < that.gsvg.width; j++) {\n that.yMaxArr[j] = 0;\n that.yArr[0][j] = 0;\n }\n that.svg.selectAll(\".probe\").remove();\n that.svg.selectAll(\".tissueLbl\").remove();\n //update\n var probes = that.svg.selectAll(\".probe.annot\")\n .data(data, key)\n //.attr(\"transform\",function(d,i){ return \"translate(\"+that.xScale(d.getAttribute(\"start\"))+\",\"+that.calcY(d.getAttribute(\"start\"),d.getAttribute(\"stop\"),that.density,i,2)+\")\";})\n .attr(\"transform\", function (d, i) {\n return \"translate(\" + that.xScale(d.getAttribute(\"start\")) + \",\" + that.calcY(parseInt(d.getAttribute(\"start\"), 10), parseInt(d.getAttribute(\"stop\"), 10), i, d.getAttribute(\"ID\").length) + \")\";\n });\n\n //add new\n probes.enter().append(\"g\")\n .attr(\"class\", \"probe annot\")\n //.attr(\"transform\",function(d,i){ return \"translate(\"+that.xScale(d.getAttribute(\"start\"))+\",\"+that.calcY(d.getAttribute(\"start\"),d.getAttribute(\"stop\"),that.density,i,2)+\")\";})\n .attr(\"transform\", function (d, i) {\n return \"translate(\" + that.xScale(d.getAttribute(\"start\")) + \",\" + that.calcY(parseInt(d.getAttribute(\"start\"), 10), parseInt(d.getAttribute(\"stop\"), 10), i, d.getAttribute(\"ID\").length) + \")\";\n })\n .append(\"rect\")\n .attr(\"height\", 10)\n .attr(\"rx\", 1)\n .attr(\"ry\", 1)\n .attr(\"width\", function (d) {\n var wX = 1;\n if (that.xScale(d.getAttribute(\"stop\")) - that.xScale(d.getAttribute(\"start\")) > 1) {\n wX = that.xScale(d.getAttribute(\"stop\")) - that.xScale(d.getAttribute(\"start\"));\n }\n return wX;\n })\n .attr(\"id\", function (d) {\n return d.getAttribute(\"ID\");\n })\n .style(\"fill\", function (d) {\n return that.color(d, \"\");\n })\n .style(\"cursor\", \"pointer\")\n .on(\"dblclick\", that.zoomToFeature)\n .on(\"mouseover\", function (d) {\n if (that.gsvg.isToolTip == 0) {\n overSelectable = 1;\n $(\"#mouseHelp\").html(\"<B>Double Click</B> to zoom in on this feature.\");\n var thisD3 = d3.select(this);\n if (thisD3.style(\"opacity\") > 0) {\n thisD3.style(\"fill\", \"green\");\n tt.transition()\n .duration(200)\n .style(\"opacity\", 1);\n tt.html(that.createToolTip(d))\n .style(\"left\", function () {\n return that.positionTTLeft(d3.event.pageX);\n })\n .style(\"top\", function () {\n return that.positionTTTop(d3.event.pageY);\n });\n //Setup Tooltip SVG\n that.setupToolTipSVG(d, 0.2);\n }\n }\n })\n .on(\"mouseout\", function (d) {\n overSelectable = 0;\n $(\"#mouseHelp\").html(\"Navigation Hints: Hold mouse over areas of the image for available actions.\");\n var thisD3 = d3.select(this);\n if (thisD3.style(\"opacity\") > 0) {\n thisD3.style(\"fill\", that.color);\n tt.transition()\n .delay(500)\n .duration(200)\n .style(\"opacity\", 0);\n }\n });\n that.svg.selectAll(\"g.probe\").each(function (d) {\n var d3This = d3.select(this);\n var strChar = \">\";\n if (d.getAttribute(\"strand\") == \"-1\") {\n strChar = \"<\";\n }\n var fullChar = strChar;\n var rectW = d3This.select(\"rect\").attr(\"width\");\n if (rectW < 7.5) {\n fullChar = \"\";\n } else {\n rectW = rectW - 7.5;\n while (rectW > 15) {\n fullChar = fullChar + strChar;\n rectW = rectW - 7.5;\n }\n }\n d3This.append(\"svg:text\").attr(\"dx\", \"1\").attr(\"dy\", \"10\").style(\"pointer-events\", \"none\").style(\"fill\", \"white\").text(fullChar);\n\n if (that.density == 2 || that.density == 3) {\n var curLbl = d.getAttribute(\"ID\");\n d3This.append(\"svg:text\").attr(\"dx\", function () {\n /*var xpos=that.xScale(d.getAttribute(\"start\"));\n\t\t\t\t\t\t\t\tif(xpos<($(window).width()/2)){\n\t\t\t\t\t\t\t\t\txpos=that.xScale(d.getAttribute(\"stop\"))-that.xScale(d.getAttribute(\"start\"))+5;\n\t\t\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t\t\txpos=-1*curLbl.length*9;;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn xpos;*/\n var xpos = that.xScale(d.getAttribute(\"stop\")) + curLbl.length * 8 + 5;\n var finalXpos = that.xScale(d.getAttribute(\"stop\")) - that.xScale(d.getAttribute(\"start\")) + 5;\n if (xpos > that.gsvg.width) {\n finalXpos = -1 * curLbl.length * 8;\n }\n return finalXpos;\n })\n .attr(\"dy\", 10)\n .attr(\"id\", \"lblTxt\")\n //.attr(\"fill\",that.colorAnnotation(d))\n .text(curLbl);\n\n } else {\n d3This.select(\"text#lblTxt\").remove();\n }\n });\n\n\n //probes.exit().remove();\n if (that.density == 1) {\n that.svg.attr(\"height\", 30);\n } else if (that.density == 2) {\n //that.svg.attr(\"height\", (d3.select(\"#Level\"+that.gsvg.levelNumber+that.trackClass).selectAll(\"g.probe\").length+1)*15);\n that.svg.attr(\"height\", (that.trackYMax + 1) * 15);\n } else if (that.density == 3) {\n that.svg.attr(\"height\", (that.trackYMax + 1) * 15);\n }\n }\n that.redrawSelectedArea();\n };\n\n that.getDisplayedData = function () {\n var dataElem = d3.select(\"#Level\" + that.gsvg.levelNumber + that.trackClass).selectAll(\"g.probe\");\n that.counts = [{value: 0, names: \"Core\"}, {value: 0, names: \"Extended\"}, {value: 0, names: \"Full\"}, {value: 0, names: \"Ambiguous\"}];\n var tmpDat = dataElem[0];\n var dispData = new Array();\n var dispDataCount = 0;\n dataElem.each(function (d) {\n var start = that.xScale(d.getAttribute(\"start\"));\n var stop = that.xScale(d.getAttribute(\"stop\"));\n if ((0 <= start && start <= that.gsvg.width) || (0 <= stop && stop <= that.gsvg.width)) {\n if (d.getAttribute(\"type\") == \"core\") {\n that.counts[0].value++;\n } else if (d.getAttribute(\"type\") == \"extended\") {\n that.counts[1].value++;\n } else if (d.getAttribute(\"type\") == \"full\") {\n that.counts[2].value++;\n } else if (d.getAttribute(\"type\") == \"ambiguous\") {\n that.counts[3].value++;\n }\n dispData[dispDataCount] = d;\n dispDataCount++;\n }\n });\n if (dataElem.size() === 0) {\n that.counts = [];\n }\n return dispData;\n };\n\n that.generateSettingsDiv = function (topLevelSelector) {\n var d = trackInfo[that.trackClass];\n that.savePrevious();\n //console.log(trackInfo);\n //console.log(d);\n d3.select(topLevelSelector).select(\"table\").select(\"tbody\").html(\"\");\n if (typeof d !== 'undefined' && typeof d.Controls !== 'undefined' && d.Controls != \"null\" && d.Controls.length > 0) {\n var controls = new String(d.Controls).split(\",\");\n var table = d3.select(topLevelSelector).select(\"table\").select(\"tbody\");\n table.append(\"tr\").append(\"td\").style(\"font-weight\", \"bold\").html(\"Track Settings: \" + d.Name);\n for (var c = 0; c < controls.length; c++) {\n if (typeof controls[c] !== 'undefined' && controls[c] != \"\") {\n var params = controls[c].split(\";\");\n\n var div = table.append(\"tr\").append(\"td\");\n var lbl = params[0].substr(5);\n\n var def = \"\";\n if (params.length > 3 && params[3].indexOf(\"Default=\") == 0) {\n def = params[3].substr(8);\n }\n if (params[1].toLowerCase().indexOf(\"select\") == 0) {\n div.append(\"text\").text(lbl + \": \");\n var selClass = params[1].split(\":\");\n var opts = params[2].split(\"}\");\n var id = that.trackClass + \"Dense\" + that.level + \"Select\";\n if (selClass[1] == \"colorSelect\") {\n id = that.trackClass + that.level + \"colorSelect\";\n }\n var sel = div.append(\"select\").attr(\"id\", id)\n .attr(\"name\", selClass[1]);\n for (var o = 0; o < opts.length; o++) {\n var option = opts[o].substr(1).split(\":\");\n if (option.length == 2) {\n var tmpOpt = sel.append(\"option\").attr(\"value\", option[1]).text(option[0]);\n if (selClass[1] == \"colorSelect\" && option[1] == that.curColor) {\n tmpOpt.attr(\"selected\", \"selected\");\n } else if (option[1] == that.density) {\n tmpOpt.attr(\"selected\", \"selected\");\n }\n }\n }\n d3.select(\"select#\" + id).on(\"change\", function () {\n if ($(this).val() == \"dabg\" || $(this).val() == \"herit\") {\n $(\"div#affyTissues\" + that.level).show();\n } else {\n $(\"div#affyTissues\" + that.level).hide();\n }\n that.updateSettingsFromUI();\n that.redraw();\n });\n } else if (params[1].toLowerCase().indexOf(\"cbx\") == 0) {\n div = div.append(\"div\").attr(\"id\", \"affyTissues\" + that.level).style(\"display\", \"none\");\n div.append(\"text\").text(lbl + \": \");\n var selClass = params[1].split(\":\");\n var opts = params[2].split(\"}\");\n\n for (var o = 0; o < opts.length; o++) {\n var option = opts[o].substr(1).split(\":\");\n if (option.length == 2) {\n var span = div.append(\"div\").style(\"display\", \"inline-block\");\n var sel = span.append(\"input\").attr(\"type\", \"checkbox\").attr(\"id\", option[1] + \"CBX\" + that.level)\n .attr(\"name\", selClass[1])\n .style(\"margin-left\", \"5px\");\n span.append(\"text\").text(option[0]);\n //console.log(def+\"::\"+option[1]);\n\n d3.select(\"input#\" + option[1] + \"CBX\" + that.level).on(\"change\", function () {\n that.updateSettingsFromUI();\n that.redraw();\n });\n }\n }\n }\n }\n }\n if (that.curColor == \"dabg\" || that.curColor == \"herit\") {\n $(\"div#affyTissues\" + that.level).show();\n } else {\n $(\"div#affyTissues\" + that.level).hide();\n }\n for (var p = 0; p < that.tissues.length; p++) {\n //console.log(\"#\"+that.tissues[p]+\"AffyCBX\"+that.level);\n $(\"#\" + that.tissues[p] + \"AffyCBX\" + that.level).prop('checked', true);\n }\n var buttonDiv = table.append(\"tr\").append(\"td\");\n buttonDiv.append(\"input\").attr(\"type\", \"button\").attr(\"value\", \"Remove Track\").style(\"float\", \"left\").style(\"margin-left\", \"5px\").on(\"click\", function () {\n $('#trackSettingDialog').fadeOut(\"fast\");\n that.gsvg.removeTrack(that.trackClass);\n var viewID = svgList[that.gsvg.levelNumber].currentView.ViewID;\n var track = viewMenu[that.gsvg.levelNumber].findTrackByClass(that.trackClass, viewID);\n var indx = viewMenu[that.gsvg.levelNumber].findTrackIndexWithViewID(track.TrackID, viewID);\n viewMenu[that.gsvg.levelNumber].removeTrackWithIDIdx(indx, viewID);\n });\n buttonDiv.append(\"input\").attr(\"type\", \"button\").attr(\"value\", \"Apply\").style(\"float\", \"right\").style(\"margin-left\", \"5px\").on(\"click\", function () {\n $('#trackSettingDialog').fadeOut(\"fast\");\n if (that.density != that.prevSetting.density || that.curColor != that.prevSetting.curColor || that.tissues != that.prevSetting.tissues) {\n that.gsvg.setCurrentViewModified();\n }\n });\n buttonDiv.append(\"input\").attr(\"type\", \"button\").attr(\"value\", \"Cancel\").style(\"float\", \"right\").style(\"margin-left\", \"5px\").on(\"click\", function () {\n that.revertPrevious();\n that.draw(that.data);\n $('#trackSettingDialog').fadeOut(\"fast\");\n });\n } else {\n var table = d3.select(topLevelSelector).select(\"table\").select(\"tbody\");\n table.append(\"tr\").append(\"td\").style(\"font-weight\", \"bold\").html(\"Track Settings: \" + d.Name);\n table.append(\"tr\").append(\"td\").html(\"Sorry no settings for this track.\");\n var buttonDiv = table.append(\"tr\").append(\"td\");\n buttonDiv.append(\"input\").attr(\"type\", \"button\").attr(\"value\", \"Remove Track\").style(\"float\", \"left\").style(\"margin-left\", \"5px\").on(\"click\", function () {\n $('#trackSettingDialog').fadeOut(\"fast\");\n });\n buttonDiv.append(\"input\").attr(\"type\", \"button\").attr(\"value\", \"Cancel\").style(\"float\", \"right\").style(\"margin-left\", \"5px\").on(\"click\", function () {\n $('#trackSettingDialog').fadeOut(\"fast\");\n });\n }\n };\n\n that.generateTrackSettingString = function () {\n var tissueStr = \"\";\n for (var k = 0; k < that.tissues.length; k++) {\n if (k > 0) {\n tissueStr = tissueStr + \":\";\n }\n tissueStr = tissueStr + that.tissues[k];\n /*if(k<(that.tissues.length-1)){\n\t\t\t\ttissueStr=tissueStr+\":\";\n\t\t\t}*/\n }\n return that.trackClass + \",\" + that.density + \",\" + that.curColor + \",\" + tissueStr + \";\";\n };\n\n that.draw(data);\n return that;\n}", "getFrameCounter() {\r\n const frame = padNumber(this.currentFrame + 1, 3);\r\n const total = padNumber(this.frameCount, 3);\r\n return `${frame} / ${total}`;\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The first time the page is loaded. Get the entire transaction json > Call `LoadTransactions`.
async function OnLoadTransactions() { const write_key = JSON.parse(localStorage.getItem('microprediction_key_current'))[0]; const url = base_url+write_key+"/"; resp = await get(url); await LoadTransactions(); document.getElementById("box-href").href = "transactions/" + write_key + "/"; document.getElementById("box-info-loaded-from").style.display = "inline-block"; }
[ "function init() {\n history = [];\n allTransactionsLoaded = false;\n\n account = StellarNetwork.remote.account(session.get('address'));\n account.on('transaction', function(data) {\n var transaction = {\n tx: data.transaction,\n meta: data.meta\n };\n\n history.unshift(transaction);\n\n $rootScope.$broadcast('transaction-history:new', transaction);\n });\n }", "async loadBlockchainData() {\n let web3\n \n this.setState({loading: true})\n if(typeof window.ethereum !== 'undefined') {\n web3 = new Web3(window.ethereum)\n await this.setState({web3})\n await this.loadAccountData()\n } else {\n let infuraURL = `https://ropsten.infura.io/v3/${process.env.REACT_APP_INFURA_API_KEY}`\n web3 = new Web3(new Web3.providers.HttpProvider(infuraURL))\n await this.setState({web3})\n }\n await this.loadContractData()\n await this.updateHouses()\n this.setState({loading: false})\n }", "function fundsPrices() {\n loadTable();\n loadShowAll_btn();\n }", "function updateLocalStorage() {\n\tlocalStorage.setItem('transactions', JSON.stringify(transactions));\n}", "function load() {\n numOfPages();\n loadList();\n}", "function top_performing_page_init() {\n //console.log('top performing page loaded');\n var xmlhttp = new XMLHttpRequest();\n var url = $('#ad-get-top-performing-pages-input').val();\n xmlhttp.onreadystatechange = function () {\n if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {\n try {\n var myArr = JSON.parse(xmlhttp.responseText);\n top_performing_page_run(myArr)\n } catch (e) {\n }\n }\n };\n xmlhttp.open(\"GET\", url, true);\n xmlhttp.send();\n }", "function loadObjects() {\n $.getJSON('https://secure.toronto.ca/cc_sr_v1/data/swm_waste_wizard_APR?limit=1000', function (data) {\n allObjects = data;\n }).error(function () {\n console.log('error: json not loaded'); // debug\n }).done(function () {\n console.log(\"JSON loaded!\"); // debug\n initLocalStorage();\n $(document).ready(function () {\n document.getElementById(\"favourites\").innerHTML = insertFavourites();\n }); // render the fav list\n addEventListenersToFav();\n });\n\n}", "function noOfTransactions() {\n document.getElementById(\"transactions\").textContent = newBlock.transactions.length;\n }", "function pageLoad(){\n var pagestate;\n if(filterParams.filterName || filterParams.filter|| filterParams.filterAll ){\n nodeFilter.setPageParams(filterParams);\n nodeFilter.updateMatchedNodes();\n pagestate=nodeFilter.getPageParams();\n nodeSummary.reload();\n\n }else{\n nodeFilter.reset();\n nodeSummary.reload();\n jQuery('#tab_link_summary > a').tab('show');\n pagestate={start:true};\n }\n\n if(typeof(history.replaceState)=='function') {\n if (!history.state) {\n //set first page load state\n history.replaceState(pagestate, null, document.location);\n }\n }\n}", "function loadBuyerUX ()\n{ \n // get the html page to load\n let toLoad = 'buyer.html';\n // if (buyers.length === 0) then autoLoad() was not successfully run before this web app starts, so the sie of the buyer list is zero\n // assume user has run autoLoad and rebuild member list\n // if autoLoad not yet run, then member list length will still be zero\n if ((typeof(buyers) === 'undefined') || (buyers === null) || (buyers.length === 0))\n { $.when($.get(toLoad), deferredMemberLoad()).done(function (page, res)\n {setupBuyer(page);});\n }\n else{\n $.when($.get(toLoad)).done(function (page)\n {setupBuyer(page);});\n }\n}", "function getCoins() {\r\n console.log(\"checking if getCoins works\");\r\n $.get(\"/api/coins\", function(data){\r\n\r\n var rowsToAdd = [];\r\n var coinPriceArray = [];\r\n for (var i = 0; i <data.length; i++) {\r\n rowsToAdd.push(createCoinRow(data[i]));\r\n }\r\n renderCoinList(rowsToAdd);\r\n console.log(\"rows to add are \" + rowsToAdd);\r\n });\r\n \r\n }", "function loadSpendingEdit(id) {\n if (mydb) {\n //Get all the cars from the database with a select statement, set outputCarList as the callback function for the executeSql command\n mydb.transaction(function (t) {\n t.executeSql(\"SELECT * FROM spending WHERE id=?\", [id], function (transaction, results) {\n if (results.rows.length>=1) {\n loadSpendingEditPage(results.rows.item(0));\n }\n });\n // t.executeSql(\"SELECT * FROM name\", [], showNames);\n });\n } else {\n var data = {};\n data['id']=1;\n data['spending_date']='2015-12-12';\n data['name']='Sepatu';\n loadSpendingEditPage(data);\n }\n}", "function addPendingTransactions() {\n blockchain.pendingTransactions.forEach(transaction => {\n const pendingTransactionsTable = document.getElementById(\"newPendingTransactionTable\");\n\n if (!document.getElementById(\"transactionId\") || transaction.transactionId !== document.getElementById(\"transactionId\").innerHTML) {\n let row = pendingTransactionsTable.insertRow();\n let transactionId = row.insertCell(0);\n transactionId.innerHTML = transaction.transactionId;\n transactionId.id = \"transactionId\";\n let txTimestamp = row.insertCell(1);\n txTimestamp.innerHTML = (new Date(transaction.txTimestamp)).toLocaleTimeString();\n let sender = row.insertCell(2);\n sender.innerHTML = transaction.sender;\n let recipient = row.insertCell(3);\n recipient.innerHTML = transaction.recipient;\n let amount = row.insertCell(4);\n amount.innerHTML = transaction.amount;\n } else {\n return;\n };\n });\n }", "async _initWeb3(mnemonic) {\n this.setState({\n loading: true,\n });\n\n const facade = new ContractFacade();\n await facade.initialize(mnemonic);\n await this._checkBalance(facade);\n\n this.setState({\n contractFacade: facade,\n mode: Modes.MainScreen,\n loading: false,\n });\n }", "function loadActiveChain() {\n $.get('/chain/load/active', function (data) {\n //if (data.length > 0) {\n $('#current-chain').attr('data-chain', JSON.stringify(data));\n\n // Draw chain\n drawChain('#current-chain');\n //}\n });\n}", "function initializeSubmitTransactionEventListener() {\n $(classSelectors.transactionWrapper).on('click', classSelectors.submitTransactionButton, async function() {\n const type = simulationView.getTransactionType(this);\n const transactionAmount = simulationView.getTransactionAmount(this);\n const cryptocurrencyId = simulationView.getCryptocurrencyId(this);\n\n const results = await state.updateModel.saveTransaction(type, transactionAmount, cryptocurrencyId);\n // TODO - This code is copy pasted in some places, turn it into an object that can be used everywhere\n const portfolioData = {\n totalUSDAmount : results.updatedPortfolio.USDAmount,\n cryptoWorthInUSD : results.updatedPortfolio.cryptoWorthInUSD,\n cryptocurrencies : results.updatedPortfolio.cryptocurrencies,\n portfolioID : results.updatedPortfolio.id,\n portfolioWorth : results.updatedPortfolio.portfolioWorth,\n title : results.updatedPortfolio.title,\n portfolioHTML : results.content\n };\n simulationView.repopulateSellCryptoTable(portfolioData);\n simulationView.updatePortfolioInfo(portfolioData);\n });\n}", "function loadLocalData() {\r\n var xmlhttp=new XMLHttpRequest();\r\n xmlhttp.open(\"GET\",\"Buses.xml\",false);\r\n xmlhttp.send();\r\n xmlData=xmlhttp.responseXML;\r\n generateBusList(xmlData, \"SAMPLE\");\r\n loadRouteColors(); // Bus list must be loaded first\r\n displayRoutesFromTripId(tripRouteShapeRef); // Bus list must be loaded first to have the trip IDs\r\n showPOIs();\r\n getTrolleyData(scope);\r\n loadTrolleyRoutes();\r\n getTrolleyStops(scope);\r\n getCitiBikes();\r\n addDoralTrolleys();\r\n addDoralTrolleyRoutes();\r\n addMetroRail();\r\n addMetroRailRoutes();\r\n addMetroRailStations();\r\n addMiamiBeachTrolleys();\r\n addMiamiBeachTrolleyRoutes();\r\n // Refresh Miami Transit API data every 5 seconds\r\n setInterval(function() {\r\n callMiamiTransitAPI();\r\n }, refreshTime);\r\n if (!test) {\r\n alert(\"Real-time data is unavailable. Check the Miami Transit website. Using sample data.\");\r\n }\r\n}", "function loadObjectsAfterWaitingForScripts(){\n\t\tlet waitingTime = 1000;\n\t\tsetTimeout(function () {\n\t\t\tloadDataObjects();\n\t\t\tactionNamespace.actionDrawStartPage();\t\n\t\t}, waitingTime);\n\t}", "function XML_(){\n let url = `https://${domain}/API/Account/${rad_id}/${APIendpoint}.json?offset=${pagenr}`;\n if (relation.length > 0) {\n url += `&load_relations=[${relation}]`;\n }\n if (query.length > 0) {\n url += query;\n }\n console.log(url);\n let uri = encodeURI(url);\n let e = new XMLHttpRequest();\n e.open(\"GET\", uri, document.getElementById('fasthands').checked),\n e.onload = function(){\n if ( e.status >= 200 && e.status < 400 ){\n t = JSON.parse(e.responseText);\n if (report === 'OrderNumbers') {\n unparse_();\n } else {\n parse_Data_();\n }\n }\n },\n e.send();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
3. Summarize the nestedData at each level. This will facilitate easy reference to max and min values, for instance, at all levels of aggregation so that graphs can more easily be put on different scales. Should also facilitate normalizing values if needed and other manipulations.
function summarizeChildren(datum) { function _summarize(datum) { var descendantValues = datum.values.reduce((acc, cur) => { cur.parent = datum; return acc.concat(cur.values ? _summarize(cur) : cur.value); }, []); var pValues = returnPValues(datum); function returnPValues(datum) { // var _datumValues = datum.values.slice(); // there's a problem here: dividing by zero when the first value is zero, or all are zero // take a slice() copy of datum.values to avoid mutating datum and shift of the first value // so long as it's value === 0. in effect, measure pValue against the first nonzero value // in the series while ( datum.values.length > 0 && datum.values[0].value === 0 ){ datum.values.shift(); } return datum.values.reduce((acc, cur) => { var min = d3.min([acc[0], cur.values ? returnPValues(cur)[0] : (cur.value - datum.values[0].value) / datum.values[0].value]); var max = d3.max([acc[1], cur.values ? returnPValues(cur)[1] : (cur.value - datum.values[0].value) / datum.values[0].value]); return [min, max]; }, [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]); } datum.descendantValues = descendantValues; datum.max = d3.max(descendantValues); datum.min = d3.min(descendantValues); datum.mean = d3.mean(descendantValues); datum.median = d3.median(descendantValues); datum.variance = d3.variance(descendantValues); datum.deviation = d3.deviation(descendantValues); datum.maxZ = d3.max(descendantValues, d => (d - datum.mean) / datum.deviation); // z-score datum.minZ = d3.min(descendantValues, d => (d - datum.mean) / datum.deviation); // z-score datum.minP = pValues[0]; // percentage values. min/max value as expressed as a percentage of the first data point (year 0). datum.maxP = pValues[1]; // percentage values. min/max value as expressed as a percentage of the first data point (year 0). return descendantValues; } _summarize(datum); return datum; }
[ "function returnNestedData(filters){\n var _nested = summarizeChildren({\n key: 'total',\n values: filterSections(filters).map(d => {\n var nested = nestBy([undefined, 'property', d, 'year'], filterData(filters));\n nested.forEach(datum => { // mutates nested\n datum.key = d;\n });\n return nested[0];\n })\n });\n return _nested;\n}", "function formatData(data){\n //var severityNames = [\"unknown\", \"negligible\", \"low\", \"medium\", \"high\", \"critical\"]\n var severityNames = [\"Critical\", \"High\", \"Medium\", \"Low\"];\n var packageNames = [];\n var blockData = [];\n data = data.sort(function(a, b) { \n return (a.Critical + a.High + a.Medium + a.Low) < (b.Critical + b.High + b.Medium + b.Low);\n //return (b.critical * 3 + b.high * 2 + b.medium * 1 ) - (a.critical * 3 + a.high * 2 + a.medium * 1 );\n });\n\n for(var i = 0; i < data.length; i++){\n var y = 0;\n packageNames.push(data[i].package);\n for(var j = 0; j < severityNames.length; j++){\n var height = parseFloat(data[i][severityNames[j]]);\n var block = {'y0': parseFloat(y),\n 'y1': parseFloat(y) + parseFloat(height),\n 'height': height,\n 'x': data[i].package,\n 'cluster': severityNames[j]};\n y += parseFloat(data[i][severityNames[j]]);\n blockData.push(block);\n }\n }\n\n return {\n blockData: blockData,\n packageNames: packageNames,\n severityNames: severityNames\n };\n\n}", "function flattenNested1(dataset) {\n var newData = [];\n var v_status_value;\n \n dataset.forEach(function(d) {\n console.log(\"forEach1\" + d.key + d.values);\n if (d.key==0) { v_status_value=\"functional\"} else if (d.key==1) {v_status_value=\"needs-repairs\"} else {v_status_value=\"non-functional\"};\n newData.push({\n status_id: d.key,\n count: d.values,\n status_value: v_status_value\n });\n });\n return newData;\n }", "function aggregateData(data) {\n const ProgressData = data[0];\n const WakatimeData = data[1];\n const AttendanceData = data[2];\n const UserData = data[3];\n\n return UserData.map((user) => {\n const progress = transformProgress(ProgressData, user);\n const wakatimes = transformWakatime(WakatimeData, user);\n const attendance = transformAttendance(AttendanceData, user);\n const actual = user.toObject();\n\n return Object.assign({}, actual, {\n progress,\n wakatime: wakatimes.wakatimes,\n timeCoding: wakatimes.total,\n attendance: attendance.attendance,\n timeOnSite: attendance.total\n });\n });\n}", "calcAggregatedMvalues() {\n var _this = this;\n var data = this.data;\n\n if (_this.debug) console.log(\"\\n\\n<<<<<<<<< RESULT PAGE CALCULATIONS >>>>>>>>>>>>>>>>>\");\n // Loop through all CATEGORIES\n $.each(data.categories, function(index, category) {\n if (_this.debug) console.log(\"\\nCALC Aggregated M values - Category: \" + category.name + \" >>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n\n var aggMni_results = []; // capture agregated Mni values for each CATEGORY (one per each solution)\n\n // Loop over each belief value for Mni\n for (var i = 0; i < category.Beliefs.length; i++) {\n aggMni_results.push(category.Beliefs[i] * (category.weight / 100));\n }\n category.Mni = aggMni_results;\n\n // CALCULATE M for each CATEGORY ////////////////////////////////////\n // 1-(sum Mni aggMni_results)\n var M_result = 1 - (aggMni_results.reduce(_this.getSum));\n // update data model, rounded to 3 decimal places\n category.M = M_result;\n\n // CALCULATE Ml for each CATEGORY ////////////////////////////////////\n // 1-(category weight (convert from percentage)\n category.Ml = 1 - (category.weight * 0.01);\n\n // CALCULATE Mdash for each CATEGORY ////////////////////////////////////\n // category weight * (1-(sum(alternative beliefs)))\n var Mdash_result = (category.weight * 0.01) * (1 - (category.Beliefs.reduce(_this.getSum)));\n category.Mdash = Mdash_result;\n\n if (_this.debug) console.log(\"MNI: \" + category.Mni);\n if (_this.debug) console.log(\"M: \" + category.M);\n if (_this.debug) console.log(\"Ml: \" + category.Ml);\n if (_this.debug) console.log(\"Mdash: \" + category.Mdash);\n });\n }", "handleCalculation(data,tree){\n this.state.data.forEach((element) =>{\n if(element.aNumber == tree.attributes.id){\n data.totalTime = data.totalTime + element.timeSpend;\n data.totalArea = data.totalArea + element.areaCleaned;\n }\n })\n if(tree.children){\n tree.children.forEach((element) =>{\n data = this.handleCalculation(data,element);\n });\n }\n return data;\n }", "getTableauData () {\n if (!Array.isArray(this.data) || this.data.length === 0) {\n throw new Error('Data is not an array or is an empty!!')\n }\n\n return this.data.map((row) => {\n return {\n 'values': row.insights.data.map((value) => {\n return {\n 'post_id': parseInt(row.id.split('_')[1]),\n 'page_id': parseInt(row.id.split('_')[0]),\n 'page_post_id': row.id,\n [value.name]: value.values[0].value\n }\n })\n }\n }).reduce((a, b) => {\n let values = b.values.reduce((aF, bF) => {\n let keys = Object.keys(bF)\n\n keys.map((key) => {\n aF[key] = bF[key]\n })\n return aF\n }, {})\n\n return a.concat(values)\n }, [])\n }", "getrenDetFormattedData(renewalsData) {\n\n var renewalTransformedDetails = {\n client: {\n type: renewalsData.market,\n renewalLetter: {\n label: \"Renewal Letter\",\n endpoint: \"\"\n },\n aggregatedPremiums: [\n {\n label: \"Medical\",\n content: {\n current: {\n label: \"Current\",\n content: \"$\"+Math.round(renewalsData.currentMedicalRate * 100) / 100\n },\n renewal: {\n label: \"Renewal\",\n content: \"$\"+Math.round(renewalsData.renewalMedicalRate * 100) / 100\n },\n increase: true\n }\n },\n {\n label: \"Dental\",\n content: {\n current: {\n label: \"Current\",\n content: \"\"\n },\n renewal: {\n label: \"Renewal\",\n content: \"\"\n },\n increase: true\n }\n },\n {\n label: \"Vision\",\n content: {\n current: {\n label: \"Current\",\n content: \"\"\n },\n renewal: {\n label: \"Renewal\",\n content: \"\"\n },\n increase: true\n }\n },\n\n ],\n fields: [\n {\n label: \"Client ID\",\n content: \"\"\n },\n {\n label: \"Renewal Date\",\n content: \"\"\n },\n {\n label: \"Market\",\n content: \"\"\n },\n {\n label: \"State\",\n content: \"\"\n },\n {\n label: \"Products\",\n content: \"\"\n },\n {\n label: \"Exchange\",\n content: renewalsData.exchange\n },\n {\n label: \"Rating Area\",\n content:(renewalsData.medicalFutureRatingArea || renewalsData.medicalCurrentRatingArea || renewalsData.dentalFutureRatingArea || renewalsData.dentalCurrentRatingArea || renewalsData.pdFutureRatingArea || renewalsData.pdCurrentRatingArea)\n },\n {\n label: \"Association\",\n content: \"\"\n },\n {\n label: \"SIC\",\n content: \"\"\n },\n {\n label: \"Group Size\",\n content: renewalsData.size\n }\n ]\n },\n plans: ([]).concat(renewalsData.dentalProducts,\n renewalsData.visionProducts, renewalsData.medicalProducts).filter(function( element ) {\n return element !== undefined;\n })\n .map((val, ind)=>{\n return(\n {\n plan: {\n heading: \"Plan \"+(ind+1),\n columns: [\n {\n label: \"\",\n content: [\"Current\", \"Renewals\"]\n },\n {\n label: \"Plan\",\n content: [val.currentProduct.currentContractPlanName, val.renewalProduct.currentContractPlanName]\n },\n {\n label: \"Contract Code\",\n content: [val.currentProduct.currentContractPlanCode, val.renewalProduct.currentContractPlanCode]\n },\n {\n label: \"Premium\",\n content: [\"$\"+Math.round(val.currentProduct.monthlyPremium * 100) / 100,\n \"$\"+Math.round(val.renewalProduct.monthlyPremium * 100) / 100]\n },\n {\n label: \"Subscribers\",\n content: [val.currentProduct.subscribers, val.renewalProduct.subscribers]\n },\n {\n label: \"Subsidy\",\n content: [\"\",\"\"]\n },\n {\n label: \"Dependants Coverage\",\n content: [\"\",\"\"]\n }\n ]\n },\n employees: {\n heading: \"Employees\",\n columns: [\n {\n label: \"Employee\",\n content: val.employees.map((empVal,empInd)=>{\n return((empVal.name).toLowerCase())\n })\n },\n {\n label: \"Coverage\",\n content: val.employees.map((empVal,empInd)=>{\n return(empVal.coverage)\n })\n },\n {\n label: \"Age\",\n content: val.employees.map((empVal,empInd)=>{\n return(empVal.age)\n })\n },\n {\n label: \"Current Rate\",\n content: val.employees.map((empVal,empInd)=>{\n return(\"$\"+ Math.round(empVal.currentRate * 100) / 100)\n })\n },\n {\n label: \"New Rate\",\n content: val.employees.map((empVal,empInd)=>{\n return(empVal.newRate)\n })\n }\n ]\n }\n }\n\n )\n }),\n\n };\n return renewalTransformedDetails;\n}", "function inner(treeData) {\n treeData.forEach(function(node) {\n if (node.nodeType !== 'City') {\n node.stats = allGeosStats[node.nodeType][node._id];\n } else {\n node.stats = allGeosStats[node.nodeType][node.name];\n }\n if (node.__children__ && node.__children__.length > 0) {\n inner(node.__children__);\n }\n });\n }", "function makeAreaData(data){\n return data.map(function(d){\n return {\n \"Date\" : d[\"Date\"],\n \"DateP\" : d[\"DateP\"],\n \"Other\" : d[\"otherPercent\"],\n \"Dormant\" : d[\"dormantPercent\"],\n \"Other Shifts\" : d[\"otherShiftsPercent\"],\n \"Leave\" : d[\"leavePercent\"],\n \"CNIC Mismatch\" : d[\"CNICPercent\"]\n }\n })\n }", "function aggregateFromGrid (inputFeatures, currentTile, gridZoom, aggregations, postAggregations) {\n var children = {}\n var numfeatures = inputFeatures.length\n for (var i = 0; i < numfeatures; i++) {\n var f = inputFeatures[i]\n var parentcell = tilebelt.getParent(tilebelt.quadkeyToTile(f.properties._quadKey))\n var parentkey = tilebelt.tileToQuadkey(parentcell)\n if (!children[parentkey]) {\n children[parentkey] = []\n }\n children[parentkey].push(f)\n }\n\n var cells = tileUtil.getProgeny(currentTile, gridZoom)\n var numcells = cells.length\n var boxes = []\n for (var c = 0; c < numcells; c++) {\n var cell = cells[c]\n var cellkey = tilebelt.tileToQuadkey([cell[1], cell[2], cell[0]])\n var features = children[cellkey] || []\n boxes.push(makeCell(cell, features, aggregations, postAggregations, currentTile))\n }\n\n return boxes\n}", "function normalise_data(unormalized_data){\n let means = [0, 0, 0, 0];\n let deviations = [0, 0, 0, 0];\n // we calculate means first\n for (let i=0; i<array_length(unormalized_data); i=i+1){\n const input = unormalized_data[i][0];\n means[0] = means[0] + input[0];\n means[1] = means[1] + input[1];\n means[2] = means[2] + input[2];\n means[3] = means[3] + input[3];\n }\n means[0] = means[0] / array_length(unormalized_data);\n means[1] = means[1] / array_length(unormalized_data);\n means[2] = means[2] / array_length(unormalized_data);\n means[3] = means[3] / array_length(unormalized_data);\n // then we calculate deviations\n for (let i=0; i<array_length(unormalized_data); i=i+1){\n const input = unormalized_data[i][0];\n deviations[0] = deviations[0] + math_pow(input[0]-means[0], 2);\n deviations[1] = deviations[1] + math_pow(input[1]-means[1], 2);\n deviations[2] = deviations[2] + math_pow(input[2]-means[2], 2);\n deviations[3] = deviations[3] + math_pow(input[3]-means[3], 2);\n }\n deviations[0] = math_sqrt(deviations[0]);\n deviations[1] = math_sqrt(deviations[1]);\n deviations[2] = math_sqrt(deviations[2]);\n deviations[3] = math_sqrt(deviations[3]);\n // normalise data\n let normalised_data = [];\n for (let i=0; i<array_length(unormalized_data); i=i+1){\n const unormalised_input = unormalized_data[i][0];\n const output = unormalized_data[i][1];\n const normalised_input = [];\n array_push(normalised_input, (unormalised_input[0] - means[0]) / deviations[0]);\n array_push(normalised_input, (unormalised_input[1] - means[1]) / deviations[1]);\n array_push(normalised_input, (unormalised_input[2] - means[2]) / deviations[2]);\n array_push(normalised_input, (unormalised_input[3] - means[3]) / deviations[3]);\n array_push(normalised_data, [normalised_input, output]);\n }\n return normalised_data;\n}", "function showSeverityDistribution(dataFor2017) {\n\n function severityBySpeed(dimension, severity) {\n return dimension.group().reduce(\n function(p, v) {\n p.total += v.number_of_accidents;\n if (v.accident_severity === severity) {\n p.by_severity += v.number_of_accidents;\n }\n return p;\n },\n function(p, v) {\n p.total -= v.number_of_accidents;\n if (v.accident_severity === severity) {\n p.by_severity -= v.number_of_accidents;\n }\n return p;\n },\n function() {\n return { total: 0, by_severity: 0 };\n }\n );\n }\n\n let dim = dataFor2017.dimension(dc.pluck(\"speed_limit\"));\n let slightBySpeeed = severityBySpeed(dim, \"Slight\");\n let seriousBySpeeed = severityBySpeed(dim, \"Serious\");\n let fatalBySpeeed = severityBySpeed(dim, \"Fatal\");\n\n dc.barChart(\"#severity-distribution\")\n .width(380)\n .height(360)\n .dimension(dim)\n .colors(d3.scale.ordinal().range([\"#e6550e\", \"#fd8c3d\", \"#3182bc\"]))\n .group(fatalBySpeeed, \"Fatal\")\n .stack(seriousBySpeeed, \"Serious\")\n .stack(slightBySpeeed, \"Slight\")\n .valueAccessor(function(d) {\n if (d.value.total > 0) {\n return (d.value.by_severity / d.value.total) * 100;\n }\n else {\n return 0;\n }\n })\n .title(\"Fatal\", function(d) {\n let percent = (d.value.by_severity / d.value.total) * 100;\n return d.key + \" mph: \" + percent.toFixed(1) +\n \"% of fatal accidents\";\n })\n .title(\"Serious\", function(d) {\n let percent = (d.value.by_severity / d.value.total) * 100;\n return d.key + \" mph: \" + percent.toFixed(1) +\n \"% of serious accidents\";\n })\n .title(\"Slight\", function(d) {\n let percent = (d.value.by_severity / d.value.total) * 100;\n return d.key + \" mph: \" + percent.toFixed(1) +\n \"% of slight accidents\";\n })\n .on(\"pretransition\", function(chart) {\n chart.selectAll(\"g.y text\")\n .style(\"font-size\", \"12px\");\n chart.selectAll(\"g.x text\")\n .style(\"font-size\", \"12px\");\n chart.select(\"svg\")\n .attr(\"height\", \"100%\")\n .attr(\"width\", \"100%\")\n .attr(\"viewBox\", \"0 0 380 360\");\n chart.selectAll(\".dc-chart text\")\n .attr(\"fill\", \"#E5E5E5\");\n chart.selectAll(\".dc-legend-item text\")\n .attr(\"font-size\", \"12px\")\n .attr(\"fill\", \"#ffffff\");\n chart.selectAll(\"line\")\n .style(\"stroke\", \"#E5E5E5\");\n chart.selectAll(\".domain\")\n .style(\"stroke\", \"#E5E5E5\");\n chart.selectAll(\".x-axis-label\")\n .attr(\"font-size\", \"14px\");\n })\n .legend(dc.legend().x(100).y(345).itemHeight(15).gap(5)\n .horizontal(true))\n .margins({ top: 10, right: 30, bottom: 40, left: 40 })\n .x(d3.scale.ordinal())\n .xUnits(dc.units.ordinal)\n .xAxisLabel(\"Speed limit (mph)\", 25)\n .yAxis().tickFormat(function(d) { return d + \"%\"; });\n}", "function renderStats() {\n let stimulant = 0;\n let sedative = 0;\n let hallucinogic = 0;\n let delirant = 0;\n let dissociative = 0;\n let depressant = 0;\n for(substance in selectedSubstances) {\n let substanceAmount = selectedSubstances[substance];\n let substanceConfig = SUBSTANCES[substance];\n power = limitRange(Math.floor(substanceAmount / 2), 1, 5);\n if(substanceConfig.stats.stimulant) {\n stimulant += power;\n }\n if(substanceConfig.stats.sedative) {\n sedative += power;\n }\n if(substanceConfig.stats.hallucinogic) {\n hallucinogic += power;\n }\n if(substanceConfig.stats.delirant) {\n delirant += power;\n }\n if(substanceConfig.stats.dissociative) {\n dissociative += power;\n }\n if(substanceConfig.stats.depressant) {\n depressant += power;\n }\n }\n if(stimulant > 5) stimulant = 5;\n if(sedative > 5) sedative = 5;\n if(hallucinogic > 5) hallucinogic = 5;\n if(delirant > 5) delirant = 5;\n if(dissociative > 5) dissociative = 5;\n if(depressant > 5) depressant = 5;\n\n stimulantData = STATS_LEVELS[stimulant];\n sedativeData = STATS_LEVELS[sedative];\n hallucinogicData = STATS_LEVELS[hallucinogic];\n delirantData = STATS_LEVELS[delirant];\n dissociativeData = STATS_LEVELS[dissociative];\n depressantData = STATS_LEVELS[depressant];\n renderStat('stimulant', stimulantData.value, stimulantData.name, stimulantData.class);\n renderStat('sedative', sedativeData.value, sedativeData.name, sedativeData.class);\n renderStat('hallucinogic', hallucinogicData.value, hallucinogicData.name, hallucinogicData.class);\n renderStat('delirant', delirantData.value, delirantData.name, delirantData.class);\n renderStat('dissociative', dissociativeData.value, dissociativeData.name, dissociativeData.class);\n renderStat('depressant', depressantData.value, depressantData.name, depressantData.class);\n}", "function getMainDataMap() {\n return {\n fans: {\n metric: 'fans',\n getter: commonGetters.getChannelsSeparatelyGetter('breakdownValues')\n },\n fansValue: {\n metric: 'fans',\n getter: commonGetters.getOnlyFromChannelsGetter('totalValue')\n },\n fansChangeValue: {\n metric: 'fans',\n getter: commonGetters.getOnlyFromChannelsGetter('changeValue')\n },\n fansChangePercent: {\n metric: 'fans',\n getter: commonGetters.getOnlyFromChannelsGetter('changePercent'),\n formatters: [\n dataFormatters.decimalToPercent\n ]\n }\n };\n} // end getMainDataMap", "MaxValue(dataKey, data) {\r\n if (data.length == 0)\r\n {\r\n return \"0\";\r\n }\r\n else\r\n {\r\n var chartValues=[];\r\n // data.\r\n var count=data.length;\r\n for(var i=0;i<count;i++)\r\n {\r\n var temp=data[i];\r\n chartValues.push(temp[dataKey]);\r\n }\r\n\r\n return Math.max.apply(0,chartValues).toFixed(2);\r\n } \r\n }", "get summary(){\n let totals = this.totals;\n let fluxes = this.fluxes;\n return {\n Q: this.Q,\n COD: [totals.COD.total, fluxes.totals.COD.total], //chemical oxygen demand\n TKN: [totals.TKN.total, fluxes.totals.TKN.total], //total kjeldahl nitrogen\n NH4: [totals.TKN.FSA, fluxes.totals.TKN.FSA], //inorganic nitrogen (NH4, ammonia)\n NOx: [this.components.S_NOx, fluxes.components.S_NOx], //nitrate (NO3) and nitrite (NO2) is not TKN\n TP: [totals.TP.total, fluxes.totals.TP.total], //total phosphorus\n PO4: [totals.TP.PO4, fluxes.totals.TP.PO4], //inorganic phosphorus\n VSS: [totals.TSS.VSS, fluxes.totals.TSS.VSS], //volatile suspended solids\n iSS: [totals.TSS.iSS, fluxes.totals.TSS.iSS], //inorganic suspended solids\n TSS: [totals.TSS.total, fluxes.totals.TSS.total], //total suspended solids\n TOC: [totals.TOC.total, fluxes.totals.TOC.total], //total organic carbon\n }\n }", "function setupSumChart() {\n var catRange,\n subRange,\n row,\n column,\n subtypeColumn,\n monthTotal = 0;\n \n catRange = sheet.getRange(SUM_CHART_RANGE);\n row = catRange.getRow();\n column = catRange.getColumn();\n \n for (var i = 0, category; (category = EXPENSE_TYPES[i]); i++) {\n catRange = sheet.getRange(row, column);\n catRange.setValue(category);\n // catRange.getA1Notations() returns the name of the category\n setCategoryMonthlyTotals(row, column + 2, catRange.getA1Notation(), CATEGORY_RANGE.getA1Notation());\n \n // Sume the value of the category to the total\n monthTotal = monthTotal + sheet.getRange(row, column + 2).getValue();\n\n //Display Subcategories, if any\n if (EXPENSE_SUBTYPES[category] && EXPENSE_SUBTYPES[category].length > 0) {\n subtypeColumn = column + 1;\n row++;\n for (var j = 0, subCategory; (subCategory = EXPENSE_SUBTYPES[category][j]); j++) {\n subRange = sheet.getRange(row, subtypeColumn);\n subRange.setValue(subCategory);\n // subRange.getA1Notations() returns the name of the category\n setCategoryMonthlyTotals(row, subtypeColumn + 1, subRange.getA1Notation(), SUBCATEGORY_RANGE.getA1Notation());\n row++;\n }\n } else {\n row++;\n }\n }\n setMonthTotals(row, column + 2, monthTotal);\n}", "function calculateData() {\n\tvar percentage = 0;\n\ttotalData = 0;\n\thighestData = 0;\n\t//Calculate Total of Chart Value\n\tfor (var i = 0; i < Object.size(chartData); i++) {\n\t\ttotalData += parseInt(chartData[i]['value']);\n\t\tif (highestData < parseInt(chartData[i]['value']))\n\t\t\thighestData = parseInt(chartData[i]['value']);\n\t}\n\t//Calculate Percentage of Chart Value\n\tfor (var i = 0; i < Object.size(chartData); i++) {\n\t\tpercentage = (chartData[i]['value'] / totalData) * 100;\n\t\tchartData[i]['percentage'] = percentage.toFixed(2);\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
su/sudo/startstopdaemon work too badly with upstart and setuid is only available in > 1.4, hence this
function setupUGID(uid, gid) { if (uid) { if (!gid) { gid = uid; } try { process.setgid(gid); util.log('changed gid to ' + gid); process.setuid(uid); util.log('changed uid to ' + uid); } catch (e) { util.log('Failed to set uid/gid to ' + [uid, gid].join('/') + ' Error: ' + e.message); } } }
[ "function start () {\n let node = process.execPath\n let daemonFile = path.join(__dirname, '../daemon')\n let daemonLog = path.resolve(untildify('~/.hotel/daemon.log'))\n\n debug(`creating ${startupFile}`)\n startup.create('hotel', node, [daemonFile], daemonLog)\n\n console.log(` Started http://localhost:${conf.port}`)\n}", "function initializeUserIfNeeded(uid) {\n}", "function stop (cb) {\n got.post(killURL, { timeout: 1000, retries: 0 }, (err) => {\n console.log(err ? ' Not running' : ' Stopped daemon')\n\n debug(`removing ${startupFile}`)\n startup.remove('hotel')\n\n cb()\n })\n}", "function startOTP() {\n console.log('Starting OTP service');\n var child = childProcess.exec('java -Xmx2g -jar '\n + globalvars.otpJarPath\n + ' --server -p 8080 -v',\n function (error, stdout, stderr) {\n console.log('OTP ERROR: ' + stderr);\n if (error !== null) {\n console.log('OTP ERROR: ' + error);\n }\n });\n\n child.stdout.on('data', function (data) {\n console.log('CHILD OTP SERVER: ' + data);\n });\n\n child.stderr.on('data', function (data) {\n console.log('CHILD OTP SERVER: ' + data);\n });\n\n child.on('close', function(code) {\n console.log('child closed: ' + code);\n });\n }", "function setupNNTPDaemon() {\n var daemon = new nntpDaemon();\n\n groups.forEach(function(element) {\n daemon.addGroup(element[0]);\n });\n\n var article = new newsArticle(kSimpleNewsArticle);\n daemon.addArticleToGroup(article, \"test.subscribe.simple\", 1);\n\n return daemon;\n}", "prepare() {\n const { sboxDir, systemDir } = this;\n const { mkdir, symlink, linkFromSystem, copyFromSystem } = this.util;\n\n /**\n * Package installation phases\n */\n const packageDepsInstall = () =>\n this.packages.reduce(\n (promise, pkg) =>\n promise.then(_ => this.satisfyPackageRequirements(pkg)),\n Promise.resolve()\n );\n const packagePreInstall = () =>\n Promise.all(this.packages.map(this.runPackageActions.bind(this, \"pre\")));\n const packagePostInstall = () =>\n Promise.all(this.packages.map(this.runPackageActions.bind(this, \"post\")));\n\n /**\n * Prepare the base dir\n */\n const makeBaseDir = () => {\n this._log(\"mkdir\", \"/\");\n return exec(`mkdir -p ${sboxDir}`);\n };\n\n /**\n * Prepare the filesystem\n */\n const makeFilesystem = () =>\n Promise.all([\n mkdir(\"/dev\"),\n mkdir(\"/bin\"),\n mkdir(\"/sbin\"),\n mkdir(\"/etc\"),\n mkdir(\"/lib\").then(x => symlink(\"/lib64\", \"lib\")),\n mkdir(\"/home\").then(x => mkdir(\"/home/user\")),\n mkdir(\"/usr\").then(x =>\n Promise.all([\n mkdir(\"/usr/bin\"),\n mkdir(\"/usr/sbin\"),\n mkdir(\"/usr/lib\"),\n mkdir(\"/usr/share\"),\n mkdir(\"/usr/local\")\n ])\n ),\n mkdir(\"/opt\"),\n mkdir(\"/proc\"),\n mkdir(\"/tmp\", 0o1777),\n mkdir(\"/root\", 0o750)\n ]);\n\n /**\n * Copy the files from the base directory into the filesystem\n */\n const copyFiles = () => {\n const createPasswdContents = () => {\n return [\n \"root:x:0:0:root:/root:/bin/bash\",\n \"nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin\",\n `user:x:${this.uid}:${this.gid}:user:/home/user:/bin/bash`,\n \"\"\n ].join(\"\\n\");\n };\n\n const createGroupContents = () => {\n return [\n \"root:x:0:\",\n \"daemon:x:1:\",\n \"nogroup:x:65534:\",\n `user:x:${this.gid}:`,\n \"\"\n ].join(\"\\n\");\n };\n\n /**\n * Copy the etc artifacts\n */\n const prepareEtc = Promise.all([\n copyFromSystem(\"/etc/resolv.conf\"),\n copyFromSystem(\"/etc/hosts\"),\n writeFileAsync(sboxDir + \"/etc/passwd\", createPasswdContents()),\n writeFileAsync(sboxDir + \"/etc/group\", createGroupContents())\n ]);\n\n /**\n * Copy the lib files\n */\n const prepareLib = Promise.all([\n linkFromSystem(\"/lib/x86_64-linux-gnu/*\", \"/lib\"),\n linkFromSystem(\"/usr/lib/x86_64-linux-gnu/*.so\", \"/usr/lib\"),\n linkFromSystem(\"/usr/lib/x86_64-linux-gnu/*.so.*\", \"/usr/lib\")\n ]);\n\n /**\n * Copy the dev files\n */\n const prepareDev = Promise.all([\n copyFromSystem(\"/dev/urandom\"),\n copyFromSystem(\"/dev/random\"),\n copyFromSystem(\"/dev/console\"),\n copyFromSystem(\"/dev/null\"),\n copyFromSystem(\"/dev/zero\"),\n copyFromSystem(\"/dev/tty\")\n ]);\n\n return Promise.all([prepareEtc, prepareLib, prepareDev]).then(\n packagePreInstall\n );\n };\n\n /**\n * Fix permissions\n */\n const fixPermissions = () => {\n return Promise.resolve()\n .then(() => exec(`chown -R root:root ${sboxDir}`))\n .then(() => exec(`chmod -R a-w ${sboxDir}`))\n .then(() => exec(`chmod -R a+w ${sboxDir}/usr/local`))\n .then(() => exec(`chmod -R a+w ${sboxDir}/opt`))\n .then(() => exec(`chmod -R a+w ${sboxDir}/dev/*`))\n .then(() =>\n exec(`chown -R ${this.uid}:${this.gid} ${sboxDir}/home/user`)\n )\n .then(() => exec(`chmod 0700 ${sboxDir}/home/user`))\n .then(() => exec(`chmod 1777 ${sboxDir}/tmp`));\n };\n\n /**\n * Mount filesystems\n */\n const prepareMounts = () =>\n Promise.all([exec(`mount -t proc ${sboxDir}/proc ${sboxDir}/proc`)]);\n\n //// Execute\n\n return packageDepsInstall()\n .then(makeBaseDir)\n .then(makeFilesystem)\n .then(copyFiles)\n .then(fixPermissions)\n .then(packagePostInstall)\n .then(prepareMounts);\n }", "function respawn(args) {\n var filename = path.resolve(__dirname, \"../../bin/tl.js\")\n var flags = args.unknown.concat([filename])\n\n if (args.color != null) flags.push(args.color ? \"--color\" : \"--no-color\")\n if (args.config != null) flags.push(\"--config\", args.config)\n if (args.cwd != null) flags.push(\"--cwd\", args.cwd)\n\n args.require.forEach(function (file) {\n flags.push(\"--require\", file)\n })\n\n // It shouldn't respawn again in the child process, but I added the flag\n // here just in case. Also, don't try to specially resolve anything in the\n // respawned local CLI.\n flags.push(\"--no-respawn\", \"--force-local\", \"--\")\n flags.push.apply(flags, args.files)\n\n // If only there was a cross-platform way to replace the current process\n // like in Ruby...\n require(\"child_process\").spawn(process.argv[0], flags, {stdio: \"inherit\"})\n .on(\"exit\", function (code) { if (code != null) process.exit(code) })\n .on(\"close\", function (code) { if (code != null) process.exit(code) })\n .on(\"error\", function (e) {\n console.error(e.stack)\n process.exit(1)\n })\n}", "destroy() {\n // Make sure there are no active PTYs\n this.activePtys.forEach(term => term.destroy());\n this.activePtys = [];\n\n // Remove the sandbox\n return exec(`umount ${this.sboxDir}/proc`).then(() =>\n exec(`rm -rf ${this.sboxDir}`)\n );\n }", "function unix_isatty() {\n return 0; // false\n}", "function executeCommand(cmd, root){\n cmd = root ? 'sudo ' + cmd : cmd;\n grunt.verbose.writeln('Executing: ' + cmd);\n\n exec(cmd, function(error, stdout, stderr){\n if(stderr.indexOf('have write permissions') !== -1){\n grunt.log.errorlns('It seems that you don\\'t have write permissions for this directory. Executing as root, you may be required to type your root password below:');\n return executeCommand(cmd, true);\n } else if(stderr.indexOf('multipart-post (~> 1.2.0)') !== -1){\n grunt.log.errorlns('An error occured with a Ruby dependency, trying to resolve the issue');\n return exec('gem install multipart-post -v 1.2.0', function(error, stdout, stderr){\n if(!error){\n return executeCommand(cmd, true);\n }\n });\n } else if(error !== null){\n return deferred.reject(stderr, 'fatal');\n }\n \n // Next step here ...\n deferred.resolve(stdout);\n });\n }", "function touchActivePidFile() {\n var stream = fs.createWriteStream(parent_dir + \"/db/pids/active_pids.txt\");\n stream.write(JSON.stringify({}, null, 2));\n stream.end();\n }", "function setupTerminationHandlers(){\n // Process on exit and signals.\n process.on('exit', function() { terminator(); });\n\n // Removed 'SIGPIPE' from the list - bugz 852598.\n ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',\n 'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'\n ].forEach(function(element, index, array) {\n process.on(element, function() { terminator(element); });\n });\n }", "function createWorkDir() {\n const directory = os.tmpdir() + '/cdp';\n fs.rmdirSync(directory, { recursive: true });\n fs.mkdirSync(directory);\n process.chdir(directory);\n return directory;\n}", "function sudoCheck(){\n\ttry{\n\t\tsudo = JSON.parse(fs.readFileSync('./akebot/sudo.json', 'utf8'))\n\t} catch(error) {\n\t\tvar sudo = {\"id\":\"\",\"username\": \"\", \"checked\": false}\n\t};\n\tif(sudo.checked === true) return;\n\tvar id = \"\";\n\tvar username = \"\";\n\tfor(var serverID in bot.servers){\n\t\tid = bot.servers[serverID].owner_id;\n\t\tusername = bot.servers[serverID].members[id].username;\n\t\tbreak;\n\t}\n\tsudo.id = id;\n\tsudo.username = username;\n\tsudo.checked = true;\n\tfs.writeFileSync('./akebot/sudo.json', JSON.stringify(sudo, null, '\\t'));\n\treturn console.log(\"Bot dev is set to \" + sudo.username + \" If this isn't you please correct it in the 'sudo.json' file\");\n}", "async startInstall() {\n this.state = AddonManager.STATE_INSTALLING;\n if (!this._callInstallListeners(\"onInstallStarted\")) {\n this.state = AddonManager.STATE_DOWNLOADED;\n this.removeTemporaryFile();\n XPIInstall.installs.delete(this);\n this._callInstallListeners(\"onInstallCancelled\");\n return;\n }\n\n // Find and cancel any pending installs for the same add-on in the same\n // install location\n for (let install of XPIInstall.installs) {\n if (install.state == AddonManager.STATE_INSTALLED &&\n install.location == this.location &&\n install.addon.id == this.addon.id) {\n logger.debug(`Cancelling previous pending install of ${install.addon.id}`);\n install.cancel();\n }\n }\n\n // Reinstall existing user-disabled addon (of the same installed version).\n // If addon is marked to be uninstalled - don't reinstall it.\n if (this.existingAddon &&\n this.existingAddon.location === this.location &&\n this.existingAddon.version === this.addon.version &&\n this.existingAddon.userDisabled &&\n !this.existingAddon.pendingUninstall) {\n await XPIDatabase.updateAddonDisabledState(this.existingAddon, false);\n this.state = AddonManager.STATE_INSTALLED;\n this._callInstallListeners(\"onInstallEnded\", this.existingAddon.wrapper);\n return;\n }\n\n let isUpgrade = this.existingAddon &&\n this.existingAddon.location == this.location;\n\n logger.debug(\"Starting install of \" + this.addon.id + \" from \" + this.sourceURI.spec);\n AddonManagerPrivate.callAddonListeners(\"onInstalling\",\n this.addon.wrapper,\n false);\n\n let stagedAddon = this.location.installer.getStagingDir();\n\n try {\n await this.location.installer.requestStagingDir();\n\n // remove any previously staged files\n await this.unstageInstall(stagedAddon);\n\n stagedAddon.append(`${this.addon.id}.xpi`);\n\n await this.stageInstall(false, stagedAddon, isUpgrade);\n\n // The install is completed so it should be removed from the active list\n XPIInstall.installs.delete(this);\n\n let install = async () => {\n if (this.existingAddon && this.existingAddon.active && !isUpgrade) {\n XPIDatabase.updateAddonActive(this.existingAddon, false);\n }\n\n // Install the new add-on into its final location\n let existingAddonID = this.existingAddon ? this.existingAddon.id : null;\n let file = await this.location.installer.installAddon({\n id: this.addon.id,\n source: stagedAddon,\n existingAddonID,\n });\n\n // Update the metadata in the database\n this.addon._sourceBundle = file;\n this.addon.rootURI = getURIForResourceInFile(file, \"\").spec;\n this.addon.visible = true;\n\n if (isUpgrade) {\n this.addon = XPIDatabase.updateAddonMetadata(this.existingAddon, this.addon, file.path);\n let state = this.location.get(this.addon.id);\n if (state) {\n state.syncWithDB(this.addon, true);\n } else {\n logger.warn(\"Unexpected missing XPI state for add-on ${id}\", this.addon);\n }\n } else {\n this.addon.active = (this.addon.visible && !this.addon.disabled);\n this.addon = XPIDatabase.addToDatabase(this.addon, file.path);\n XPIStates.addAddon(this.addon);\n this.addon.installDate = this.addon.updateDate;\n XPIDatabase.saveChanges();\n }\n XPIStates.save();\n\n AddonManagerPrivate.callAddonListeners(\"onInstalled\",\n this.addon.wrapper);\n\n logger.debug(`Install of ${this.sourceURI.spec} completed.`);\n this.state = AddonManager.STATE_INSTALLED;\n this._callInstallListeners(\"onInstallEnded\", this.addon.wrapper);\n\n XPIDatabase.recordAddonTelemetry(this.addon);\n\n // Notify providers that a new theme has been enabled.\n if (this.addon.type === \"theme\" && this.addon.active)\n AddonManagerPrivate.notifyAddonChanged(this.addon.id, this.addon.type);\n };\n\n this._startupPromise = (async () => {\n if (this.existingAddon) {\n await XPIInternal.BootstrapScope.get(this.existingAddon).update(\n this.addon, !this.addon.disabled, install);\n\n if (this.addon.disabled) {\n flushJarCache(this.file);\n }\n } else {\n await install();\n await XPIInternal.BootstrapScope.get(this.addon).install(undefined, true);\n }\n })();\n\n await this._startupPromise;\n } catch (e) {\n logger.warn(`Failed to install ${this.file.path} from ${this.sourceURI.spec} to ${stagedAddon.path}`, e);\n\n if (stagedAddon.exists())\n recursiveRemove(stagedAddon);\n this.state = AddonManager.STATE_INSTALL_FAILED;\n this.error = AddonManager.ERROR_FILE_ACCESS;\n XPIInstall.installs.delete(this);\n AddonManagerPrivate.callAddonListeners(\"onOperationCancelled\",\n this.addon.wrapper);\n this._callInstallListeners(\"onInstallFailed\");\n } finally {\n this.removeTemporaryFile();\n this.location.installer.releaseStagingDir();\n }\n }", "function ensureUp(config) {\n\n // Ensure that the shared directory is an absolute path.\n config.sharedDir = makeAbsolute(config.sharedDir);\n\n // Get the operations that would need to happen.\n var ops = opsForUp(config);\n var steps = {\n dirStatus: [],\n todo: [],\n done: []\n };\n\n // Deal with creating shared directory.\n if (ops.sharedNeedsCreate) {\n if (config.dryRun) {\n steps.dirStatus = \"Doesn't exist yet\";\n steps.todo.push([\n \"Create '\" + config.sharedDir + \"' to share with the demo\"\n ]);\n } else {\n if (!config.quiet)\n console.log(\"\\nCreating shared directory ...\\n\");\n \n makeSharedDir(config.sharedDir);\n }\n } else {\n if (config.dryRun) {\n steps.dirStatus =\n \"Already exists. Its contents will be visible in the demo at /shared\";\n }\n }\n\n // Deal with removing stopped / exited container that was never\n // removed. This shouldn't happen unless there's a problem with\n // the docker daemon. The code here is just in case.\n if (ops.containerNeedsRemove) {\n if (config.dryRun) {\n let commandLine = docker.removeContainer({\n dryRun: true,\n containerName: config.containerName\n });\n steps.todo.push([\n \"Run 'docker rm' to enable running the demo again\"\n ]);\n } else {\n docker.removeContainer({\n quiet: config.quiet,\n containerName: config.containerName\n });\n }\n }\n\n // Deal with running the container for the first time.\n if (ops.containerNeedsUp) {\n if (config.dryRun) {\n let commandLine = docker.runContainer({\n dryRun: true,\n sharedDir: config.sharedDir,\n containerName: config.containerName,\n dockerImage: config.dockerImage\n });\n steps.todo.push([\n \"Run 'docker run' to load the demo files into an idle container\"\n ]);\n steps.todo.push([\n \"Make '\" + config.sharedDir + \"' visible inside the container at /shared\"\n ]);\n } else {\n docker.runContainer({\n quiet: config.quiet,\n sharedDir: config.sharedDir,\n containerName: config.containerName,\n dockerImage: config.dockerImage\n });\n }\n } else {\n if (config.dryRun) {\n steps.done.push([\n \"Up, skipping 'docker run'\"\n ]);\n }\n }\n\n return steps;\n}", "get uid()\n\t{\n\t\treturn this._uid;\n\t}", "function reboot() {\n sendPowerCommand('reboot');\n}", "exitPrefixUnaryOperation(ctx) {\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return speed is RPM
function motorGetSpeed() { return currentSpeedRpm; }
[ "get speedVariation() {}", "getSpeed() {\n return this.model ? this.model.getCurrentSpeedKmHour() : null;\n }", "get sustainedClockSpeed() {\n return this.getNumberAttribute('sustained_clock_speed');\n }", "_calculateTargetedSpeed() {\n if (this.mcp.autopilotMode !== MCP_MODE.AUTOPILOT.ON) {\n return;\n }\n\n if (this.flightPhase === FLIGHT_PHASE.LANDING) {\n return this._calculateTargetedSpeedDuringLanding();\n }\n\n switch (this.mcp.speedMode) {\n case MCP_MODE.SPEED.OFF:\n return this._calculateLegalSpeed(this.speed);\n\n case MCP_MODE.SPEED.HOLD:\n return this._calculateLegalSpeed(this.mcp.speed);\n\n // future functionality\n // case MCP_MODE.SPEED.LEVEL_CHANGE:\n // return;\n\n case MCP_MODE.SPEED.N1:\n return this._calculateLegalSpeed(this.model.speed.max);\n\n case MCP_MODE.SPEED.VNAV: {\n const vnavSpeed = this._calculateTargetedSpeedVnav();\n\n return this._calculateLegalSpeed(vnavSpeed);\n }\n\n default:\n console.warn('Expected MCP speed mode of \"OFF\", \"HOLD\", \"LEVEL_CHANGE\", \"N1\", or \"VNAV\", but ' +\n `received \"${this.mcp[MCP_MODE_NAME.SPEED]}\"`);\n return this._calculateLegalSpeed(this.speed);\n }\n }", "function checkSpeed(speed) {\n\t\tif(speed > 0 && speed <= 80)\n\t\t\treturn true;\n\t\telse return false;\n\t}", "function speedCalc() {\n\t\t\treturn (0.4 + 0.01 * (50 - invadersAlive)) * difficulty;\n\t\t}", "function format_speed(speed) {\n return Number(speed).toFixed(2) + ' Mbps';\n}", "function checkSpeed (speed) {\n const speedLimit = 70;\n const kmPerPoint = 5;\n\n if(speed < speedLimit + kmPerPoint) {\n console.log('Ok');\n return;\n }\n const points = Math.floor((speed - speedLimit) / kmPerPoint);\n if (points >= 12) \n console.log('License suspended');\n else \n console.log('Points:', points);\n \n}", "incrementSpeed() {\n\t\t\tswitch (this.speed)\n\t\t\t{\n\t\t\t\tcase 1000:\n\t\t\t\t\tthis.speed = 2000;\n\t\t\t\tbreak;\n\t\t\t\tcase 2000:\n\t\t\t\t\tthis.speed = 5000;\n\t\t\t\tbreak;\n\t\t\t\tcase 5000:\n\t\t\t\t\tthis.speed = 10000;\n\t\t\t\tbreak;\n\t\t\t\tcase 10000:\n\t\t\t\t\tthis.speed = 20000;\n\t\t\t\tbreak;\n\t\t\t\tcase 20000:\n\t\t\t\t\tthis.speed = 50000;\n\t\t\t\tbreak;\n\t\t\t\tcase 50000:\n\t\t\t\t\tthis.speed = 60000; // one second is one minute\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthis.speed = 1000; // one second is one second\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}", "validateSpeed(){\n if(this.speed ==''|| this.speed < 0 || this.speed > 900){\n return \"Speed cannot be empty, should not be negative and should not be more than 900\";}\n else{\n return this.speed;\n }\n }", "function calculateSpeed(distance, time){\n return distance / time;\n}", "updateSpeedPhysics() {\n let speedChange = 0;\n const differenceBetweenPresentAndTargetSpeeds = this.speed - this.target.speed;\n\n if (differenceBetweenPresentAndTargetSpeeds === 0) {\n return;\n }\n\n if (this.speed > this.target.speed) {\n speedChange = -this.model.rate.decelerate * TimeKeeper.getDeltaTimeForGameStateAndTimewarp() / 2;\n\n if (this.isOnGround()) {\n speedChange *= PERFORMANCE.DECELERATION_FACTOR_DUE_TO_GROUND_BRAKING;\n }\n } else if (this.speed < this.target.speed) {\n speedChange = this.model.rate.accelerate * TimeKeeper.getDeltaTimeForGameStateAndTimewarp() / 2;\n speedChange *= extrapolate_range_clamp(0, this.speed, this.model.speed.min, 2, 1);\n }\n\n this.speed += speedChange;\n\n if (abs(speedChange) > abs(differenceBetweenPresentAndTargetSpeeds)) {\n this.speed = this.target.speed;\n }\n }", "function getMOI(type, speed) {\n\tvar speedScale = 1-(0.26 * speed/100);\n\t//console.log('scale'+speedScale+'speed'+speed);\n\t\n\tvar moi = 0;\n\tif (type == 0) moi = 6.29;\n\telse if (type == 1) moi = 6.29;\n\telse if (type == 2) moi = 5.14;\n\telse if (type == 3) moi = 3.85;\n\telse if (type == 4) moi = 3.85;\n\telse if (type == 5) moi = 4.30;\n\telse if (type == 6) moi = 4.30;\n\telse if (type == 7) moi = 0.00;\n\telse if (type == 8) moi = 0.00;\n\telse if (type == 9) moi = 4.48;\n\telse if (type == 10) moi = 4.58;\n\telse if (type == 11) moi = 4.58;\n\telse if (type == 12) moi = 4.58;\n\telse if (type == 13) moi = 4.48;\n\telse if (type == 14) moi = 4.48;\n\telse if (type == 15) moi = 4.48;\n\telse if (type == 16) moi = 4.58;\n\telse if (type == 17) moi = 4.58;\n\telse if (type == 18) moi = 0.00;\n\telse if (type == 19) moi = 0.00;\n\telse if (type == 20) moi = 4.48;\n\t\n\treturn moi * speedScale;\n}", "get WindSpeedMph() {\n return this.windMph;\n }", "function slower () {\n\tvar extra = speed * 0.3;\n\tif (speed - extra < 0.000002) {\n\t\tspeed = 0.000002;\n\t} else {\n\t\tspeed -= extra;\n\t}\n\ttempSpeed = speed;\n}", "calculateTickRate(enemySpeed){\n this.tickRate = Math.round((this.speed / (this.speed + enemySpeed)) * 100);\n }", "speedToDuration(value, angle2) {\n if (typeof value !== \"number\") {\n const speed = parseSpeed(value);\n return angle2 / Math.abs(speed) * 1e3;\n } else {\n return Math.abs(value);\n }\n }", "get WindSpeedKmh() {\n return this.windMph;\n }", "function effectiveWindSpeedLimit (rxi) {\n return 0.9 * rxi\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if a panel with a given id is expanded.
isExpanded(panelId) { return this.activeIds.indexOf(panelId) > -1; }
[ "_expandPanel(panel) {\n panel.expanded = true;\n }", "function _isPanelOpen() {\n return $issuesPanel.is(\":visible\");\n }", "_collapsePanel(panel) {\n panel.expanded = false;\n }", "function searchPanelOpen(state) {\n var _a\n return (\n ((_a = state.field(searchState, false)) === null || _a === void 0\n ? void 0\n : _a.panel) != null\n )\n }", "function elementCanExpand() {\n return element.offset().top + element.height() < $(window).height() + 100; // 100 = number of pixels below view\n }", "function isExpandedView(entryTarget)\n{\n return $(entryTarget).parent().hasClass(\"cards\");\n}", "isItemExpanded(item) {\n return this.isItemParent(item)\n && this.composer.getItemPropertyValue(item, 'expanded') === true;\n }", "async function checkPanelOpens() {\n info(\"Waiting for panel to open.\");\n let promise = promisePanelOpened();\n DownloadsCommon.getData(window)._notifyDownloadEvent(\"start\");\n is(\n DownloadsPanel.isPanelShowing,\n true,\n \"Panel state should indicate a preparation to be opened.\"\n );\n await promise;\n\n is(DownloadsPanel.panel.state, \"open\", \"Panel should be opened.\");\n\n DownloadsPanel.hidePanel();\n}", "function supplierExpanded() {\n var isFromSupplier = PPSTService.getAddingSupplier();\n if (isFromSupplier) {\n // Expand \n $scope.expandASection('suppliers-section', 8);\n PPSTService.setAddingSupplier(false);\n }\n }", "isExpandedCharacters() {\n return this.node.classList.contains(CSS_PREFIX + \"-expanded\");\n }", "function persist_expanded_child(id) {\r\n\tvar expand_these = JSON.parse(localStorage.getItem('rental_property_manager.dvp_expand'));\r\n\tif(expand_these == undefined) expand_these = [];\r\n\r\n\tif($j('[id=' + id + ']').hasClass('active')) {\r\n\t\tif(expand_these.indexOf(id) < 0) {\r\n\t\t\t// expanded button and not persisting in cookie? save it!\r\n\t\t\texpand_these.push(id);\r\n\t\t\tlocalStorage.setItem('rental_property_manager.dvp_expand', JSON.stringify(expand_these));\r\n\t\t}\r\n\t} else {\r\n\t\tif(expand_these.indexOf(id) >= 0) {\r\n\t\t\t// collapsed button and persisting in cookie? remove it!\r\n\t\t\texpand_these.splice(expand_these.indexOf(id), 1);\r\n\t\t\tlocalStorage.setItem('rental_property_manager.dvp_expand', JSON.stringify(expand_these));\r\n\t\t}\r\n\t}\r\n}", "function expandPath(id, expanded, collapsed) {\r\n var parts = id.split('-');\r\n if (parts) {\r\n var part = '';\r\n var i;\r\n for (i = 0; i < parts.length; ++i) {\r\n part += parts[i];\r\n expandOrCollapse(part, expanded, collapsed, true);\r\n part += '-';\r\n }\r\n }\r\n}", "function collapseExpandLayers(id, parentDisplayType) {\n var elements = document.getElementsByName(id);\n var displayType = getDisplayType(id, parentDisplayType);\n var layerLabel = displayType == 'block' ?\n getArrowImg('open') : getArrowImg('close');\n document.getElementById('collapse_' + id).innerHTML = layerLabel;\n for (var i = 0; i < elements.length; i++) {\n elements[i].style.display = displayType;\n }\n collapseChildLayers(id, displayType);\n}", "function openQuickPanel(courseID) {\n\t\t\t$rootScope.$broadcast('course-selected', courseID);\n\t\t\t$mdSidenav('quick-panel').toggle();\n\t\t}", "get canExpand() {\n return this._hasChildren && !this.node.singleTextChild;\n }", "function checkAndEnable(id, enable) {\n if (enable) {\n $(id).show();\n } else {\n $(id).hide();\n }\n}", "function toggle_panel(){\n var content = document.getElementById(\"panel-content\");\n if(panel_visible){\n content.style.display = \"none\";\n }else{\n content.style.display = \"block\";\n }\n panel_visible = !panel_visible;\n createCookie(\"panel-state\" + panel_title, (panel_visible ? \"true\" : \"false\"), 42);\n}", "isExpanded(range) {\n return !Range.isCollapsed(range);\n }", "async hasToggleIndicator() {\n return (await this._expansionIndicator()) !== null;\n }", "function checkLoanAdvance(id)\r\n{\r\n\tvar rc;\r\n\tvar temp;\r\n\r\n\trc = showLoanItem('advance');\r\n\tif (rc == '0'){\r\n\t\ttemp = document.getElementById(id);\r\n\t\ttemp.style.display = 'none';\r\n\t}\r\n}//end checkLoanAdvance" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
destroyEightQueens UI Data clear the game data from localStorage
destroyEightQueens(lsItem) { window.localStorage.removeItem( lsItem ); }
[ "function clear(){\n localStorage.clear();\n highScores=[];\n highScoreParent.innerHTML=\"\";\n }", "function clearLeaderboard() {\n leaderboardArr = [];\n localStorage.clear();\n displayLeaderboard();\n}", "function clearEmptyGames() {\n\n }", "function clearScore() {\n localStorage.setItem(\"highscore\", \"\");\n localStorage.setItem(\"highscoreName\", \"\");\n resetGame();\n}", "function clearGrid() {\n score = 0\n mode = null\n firstMove = false\n moves = 10\n timer = 60\n interval = null\n grid.innerHTML = ''\n }", "function clearScore(){\n localStorage.setItem('highscore','');\n localStorage.setItem('highscoreName','');\n reset();\n}", "function clearScores() {\n localStorage.removeItem(\"LastScoreBoard\"); // removes the stringified key/value of the previous ScoreBoard from localStorage\n scoreSubmissiones = []; // clears the scoreboard submissions array containing previous score entries\n scoresTableBody.innerHTML = \"\"; // clears the rendered HTML of the scores table body\n}", "finish() {\n document.querySelector(\".game-page\").style.display = \"none\";\n document.querySelector(\".scores-page\").style.display = \"block\";\n localStorage.setItem(\n \"game\" + Date.now(),\n this.player.name + \",\" + this.player.score\n );\n this.reset();\n _mylib__WEBPACK_IMPORTED_MODULE_3__[\n \"default\"\n ].createHighscoresTable();\n }", "clearDataFromLocalStorage() {\n localStorage.db = [];\n }", "destroy() {\n\t\tif (this.timer) {\n\t\t\tclearTimeout(this.timer);\n\t\t}\n\t\tfor (const i in this.playerTable) {\n\t\t\tthis.playerTable[i].destroy();\n\t\t}\n\t\t// destroy this game\n\t\tthis.room.game = null;\n\t}", "function removeGame() {\n\t//todo: add formal message telling client other player disconnected\n\tsocket.emit('delete game', gameID);\n\tclient.fleet = ['temp2', 'temp3', 'temp4', 'temp5'];\n\tenemyFleet = new Array(4);\n\tclient.clearGrids();\n\tsocket.off(gameID + ' player disconnect');\t\n\tgameID = -1;\n\tprepWindow = -1;\n\tpositionWindow = -1;\n\tplayWindow = -1;\n}", "free() {\n for (let name in Memory.creeps) {\n if (Game.creeps[name] === undefined) {\n delete Memory.creeps[name];\n }\n }\n }", "clearGrid() {\n for (let row = 0; row < this.N; row++) {\n for (let column = 0; column < this.N; column++) {\n this.grid[row][column].element.remove();\n }\n }\n this.grid = null;\n\n this.width = 0;\n this.height = 0;\n this.N = 0;\n\n this.startTile = null;\n this.endTile = null;\n }", "resetStats() {\n\t\tthis.gameDataList = [];\n\t\tthis.curGameData = null;\n\t}", "deleteGrid() {\n this.gridArray.length = 0; // deleting the grid array\n let child = this.gridDOM.lastElementChild;\n\n // deleting all the squares from the grid\n while(child) {\n this.gridDOM.removeChild(child);\n child = this.gridDOM.lastElementChild;\n }\n }", "function clearCanvas() {\n elements.gridCanvas.innerHTML = '';\n }", "function clearHighScoreTable() {\n var highScoreTable = getHighScoreTable();\n for (var i = 0; i < highScoreTable.length; i++) {\n var name = \"player\" + i;\n deleteCookie(name);\n }\n}", "function resetGame() {\n // wipe these variables\n isInitialised = false;\n readySet = {};\n }", "function resetBoard() {\r\n gameboard.forEach(function(space, index) { \r\n this[index] = null; \r\n }, gameboard)\r\n _render()\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }